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