blib/lib/DBIx/QuickORM/Manual/Transactions.pm

filter: Statementstmt 100% 8 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 10 / 10 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/DBIx/QuickORM/Manual/RowClasses.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Types.pm »
1 package DBIx::QuickORM::Manual::Transactions;
2 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 2 our $VERSION = '0.000031';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Transactions - Transactions, savepoints, retries, and the rows you hold, by example.
14  
15 =head1 DESCRIPTION
16  
17 C<< $orm->txn >> opens a transaction. One opened inside another is a
18 savepoint.
19  
20 =head1 SCHEMA
21  
22 The examples use PostgreSQL and this schema:
23  
24 =for highlighter language=sql
25  
26 CREATE TABLE users (
27 id SERIAL PRIMARY KEY,
28 name TEXT NOT NULL,
29 email TEXT UNIQUE,
30 prefs JSON,
31 referred_by INTEGER REFERENCES users (id),
32 created TIMESTAMP NOT NULL DEFAULT now()
33 );
34  
35 CREATE TABLE posts (
36 id SERIAL PRIMARY KEY,
37 user_id INTEGER NOT NULL REFERENCES users (id),
38 title TEXT NOT NULL,
39 views INTEGER NOT NULL DEFAULT 0
40 );
41  
42 =head1 BLOCK FORM
43  
44 =for highlighter language=perl
45  
46 $orm->txn(sub {
47 my $ann = $orm->insert(users => {name => 'Ann'});
48 $orm->insert(posts => {
49 user_id => $ann->field('id'),
50 title => 'Hello',
51 });
52 }); # commits when the block returns
53  
54 my $ok = eval {
55 $orm->txn(sub {
56 $orm->insert(users => {name => 'Bob'});
57 die "no\n"; # rolls back, and the exception is rethrown
58 });
59 1;
60 };
61  
62 # returns what the block returns
63 my $count = $orm->txn(sub { $orm->handle('users')->count });
64  
65 $orm->txn(sub {
66 my $txn = shift;
67 $orm->insert(users => {name => 'Cy'});
68 # or commit: the transaction is over, and the rest of the block runs outside it
69 $txn->rollback;
70 });
71  
72 =head1 OBJECT FORM
73  
74 my $txn = $orm->txn;
75 $orm->insert(users => {name => 'Di'});
76 $txn->commit;
77  
78 my $undo = $orm->txn;
79 $orm->insert(users => {name => 'Eve'});
80 $undo->rollback;
81  
82 C<commit> and C<rollback> end the transaction, not your code: what follows
83 them runs outside it. A transaction object that goes out of scope unfinished
84 is rolled back, with a warning saying where it was opened.
85  
86 =head1 SAVEPOINTS
87  
88 $orm->txn(sub {
89 $orm->insert(users => {name => 'Fay'});
90 eval {
91 $orm->txn(sub {
92 $orm->insert(users => {name => 'Gus'});
93 die "undo Gus only\n";
94 });
95 };
96 $orm->insert(users => {name => 'Hal'});
97 }); # Fay and Hal are committed, but Gus was rolled back with his savepoint
98  
99 my $outer = $orm->txn;
100 my $inner = $orm->txn; # a savepoint
101 $orm->insert(users => {name => 'Ian'});
102 $inner->rollback; # the innermost open transaction has to finish first
103 $outer->commit; # without Ian
104  
105 Committing or rolling back C<$outer> while C<$inner> is still open croaks.
106 DuckDB has no savepoints, so nesting croaks there
107 (L<DBIx::QuickORM::Manual::Dialects/TRANSACTIONS>).
108  
109 =head1 A FAILED STATEMENT
110  
111 $orm->insert(users => {name => 'Lu', email => 'lu@example.com'});
112  
113 $orm->txn(sub {
114 # the failure rolls back only the nested transaction
115 my $dup = !eval {
116 $orm->txn(sub {
117 $orm->insert(users => {name => 'Lu2', email => 'lu@example.com'});
118 });
119 1;
120 };
121 $orm->insert(users => {name => 'Mo'});
122 }); # Mo is committed
123  
124 my $ok = eval {
125 $orm->txn(sub {
126 $orm->insert(users => {name => 'Ned'});
127 # caught, but the failure marks the transaction failed
128 eval { $orm->insert(users => {name => 'Ned2', email => 'lu@example.com'}) };
129 }); # croaks: the commit rolls back instead, so Ned is gone too
130 1;
131 };
132  
133 A statement that fails inside a transaction marks it failed, even when your
134 code catches the error. From then on every statement croaks, except the
135 rollback. A commit rolls back instead, then croaks. This holds on every
136 database, so no failed work is ever taken for committed.
137  
138 To recover and go on, run the work that may fail in a nested transaction.
139 Rolling back the savepoint clears the mark. The block form does that when
140 the exception leaves it. C<find_or_insert> does this itself. DuckDB has no
141 savepoints, so there a failure leaves the transaction nothing but its
142 rollback.
143  
144 =head1 ISOLATION
145  
146 # every outermost transaction opens at read committed unless told otherwise
147 $orm->txn(sub { $orm->insert(users => {name => 'Kim'}) });
148  
149 # one transaction at another level
150 my $total = $orm->txn(
151 sub { $orm->handle('posts')->count },
152 isolation => 'repeatable read',
153 );
154  
155 # another default for every transaction of this ORM
156 my $strict = DBIx::QuickORM->new(
157 connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) },
158 isolation => 'serializable',
159 );
160  
161 # a plain BEGIN: the database's own default level
162 $orm->txn(sub { $orm->handle('users')->count }, isolation => 'server');
163  
164 Every outermost transaction states its isolation level when it opens. The
165 default is C<read committed> on every database that can set a level, so a
166 transaction behaves the same on PostgreSQL and the MySQL family, whose
167 servers default to different levels. Stating it each time also means a
168 changed server or session setting cannot change it.
169  
170 The levels are C<read uncommitted>, C<read committed>, C<repeatable read>,
171 and C<serializable>, in upper or lower case. C<server> sends a plain C<BEGIN>
172 and leaves the level to the database. Anything else croaks.
173  
174 The level comes from the C<txn> call's C<isolation>, else the ORM's
175 C<isolation> (C<new> argument, or C<override> in the DSL), else C<read
176 committed>. Only an outermost transaction takes one. A savepoint runs at its
177 transaction's level. A retried block begins at the same level each time.
178  
179 What each database is sent, and its own default:
180  
181 =over 4
182  
183 =item PostgreSQL
184  
185 C<BEGIN ISOLATION LEVEL READ COMMITTED>, one statement. The server's default
186 is C<read committed>. C<read uncommitted> runs as C<read committed>.
187  
188 =item MySQL and MariaDB
189  
190 C<SET TRANSACTION ISOLATION LEVEL READ COMMITTED>, then C<BEGIN>. The SET
191 covers the next transaction only. The server's default is C<repeatable
192 read>.
193  
194 =item SQLite
195  
196 C<BEGIN>. SQLite has no level to set: its transactions are serializable.
197  
198 =item DuckDB
199  
200 C<BEGIN>. DuckDB has no level to set: its transactions use snapshot
201 isolation.
202  
203 =back
204  
205 On SQLite and DuckDB the default sends nothing extra. There, leave
206 C<isolation> out or give C<server>: naming any level, C<read committed>
207 included, croaks when a transaction opens, whether the C<txn> call or the ORM
208 names it.
209  
210 The MySQL family with binary logging on and C<binlog_format=STATEMENT>:
211 InnoDB refuses writes at C<read committed> and C<read uncommitted>, since
212 statement-based logging needs C<repeatable read>. Use C<ROW> (MySQL's
213 default) or C<MIXED> (MariaDB's), or give the ORM
214 C<< isolation => 'repeatable read' >>.
215  
216 =head1 RETRY
217  
218 use DBIx::QuickORM::Value qw/sql/;
219  
220 my $post_id = $orm->handle('posts')->only->field('id');
221  
222 $orm->txn(
223 sub {
224 my $post = $orm->find(posts => $post_id);
225 $post->update({views => $post->field('views') + 1});
226 },
227 # the database reports a conflicting write as a serialization failure
228 isolation => 'serializable',
229 retry => 3, # then the block runs again, up to 3 more times
230 );
231  
232 my $post = $orm->find(posts => $post_id);
233  
234 # the database does the arithmetic, so concurrent increments all count
235 $post->update({views => sql('views + 1')});
236  
237 Only an outermost transaction can be retried, and the block must be safe to
238 run again. C<< retry => 3 >> allows four attempts. The last failure is
239 rethrown. L<DBIx::QuickORM::Manual::Errors> shows which errors count.
240  
241 At the default C<read committed> level a read-then-write like this does not
242 fail: the second writer silently overwrites the first. C<isolation>
243 makes the database notice the conflict. Better, let the database do the
244 arithmetic with C<sql()> (L<DBIx::QuickORM::Manual::Values>), or use
245 C<cas_update> (below) when the new value depends on what was read.
246  
247 =head1 THE ROWS YOU HOLD
248  
249 C<< $row->is_canon >> asks whether a row object's data is the ORM's canonical
250 copy of its row (L<DBIx::QuickORM::Manual::Caching>).
251  
252 my $post = $orm->find(posts => $post_id); # canonical: the ORM's cached copy of the row
253  
254 my ($before, $inside);
255 $orm->txn(sub {
256 # false: a row read before the transaction is not canonical inside it
257 $before = $post->is_canon;
258  
259 # read again: the database holds the same data, so $post's copy is reused
260 my $same = $orm->find(posts => $post_id);
261 $inside = $post->is_canon; # true
262 });
263  
264 my $after = $post->is_canon; # true: the commit kept the copy the transaction reused
265  
266 my $gone;
267 $orm->txn(sub {
268 my $txn = shift;
269 my $tmp = $orm->insert(users => {name => 'Jo'});
270 $txn->rollback;
271 $gone = $tmp->is_canon; # false: a rollback forgets everything the transaction held
272 });
273  
274 my $stale;
275 $orm->txn(sub {
276 my $post = $orm->find(posts => $post_id);
277 eval {
278 $orm->txn(sub {
279 $post->update({views => 99});
280 die "undo\n";
281 });
282 };
283 $stale = $post->is_canon; # false: the savepoint's data was rolled back
284 $post->refresh; # reads the database: back to the earlier views
285 });
286  
287 A commit keeps the copies the transaction read or wrote, and its deletes,
288 held weakly unless C<retain_cache>. A rollback forgets them. Either way, rows
289 from before that the transaction did not touch are canonical again once it
290 ends.
291  
292 Once the transaction writes, deletes, re-reads with changed data, or clears
293 (C<clear_cache>) a row, that row's copy from before is gone, even after a
294 rollback. A bulk C<update> or C<delete> drops every copy of its table's rows
295 from before the transaction. So after a rollback no row the transaction wrote,
296 or re-read with changed data, is canonical: C<refresh> one it updated, and
297 insert again one it inserted.
298  
299 A savepoint starts with the row cache of the transaction around it. Rolling
300 it back restores that, so a row changed or deleted inside it is canonical
301 again in its earlier form. A row object that took the savepoint's data is
302 not, so C<refresh> it.
303  
304 Row state follows the transaction. A rollback undoes its deletes: those rows
305 are no longer C<was_deleted>. It undoes its inserts too: those rows are no
306 longer C<is_in_db>, and can be inserted again. A savepoint rollback undoes
307 only what the savepoint did.
308  
309 When a commit or rollback statement itself fails, the outcome is unknown and
310 the error says so. Row state then follows the rollback rules as a guess. The
311 database may in fact have committed. Re-read the rows the transaction
312 touched before trusting C<is_in_db> or C<was_deleted>.
313  
314 Caveat: a row inserted in the transaction and then re-read with changed data
315 (not through C<update> or C<refresh>) may still report C<is_in_db> after the
316 rollback. C<refresh> it to check.
317  
318 =head1 WRITING A ROW READ BEFORE THE TRANSACTION
319  
320 my $post = $orm->find(posts => $post_id);
321  
322 $orm->txn(sub {
323 # croaks: $post is not canonical inside the transaction
324 my $ok = eval { $post->update({views => 5}); 1 };
325  
326 # succeeds only if views still equals the value $post read
327 $post->cas_update({views => 5}) or die "Changed elsewhere\n";
328 });
329  
330 $orm->txn(sub {
331 $post->refresh; # reads the database: $post is canonical again
332 $post->update({views => 6}); # then update as usual
333 });
334  
335 Inside a transaction C<update> and C<delete> check that the row is canonical,
336 whatever the ORM-wide C<enforce_canon> says, unless the call passes
337 C<< enforce_canon => 0 >> (L<DBIx::QuickORM::Manual::Caching/ENFORCE_CANON>).
338 C<cas_update> never checks: it compares the fields it changes (or the C<cas>
339 fields) with the database instead.
340  
341 =cut
342  
343 2 1;
344  
345 __END__
« blib/lib/DBIx/QuickORM/Manual/RowClasses.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Types.pm »