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