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