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