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