blib/lib/DBIx/QuickORM/Manual/Caching.pm untested

filter: Statementstmt 0.0% 0 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 2 Podpod n/a totaltotal 0.0% 0 / 10 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package DBIx::QuickORM::Manual::Caching;
2 use strict;
3 use warnings;
4  
5 our $VERSION = '0.000033';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Caching - The ORM's one canonical copy of each row, by
14 example.
15  
16 =head1 DESCRIPTION
17  
18 The ORM caches one copy of the data of each row it has read or written, per
19 table and primary key: the I<canonical> copy (the code calls it I<canon>). A
20 row is canonical when its data is that copy. That does not mean it matches
21 the database right now. Two reads of one row can share it, and a write
22 through a row object needs it. C<< $row->is_canon >> asks whether a row
23 object is canonical.
24  
25 =head1 SCHEMA
26  
27 The examples use PostgreSQL and this schema:
28  
29 =for highlighter language=sql
30  
31 CREATE TABLE users (
32 id SERIAL PRIMARY KEY,
33 name TEXT NOT NULL,
34 email TEXT UNIQUE,
35 prefs JSON,
36 referred_by INTEGER REFERENCES users (id),
37 created TIMESTAMP NOT NULL DEFAULT now()
38 );
39  
40 CREATE TABLE posts (
41 id SERIAL PRIMARY KEY,
42 user_id INTEGER NOT NULL REFERENCES users (id),
43 title TEXT NOT NULL,
44 views INTEGER NOT NULL DEFAULT 0
45 );
46  
47 =head1 ONE COPY PER ROW
48  
49 =for highlighter language=perl
50  
51 my $one = $orm->find(users => $id);
52 my $two = $orm->handle('users')->where({id => $id})->only;
53  
54 # true: the same hash, so two objects share one copy of the data
55 my $shared = $one->row_data == $two->row_data;
56  
57 $one->update({name => 'Ann B'});
58 my $stale = $two->is_canon; # false: $one's write replaced the canonical copy
59 my $name = $two->field('name'); # 'Ann': $two still holds the data it read
60  
61 # croaks: $two is not canonical
62 my $ok = eval { $two->update({email => 'b@example.com'}); 1 };
63  
64 $two->refresh; # reads the database: $two is canonical again
65 $two->update({email => 'b@example.com'});
66  
67 Refusing the write is the point: C<$one> changed the row, so C<$two> is stale
68 even for a write to another field, and a write decided on stale data is the
69 bug this catches. C<cas_update> writes a stale row safely by comparing with
70 the database (L<DBIx::QuickORM::Manual::Transactions>).
71  
72 =head1 ENFORCE_CANON
73  
74 # write by primary key alone, whatever the ORM holds
75 $two->update({email => 'c@example.com'}, enforce_canon => 0);
76  
77 my $lax = DBIx::QuickORM->new(
78 credentials => {
79 dsn => $dsn,
80 user => $user,
81 pass => $pass,
82 },
83 enforce_canon => 0, # for every write outside a transaction
84 );
85  
86 Inside a transaction every C<update> and C<delete> checks, whatever the
87 ORM-wide C<enforce_canon> says, unless the call itself passes
88 C<< enforce_canon => 0 >>.
89  
90 =head1 READS FROM THE CANONICAL COPY
91  
92 my $ann = $orm->find(users => $id);
93 my $again = $orm->find(users => $id); # no query: the canonical copy has every field asked for
94  
95 my $fresh = $orm->find(
96 users => $id,
97 cache => 0, # reads the database (same data, so the canonical copy stays)
98 );
99  
100 When another process has changed the row:
101  
102 my $changed = $orm->find(
103 users => $id,
104 cache => 0, # new data: this becomes the canonical copy
105 );
106  
107 my $old = $ann->is_canon; # false
108 $ann->refresh; # true again
109  
110 C<find> and C<refresh_row> return the canonical copy when it has every field
111 asked for. C<where> only builds a handle: its first read runs the query, and
112 later reads and every C<iter> reuse its rows until C<clear>. A query's rows
113 keep the canonical copy when the data matches and they hold every field it
114 holds, and replace it otherwise (L</"FIELDS LEFT OUT OF A SELECT">).
115  
116 C<< $row->refresh >> always reads the database.
117  
118 A C<no_cache> handle's queries skip the row cache: their rows are not
119 canonical, and the row cache does not change. C<cache> undoes it on a handle.
120 C<bare> is C<no_cache> with hashrefs for rows.
121  
122 my $apart = $orm->handle('users')->no_cache;
123 my @rows = $apart->all; # not canonical, and the row cache does not change
124  
125 # find is a CRUD operation and reads the canonical copy first, but cache => 0 forces a read
126 my $read = $apart->find($id, cache => 0);
127  
128 =head1 FIELDS LEFT OUT OF A SELECT
129  
130 C<omit>, C<default_fields>, C<auto_omit>, and a handle's C<fields> leave
131 fields out of a select. A row fetches a missing field the first time it reads
132 it, with one query (so in a loop, select the fields up front). Where the
133 database has C<RETURNING>, a write reads back the default fields, the fields
134 written, and for an update the fields the row held. C<refresh> reads the
135 fields the row holds too.
136  
137 A read that lacks a field the canonical copy holds cannot vouch for that
138 field, so its data replaces the canonical copy:
139  
140 my $full = $orm->find(users => $id); # every field
141 my $slim = $orm->handle('users')->fields(['name'])->where({id => $id})->only; # the same row, fewer fields
142  
143 my $canon = $full->is_canon; # false: $slim's read replaced the canonical copy
144  
145 # true: the write croaks, and $@ says the row data is no longer canonical
146 my $refused = !eval { $full->update({name => 'Ann F'}); 1 };
147  
148 $full->refresh; # canonical again, prefs included
149 $full->update({name => 'Ann F'});
150  
151 C<$full> keeps the fields it read, but the row was fetched again elsewhere, so
152 its data may be stale. C<cas_update> writes it safely without a refresh.
153  
154 With C<auto_omit>, C<omit>, or C<default_fields> this is common. A row
155 holding an omitted field, because a write read it back or the row read it,
156 stops being canonical when a default listing reads the same row again. Insert
157 a row with its JSON, list the table, then update that row, and the update
158 croaks. The same happens to a row that read its JSON before the listing.
159 Refresh the row, write it with C<cas_update>, or give the listing a
160 C<fields> naming every field the row holds (C<fields> replaces the default
161 fields). Without omitted fields it takes two reads of one row with different
162 C<fields>.
163  
164 C<cas_update> croaks on a field the row does not hold: read an omitted field
165 first, or select it with C<fields>, to compare it.
166  
167 =head1 WHY A ROW IS NOT CANONICAL
168  
169 A row's C<canon_status> (or the ORM's) says why its data is not the canonical
170 copy, without writing. Build the ORM with C<< debug => 1 >> and it also names
171 the call that made it so:
172  
173 my $orm = DBIx::QuickORM->new(
174 credentials => \%credentials,
175 debug => 1, # record which call makes a row stale
176 );
177  
178 my $full = $orm->find(users => $id);
179 my $slim = $orm->handle('users')->fields(['name'])->where({id => $id})->only;
180  
181 my $why = $full->canon_status;
182 # {cause => 'replaced', by => ['main', 'app.pl', 7, 'DBIx::QuickORM::Handle::only']}
183  
184 eval { $full->update({name => 'Ann F'}) };
185 # $@: The row data for 'users' is no longer canonical: the row was fetched or
186 # written again elsewhere in the code, leaving this copy stale. Last replaced by
187 # DBIx::QuickORM::Handle::only call in app.pl at line 7. Refresh the row ...
188  
189 It is undef for a canonical row. The causes are C<replaced>,
190 C<cache_cleared>, C<txn>, C<deleted>, C<not_in_db>, and C<not_cached>
191 (L<DBIx::QuickORM/"The row cache"> lists what each means). The croak for
192 writing such a row names the same cause and call, as above.
193  
194 The call is the outermost public method that made the change: a row's
195 C<refresh> rather than the C<refresh_row> it calls. It is left out when it is
196 not known, such as for a row whose missing field was fetched through
197 C<field>, or a whole table cleared (given then as the last clear).
198  
199 Without C<debug> no call is recorded. C<canon_status> gives the cause it can
200 work out when asked (C<< {cause => 'replaced'} >> above, though a copy that was
201 never canonical looks the same), and the croak says to construct the ORM with
202 C<< debug => 1 >> to record the call.
203  
204 =head2 What debug costs
205  
206 Recording means one more step on every call that may write or replace row
207 data: noting the caller, and a note on each row that stops being canonical.
208 Measured on one machine (CPU time per operation, local servers), it adds:
209  
210 =over 4
211  
212 =item *
213  
214 about 1.3 to 5 µs to a single-row update (MariaDB 28.6 to 30 µs, PostgreSQL
215 32.5 to 35, SQLite 42.6 to 46 or 48), and 0.6 to 3 µs to an insert
216  
217 =item *
218  
219 about 1 µs to a C<find>, and to a handle's first read (once per query)
220  
221 =item *
222  
223 nothing per row to a fetch of many rows, unless a row it reads replaces a
224 copy already held
225  
226 =back
227  
228 So a loop of single-row writes runs 3% to 12% slower. A web request that
229 makes 20 queries adds 20 to 80 µs: 0.3% to 1.3% of the queries' time when
230 each takes 300 µs on the network, and less of a request that also renders a
231 page or calls other services. Turn it on while chasing a stale row, or
232 for a whole development or test run. Leave it off for loops of many small
233 writes where every microsecond counts.
234  
235 =head1 HOW LONG ROWS ARE HELD
236  
237 By default a copy is held only while your code holds a row object (or its
238 data) for it. C<< retain_cache => 1 >> holds every copy until C<clear_cache>.
239 Inside a transaction every copy is held until the transaction ends.
240  
241 C<refresh_row> takes the key in any form (L<DBIx::QuickORM::Manual::Keys>).
242 With C<< db => 0 >> it asks the row cache only, without querying
243 the database, so it shows whether a copy is held:
244  
245 # the row object is gone at once
246 my $tmp_id = $orm->insert(users => {name => 'Tmp'})->field('id');
247 my $held = $orm->refresh_row(
248 users => {id => $tmp_id},
249 db => 0, # undef: nothing holds the row any more
250 );
251  
252 my $keeper = DBIx::QuickORM->new(
253 credentials => {
254 dsn => $dsn,
255 user => $user,
256 pass => $pass,
257 },
258 retain_cache => 1,
259 );
260  
261 my $kept_id = $keeper->insert(users => {name => 'Kept'})->field('id');
262 my $kept = $keeper->refresh_row(
263 users => {id => $kept_id},
264 db => 0, # the row: held until clear_cache
265 );
266  
267 =head1 CLEAR_CACHE
268  
269 # one row: a hashref, arrayref, row, or single value, as find takes it
270 $orm->clear_cache(users => $id);
271 $orm->clear_cache('users'); # one table
272 $orm->clear_cache; # everything
273 my $current = $ann->is_canon; # false: refresh makes it canonical again
274  
275 my $post = $orm->find(posts => $post_id);
276  
277 # a bulk update or delete drops the canonical copies of its table's rows
278 $orm->handle('posts')->where({views => 0})->update({views => 1});
279 my $dropped = $post->is_canon; # false
280  
281 # mark_deleted: the held rows it deleted also say so
282 my $temp = $orm->insert(posts => {
283 user_id => $ann->field('id'),
284 title => 'Temp',
285 });
286 $orm->handle('posts')->where({title => 'Temp'})->delete(mark_deleted => 1);
287 my $deleted = $temp->was_deleted; # true
288  
289 =head1 TRANSACTIONS
290  
291 A row read before a transaction is not canonical inside it until it is read
292 again. A commit keeps what the transaction held, and a rollback forgets it.
293 L<DBIx::QuickORM::Manual::Transactions/"THE ROWS YOU HOLD"> shows each case.
294  
295 =head1 TYPED KEYS
296  
297 A typed primary key finds the canonical copy in any form:
298 L<DBIx::QuickORM::Manual::Keys/"TYPED KEYS">.
299  
300 =head1 PICKING A LOOKUP TABLE
301  
302 Everything above is the default lookup table, C<Identity>. You can use the
303 C<lookup> argument on the ORM to pick another:
304  
305 my $plain = DBIx::QuickORM->new(credentials => \%credentials, lookup => 'Scoped');
306 my $one = $plain->find(users => $id);
307 my $two = $plain->find(users => $id); # new row data: nothing is cached
308 my $both = $one->is_canon && $two->is_canon; # true outside a transaction
309  
310 =over 4
311  
312 =item C<Identity>
313  
314 One canonical copy per row, cached, as this page describes.
315  
316 =item C<Scoped>
317  
318 No cache, and every copy of a row is canonical, as in L<DBIx::Class>. It keeps
319 one protection: row data from outside a transaction cannot write in it, and
320 row data from one that rolled back cannot write anywhere. Outside a
321 transaction nothing is checked, so a stale copy writes freely
322 (L<DBIx::QuickORM::LookupTable::Scoped/Risks>).
323  
324 =item C<Unchecked>
325  
326 No cache and no checks at all: keeping rows current is up to you. Whether a
327 row is in the database still applies
328 (L<DBIx::QuickORM::LookupTable::Unchecked>).
329  
330 =back
331  
332 Without a cache, C<cache> options always miss and C<retain_cache> croaks.
333 L<DBIx::QuickORM::Role::LookupTable> says how to write your own.
334  
335 =head1 WHEN TO CARE
336  
337 =over 4
338  
339 =item *
340  
341 Read a row, use it, drop it: never.
342  
343 =item *
344  
345 Keep a row object while other code writes the row, or across a transaction:
346 C<refresh> before writing it, or write it with C<cas_update>.
347  
348 =item *
349  
350 Several processes: each has its own copies. For a write that depends on what
351 was read, use C<cas_update> with C<< cas => [...] >> naming the fields it
352 depends on. A transaction alone does not stop another writer at the default
353 isolation level (L<DBIx::QuickORM::Manual::Transactions/ISOLATION>).
354  
355 =item *
356  
357 Reading many rows you do not write: skip the row cache with C<no_cache> or
358 C<bare> (L<DBIx::QuickORM::Manual::Optimizations/READING MANY ROWS>).
359  
360 =back
361  
362 =cut
363  
364 1;
365  
366 __END__