blib/lib/DBIx/QuickORM/Manual/DBIC.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::DBIC;
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::DBIC - Coming from DBIx::Class: the concepts mapped, and the same tasks side by side.
14  
15 =head1 DESCRIPTION
16  
17 A mapping of DBIx::Class concepts to equivalent DBIx::QuickORM ones, then
18 each common task written both ways.
19  
20 The DBIx::QuickORM examples use C<$orm>, an ORM connected to the database
21 under L</SCHEMA>. The DBIx::Class examples use C<$schema>, a C<My::Schema>
22 over its C<users> and C<posts> tables, with the Result classes
23 L</DEFINING THE SCHEMA> shows.
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 And a log whose C<user_id> has no foreign key constraint:
48  
49 CREATE TABLE audit_log (
50 id SERIAL PRIMARY KEY,
51 user_id INTEGER,
52 action TEXT NOT NULL
53 );
54  
55 =head1 CONCEPT MAP
56  
57 =over 4
58  
59 =item Schema: the ORM object
60  
61 C<< My::Schema->connect(...) >> becomes C<< DBIx::QuickORM->new(...) >>
62 (L<DBIx::QuickORM>). It holds the connection and the schema, which it reads
63 from the database. See L</CONNECTING>.
64  
65 =item Result class, ResultSource: a scanned table
66  
67 Tables, columns, primary keys, and foreign keys come from the database. A
68 table needs a class only to adjust what the scan found or to add row methods
69 (L<DBIx::QuickORM::DSL>, L<DBIx::QuickORM::Manual::Classes>). See
70 L</DEFINING THE SCHEMA>.
71  
72 =item ResultSet: Handle
73  
74 L<DBIx::QuickORM::Handle>: a query that runs when asked. Every modifier
75 returns a new handle, and the one it was called on never changes. It has
76 C<next> and C<reset>, and C<iter> returns an L<DBIx::QuickORM::Iterator> with
77 its own position. See L</QUERIES>.
78  
79 =item Result object: Row
80  
81 L<DBIx::QuickORM::Row>. Fields are read with C<field>. There are no setters and no dirty state:
82 C<update> writes at once. See L</CREATE, READ, UPDATE, DELETE>.
83  
84 =item belongs_to, has_many: foreign keys, followed with C<follow_fk>
85  
86 Relationships are not declared. The database's foreign keys are scanned.
87 C<< $row->follow_fk($table) >> is a handle on the linked rows. For a key the
88 database does not declare, C<via> names the fields on one call and C<fks>
89 declares the key for all (L<DBIx::QuickORM::Manual::ForeignKeys>).
90 See L</RELATIONSHIPS> and L</DEFINING THE SCHEMA>.
91  
92 =item create_related: C<insert_fk> and C<insert_many_fk>
93  
94 C<< $row->insert_fk($table, \%fields) >> inserts a row that points at this
95 one, filling in its foreign key fields. See L</RELATIONSHIPS>.
96  
97 =item join, prefetch: C<join> and C<left_join>
98  
99 Each result is a flat join row (L<DBIx::QuickORM::JoinRow>) holding one row
100 object per table. Nothing is collapsed into nested structures
101 (L<DBIx::QuickORM::Manual::Joins>). See L</JOINS AND PREFETCH>.
102  
103 =item InflateColumn: types
104  
105 Chosen from each column's declared type. JSON, UUID, date, and timestamp
106 columns inflate without being declared (C<TIME> does not). A type is a class
107 that consumes L<DBIx::QuickORM::Role::Type> (L<DBIx::QuickORM::Manual::Types>).
108 See L</INFLATION>.
109  
110 =item txn_do, txn_scope_guard: C<txn>
111  
112 C<txn> with a block, or C<txn> returning an object
113 (L<DBIx::QuickORM::Txn>) to C<commit> or C<rollback>. A nested C<txn> is always a savepoint
114 (L<DBIx::QuickORM::Manual::Transactions>). See L</TRANSACTIONS>.
115  
116 =item deploy: nothing
117  
118 The database is the only schema. Create tables with your own SQL or
119 migration tool. See L</DEPLOYING>.
120  
121 =item Independent result objects: one canonical copy per row
122  
123 DBIx::Class gives each query a fresh object for the same row, and each
124 writes the columns it changed. DBIx::QuickORM keeps one canonical copy of each
125 row's data and rejects a write through a row object whose data it has
126 superseded (L<DBIx::QuickORM::Manual::Caching>). See L</ONE COPY PER ROW>.
127  
128 =item get_column, select and as, group_by: C<count> and computed columns
129  
130 C<< $rs->get_column >> for an aggregate is a computed column in C<fields>,
131 read from an L<DBIx::QuickORM::AggregateRow>
132 (L<DBIx::QuickORM::Manual::Aggregates>). C<< $row->get_column >> is
133 C<raw_field>. See L</COUNTS AND AGGREGATES>.
134  
135 =item C<\'NOW()'>, C<\['? + 1', 2]>: C<sql>
136  
137 Literal SQL is C<sql(...)> from L<DBIx::QuickORM::Value>
138 (L<DBIx::QuickORM::Manual::Values>). See L</LITERAL SQL>.
139  
140 =item new_result, insert, in_storage: C<vivify>, C<insert>, C<is_in_db>
141  
142 See L</CREATE, READ, UPDATE, DELETE>.
143  
144 =item find_or_create: C<find_or_insert>
145  
146 See L</CREATE, READ, UPDATE, DELETE>.
147  
148 =item HashRefInflator: C<data_only> (or C<bare>)
149  
150 L<DBIx::QuickORM::Manual::RowClasses/HASHREFS>. See L</PLAIN HASHREFS>.
151  
152 =item populate: C<insert_many>
153  
154 L<DBIx::QuickORM::Manual::BulkInsert>. See L</BULK WRITES>.
155  
156 =item discard_changes: C<refresh>
157  
158 See L</CREATE, READ, UPDATE, DELETE>.
159  
160 =back
161  
162 =head1 DEFINING THE SCHEMA
163  
164 DBIx::Class, in three files (C<load_namespaces> finds Result classes on
165 disk, but packages in one file register nothing).
166 F<lib/My/Schema/Result/User.pm>:
167  
168 =for highlighter language=perl
169  
170 package My::Schema::Result::User;
171 use base 'DBIx::Class::Core';
172  
173 __PACKAGE__->load_components('InflateColumn::DateTime');
174 __PACKAGE__->table('users');
175 __PACKAGE__->add_columns(
176 id => {
177 data_type => 'integer',
178 is_auto_increment => 1,
179 },
180 name => {data_type => 'text'},
181 email => {
182 data_type => 'text',
183 is_nullable => 1,
184 },
185 prefs => {
186 data_type => 'json',
187 is_nullable => 1,
188 },
189 referred_by => {
190 data_type => 'integer',
191 is_nullable => 1,
192 },
193 # read back after create, like the key
194 created => {
195 data_type => 'timestamp',
196 retrieve_on_insert => 1,
197 },
198 );
199 __PACKAGE__->set_primary_key('id');
200 __PACKAGE__->has_many(posts => 'My::Schema::Result::Post', 'user_id');
201  
202 1;
203  
204 F<lib/My/Schema/Result/Post.pm>:
205  
206 package My::Schema::Result::Post;
207 use base 'DBIx::Class::Core';
208  
209 __PACKAGE__->table('posts');
210 __PACKAGE__->add_columns(
211 id => {
212 data_type => 'integer',
213 is_auto_increment => 1,
214 },
215 user_id => {data_type => 'integer'},
216 title => {data_type => 'text'},
217 views => {
218 data_type => 'integer',
219 default_value => 0,
220 },
221 );
222 __PACKAGE__->set_primary_key('id');
223 __PACKAGE__->belongs_to(author => 'My::Schema::Result::User', 'user_id');
224  
225 1;
226  
227 F<lib/My/Schema.pm>:
228  
229 package My::Schema;
230 use base 'DBIx::Class::Schema';
231  
232 __PACKAGE__->load_namespaces;
233  
234 1;
235  
236 DBIx::QuickORM:
237  
238 my $orm = DBIx::QuickORM->new(credentials => {
239 dsn => $dsn,
240 user => $user,
241 pass => $pass,
242 }); # scans the tables, columns, keys, and types
243  
244 my $alice = $orm->insert(users => {
245 name => 'Alice',
246 email => 'alice@example.com',
247 prefs => {theme => 'dark'},
248 });
249  
250 my $post = $orm->insert(posts => {
251 user_id => $alice->field('id'),
252 title => 'Hello',
253 });
254  
255 my $author = $post->follow_fk('users')->only; # the foreign key was scanned, not declared
256 my $year = $alice->field('created')->datetime_ref->year; # a lazy DateTime, from the column's type
257  
258 Nothing is declared in Perl. To adjust a table or give its rows methods, see
259 L</ROW METHODS> and L<DBIx::QuickORM::Manual::Classes>.
260  
261 A foreign key the database does not declare, such as C<audit_log.user_id>,
262 is followed by naming its fields with C<via>. DBIx::Class declares it as it
263 declares every relationship, with C<belongs_to> and C<has_many>.
264  
265 my $entry = $orm->insert(audit_log => {
266 user_id => $alice->field('id'),
267 action => 'login',
268 });
269  
270 my $by = $entry->follow_fk('users', via => {user_id => 'id'})->only;
271  
272 To declare it once for every call, give it to C<new> with C<fks>. Then it is
273 followed like a scanned one.
274  
275 my $logged = DBIx::QuickORM->new(
276 credentials => {
277 dsn => $dsn,
278 user => $user,
279 pass => $pass,
280 },
281 fks => {audit_log => {users => [{user_id => 'id'}]}}, # audit_log.user_id points at users.id
282 );
283  
284 my $entry = $logged->insert(audit_log => {
285 user_id => $alice->field('id'),
286 action => 'login',
287 });
288  
289 my $who = $entry->follow_fk('users')->only;
290 my @log = $logged->find(users => $alice->field('id'))->follow_fk('audit_log')->all;
291  
292 =head1 CONNECTING
293  
294 DBIx::Class:
295  
296 my $schema = My::Schema->connect($dsn, $user, $pass, {AutoCommit => 1});
297 $schema = My::Schema->connect(sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) });
298  
299 DBIx::QuickORM:
300  
301 my $orm = DBIx::QuickORM->new(credentials => {
302 dsn => $dsn,
303 user => $user,
304 pass => $pass,
305 });
306  
307 # a new handle each call
308 $orm = DBIx::QuickORM->new(
309 connect => sub { DBI->connect($dsn, $user, $pass, {RaiseError => 1}) },
310 );
311 $orm = DBIx::QuickORM->new(dbh => $dbh); # a handle you already have
312  
313 Every form needs C<RaiseError> and C<AutoCommit> on, and C<credentials>
314 turns both on itself. With C<dbh> the ORM cannot open a second connection, so
315 a forked child, C<aside>, and C<forked> croak
316 (L<DBIx::QuickORM::Manual::Background>).
317  
318 =head1 CREATE, READ, UPDATE, DELETE
319  
320 DBIx::Class:
321  
322 my $alice = $schema->resultset('User')->create({name => 'Alice'});
323 my $found = $schema->resultset('User')->find($alice->id);
324 my $bob = $schema->resultset('User')->search({email => 'bob@example.com'})->single;
325  
326 my $name = $alice->name;
327 $alice->name('Alice Smith');
328 $alice->update; # or $alice->update({name => 'Alice Smith'})
329 $alice->discard_changes;
330 $alice->delete;
331  
332 DBIx::QuickORM:
333  
334 my $alice = $orm->insert(users => {name => 'Alice'});
335 my $found = $orm->find(users => $alice->field('id'));
336  
337 # undef when there is none, and croaks on more than one
338 my $bob = $orm->handle('users')->where({email => 'bob@example.com'})->only;
339  
340 my $name = $alice->field('name');
341 $alice->update({name => 'Alice Smith'}); # written now
342 $alice->refresh;
343 $alice->delete;
344  
345 C<single> warns and returns the first row when more than one matches, but
346 C<only> croaks. C<find> takes the primary key only
347 (L<DBIx::QuickORM::Manual::Keys>): there is no lookup by another unique
348 constraint.
349  
350 C<find_or_create> is C<find_or_insert>, finding by the C<by> fields (the
351 primary key by default):
352  
353 my $carol = $orm->find_or_insert(
354 users => {
355 name => 'Carol',
356 email => 'carol@example.com',
357 },
358 by => ['email'],
359 );
360  
361 C<new_result>, C<insert>, and C<in_storage> are C<vivify>, C<insert>, and
362 C<is_in_db>. A row not yet inserted changes with C<modify>:
363  
364 my $draft = $orm->vivify(users => {name => 'Draft'}); # not in the database yet
365 $draft->modify({email => 'draft@example.com'});
366 $draft->insert;
367 my $stored = $draft->is_in_db; # true
368  
369 =head1 QUERIES
370  
371 DBIx::Class:
372  
373 my $rs = $schema->resultset('Post')->search(
374 {views => {'>' => 5}},
375 {
376 order_by => {-desc => 'views'},
377 rows => 10,
378 offset => 20,
379 },
380 );
381 my $hellos = $rs->search({title => {-like => 'Hello%'}}); # ANDed onto the condition
382  
383 my $count = $rs->count; # applies rows and offset: at most 10
384 my @all = $rs->all;
385 while (my $post = $rs->next) {
386 my $title = $post->title;
387 }
388 my $first = $rs->first;
389  
390 DBIx::QuickORM:
391  
392 my $h = $orm->handle('posts')
393 ->where({views => {'>' => 5}})
394 ->order_by({-desc => 'views'})
395 ->limit(10)
396 ->offset(20);
397  
398 # and() adds to the condition, but where() replaces it
399 my $hellos = $h->and({title => {-like => 'Hello%'}});
400  
401 my $count = $h->count; # ignores limit and offset: every matching row
402 my @all = $h->all; # runs the query and fetches every row
403 while (my $post = $h->next) {
404 my $title = $post->field('title');
405 }
406 my $first = $h->first;
407 my $it = $h->iter; # an independent cursor over the same rows
408  
409 C<count> ignores C<limit> and C<offset>, so it gives the total DBIx::Class's
410 C<pager> would. DBIx::Class's C<count> applies C<rows> and C<offset>.
411  
412 C<< $rs->next >> and C<< $rs->reset >> are C<< $h->next >> and
413 C<< $h->reset >>. A handle runs its query once, on the first read, and keeps
414 the rows until C<< $h->clear >>. Every read shares them. For independent
415 cursors over the same rows, take iterators with C<iter>.
416  
417 Conditions take L<SQL::Abstract> syntax in both: DBIx::Class through
418 L<SQL::Abstract::Classic> and its extensions, DBIx::QuickORM through
419 L<SQL::Abstract> 2.x. The conditions shown work in both.
420  
421 A C<where> may also be SQL you write: a plain string is used as written, and
422 C<sql()> adds binds (L<DBIx::QuickORM::Manual::Values/SQL>). C<and> and C<or>
423 put either in parentheses. Never
424 interpolate untrusted input into the string.
425  
426 use DBIx::QuickORM::Value qw/sql/;
427  
428 my $titled = $h->and("title <> ''");
429 my $short = $h->and(sql('length(title) < ?', 8));
430  
431 A custom ResultSet class becomes a sub that takes a handle and returns a
432 narrower one. Unlike C<search>, C<and> and C<or> croak on a handle with no
433 C<where>. Start a condition with C<where>.
434  
435 sub popular {
436 my ($posts) = @_;
437 return $posts->and({views => {'>' => 5}});
438 }
439  
440 my $n = popular($hellos)->count;
441  
442 =head1 LITERAL SQL
443  
444 DBIx::Class:
445  
446 my $ida = $schema->resultset('User')->create({name => 'Ida', created => \'NOW()'});
447 $schema->resultset('Post')->search({id => $post_id})->update({views => \['views + ?', 2]});
448  
449 DBIx::QuickORM:
450  
451 use DBIx::QuickORM::Value qw/sql/;
452  
453 my $ida = $orm->insert(users => {name => 'Ida', created => sql('now()')});
454 $orm->handle('posts')->where({id => $post_id})->update({views => sql('views + ?', 2)});
455  
456 C<sql()> takes the SQL and its binds, as a value or in a C<where>
457 (L<DBIx::QuickORM::Manual::Values/SQL>).
458  
459 =head1 PLAIN HASHREFS
460  
461 DBIx::Class:
462  
463 my @data = $schema->resultset('Post')->search(
464 undef,
465 {result_class => 'DBIx::Class::ResultClass::HashRefInflator'},
466 )->all;
467  
468 DBIx::QuickORM:
469  
470 my @data = $orm->handle('posts')->data_only->all; # row_class(undef)
471 my $title = $data[0]->{title};
472  
473 These hashrefs are the row cache's own copies. C<bare> gives hashrefs the
474 cache never sees, like HashRefInflator's.
475  
476 For every query of a table, C<< row_classes => {posts => undef} >> when
477 constructing the ORM. For every table, C<< row_class => undef >>
478 (L<DBIx::QuickORM::Manual::RowClasses/HASHREFS>).
479  
480 L<DBIx::QuickORM::Manual::Optimizations> times both ORMs at these tasks.
481  
482 =head1 RELATIONSHIPS
483  
484 DBIx::Class:
485  
486 my $author = $post->author; # belongs_to: a Result object
487 my @posts = $author->posts; # has_many: the rows in list context
488 my $rs = $author->posts; # a ResultSet in scalar context
489 my $busy = $author->search_related('posts', {views => {'>' => 5}})->count;
490 my $new = $author->create_related('posts', {title => 'New'});
491  
492 DBIx::QuickORM:
493  
494 # single: user_id reaches the users primary key
495 my $author = $post->follow_fk('users')->only;
496 my @posts = $author->follow_fk('posts')->all; # multi: any number of posts
497 my $h = $author->follow_fk('posts'); # a handle
498 my $busy = $h->and({views => {'>' => 5}})->count;
499 my $new = $author->insert_fk('posts', {title => 'New'}); # user_id is filled in
500  
501 C<insert_many_fk> inserts several, as C<insert_many> does:
502 C<< $author->insert_many_fk('posts', {title => 'A'}, {title => 'B'}) >>.
503  
504 The direction comes from the key. Narrow a C<follow_fk> handle with C<and>:
505 C<where> replaces the whole condition, the key's part included. When two keys
506 connect the same tables, C<link> picks one
507 (L<DBIx::QuickORM::Manual::ForeignKeys>).
508  
509 =head1 JOINS AND PREFETCH
510  
511 DBIx::Class:
512  
513 my @posts = $schema->resultset('Post')->search(
514 {'author.name' => 'Alice'},
515 {
516 prefetch => 'author',
517 order_by => 'me.id',
518 },
519 );
520 for my $post (@posts) {
521 my $title = $post->title;
522 my $author = $post->author->name; # prefetched: no second query
523 }
524  
525 DBIx::QuickORM:
526  
527 my @pairs = $orm->handle('posts')
528 ->join('users')
529 ->where({'users.name' => 'Alice'})
530 ->order_by('posts.id')
531 ->all;
532  
533 for my $pair (@pairs) {
534 my $title = $pair->row('posts')->field('title');
535 my $author = $pair->row('users')->field('name');
536 }
537  
538 Fields are C<table.field>. The base table goes by its own name, and there is
539 no C<me>. Results are flat: a user with two posts appears in two join rows,
540 both holding the same user row object. C<left_join> is the LEFT JOIN
541 (L<DBIx::QuickORM::Manual::Joins>).
542  
543 =head1 INFLATION
544  
545 DBIx::Class:
546  
547 __PACKAGE__->load_components('InflateColumn::DateTime');
548 __PACKAGE__->add_columns(created => {data_type => 'timestamp'});
549  
550 my $year = $alice->created->year;
551  
552 DBIx::QuickORM:
553  
554 my $year = $alice->field('created')->datetime_ref->year; # a lazy DateTime
555 my $theme = $alice->field('prefs')->{theme}; # JSON as Perl data
556 my $text = $alice->raw_field('created'); # as the database returned it
557  
558 my $plain = DBIx::QuickORM->new(
559 credentials => {
560 dsn => $dsn,
561 user => $user,
562 pass => $pass,
563 },
564 types => {users => {prefs => undef}}, # prefs stays text
565 );
566  
567 Types are chosen when the ORM is built, from each column's declared type.
568 C<types> adjusts them. L<DBIx::QuickORM::Manual::Types> is how to write one.
569  
570 =head1 TRANSACTIONS
571  
572 DBIx::Class:
573  
574 $schema->txn_do(sub {
575 $schema->resultset('User')->create({name => 'Dave'});
576 });
577  
578 my $guard = $schema->txn_scope_guard;
579 $schema->resultset('User')->create({name => 'Eve'});
580 $guard->commit; # rolled back if the guard goes out of scope first
581  
582 DBIx::QuickORM:
583  
584 $orm->txn(sub {
585 $orm->insert(users => {name => 'Dave'});
586 }); # commits on return. An exception rolls back and is rethrown
587  
588 my $txn = $orm->txn;
589 $orm->insert(users => {name => 'Eve'});
590 # or rollback. Unfinished when it goes out of scope: rolled back, with a warning
591 $txn->commit;
592  
593 A C<txn> inside another is always a savepoint (DBIx::Class makes one only
594 with C<< auto_savepoint => 1 >>). DuckDB has none and croaks. A root
595 transaction starts with an empty row cache: rows read before it are not
596 canonical inside it, so a write through one croaks until C<refresh>.
597 C<cas_update> writes one without a refresh
598 (L<DBIx::QuickORM::Manual::Transactions>).
599  
600 =head1 BULK WRITES
601  
602 DBIx::Class:
603  
604 $schema->resultset('User')->populate([{name => 'Fay'}, {name => 'Gus'}]);
605 my $changed = $schema->resultset('Post')->search({views => 0})->update({views => 1});
606 my $removed = $schema->resultset('Post')->search({views => {'<' => 0}})->delete;
607  
608 DBIx::QuickORM:
609  
610 $orm->insert_many(users => [{name => 'Fay'}, {name => 'Gus'}]); # void context: nothing read back
611 my $changed = $orm->handle('posts')->where({views => 0})->update({views => 1});
612 my $removed = $orm->handle('posts')->where({views => {'<' => 0}})->delete;
613  
614 Like C<populate>, C<insert_many> in void context only inserts. Otherwise it
615 returns an arrayref of the new rows, or with C<< count => 1 >> how many it
616 inserted (L<DBIx::QuickORM::Manual::BulkInsert>).
617  
618 Neither updates the row objects you hold. DBIx::Class's keep their old
619 values. DBIx::QuickORM's stop being canonical, so a write through one croaks
620 until C<refresh>.
621  
622 =head1 COUNTS AND AGGREGATES
623  
624 DBIx::Class:
625  
626 my $n = $schema->resultset('Post')->count;
627 my $top = $schema->resultset('Post')->get_column('views')->max;
628  
629 my @per_user = $schema->resultset('Post')->search(undef, {
630 select => [
631 'user_id',
632 {
633 count => '*',
634 -as => 'posts',
635 },
636 ],
637 as => ['user_id', 'posts'],
638 group_by => ['user_id'],
639 });
640 my $posts = $per_user[0]->get_column('posts');
641  
642 DBIx::QuickORM:
643  
644 use DBIx::QuickORM::Value qw/sql/;
645  
646 my $n = $orm->handle('posts')->count;
647 my $top = $orm->handle('posts')
648 ->fields({top => [max => 'views']})
649 ->only
650 ->field('top');
651  
652 my @per_user = $orm->handle('posts')
653 ->group_by('user_id')
654 ->fields({
655 user_id => 'user_id',
656 posts => [count => '*'],
657 views => sql('SUM(views)'), # any SQL
658 })
659 ->order_by('user_id')
660 ->all;
661  
662 my $posts = $per_user[0]->field('posts');
663  
664 A computed column is named once, in C<fields>. There is no separate C<as>
665 (L<DBIx::QuickORM::Manual::Aggregates>).
666  
667 =head1 ONE COPY PER ROW
668  
669 DBIx::Class:
670  
671 my $first = $schema->resultset('User')->find($id);
672 my $second = $schema->resultset('User')->find($id); # a second, independent object
673  
674 $first->update({name => 'Ann'});
675 my $old = $second->name; # still the name $second read
676 $second->update({email => 'b@example.com'}); # writes only email: both changes survive
677 $second->discard_changes; # now Ann
678  
679 DBIx::QuickORM:
680  
681 my $first = $orm->find(users => $id);
682  
683 # a second object over the same canonical copy of the data
684 my $second = $orm->find(users => $id);
685  
686 $first->update({name => 'Ann'});
687  
688 # still the name $second read
689 my $old = $second->field('name');
690  
691 # false: $first's write superseded the data $second holds
692 my $current = $second->is_canon;
693  
694 # croaks: $second is not canonical
695 my $ok = eval { $second->update({email => 'b@example.com'}); 1 };
696  
697 # Ann, and canonical again
698 $second->refresh;
699 $second->update({email => 'b@example.com'});
700  
701 DBIx::Class has no identity map (one object per row): each C<find> is a new
702 object, and each object writes the columns it changed, so both updates
703 survive. DBIx::QuickORM keeps one canonical copy of the data and refuses a
704 write through an object it has superseded. C<cas_update> writes such a row
705 safely by comparing with the database (L<DBIx::QuickORM::Manual::Caching>).
706  
707 =head1 ROW METHODS
708  
709 DBIx::Class:
710  
711 package My::Schema::Result::User;
712 # the Result class from above
713  
714 sub display_name {
715 my $self = shift;
716 return $self->name . ' <' . $self->email . '>';
717 }
718  
719 DBIx::QuickORM:
720  
721 package My::User;
722 use parent 'DBIx::QuickORM::Row';
723  
724 sub display_name {
725 my $self = shift;
726 return $self->field('name') . ' <' . $self->field('email') . '>';
727 }
728  
729 package main;
730  
731 my $orm = DBIx::QuickORM->new(
732 credentials => {
733 dsn => $dsn,
734 user => $user,
735 pass => $pass,
736 },
737 row_classes => {users => 'My::User'},
738 );
739  
740 my $label = $orm->find(users => $id)->display_name;
741  
742 C<row_classes> names a class per table, C<row_class> one for every table
743 (L<DBIx::QuickORM::Manual::RowClasses>).
744  
745 To skip listing them, name the classes after the tables, as
746 C<load_namespaces> does: C<users> gets C<My::Rows::Users>, when that module
747 exists.
748  
749 my $named = DBIx::QuickORM->new(
750 credentials => {
751 dsn => $dsn,
752 user => $user,
753 pass => $pass,
754 },
755 row_namespace => 'My::Rows',
756 );
757  
758 Or define the ORM as a package (L<DBIx::QuickORM::DSL>), with table
759 adjustments too. C<tables> names a namespace, and every module
760 under it is loaded. F<lib/My/ORM.pm>:
761  
762 package My::ORM;
763 use DBIx::QuickORM::DSL ':orm';
764  
765 orm { tables 'My::Tables' };
766  
767 1;
768  
769 Each module's C<table> block names its table, and its C<row> block makes the
770 module that table's row class. F<lib/My/Tables/Users.pm>:
771  
772 package My::Tables::Users;
773 use DBIx::QuickORM::DSL qw/:table :row/;
774  
775 table { name 'users' };
776 row { parent };
777  
778 sub display_name {
779 my $self = shift;
780 return $self->field('name') . ' <' . $self->field('email') . '>';
781 }
782  
783 1;
784  
785 C<< My::ORM->new >> takes the connection arguments, and its C<users> rows
786 are C<My::Tables::Users> objects (L<DBIx::QuickORM::Manual::Classes>).
787  
788 =head1 DEPLOYING
789  
790 DBIx::Class:
791  
792 $schema->deploy; # CREATE TABLE from the Result classes
793  
794 DBIx::QuickORM:
795  
796 $dbh->do($_) for @create_statements; # your own SQL, or your migration tool
797 my $orm = DBIx::QuickORM->new(dbh => $dbh, rescan => 1); # scans what is there now
798  
799 Nothing in Perl describes the tables, so there is nothing to deploy from.
800  
801 =head1 WHAT YOU WRITE YOURSELF
802  
803 C<create> with related rows: insert the row, then its related rows with
804 C<insert_many_fk>, in a transaction (L<DBIx::QuickORM::Manual::Transactions>).
805  
806 my $zed = $orm->txn(sub {
807 my $zed = $orm->insert(users => {name => 'Zed'});
808 $zed->insert_many_fk('posts', {title => 'One'}, {title => 'Two'});
809 return $zed;
810 });
811  
812 Cascading deletes: DBIx::QuickORM does not cascade. Let the database do it:
813 declare the foreign key with C<ON DELETE CASCADE> in the schema
814 (C<< user_id INTEGER REFERENCES users (id) ON DELETE CASCADE >>).
815  
816 Or delete the children first, in a transaction:
817  
818 $orm->txn(sub {
819 $zed->refresh; # read before the transaction, so not canonical in it
820 $zed->follow_fk('posts')->delete;
821 $zed->delete;
822 });
823  
824 Without either, deleting a referenced row croaks with the database's foreign
825 key error. DBIx::Class's C<has_many> cascade deletes the related rows after
826 the parent, so it only helps without a foreign key constraint.
827  
828 Also without an equivalent: C<many_to_many> (join through the link table),
829 C<update_or_create>, components, and C<resultset_attributes>.
830 For the SQL as it runs, L<DBI>'s C<DBI_TRACE> stands in for C<DBIC_TRACE>.
831  
832 =cut
833  
834 1;
835  
836 __END__