blib/lib/DBIx/QuickORM/Manual/Quickstart.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/Optimizations.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/RowClasses.pm »
1 package DBIx::QuickORM::Manual::Quickstart;
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.000032';
6  
7 =pod
8  
9 =encoding UTF-8
10  
11 =head1 NAME
12  
13 DBIx::QuickORM::Manual::Quickstart - Introduces the fundamentals with a simple example, then expands into advanced capabilities from there.
14  
15 =head1 DESCRIPTION
16  
17 Short examples of what most applications do with the ORM. They use
18 PostgreSQL and this schema:
19  
20 =for highlighter language=sql
21  
22 CREATE TABLE users (
23 id SERIAL PRIMARY KEY,
24 name TEXT NOT NULL,
25 email TEXT UNIQUE,
26 prefs JSON,
27 referred_by INTEGER REFERENCES users (id),
28 created TIMESTAMP NOT NULL DEFAULT now()
29 );
30  
31 CREATE TABLE posts (
32 id SERIAL PRIMARY KEY,
33 user_id INTEGER NOT NULL REFERENCES users (id),
34 title TEXT NOT NULL,
35 views INTEGER NOT NULL DEFAULT 0
36 );
37  
38 And a log whose C<user_id> has no foreign key constraint:
39  
40 CREATE TABLE audit_log (
41 id SERIAL PRIMARY KEY,
42 user_id INTEGER,
43 action TEXT NOT NULL
44 );
45  
46 The ORM reads the schema from the database. Nothing is declared in Perl.
47 C<prefs> comes back as Perl data and C<created> as a lazy L<DateTime>
48 (L<DBIx::QuickORM::Type::DateTime::Lazy>), from their declared types
49 (L<DBIx::QuickORM::Manual::Types>).
50  
51 Other databases differ in places: L<DBIx::QuickORM::Manual::Dialects>.
52  
53 =head1 CONNECTING
54  
55 =for highlighter language=perl
56  
57 use DBIx::QuickORM;
58  
59 my $orm = DBIx::QuickORM->new(
60 credentials => {
61 dsn => $dsn,
62 user => $user,
63 pass => $pass,
64 },
65 );
66  
67 Or a sub that returns a new handle each time it is called:
68  
69 my $orm = DBIx::QuickORM->new(
70 connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) },
71 );
72  
73 Or a handle you already have, with C<RaiseError> on:
74  
75 my $orm = DBIx::QuickORM->new(dbh => $dbh);
76  
77 The ORM cannot open a second connection from a C<dbh>, so with it a forked
78 child cannot reconnect, and C<aside()> and C<forked()> croak
79 (L<DBIx::QuickORM::Manual::Background>).
80  
81 The ORM controls its handle's attributes and may change any of them. Do not
82 change them, run SQL on the handle, or control transactions on it outside the
83 ORM.
84  
85 Change rows only through the ORM's methods, such as C<< $row->update >>. If
86 you edit a row's data hash directly, the ORM does not know about it, so its
87 row cache and change tracking go stale (L<DBIx::QuickORM::Manual::Caching>).
88  
89 =head1 CREATE, READ, UPDATE, DELETE, FIND
90  
91 my $alice = $orm->insert(users => {
92 name => 'Alice',
93 email => 'alice@example.com',
94 prefs => {theme => 'dark'},
95 });
96  
97 my $id = $alice->field('id'); # the key the database generated
98 my $theme = $alice->field('prefs')->{theme}; # JSON comes back as Perl data
99 my $json = $alice->raw_field('prefs'); # '{"theme":"dark"}': the value as stored
100 my $year = $alice->field('created')->datetime_ref->year; # timestamps come back as lazy DateTimes
101  
102 my $found = $orm->find(users => $id); # by primary key
103  
104 # undef: no such user
105 my $bob = $orm->handle('users')->where({email => 'bob@example.com'})->only;
106  
107 $alice->update({name => 'Alice Smith'});
108 $alice->refresh; # read it again from the database
109  
110 my $temp = $orm->insert(users => {name => 'Temp'});
111 $temp->delete;
112  
113 Rows have no setters: change them with C<update>.
114  
115 Find a row, or insert it when there is none:
116  
117 my $gil = $orm->find_or_insert(
118 users => {
119 name => 'Gil',
120 email => 'gil@example.com',
121 },
122 by => ['email'], # the fields to find by (the primary key by default)
123 );
124  
125 When another process inserts the same row first, it finds that one, given a
126 unique constraint on the C<by> fields (limits:
127 L<DBIx::QuickORM/Finding or inserting>).
128  
129 A table handle has it too: C<< $users->find_or_insert(\%fields, by => ['email']) >>.
130  
131 Values are deflated by their field's type on the way in: Alice's C<prefs>
132 hashref went in as JSON. C<raw()> sends one value as given:
133  
134 use DBIx::QuickORM::Value qw/raw/;
135  
136 my $hal = $orm->insert(users => {
137 name => 'Hal',
138 prefs => raw('{"theme":"light"}'), # already JSON text: sent as is
139 });
140  
141 C<< raw => 1 >> on the call does the same for every value.
142  
143 See L<DBIx::QuickORM::Manual::Keys> for the forms a key takes, and
144 L<DBIx::QuickORM::Manual::Values> for inflation, deflation, and the value
145 markers. Rows are L<DBIx::QuickORM::Row> objects, and table handles are
146 L<DBIx::QuickORM::Handle> objects.
147  
148 =head1 HANDLES
149  
150 A handle is a query. Modifiers return a new handle. The one they are called
151 on never changes, so calling one in void context croaks.
152  
153 my $users = $orm->handle('users');
154 my $sorted = $users->order_by('name'); # $users is unchanged
155 my $page = $sorted->limit(10)->offset(20);
156 my $alices = $users->where({name => {-like => 'Alice%'}});
157  
158 my $count = $users->count;
159 my @all = $sorted->all;
160 my @data = $sorted->data_only->all; # plain hashrefs, not row objects
161  
162 One row at a time, on a table handle:
163  
164 my $carol = $users->insert({name => 'Carol'});
165 my $again = $users->find($carol->field('id'));
166 $users->update_row($carol, {email => 'carol@example.com'});
167 $users->delete_row($carol);
168  
169 Many rows at once:
170  
171 my $added = $users->insert_many([{name => 'Dan'}, {name => 'Erin'}]); # an arrayref of rows
172 my $renamed = $users->where({name => 'Dan'})->update({name => 'Daniel'});
173 my $removed = $users->where({name => 'Erin'})->delete;
174  
175 See L<DBIx::QuickORM::Manual::BulkInsert> for C<insert_many>, and
176 L<DBIx::QuickORM::Manual::RowClasses> for C<data_only> and row classes of
177 your own. L<DBIx::QuickORM::Handle> documents every handle method.
178  
179 =head1 ITERATING
180  
181 my $posts = $orm->handle('posts')->order_by('id');
182 while (my $row = $posts->next) {
183 my $title = $row->field('title');
184 }
185  
186 my $it = $posts->iter; # its own position over the same rows
187 $posts->clear; # forget the rows, so the next read queries again
188  
189 A handle sends its query on the first read and keeps the rows until C<clear>.
190 C<next> and C<reset> move the handle's own position. Each C<iter> returns a
191 new iterator with its own.
192  
193 A handle from a foreign key knows whether it can match more than one row:
194  
195 my $post = $posts->first;
196 my $author = $post->follow_fk('users')->only; # single: the key points at one row
197 my @posts = $alice->follow_fk('posts')->all; # multi: any number of rows
198  
199 C<only> returns the one row, or undef. It croaks when there is more than one,
200 and always on a multi handle. See L<DBIx::QuickORM::Manual::ForeignKeys>.
201  
202 C<via> follows fields the database never declared as a key:
203  
204 my $entry = $orm->insert(audit_log => {user_id => $alice->field('id'), action => 'login'});
205 my $who = $entry->follow_fk('users', via => {user_id => 'id'})->only; # Alice
206  
207 L<DBIx::QuickORM::Iterator> documents iterators.
208  
209 =head1 JOINS
210  
211 my @pairs = $orm->handle('posts')
212 ->join('users')
213 ->where({'users.name' => 'Alice Smith'})
214 ->all;
215  
216 for my $pair (@pairs) {
217 my $title = $pair->row('posts')->field('title');
218 my $author = $pair->row('users')->field('name');
219 }
220  
221 Each result holds one row per table. Fields are named C<table.field>.
222  
223 C<left_join> keeps every user. C<row('posts')> is undef for a user without
224 posts:
225  
226 my @everyone = $orm->handle('users')->left_join('posts')->all;
227  
228 C<as> names the joined table, and its fields are C<alias.field>. C<link>
229 picks the foreign key when there is more than one way to join, as a self join
230 has:
231  
232 my @referred = $orm->handle('users')
233 ->join(
234 'users',
235 as => 'referrer',
236 link => {referred_by => 'id'},
237 )
238 ->order_by('referrer.name')
239 ->all;
240  
241 for my $pair (@referred) {
242 my $who = $pair->row('users')->field('name');
243 my $by = $pair->row('referrer')->field('name');
244 }
245  
246 See L<DBIx::QuickORM::Manual::Joins>.
247  
248 =head1 AGGREGATES
249  
250 my @stats = $orm->handle('posts')
251 ->group_by('user_id')
252 ->fields({
253 user_id => 'user_id',
254 posts => [count => '*'], # COUNT(*)
255 titles => \'COUNT(DISTINCT title)', # or any SQL
256 views => [sum => 'views'],
257 })
258 ->order_by('user_id')
259 ->all;
260  
261 for my $stat (@stats) {
262 my $count = $stat->field('posts');
263 my $poster = $stat->follow_fk('users')->only; # user_id keeps its foreign key
264 }
265  
266 See L<DBIx::QuickORM::Manual::Aggregates>, and L<DBIx::QuickORM::Manual::Values>
267 for C<sql()>.
268  
269 =head1 TRANSACTIONS
270  
271 $orm->txn(sub {
272 my $dave = $orm->insert(users => {name => 'Dave'});
273 $orm->insert(posts => {
274 user_id => $dave->field('id'),
275 title => 'First post',
276 });
277 }); # commits when the block returns. An exception rolls back and is rethrown
278  
279 my $txn = $orm->txn;
280 $orm->insert(users => {name => 'Nobody'});
281 $txn->rollback; # or $txn->commit
282  
283 A transaction opened inside another is a savepoint.
284  
285 Rows read before a transaction are not canonical inside it: refresh one before
286 writing it there, or write it with C<cas_update> (L</COMPARE-AND-SWAP>).
287  
288 $orm->txn(
289 sub {
290 $post->refresh; # $post was read before the transaction
291 $post->update({views => 2});
292 },
293 isolation => 'serializable',
294 retry => 3,
295 );
296  
297 Every outermost transaction opens at C<read committed> unless C<isolation>
298 (on the call, or the ORM's) names another level. A savepoint keeps its
299 transaction's level. At C<serializable>, a write that conflicts with another
300 transaction fails with a serialization failure instead of overwriting it.
301  
302 C<retry> runs the block again, up to 3 more times, after a deadlock, a
303 serialization failure, or a lock timeout (L<DBIx::QuickORM::Manual::Errors>).
304  
305 See L<DBIx::QuickORM::Manual::Transactions>.
306  
307 =head1 COMPARE-AND-SWAP
308  
309 # cas_update writes only while views still holds the value this row read, and
310 # returns undef when it changed elsewhere first: read the row again and retry.
311 while (1) {
312 last if $post->cas_update({views => $post->field('views') + 1});
313 $post->refresh;
314 }
315  
316 The loop ends once this process is the one that incremented C<views>, however
317 many others increment it at the same time. C<cas_update> compares the fields
318 it changes. C<< cas => [...] >> names other fields to compare instead.
319  
320 C<update> compares too, given C<cas>, or C<auto_cas> for every changed field
321 the row holds:
322  
323 $post->update({views => 10}, auto_cas => 1);
324  
325 C<cas_update> also works on a row that is not canonical, such as one read
326 before a transaction:
327  
328 $orm->txn(sub {
329 $post->cas_update({views => 11}) or die "Changed elsewhere\n";
330 });
331  
332 See L<DBIx::QuickORM::Manual::Caching> for which rows are canonical.
333  
334 =head1 LEAVING FIELDS OUT
335  
336 C<auto_omit> leaves fields of the types you name out of default selects. A
337 row fetches such a field the first time it reads it. Nothing is left out
338 unless you ask:
339  
340 my $lean = DBIx::QuickORM->new(
341 connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) },
342 auto_omit => {types => ['JSON']}, # or db_types => ['json'], by database type
343 );
344  
345 my $lean_alice = $lean->find(users => $id); # prefs is not fetched
346 my $her_prefs = $lean_alice->field('prefs'); # fetched now
347  
348 In a loop over many rows, select such fields up front with a handle's
349 C<fields>. C<omit> and C<default_fields> choose a table's fields by name
350 instead (L<DBIx::QuickORM/"PUBLIC METHODS">).
351  
352 A read of a row that lacks a field the ORM's copy of that row holds replaces
353 the copy. Earlier row objects keep their fields, but are no longer canonical:
354  
355 my $first = $orm->find(users => $id); # every field, prefs included
356 my $second = $orm->handle('users')->fields(['name'])->where({id => $id})->only; # the same row, without prefs
357  
358 my $canon = $first->is_canon; # false: the second read replaced the ORM's copy
359  
360 # true: the write croaks, and $@ says the row data is no longer canonical
361 my $refused = !eval { $first->update({name => 'Alice S.'}); 1 };
362  
363 $first->refresh; # reads the row again, prefs included
364 $first->update({name => 'Alice S.'});
365  
366 With C<auto_omit>, C<omit>, or C<default_fields> this is common. A row
367 holding an omitted field, because a write read it back or the row read it,
368 stops being canonical when a default listing reads it again. Insert a row with
369 its JSON, list the table, then update that row, and the update croaks.
370 Refresh the row, write it with C<cas_update>, or give the listing a C<fields>
371 naming every field the row holds (C<fields> replaces the default fields).
372 Without omitted fields it takes two reads of one row with different
373 C<fields>. See L<DBIx::QuickORM::Manual::Caching/"FIELDS LEFT OUT OF A SELECT">. A row's
374 C<canon_status> says why it is not canonical, and with C<< debug => 1 >> which
375 call made it so (L<DBIx::QuickORM::Manual::Caching/"WHY A ROW IS NOT CANONICAL">).
376 What leaving fields out saves and costs:
377 L<DBIx::QuickORM::Manual::Optimizations/"LEAVING FIELDS OUT">.
378  
379 =head1 ASYNC, ASIDE, AND FORKED QUERIES
380  
381 my $later = $orm->handle('posts')->async->iter; # starts the query and returns at once
382  
383 do_something_else() until $later->ready;
384  
385 # waits for the rows when they are not there yet
386 my @fetched = $later->all;
387  
388 An async query runs on the ORM's connection: until its rows are collected,
389 anything else that sends SQL on that connection croaks. C<aside> and
390 C<forked> run elsewhere:
391  
392 my $aside = $orm->handle('users')->aside->iter; # on a second connection
393 my $forked = $orm->handle('users')->forked->iter; # in a child process
394 my @found = ($aside->all, $forked->all);
395  
396 A handle runs one background query, however many iterators read it.
397  
398 See L<DBIx::QuickORM::Manual::Background>, and
399 L<DBIx::QuickORM::Manual::Dialects> for the databases each one runs on.
400  
401 =head1 DEFINING THE ORM IN PACKAGES
402  
403 Larger applications can define the ORM, its table adjustments, and row classes
404 as packages. F<lib/My/ORM.pm>:
405  
406 package My::ORM;
407 use DBIx::QuickORM::DSL ':orm';
408  
409 orm {
410 tables 'My::Tables'; # the modules directly under My::Tables
411 };
412  
413 1;
414  
415 F<lib/My/Tables/Users.pm> adjusts C<users> and is its row class:
416  
417 package My::Tables::Users;
418 use DBIx::QuickORM::DSL qw/:table :row/;
419  
420 table {
421 name 'users';
422 omit qw/prefs/; # selected only when asked for
423 };
424  
425 row { parent };
426  
427 sub display_name { $_[0]->field('name') . ' <' . $_[0]->field('email') . '>' }
428  
429 1;
430  
431 Then:
432  
433 use My::ORM;
434  
435 my $app = My::ORM->new(
436 credentials => {
437 dsn => $dsn,
438 user => $user,
439 pass => $pass,
440 },
441 );
442  
443 my $label = $app->find(users => $id)->display_name; # a My::Tables::Users row
444  
445 Without the DSL, C<row_namespace> gives each table the row class named after
446 it, when that module exists: C<users> gets C<My::Rows::Users>.
447 C<row_class_name> picks other names.
448  
449 my $named = DBIx::QuickORM->new(
450 credentials => {
451 dsn => $dsn,
452 user => $user,
453 pass => $pass,
454 },
455 row_namespace => 'My::Rows',
456 );
457  
458 See L<DBIx::QuickORM::Manual::Classes> for the class-based ORM and
459 L<DBIx::QuickORM::Manual::RowClasses> for row classes.
460  
461 =head1 FORKING
462  
463 A forked child that uses the ORM gets its own connection. The parent's is
464 left alone.
465  
466 my $pid = fork // die "Could not fork: $!";
467 unless ($pid) {
468 my $count = $orm->handle('users')->count; # the ORM reconnects in the child by itself
469 exit($count ? 0 : 1);
470 }
471 waitpid($pid, 0);
472  
473 Rows the child inherited are not canonical there: refresh one before writing
474 it. See L<DBIx::QuickORM::Manual::Background/"FORKING YOUR OWN PROCESS">.
475  
476 =cut
477  
478 2 1;
479  
480 __END__
« blib/lib/DBIx/QuickORM/Manual/Optimizations.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/RowClasses.pm »