prefetch docs: prefetch works on all rel types
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class.pm
1 package DBIx::Class;
2
3 use strict;
4 use warnings;
5
6 BEGIN {
7   package DBIx::Class::_ENV_;
8
9   if ($] < 5.009_005) {
10     require MRO::Compat;
11     *OLD_MRO = sub () { 1 };
12   }
13   else {
14     require mro;
15     *OLD_MRO = sub () { 0 };
16   }
17
18   # ::Runmode would only be loaded by DBICTest, which in turn implies t/
19   *DBICTEST = eval { DBICTest::RunMode->is_author }
20     ? sub () { 1 }
21     : sub () { 0 }
22   ;
23
24   # During 5.13 dev cycle HELEMs started to leak on copy
25   *PEEPEENESS = (defined $ENV{DBICTEST_ALL_LEAKS}
26     # request for all tests would force "non-leaky" illusion and vice-versa
27     ? ! $ENV{DBICTEST_ALL_LEAKS}
28
29     # otherwise confess that this perl is busted ONLY on smokers
30     : do {
31       if (eval { DBICTest::RunMode->is_smoker }) {
32
33         # leaky 5.13.6 (fixed in blead/cefd5c7c)
34         if ($] == '5.013006') { 1 }
35
36         # not sure why this one leaks, but disable anyway - ANDK seems to make it weep
37         elsif ($] == '5.013005') { 1 }
38
39         else { 0 }
40       }
41       else { 0 }
42     }
43   ) ? sub () { 1 } : sub () { 0 };
44 }
45
46 use mro 'c3';
47
48 use DBIx::Class::Optional::Dependencies;
49
50 use vars qw($VERSION);
51 use base qw/DBIx::Class::Componentised DBIx::Class::AccessorGroup/;
52 use DBIx::Class::StartupCheck;
53
54 __PACKAGE__->mk_group_accessors(inherited => '_skip_namespace_frames');
55 __PACKAGE__->_skip_namespace_frames('^DBIx::Class|^SQL::Abstract|^Try::Tiny');
56
57 sub mk_classdata {
58   shift->mk_classaccessor(@_);
59 }
60
61 sub mk_classaccessor {
62   my $self = shift;
63   $self->mk_group_accessors('inherited', $_[0]);
64   $self->set_inherited(@_) if @_ > 1;
65 }
66
67 sub component_base_class { 'DBIx::Class' }
68
69 # Always remember to do all digits for the version even if they're 0
70 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
71 # brain damage and presumably various other packaging systems too
72 $VERSION = '0.08190';
73
74 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
75
76 sub MODIFY_CODE_ATTRIBUTES {
77   my ($class,$code,@attrs) = @_;
78   $class->mk_classdata('__attr_cache' => {})
79     unless $class->can('__attr_cache');
80   $class->__attr_cache->{$code} = [@attrs];
81   return ();
82 }
83
84 sub _attr_cache {
85   my $self = shift;
86   my $cache = $self->can('__attr_cache') ? $self->__attr_cache : {};
87
88   return {
89     %$cache,
90     %{ $self->maybe::next::method || {} },
91   };
92 }
93
94 1;
95
96 =head1 NAME
97
98 DBIx::Class - Extensible and flexible object <-> relational mapper.
99
100 =head1 GETTING HELP/SUPPORT
101
102 The community can be found via:
103
104 =over
105
106 =item * Web Site: L<http://www.dbix-class.org/>
107
108 =item * IRC: irc.perl.org#dbix-class
109
110 =for html
111 <a href="http://chat.mibbit.com/#dbix-class@irc.perl.org">(click for instant chatroom login)</a>
112
113 =item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
114
115 =item * RT Bug Tracker: L<https://rt.cpan.org/Dist/Display.html?Queue=DBIx-Class>
116
117 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
118
119 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
120
121 =item * twitter L<http://www.twitter.com/dbix_class>
122
123 =back
124
125 =head1 SYNOPSIS
126
127 Create a schema class called MyApp/Schema.pm:
128
129   package MyApp::Schema;
130   use base qw/DBIx::Class::Schema/;
131
132   __PACKAGE__->load_namespaces();
133
134   1;
135
136 Create a result class to represent artists, who have many CDs, in
137 MyApp/Schema/Result/Artist.pm:
138
139 See L<DBIx::Class::ResultSource> for docs on defining result classes.
140
141   package MyApp::Schema::Result::Artist;
142   use base qw/DBIx::Class::Core/;
143
144   __PACKAGE__->table('artist');
145   __PACKAGE__->add_columns(qw/ artistid name /);
146   __PACKAGE__->set_primary_key('artistid');
147   __PACKAGE__->has_many(cds => 'MyApp::Schema::Result::CD');
148
149   1;
150
151 A result class to represent a CD, which belongs to an artist, in
152 MyApp/Schema/Result/CD.pm:
153
154   package MyApp::Schema::Result::CD;
155   use base qw/DBIx::Class::Core/;
156
157   __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
158   __PACKAGE__->table('cd');
159   __PACKAGE__->add_columns(qw/ cdid artistid title year /);
160   __PACKAGE__->set_primary_key('cdid');
161   __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Result::Artist', 'artistid');
162
163   1;
164
165 Then you can use these classes in your application's code:
166
167   # Connect to your database.
168   use MyApp::Schema;
169   my $schema = MyApp::Schema->connect($dbi_dsn, $user, $pass, \%dbi_params);
170
171   # Query for all artists and put them in an array,
172   # or retrieve them as a result set object.
173   # $schema->resultset returns a DBIx::Class::ResultSet
174   my @all_artists = $schema->resultset('Artist')->all;
175   my $all_artists_rs = $schema->resultset('Artist');
176
177   # Output all artists names
178   # $artist here is a DBIx::Class::Row, which has accessors
179   # for all its columns. Rows are also subclasses of your Result class.
180   foreach $artist (@all_artists) {
181     print $artist->name, "\n";
182   }
183
184   # Create a result set to search for artists.
185   # This does not query the DB.
186   my $johns_rs = $schema->resultset('Artist')->search(
187     # Build your WHERE using an SQL::Abstract structure:
188     { name => { like => 'John%' } }
189   );
190
191   # Execute a joined query to get the cds.
192   my @all_john_cds = $johns_rs->search_related('cds')->all;
193
194   # Fetch the next available row.
195   my $first_john = $johns_rs->next;
196
197   # Specify ORDER BY on the query.
198   my $first_john_cds_by_title_rs = $first_john->cds(
199     undef,
200     { order_by => 'title' }
201   );
202
203   # Create a result set that will fetch the artist data
204   # at the same time as it fetches CDs, using only one query.
205   my $millennium_cds_rs = $schema->resultset('CD')->search(
206     { year => 2000 },
207     { prefetch => 'artist' }
208   );
209
210   my $cd = $millennium_cds_rs->next; # SELECT ... FROM cds JOIN artists ...
211   my $cd_artist_name = $cd->artist->name; # Already has the data so no 2nd query
212
213   # new() makes a DBIx::Class::Row object but doesnt insert it into the DB.
214   # create() is the same as new() then insert().
215   my $new_cd = $schema->resultset('CD')->new({ title => 'Spoon' });
216   $new_cd->artist($cd->artist);
217   $new_cd->insert; # Auto-increment primary key filled in after INSERT
218   $new_cd->title('Fork');
219
220   $schema->txn_do(sub { $new_cd->update }); # Runs the update in a transaction
221
222   # change the year of all the millennium CDs at once
223   $millennium_cds_rs->update({ year => 2002 });
224
225 =head1 DESCRIPTION
226
227 This is an SQL to OO mapper with an object API inspired by L<Class::DBI>
228 (with a compatibility layer as a springboard for porting) and a resultset API
229 that allows abstract encapsulation of database operations. It aims to make
230 representing queries in your code as perl-ish as possible while still
231 providing access to as many of the capabilities of the database as possible,
232 including retrieving related records from multiple tables in a single query,
233 JOIN, LEFT JOIN, COUNT, DISTINCT, GROUP BY, ORDER BY and HAVING support.
234
235 DBIx::Class can handle multi-column primary and foreign keys, complex
236 queries and database-level paging, and does its best to only query the
237 database in order to return something you've directly asked for. If a
238 resultset is used as an iterator it only fetches rows off the statement
239 handle as requested in order to minimise memory usage. It has auto-increment
240 support for SQLite, MySQL, PostgreSQL, Oracle, SQL Server and DB2 and is
241 known to be used in production on at least the first four, and is fork-
242 and thread-safe out of the box (although
243 L<your DBD may not be|DBI/Threads_and_Thread_Safety>).
244
245 This project is still under rapid development, so large new features may be
246 marked EXPERIMENTAL - such APIs are still usable but may have edge bugs.
247 Failing test cases are *always* welcome and point releases are put out rapidly
248 as bugs are found and fixed.
249
250 We do our best to maintain full backwards compatibility for published
251 APIs, since DBIx::Class is used in production in many organisations,
252 and even backwards incompatible changes to non-published APIs will be fixed
253 if they're reported and doing so doesn't cost the codebase anything.
254
255 The test suite is quite substantial, and several developer releases
256 are generally made to CPAN before the branch for the next release is
257 merged back to trunk for a major release.
258
259 =head1 WHERE TO GO NEXT
260
261 L<DBIx::Class::Manual::DocMap> lists each task you might want help on, and
262 the modules where you will find documentation.
263
264 =head1 AUTHOR
265
266 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
267
268 (I mostly consider myself "project founder" these days but the AUTHOR heading
269 is traditional :)
270
271 =head1 CONTRIBUTORS
272
273 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
274
275 acca: Alexander Kuznetsov <acca@cpan.org>
276
277 aherzog: Adam Herzog <adam@herzogdesigns.com>
278
279 Alexander Keusch <cpan@keusch.at>
280
281 alnewkirk: Al Newkirk <we@ana.im>
282
283 amiri: Amiri Barksdale <amiri@metalabel.com>
284
285 amoore: Andrew Moore <amoore@cpan.org>
286
287 andyg: Andy Grundman <andy@hybridized.org>
288
289 ank: Andres Kievsky
290
291 arc: Aaron Crane <arc@cpan.org>
292
293 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
294
295 ash: Ash Berlin <ash@cpan.org>
296
297 bert: Norbert Csongradi <bert@cpan.org>
298
299 blblack: Brandon L. Black <blblack@gmail.com>
300
301 bluefeet: Aran Deltac <bluefeet@cpan.org>
302
303 bphillips: Brian Phillips <bphillips@cpan.org>
304
305 boghead: Bryan Beeley <cpan@beeley.org>
306
307 bricas: Brian Cassidy <bricas@cpan.org>
308
309 brunov: Bruno Vecchi <vecchi.b@gmail.com>
310
311 caelum: Rafael Kitover <rkitover@cpan.org>
312
313 caldrin: Maik Hentsche <maik.hentsche@amd.com>
314
315 castaway: Jess Robinson
316
317 claco: Christopher H. Laco
318
319 clkao: CL Kao
320
321 da5id: David Jack Olrik <djo@cpan.org>
322
323 debolaz: Anders Nor Berle <berle@cpan.org>
324
325 dew: Dan Thomas <dan@godders.org>
326
327 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
328
329 dnm: Justin Wheeler <jwheeler@datademons.com>
330
331 dpetrov: Dimitar Petrov <mitakaa@gmail.com>
332
333 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
334
335 dyfrgi: Michael Leuchtenburg <michael@slashhome.org>
336
337 felliott: Fitz Elliott <fitz.elliott@gmail.com>
338
339 freetime: Bill Moseley <moseley@hank.org>
340
341 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
342
343 goraxe: Gordon Irving <goraxe@cpan.org>
344
345 gphat: Cory G Watson <gphat@cpan.org>
346
347 Grant Street Group L<http://www.grantstreet.com/>
348
349 groditi: Guillermo Roditi <groditi@cpan.org>
350
351 Haarg: Graham Knop <haarg@haarg.org>
352
353 hobbs: Andrew Rodland <arodland@cpan.org>
354
355 ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
356
357 initself: Mike Baas <mike@initselftech.com>
358
359 jawnsy: Jonathan Yu <jawnsy@cpan.org>
360
361 jasonmay: Jason May <jason.a.may@gmail.com>
362
363 jesper: Jesper Krogh
364
365 jgoulah: John Goulah <jgoulah@cpan.org>
366
367 jguenther: Justin Guenther <jguenther@cpan.org>
368
369 jhannah: Jay Hannah <jay@jays.net>
370
371 jnapiorkowski: John Napiorkowski <jjn1056@yahoo.com>
372
373 jon: Jon Schutz <jjschutz@cpan.org>
374
375 jshirley: J. Shirley <jshirley@gmail.com>
376
377 kaare: Kaare Rasmussen
378
379 konobi: Scott McWhirter
380
381 littlesavage: Alexey Illarionov <littlesavage@orionet.ru>
382
383 lukes: Luke Saunders <luke.saunders@gmail.com>
384
385 marcus: Marcus Ramberg <mramberg@cpan.org>
386
387 mattlaw: Matt Lawrence
388
389 mattp: Matt Phillips <mattp@cpan.org>
390
391 michaelr: Michael Reddick <michael.reddick@gmail.com>
392
393 milki: Jonathan Chu <milki@rescomp.berkeley.edu>
394
395 ned: Neil de Carteret
396
397 nigel: Nigel Metheringham <nigelm@cpan.org>
398
399 ningu: David Kamholz <dkamholz@cpan.org>
400
401 Nniuq: Ron "Quinn" Straight" <quinnfazigu@gmail.org>
402
403 norbi: Norbert Buchmuller <norbi@nix.hu>
404
405 nuba: Nuba Princigalli <nuba@cpan.org>
406
407 Numa: Dan Sully <daniel@cpan.org>
408
409 ovid: Curtis "Ovid" Poe <ovid@cpan.org>
410
411 oyse: Ã˜ystein Torget <oystein.torget@dnv.com>
412
413 paulm: Paul Makepeace
414
415 penguin: K J Cheetham
416
417 perigrin: Chris Prather <chris@prather.org>
418
419 peter: Peter Collingbourne <peter@pcc.me.uk>
420
421 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
422
423 plu: Johannes Plunien <plu@cpan.org>
424
425 Possum: Daniel LeWarne <possum@cpan.org>
426
427 quicksilver: Jules Bean
428
429 rafl: Florian Ragwitz <rafl@debian.org>
430
431 rainboxx: Matthias Dietrich <perl@rb.ly>
432
433 rbo: Robert Bohne <rbo@cpan.org>
434
435 rbuels: Robert Buels <rmb32@cornell.edu>
436
437 rdj: Ryan D Johnson <ryan@innerfence.com>
438
439 ribasushi: Peter Rabbitson <ribasushi@cpan.org>
440
441 rjbs: Ricardo Signes <rjbs@cpan.org>
442
443 robkinyon: Rob Kinyon <rkinyon@cpan.org>
444
445 Robert Olson <bob@rdolson.org>
446
447 Roman: Roman Filippov <romanf@cpan.org>
448
449 Sadrak: Felix Antonius Wilhelm Ostmann <sadrak@cpan.org>
450
451 sc_: Just Another Perl Hacker
452
453 scotty: Scotty Allen <scotty@scottyallen.com>
454
455 semifor: Marc Mims <marc@questright.com>
456
457 solomon: Jared Johnson <jaredj@nmgi.com>
458
459 spb: Stephen Bennett <stephen@freenode.net>
460
461 Squeeks <squeek@cpan.org>
462
463 sszabo: Stephan Szabo <sszabo@bigpanda.com>
464
465 talexb: Alex Beamish <talexb@gmail.com>
466
467 tamias: Ronald J Kimball <rjk@tamias.net>
468
469 teejay : Aaron Trevena <teejay@cpan.org>
470
471 Todd Lipcon
472
473 Tom Hukins
474
475 tonvoon: Ton Voon <tonvoon@cpan.org>
476
477 triode: Pete Gamache <gamache@cpan.org>
478
479 typester: Daisuke Murase <typester@cpan.org>
480
481 victori: Victor Igumnov <victori@cpan.org>
482
483 wdh: Will Hawes
484
485 willert: Sebastian Willert <willert@cpan.org>
486
487 wreis: Wallace Reis <wreis@cpan.org>
488
489 yrlnry: Mark Jason Dominus <mjd@plover.com>
490
491 zamolxes: Bogdan Lucaciu <bogdan@wiz.ro>
492
493 =head1 COPYRIGHT
494
495 Copyright (c) 2005 - 2010 the DBIx::Class L</AUTHOR> and L</CONTRIBUTORS>
496 as listed above.
497
498 =head1 LICENSE
499
500 This library is free software and may be distributed under the same terms
501 as perl itself.
502
503 =cut