Add extra doc line expanding on the role of the prefetch attribute
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class.pm
1 package DBIx::Class;
2
3 use strict;
4 use warnings;
5
6 our $VERSION;
7 # Always remember to do all digits for the version even if they're 0
8 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
9 # brain damage and presumably various other packaging systems too
10
11 # $VERSION declaration must stay up here, ahead of any other package
12 # declarations, as to not confuse various modules attempting to determine
13 # this ones version, whether that be s.c.o. or Module::Metadata, etc
14 $VERSION = '0.082700_01';
15
16 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
17
18 use DBIx::Class::_Util;
19 use mro 'c3';
20
21 use DBIx::Class::Optional::Dependencies;
22
23 use base qw/DBIx::Class::Componentised DBIx::Class::AccessorGroup/;
24 use DBIx::Class::StartupCheck;
25 use DBIx::Class::Exception;
26
27 __PACKAGE__->mk_group_accessors(inherited => '_skip_namespace_frames');
28 __PACKAGE__->_skip_namespace_frames('^DBIx::Class|^SQL::Abstract|^Try::Tiny|^Class::Accessor::Grouped|^Context::Preserve');
29
30 sub mk_classdata {
31   shift->mk_classaccessor(@_);
32 }
33
34 sub mk_classaccessor {
35   my $self = shift;
36   $self->mk_group_accessors('inherited', $_[0]);
37   $self->set_inherited(@_) if @_ > 1;
38 }
39
40 sub component_base_class { 'DBIx::Class' }
41
42 sub MODIFY_CODE_ATTRIBUTES {
43   my ($class,$code,@attrs) = @_;
44   $class->mk_classdata('__attr_cache' => {})
45     unless $class->can('__attr_cache');
46   $class->__attr_cache->{$code} = [@attrs];
47   return ();
48 }
49
50 sub _attr_cache {
51   my $self = shift;
52   my $cache = $self->can('__attr_cache') ? $self->__attr_cache : {};
53
54   return {
55     %$cache,
56     %{ $self->maybe::next::method || {} },
57   };
58 }
59
60 1;
61
62 =encoding UTF-8
63
64 =head1 NAME
65
66 DBIx::Class - Extensible and flexible object <-> relational mapper.
67
68 =head1 WHERE TO START READING
69
70 See L<DBIx::Class::Manual::DocMap> for an overview of the exhaustive documentation.
71 To get the most out of DBIx::Class with the least confusion it is strongly
72 recommended to read (at the very least) the
73 L<Manuals|DBIx::Class::Manual::DocMap/Manuals> in the order presented there.
74
75 =cut
76
77 # *DO NOT* change this heading - it is linked throughout the ecosystem
78
79 sub DBIx::Class::_ENV_::HELP_URL () {
80   'http://p3rl.org/DBIx::Class#GETTING_HELP/SUPPORT'
81 }
82
83 =head1 GETTING HELP/SUPPORT
84
85 Due to the sheer size of its problem domain, DBIx::Class is a relatively
86 complex framework. After you start using DBIx::Class questions will inevitably
87 arise. If you are stuck with a problem or have doubts about a particular
88 approach do not hesitate to contact us via any of the following options (the
89 list is sorted by "fastest response time"):
90
91 =over
92
93 =item * IRC: irc.perl.org#dbix-class
94
95 =for html
96 <a href="https://chat.mibbit.com/#dbix-class@irc.perl.org">(click for instant chatroom login)</a>
97
98 =item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
99
100 =item * RT Bug Tracker: L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=DBIx-Class>
101
102 =item * Twitter: L<https://www.twitter.com/dbix_class>
103
104 =item * Web Site: L<http://www.dbix-class.org/>
105
106 =back
107
108 =head1 SYNOPSIS
109
110 For the very impatient: L<DBIx::Class::Manual::QuickStart>
111
112 This code in the next step can be generated automatically from an existing
113 database, see L<dbicdump> from the distribution C<DBIx-Class-Schema-Loader>.
114
115 =head2 Schema classes preparation
116
117 Create a schema class called F<MyApp/Schema.pm>:
118
119   package MyApp::Schema;
120   use base qw/DBIx::Class::Schema/;
121
122   __PACKAGE__->load_namespaces();
123
124   1;
125
126 Create a result class to represent artists, who have many CDs, in
127 F<MyApp/Schema/Result/Artist.pm>:
128
129 See L<DBIx::Class::ResultSource> for docs on defining result classes.
130
131   package MyApp::Schema::Result::Artist;
132   use base qw/DBIx::Class::Core/;
133
134   __PACKAGE__->table('artist');
135   __PACKAGE__->add_columns(qw/ artistid name /);
136   __PACKAGE__->set_primary_key('artistid');
137   __PACKAGE__->has_many(cds => 'MyApp::Schema::Result::CD', 'artistid');
138
139   1;
140
141 A result class to represent a CD, which belongs to an artist, in
142 F<MyApp/Schema/Result/CD.pm>:
143
144   package MyApp::Schema::Result::CD;
145   use base qw/DBIx::Class::Core/;
146
147   __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
148   __PACKAGE__->table('cd');
149   __PACKAGE__->add_columns(qw/ cdid artistid title year /);
150   __PACKAGE__->set_primary_key('cdid');
151   __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Result::Artist', 'artistid');
152
153   1;
154
155 =head2 API usage
156
157 Then you can use these classes in your application's code:
158
159   # Connect to your database.
160   use MyApp::Schema;
161   my $schema = MyApp::Schema->connect($dbi_dsn, $user, $pass, \%dbi_params);
162
163   # Query for all artists and put them in an array,
164   # or retrieve them as a result set object.
165   # $schema->resultset returns a DBIx::Class::ResultSet
166   my @all_artists = $schema->resultset('Artist')->all;
167   my $all_artists_rs = $schema->resultset('Artist');
168
169   # Output all artists names
170   # $artist here is a DBIx::Class::Row, which has accessors
171   # for all its columns. Rows are also subclasses of your Result class.
172   foreach $artist (@all_artists) {
173     print $artist->name, "\n";
174   }
175
176   # Create a result set to search for artists.
177   # This does not query the DB.
178   my $johns_rs = $schema->resultset('Artist')->search(
179     # Build your WHERE using an SQL::Abstract structure:
180     { name => { like => 'John%' } }
181   );
182
183   # Execute a joined query to get the cds.
184   my @all_john_cds = $johns_rs->search_related('cds')->all;
185
186   # Fetch the next available row.
187   my $first_john = $johns_rs->next;
188
189   # Specify ORDER BY on the query.
190   my $first_john_cds_by_title_rs = $first_john->cds(
191     undef,
192     { order_by => 'title' }
193   );
194
195   # Create a result set that will fetch the artist data
196   # at the same time as it fetches CDs, using only one query.
197   my $millennium_cds_rs = $schema->resultset('CD')->search(
198     { year => 2000 },
199     { prefetch => 'artist' }
200   );
201
202   my $cd = $millennium_cds_rs->next; # SELECT ... FROM cds JOIN artists ...
203   my $cd_artist_name = $cd->artist->name; # Already has the data so no 2nd query
204
205   # new() makes a Result object but doesnt insert it into the DB.
206   # create() is the same as new() then insert().
207   my $new_cd = $schema->resultset('CD')->new({ title => 'Spoon' });
208   $new_cd->artist($cd->artist);
209   $new_cd->insert; # Auto-increment primary key filled in after INSERT
210   $new_cd->title('Fork');
211
212   $schema->txn_do(sub { $new_cd->update }); # Runs the update in a transaction
213
214   # change the year of all the millennium CDs at once
215   $millennium_cds_rs->update({ year => 2002 });
216
217 =head1 DESCRIPTION
218
219 This is an SQL to OO mapper with an object API inspired by L<Class::DBI>
220 (with a compatibility layer as a springboard for porting) and a resultset API
221 that allows abstract encapsulation of database operations. It aims to make
222 representing queries in your code as perl-ish as possible while still
223 providing access to as many of the capabilities of the database as possible,
224 including retrieving related records from multiple tables in a single query,
225 C<JOIN>, C<LEFT JOIN>, C<COUNT>, C<DISTINCT>, C<GROUP BY>, C<ORDER BY> and
226 C<HAVING> support.
227
228 DBIx::Class can handle multi-column primary and foreign keys, complex
229 queries and database-level paging, and does its best to only query the
230 database in order to return something you've directly asked for. If a
231 resultset is used as an iterator it only fetches rows off the statement
232 handle as requested in order to minimise memory usage. It has auto-increment
233 support for SQLite, MySQL, PostgreSQL, Oracle, SQL Server and DB2 and is
234 known to be used in production on at least the first four, and is fork-
235 and thread-safe out of the box (although
236 L<your DBD may not be|DBI/Threads and Thread Safety>).
237
238 This project is still under rapid development, so large new features may be
239 marked B<experimental> - such APIs are still usable but may have edge bugs.
240 Failing test cases are I<always> welcome and point releases are put out rapidly
241 as bugs are found and fixed.
242
243 We do our best to maintain full backwards compatibility for published
244 APIs, since DBIx::Class is used in production in many organisations,
245 and even backwards incompatible changes to non-published APIs will be fixed
246 if they're reported and doing so doesn't cost the codebase anything.
247
248 The test suite is quite substantial, and several developer releases
249 are generally made to CPAN before the branch for the next release is
250 merged back to trunk for a major release.
251
252 =head1 HOW TO CONTRIBUTE
253
254 Contributions are always welcome, in all usable forms (we especially
255 welcome documentation improvements). The delivery methods include git-
256 or unified-diff formatted patches, GitHub pull requests, or plain bug
257 reports either via RT or the Mailing list. Contributors are generally
258 granted full access to the official repository after their first patch
259 passes successful review.
260
261 =for comment
262 FIXME: Getty, frew and jnap need to get off their asses and finish the contrib section so we can link it here ;)
263
264 This project is maintained in a git repository. The code and related tools are
265 accessible at the following locations:
266
267 =over
268
269 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
270
271 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
272
273 =item * GitHub mirror: L<https://github.com/dbsrgits/DBIx-Class>
274
275 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/DBIx-Class.git>
276
277 =item * Travis-CI log: L<https://travis-ci.org/dbsrgits/dbix-class/builds>
278
279 =for html
280 &#x21AA; Stable branch CI status: <img src="https://secure.travis-ci.org/dbsrgits/dbix-class.png?branch=master"></img>
281
282 =back
283
284 =head1 AUTHOR
285
286 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
287
288 (I mostly consider myself "project founder" these days but the AUTHOR heading
289 is traditional :)
290
291 =head1 CONTRIBUTORS
292
293 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
294
295 acca: Alexander Kuznetsov <acca@cpan.org>
296
297 aherzog: Adam Herzog <adam@herzogdesigns.com>
298
299 Alexander Keusch <cpan@keusch.at>
300
301 alexrj: Alessandro Ranellucci <aar@cpan.org>
302
303 alnewkirk: Al Newkirk <we@ana.im>
304
305 amiri: Amiri Barksdale <amiri@metalabel.com>
306
307 amoore: Andrew Moore <amoore@cpan.org>
308
309 Andrew Mehta <Andrew@unitedgames.co.uk>
310
311 andrewalker: Andre Walker <andre@andrewalker.net>
312
313 andyg: Andy Grundman <andy@hybridized.org>
314
315 ank: Andres Kievsky
316
317 arc: Aaron Crane <arc@cpan.org>
318
319 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
320
321 ash: Ash Berlin <ash@cpan.org>
322
323 bert: Norbert Csongrádi <bert@cpan.org>
324
325 bfwg: Colin Newell <colin.newell@gmail.com>
326
327 blblack: Brandon L. Black <blblack@gmail.com>
328
329 bluefeet: Aran Deltac <bluefeet@cpan.org>
330
331 bphillips: Brian Phillips <bphillips@cpan.org>
332
333 boghead: Bryan Beeley <cpan@beeley.org>
334
335 brd: Brad Davis <brd@FreeBSD.org>
336
337 bricas: Brian Cassidy <bricas@cpan.org>
338
339 brunov: Bruno Vecchi <vecchi.b@gmail.com>
340
341 caelum: Rafael Kitover <rkitover@cpan.org>
342
343 caldrin: Maik Hentsche <maik.hentsche@amd.com>
344
345 castaway: Jess Robinson
346
347 claco: Christopher H. Laco
348
349 clkao: CL Kao
350
351 Ctrl-o L<http://ctrlo.com/>
352
353 da5id: David Jack Olrik <djo@cpan.org>
354
355 dariusj: Darius Jokilehto <dariusjokilehto@yahoo.co.uk>
356
357 davewood: David Schmidt <davewood@gmx.at>
358
359 daxim: Lars Dɪᴇᴄᴋᴏᴡ 迪拉斯 <daxim@cpan.org>
360
361 debolaz: Anders Nor Berle <berle@cpan.org>
362
363 dew: Dan Thomas <dan@godders.org>
364
365 dim0xff: Dmitry Latin <dim0xff@gmail.com>
366
367 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
368
369 dnm: Justin Wheeler <jwheeler@datademons.com>
370
371 dpetrov: Dimitar Petrov <mitakaa@gmail.com>
372
373 duncan_dmg: Duncan Garland <Duncan.Garland@motortrak.com>
374
375 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
376
377 dyfrgi: Michael Leuchtenburg <michael@slashhome.org>
378
379 edenc: Eden Cardim <edencardim@gmail.com>
380
381 Eligo L<http://eligo.co.uk/>
382
383 ether: Karen Etheridge <ether@cpan.org>
384
385 felliott: Fitz Elliott <fitz.elliott@gmail.com>
386
387 freetime: Bill Moseley <moseley@hank.org>
388
389 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
390
391 goraxe: Gordon Irving <goraxe@cpan.org>
392
393 gphat: Cory G Watson <gphat@cpan.org>
394
395 Grant Street Group L<http://www.grantstreet.com/>
396
397 groditi: Guillermo Roditi <groditi@cpan.org>
398
399 guacamole: Fred Steinberg <fred.steinberg@gmail.com>
400
401 Haarg: Graham Knop <haarg@haarg.org>
402
403 hobbs: Andrew Rodland <arodland@cpan.org>
404
405 idn: Ian Norton <i.norton@shadowcat.co.uk>
406
407 ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
408
409 initself: Mike Baas <mike@initselftech.com>
410
411 ironcamel: Naveed Massjouni <naveedm9@gmail.com>
412
413 jawnsy: Jonathan Yu <jawnsy@cpan.org>
414
415 jasonmay: Jason May <jason.a.may@gmail.com>
416
417 jegade: Jens Gassmann <jens.gassmann@atomix.de>
418
419 jesper: Jesper Krogh
420
421 jgoulah: John Goulah <jgoulah@cpan.org>
422
423 jguenther: Justin Guenther <jguenther@cpan.org>
424
425 jhannah: Jay Hannah <jay@jays.net>
426
427 jmac: Jason McIntosh <jmac@appleseed-sc.com>
428
429 jnapiorkowski: John Napiorkowski <jjn1056@yahoo.com>
430
431 jon: Jon Schutz <jjschutz@cpan.org>
432
433 Joe Carlson <jwcarlson@lbl.gov>
434
435 jshirley: J. Shirley <jshirley@gmail.com>
436
437 kaare: Kaare Rasmussen
438
439 konobi: Scott McWhirter
440
441 littlesavage: Alexey Illarionov <littlesavage@orionet.ru>
442
443 lukes: Luke Saunders <luke.saunders@gmail.com>
444
445 marcus: Marcus Ramberg <mramberg@cpan.org>
446
447 mattlaw: Matt Lawrence
448
449 mattp: Matt Phillips <mattp@cpan.org>
450
451 mdk: Mark Keating <m.keating@shadowcat.co.uk>
452
453 mna: Maya
454
455 michaelr: Michael Reddick <michael.reddick@gmail.com>
456
457 milki: Jonathan Chu <milki@rescomp.berkeley.edu>
458
459 minty: Murray Walker <perl@minty.org>
460
461 mithaldu: Christian Walde <walde.christian@gmail.com>
462
463 mjemmeson: Michael Jemmeson <michael.jemmeson@gmail.com>
464
465 mrf: Mike Francis <ungrim97@gmail.com>
466
467 mstratman: Mark A. Stratman <stratman@gmail.com>
468
469 ned: Neil de Carteret
470
471 nigel: Nigel Metheringham <nigelm@cpan.org>
472
473 ningu: David Kamholz <dkamholz@cpan.org>
474
475 Nniuq: Ron "Quinn" Straight" <quinnfazigu@gmail.org>
476
477 norbi: Norbert Buchmuller <norbi@nix.hu>
478
479 nuba: Nuba Princigalli <nuba@cpan.org>
480
481 Numa: Dan Sully <daniel@cpan.org>
482
483 ovid: Curtis "Ovid" Poe <ovid@cpan.org>
484
485 oyse: E<Oslash>ystein Torget <oystein.torget@dnv.com>
486
487 paulm: Paul Makepeace
488
489 penguin: K J Cheetham
490
491 perigrin: Chris Prather <chris@prather.org>
492
493 peter: Peter Collingbourne <peter@pcc.me.uk>
494
495 Peter Siklósi <einon@einon.hu>
496
497 Peter Valdemar ME<oslash>rch <peter@morch.com>
498
499 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
500
501 plu: Johannes Plunien <plu@cpan.org>
502
503 pplu: Jose Luis Martinez <jlmartinez@capside.com>
504
505 Possum: Daniel LeWarne <possum@cpan.org>
506
507 quicksilver: Jules Bean
508
509 rafl: Florian Ragwitz <rafl@debian.org>
510
511 rainboxx: Matthias Dietrich <perl@rb.ly>
512
513 Relequestual: Ben Hutton <relequestual@gmail.com>
514
515 rbo: Robert Bohne <rbo@cpan.org>
516
517 rbuels: Robert Buels <rmb32@cornell.edu>
518
519 rdj: Ryan D Johnson <ryan@innerfence.com>
520
521 ribasushi: Peter Rabbitson <ribasushi@cpan.org>
522
523 rjbs: Ricardo Signes <rjbs@cpan.org>
524
525 robkinyon: Rob Kinyon <rkinyon@cpan.org>
526
527 Robert Olson <bob@rdolson.org>
528
529 moltar: Roman Filippov <romanf@cpan.org>
530
531 Sadrak: Felix Antonius Wilhelm Ostmann <sadrak@cpan.org>
532
533 sc_: Just Another Perl Hacker
534
535 scotty: Scotty Allen <scotty@scottyallen.com>
536
537 semifor: Marc Mims <marc@questright.com>
538
539 SineSwiper: Brendan Byrd <bbyrd@cpan.org>
540
541 skaufman: Samuel Kaufman <sam@socialflow.com>
542
543 solomon: Jared Johnson <jaredj@nmgi.com>
544
545 spb: Stephen Bennett <stephen@freenode.net>
546
547 Squeeks <squeek@cpan.org>
548
549 sszabo: Stephan Szabo <sszabo@bigpanda.com>
550
551 Stephen Peters <steve@stephenpeters.me>
552
553 talexb: Alex Beamish <talexb@gmail.com>
554
555 tamias: Ronald J Kimball <rjk@tamias.net>
556
557 TBSliver: Tom Bloor <t.bloor@shadowcat.co.uk>
558
559 teejay : Aaron Trevena <teejay@cpan.org>
560
561 theorbtwo: James Mastros <james@mastros.biz>
562
563 Todd Lipcon
564
565 Tom Hukins
566
567 tonvoon: Ton Voon <tonvoon@cpan.org>
568
569 triode: Pete Gamache <gamache@cpan.org>
570
571 typester: Daisuke Murase <typester@cpan.org>
572
573 victori: Victor Igumnov <victori@cpan.org>
574
575 wdh: Will Hawes
576
577 wesm: Wes Malone <wes@mitsi.com>
578
579 willert: Sebastian Willert <willert@cpan.org>
580
581 wreis: Wallace Reis <wreis@cpan.org>
582
583 xenoterracide: Caleb Cushing <xenoterracide@gmail.com>
584
585 uree: Oriol Soriano <oriol.soriano@capside.com>
586
587 yrlnry: Mark Jason Dominus <mjd@plover.com>
588
589 zamolxes: Bogdan Lucaciu <bogdan@wiz.ro>
590
591 Zefram: Andrew Main <zefram@fysh.org>
592
593 =head1 COPYRIGHT
594
595 Copyright (c) 2005 - 2011 the DBIx::Class L</AUTHOR> and L</CONTRIBUTORS>
596 as listed above.
597
598 =head1 LICENSE
599
600 This library is free software and may be distributed under the same terms
601 as perl itself.