blib/lib/DBIx/QuickORM/Manual/DBIC.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/Classes.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Dialects.pm »
1 package DBIx::QuickORM::Manual::DBIC;
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::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>
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 For every query of a table, C<< row_classes => {posts => undef} >> when
474 constructing the ORM. For every table, C<< row_class => undef >>
475 (L<DBIx::QuickORM::Manual::RowClasses/HASHREFS>).
476  
477 =head1 RELATIONSHIPS
478  
479 DBIx::Class:
480  
481 my $author = $post->author; # belongs_to: a Result object
482 my @posts = $author->posts; # has_many: the rows in list context
483 my $rs = $author->posts; # a ResultSet in scalar context
484 my $busy = $author->search_related('posts', {views => {'>' => 5}})->count;
485 my $new = $author->create_related('posts', {title => 'New'});
486  
487 DBIx::QuickORM:
488  
489 # single: user_id reaches the users primary key
490 my $author = $post->follow_fk('users')->only;
491 my @posts = $author->follow_fk('posts')->all; # multi: any number of posts
492 my $h = $author->follow_fk('posts'); # a handle
493 my $busy = $h->and({views => {'>' => 5}})->count;
494 my $new = $author->insert_fk('posts', {title => 'New'}); # user_id is filled in
495  
496 C<insert_many_fk> inserts several, as C<insert_many> does:
497 C<< $author->insert_many_fk('posts', {title => 'A'}, {title => 'B'}) >>.
498  
499 The direction comes from the key. Narrow a C<follow_fk> handle with C<and>:
500 C<where> replaces the whole condition, the key's part included. When two keys
501 connect the same tables, C<link> picks one
502 (L<DBIx::QuickORM::Manual::ForeignKeys>).
503  
504 =head1 JOINS AND PREFETCH
505  
506 DBIx::Class:
507  
508 my @posts = $schema->resultset('Post')->search(
509 {'author.name' => 'Alice'},
510 {
511 prefetch => 'author',
512 order_by => 'me.id',
513 },
514 );
515 for my $post (@posts) {
516 my $title = $post->title;
517 my $author = $post->author->name; # prefetched: no second query
518 }
519  
520 DBIx::QuickORM:
521  
522 my @pairs = $orm->handle('posts')
523 ->join('users')
524 ->where({'users.name' => 'Alice'})
525 ->order_by('posts.id')
526 ->all;
527  
528 for my $pair (@pairs) {
529 my $title = $pair->row('posts')->field('title');
530 my $author = $pair->row('users')->field('name');
531 }
532  
533 Fields are C<table.field>. The base table goes by its own name, and there is
534 no C<me>. Results are flat: a user with two posts appears in two join rows,
535 both holding the same user row object. C<left_join> is the LEFT JOIN
536 (L<DBIx::QuickORM::Manual::Joins>).
537  
538 =head1 INFLATION
539  
540 DBIx::Class:
541  
542 __PACKAGE__->load_components('InflateColumn::DateTime');
543 __PACKAGE__->add_columns(created => {data_type => 'timestamp'});
544  
545 my $year = $alice->created->year;
546  
547 DBIx::QuickORM:
548  
549 my $year = $alice->field('created')->datetime_ref->year; # a lazy DateTime
550 my $theme = $alice->field('prefs')->{theme}; # JSON as Perl data
551 my $text = $alice->raw_field('created'); # as the database returned it
552  
553 my $plain = DBIx::QuickORM->new(
554 credentials => {
555 dsn => $dsn,
556 user => $user,
557 pass => $pass,
558 },
559 types => {users => {prefs => undef}}, # prefs stays text
560 );
561  
562 Types are chosen when the ORM is built, from each column's declared type.
563 C<types> adjusts them. L<DBIx::QuickORM::Manual::Types> is how to write one.
564  
565 =head1 TRANSACTIONS
566  
567 DBIx::Class:
568  
569 $schema->txn_do(sub {
570 $schema->resultset('User')->create({name => 'Dave'});
571 });
572  
573 my $guard = $schema->txn_scope_guard;
574 $schema->resultset('User')->create({name => 'Eve'});
575 $guard->commit; # rolled back if the guard goes out of scope first
576  
577 DBIx::QuickORM:
578  
579 $orm->txn(sub {
580 $orm->insert(users => {name => 'Dave'});
581 }); # commits on return. An exception rolls back and is rethrown
582  
583 my $txn = $orm->txn;
584 $orm->insert(users => {name => 'Eve'});
585 # or rollback. Unfinished when it goes out of scope: rolled back, with a warning
586 $txn->commit;
587  
588 A C<txn> inside another is always a savepoint (DBIx::Class makes one only
589 with C<< auto_savepoint => 1 >>). DuckDB has none and croaks. A root
590 transaction starts with an empty row cache: rows read before it are not
591 canonical inside it, so a write through one croaks until C<refresh>.
592 C<cas_update> writes one without a refresh
593 (L<DBIx::QuickORM::Manual::Transactions>).
594  
595 =head1 BULK WRITES
596  
597 DBIx::Class:
598  
599 $schema->resultset('User')->populate([{name => 'Fay'}, {name => 'Gus'}]);
600 my $changed = $schema->resultset('Post')->search({views => 0})->update({views => 1});
601 my $removed = $schema->resultset('Post')->search({views => {'<' => 0}})->delete;
602  
603 DBIx::QuickORM:
604  
605 $orm->insert_many(users => [{name => 'Fay'}, {name => 'Gus'}]); # void context: nothing read back
606 my $changed = $orm->handle('posts')->where({views => 0})->update({views => 1});
607 my $removed = $orm->handle('posts')->where({views => {'<' => 0}})->delete;
608  
609 Like C<populate>, C<insert_many> in void context only inserts. Otherwise it
610 returns an arrayref of the new rows, or with C<< count => 1 >> how many it
611 inserted (L<DBIx::QuickORM::Manual::BulkInsert>).
612  
613 Neither updates the row objects you hold. DBIx::Class's keep their old
614 values. DBIx::QuickORM's stop being canonical, so a write through one croaks
615 until C<refresh>.
616  
617 =head1 COUNTS AND AGGREGATES
618  
619 DBIx::Class:
620  
621 my $n = $schema->resultset('Post')->count;
622 my $top = $schema->resultset('Post')->get_column('views')->max;
623  
624 my @per_user = $schema->resultset('Post')->search(undef, {
625 select => [
626 'user_id',
627 {
628 count => '*',
629 -as => 'posts',
630 },
631 ],
632 as => ['user_id', 'posts'],
633 group_by => ['user_id'],
634 });
635 my $posts = $per_user[0]->get_column('posts');
636  
637 DBIx::QuickORM:
638  
639 use DBIx::QuickORM::Value qw/sql/;
640  
641 my $n = $orm->handle('posts')->count;
642 my $top = $orm->handle('posts')
643 ->fields({top => [max => 'views']})
644 ->only
645 ->field('top');
646  
647 my @per_user = $orm->handle('posts')
648 ->group_by('user_id')
649 ->fields({
650 user_id => 'user_id',
651 posts => [count => '*'],
652 views => sql('SUM(views)'), # any SQL
653 })
654 ->order_by('user_id')
655 ->all;
656  
657 my $posts = $per_user[0]->field('posts');
658  
659 A computed column is named once, in C<fields>. There is no separate C<as>
660 (L<DBIx::QuickORM::Manual::Aggregates>).
661  
662 =head1 ONE COPY PER ROW
663  
664 DBIx::Class:
665  
666 my $first = $schema->resultset('User')->find($id);
667 my $second = $schema->resultset('User')->find($id); # a second, independent object
668  
669 $first->update({name => 'Ann'});
670 my $old = $second->name; # still the name $second read
671 $second->update({email => 'b@example.com'}); # writes only email: both changes survive
672 $second->discard_changes; # now Ann
673  
674 DBIx::QuickORM:
675  
676 my $first = $orm->find(users => $id);
677  
678 # a second object over the same canonical copy of the data
679 my $second = $orm->find(users => $id);
680  
681 $first->update({name => 'Ann'});
682  
683 # still the name $second read
684 my $old = $second->field('name');
685  
686 # false: $first's write superseded the data $second holds
687 my $current = $second->is_canon;
688  
689 # croaks: $second is not canonical
690 my $ok = eval { $second->update({email => 'b@example.com'}); 1 };
691  
692 # Ann, and canonical again
693 $second->refresh;
694 $second->update({email => 'b@example.com'});
695  
696 DBIx::Class has no identity map (one object per row): each C<find> is a new
697 object, and each object writes the columns it changed, so both updates
698 survive. DBIx::QuickORM keeps one canonical copy of the data and refuses a
699 write through an object it has superseded. C<cas_update> writes such a row
700 safely by comparing with the database (L<DBIx::QuickORM::Manual::Caching>).
701  
702 =head1 ROW METHODS
703  
704 DBIx::Class:
705  
706 package My::Schema::Result::User;
707 # the Result class from above
708  
709 sub display_name {
710 my $self = shift;
711 return $self->name . ' <' . $self->email . '>';
712 }
713  
714 DBIx::QuickORM:
715  
716 package My::User;
717 use parent 'DBIx::QuickORM::Row';
718  
719 sub display_name {
720 my $self = shift;
721 return $self->field('name') . ' <' . $self->field('email') . '>';
722 }
723  
724 package main;
725  
726 my $orm = DBIx::QuickORM->new(
727 credentials => {
728 dsn => $dsn,
729 user => $user,
730 pass => $pass,
731 },
732 row_classes => {users => 'My::User'},
733 );
734  
735 my $label = $orm->find(users => $id)->display_name;
736  
737 C<row_classes> names a class per table, C<row_class> one for every table
738 (L<DBIx::QuickORM::Manual::RowClasses>).
739  
740 To skip listing them, name the classes after the tables, as
741 C<load_namespaces> does: C<users> gets C<My::Rows::Users>, when that module
742 exists.
743  
744 my $named = DBIx::QuickORM->new(
745 credentials => {
746 dsn => $dsn,
747 user => $user,
748 pass => $pass,
749 },
750 row_namespace => 'My::Rows',
751 );
752  
753 Or define the ORM as a package (L<DBIx::QuickORM::DSL>), with table
754 adjustments too. C<tables> names a namespace, and every module
755 under it is loaded. F<lib/My/ORM.pm>:
756  
757 package My::ORM;
758 use DBIx::QuickORM::DSL ':orm';
759  
760 orm { tables 'My::Tables' };
761  
762 1;
763  
764 Each module's C<table> block names its table, and its C<row> block makes the
765 module that table's row class. F<lib/My/Tables/Users.pm>:
766  
767 package My::Tables::Users;
768 use DBIx::QuickORM::DSL qw/:table :row/;
769  
770 table { name 'users' };
771 row { parent };
772  
773 sub display_name {
774 my $self = shift;
775 return $self->field('name') . ' <' . $self->field('email') . '>';
776 }
777  
778 1;
779  
780 C<< My::ORM->new >> takes the connection arguments, and its C<users> rows
781 are C<My::Tables::Users> objects (L<DBIx::QuickORM::Manual::Classes>).
782  
783 =head1 DEPLOYING
784  
785 DBIx::Class:
786  
787 $schema->deploy; # CREATE TABLE from the Result classes
788  
789 DBIx::QuickORM:
790  
791 $dbh->do($_) for @create_statements; # your own SQL, or your migration tool
792 my $orm = DBIx::QuickORM->new(dbh => $dbh); # scans what is there
793  
794 Nothing in Perl describes the tables, so there is nothing to deploy from.
795  
796 =head1 WHAT YOU WRITE YOURSELF
797  
798 C<create> with related rows: insert the row, then its related rows with
799 C<insert_many_fk>, in a transaction (L<DBIx::QuickORM::Manual::Transactions>).
800  
801 my $zed = $orm->txn(sub {
802 my $zed = $orm->insert(users => {name => 'Zed'});
803 $zed->insert_many_fk('posts', {title => 'One'}, {title => 'Two'});
804 return $zed;
805 });
806  
807 Cascading deletes: DBIx::QuickORM does not cascade. Let the database do it:
808 declare the foreign key with C<ON DELETE CASCADE> in the schema
809 (C<< user_id INTEGER REFERENCES users (id) ON DELETE CASCADE >>).
810  
811 Or delete the children first, in a transaction:
812  
813 $orm->txn(sub {
814 $zed->refresh; # read before the transaction, so not canonical in it
815 $zed->follow_fk('posts')->delete;
816 $zed->delete;
817 });
818  
819 Without either, deleting a referenced row croaks with the database's foreign
820 key error. DBIx::Class's C<has_many> cascade deletes the related rows after
821 the parent, so it only helps without a foreign key constraint.
822  
823 Also without an equivalent: C<many_to_many> (join through the link table),
824 C<update_or_create>, components, and C<resultset_attributes>.
825 For the SQL as it runs, L<DBI>'s C<DBI_TRACE> stands in for C<DBIC_TRACE>.
826  
827 =cut
828  
829 2 1;
830  
831 __END__
« blib/lib/DBIx/QuickORM/Manual/Classes.pm ↑ Summary blib/lib/DBIx/QuickORM/Manual/Dialects.pm »