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