Conversion of eval => try (part 1)
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class.pm
1 package DBIx::Class;
2
3 use strict;
4 use warnings;
5
6 use MRO::Compat;
7 use mro 'c3';
8
9 use DBIx::Class::Optional::Dependencies;
10
11 use vars qw($VERSION);
12 use base qw/DBIx::Class::Componentised Class::Accessor::Grouped/;
13 use DBIx::Class::StartupCheck;
14 use Try::Tiny;
15
16 sub mk_classdata {
17   shift->mk_classaccessor(@_);
18 }
19
20 sub mk_classaccessor {
21   my $self = shift;
22   $self->mk_group_accessors('inherited', $_[0]);
23   $self->set_inherited(@_) if @_ > 1;
24 }
25
26 sub component_base_class { 'DBIx::Class' }
27
28 # Always remember to do all digits for the version even if they're 0
29 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
30 # brain damage and presumably various other packaging systems too
31 $VERSION = '0.08121_01';
32
33 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
34
35 sub MODIFY_CODE_ATTRIBUTES {
36   my ($class,$code,@attrs) = @_;
37   $class->mk_classdata('__attr_cache' => {})
38     unless $class->can('__attr_cache');
39   $class->__attr_cache->{$code} = [@attrs];
40   return ();
41 }
42
43 sub _attr_cache {
44   my $self = shift;
45   my $cache = $self->can('__attr_cache') ? $self->__attr_cache : {};
46   my $rest;
47   my $exception;
48   try {
49     $rest = $self->next::method;
50   } catch {
51     $exception = 1;
52   };
53   return $exception ? $cache : { %$cache, %$rest };
54 }
55
56 1;
57
58 =head1 NAME
59
60 DBIx::Class - Extensible and flexible object <-> relational mapper.
61
62 =head1 GETTING HELP/SUPPORT
63
64 The community can be found via:
65
66 =over
67
68 =item * IRC: L<irc.perl.org#dbix-class (click for instant chatroom login)
69 |http://mibbit.com/chat/#dbix-class@irc.perl.org>
70
71 =item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
72
73 =item * RT Bug Tracker: L<https://rt.cpan.org/Dist/Display.html?Queue=DBIx-Class>
74
75 =item * SVNWeb: L<http://dev.catalyst.perl.org/svnweb/bast/browse/DBIx-Class/0.08>
76
77 =item * SVN: L<http://dev.catalyst.perl.org/repos/bast/DBIx-Class/0.08>
78
79 =back
80
81 =head1 SYNOPSIS
82
83 Create a schema class called MyDB/Schema.pm:
84
85   package MyDB::Schema;
86   use base qw/DBIx::Class::Schema/;
87
88   __PACKAGE__->load_namespaces();
89
90   1;
91
92 Create a result class to represent artists, who have many CDs, in
93 MyDB/Schema/Result/Artist.pm:
94
95 See L<DBIx::Class::ResultSource> for docs on defining result classes.
96
97   package MyDB::Schema::Result::Artist;
98   use base qw/DBIx::Class::Core/;
99
100   __PACKAGE__->table('artist');
101   __PACKAGE__->add_columns(qw/ artistid name /);
102   __PACKAGE__->set_primary_key('artistid');
103   __PACKAGE__->has_many(cds => 'MyDB::Schema::Result::CD');
104
105   1;
106
107 A result class to represent a CD, which belongs to an artist, in
108 MyDB/Schema/Result/CD.pm:
109
110   package MyDB::Schema::Result::CD;
111   use base qw/DBIx::Class::Core/;
112
113   __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
114   __PACKAGE__->table('cd');
115   __PACKAGE__->add_columns(qw/ cdid artistid title year /);
116   __PACKAGE__->set_primary_key('cdid');
117   __PACKAGE__->belongs_to(artist => 'MyDB::Schema::Artist', 'artistid');
118
119   1;
120
121 Then you can use these classes in your application's code:
122
123   # Connect to your database.
124   use MyDB::Schema;
125   my $schema = MyDB::Schema->connect($dbi_dsn, $user, $pass, \%dbi_params);
126
127   # Query for all artists and put them in an array,
128   # or retrieve them as a result set object.
129   # $schema->resultset returns a DBIx::Class::ResultSet
130   my @all_artists = $schema->resultset('Artist')->all;
131   my $all_artists_rs = $schema->resultset('Artist');
132
133   # Output all artists names
134   # $artist here is a DBIx::Class::Row, which has accessors
135   # for all its columns. Rows are also subclasses of your Result class.
136   foreach $artist (@all_artists) {
137     print $artist->name, "\n";
138   }
139
140   # Create a result set to search for artists.
141   # This does not query the DB.
142   my $johns_rs = $schema->resultset('Artist')->search(
143     # Build your WHERE using an SQL::Abstract structure:
144     { name => { like => 'John%' } }
145   );
146
147   # Execute a joined query to get the cds.
148   my @all_john_cds = $johns_rs->search_related('cds')->all;
149
150   # Fetch the next available row.
151   my $first_john = $johns_rs->next;
152
153   # Specify ORDER BY on the query.
154   my $first_john_cds_by_title_rs = $first_john->cds(
155     undef,
156     { order_by => 'title' }
157   );
158
159   # Create a result set that will fetch the artist data
160   # at the same time as it fetches CDs, using only one query.
161   my $millennium_cds_rs = $schema->resultset('CD')->search(
162     { year => 2000 },
163     { prefetch => 'artist' }
164   );
165
166   my $cd = $millennium_cds_rs->next; # SELECT ... FROM cds JOIN artists ...
167   my $cd_artist_name = $cd->artist->name; # Already has the data so no 2nd query
168
169   # new() makes a DBIx::Class::Row object but doesnt insert it into the DB.
170   # create() is the same as new() then insert().
171   my $new_cd = $schema->resultset('CD')->new({ title => 'Spoon' });
172   $new_cd->artist($cd->artist);
173   $new_cd->insert; # Auto-increment primary key filled in after INSERT
174   $new_cd->title('Fork');
175
176   $schema->txn_do(sub { $new_cd->update }); # Runs the update in a transaction
177
178   # change the year of all the millennium CDs at once
179   $millennium_cds_rs->update({ year => 2002 });
180
181 =head1 DESCRIPTION
182
183 This is an SQL to OO mapper with an object API inspired by L<Class::DBI>
184 (with a compatibility layer as a springboard for porting) and a resultset API
185 that allows abstract encapsulation of database operations. It aims to make
186 representing queries in your code as perl-ish as possible while still
187 providing access to as many of the capabilities of the database as possible,
188 including retrieving related records from multiple tables in a single query,
189 JOIN, LEFT JOIN, COUNT, DISTINCT, GROUP BY, ORDER BY and HAVING support.
190
191 DBIx::Class can handle multi-column primary and foreign keys, complex
192 queries and database-level paging, and does its best to only query the
193 database in order to return something you've directly asked for. If a
194 resultset is used as an iterator it only fetches rows off the statement
195 handle as requested in order to minimise memory usage. It has auto-increment
196 support for SQLite, MySQL, PostgreSQL, Oracle, SQL Server and DB2 and is
197 known to be used in production on at least the first four, and is fork-
198 and thread-safe out of the box (although your DBD may not be).
199
200 This project is still under rapid development, so large new features may be
201 marked EXPERIMENTAL - such APIs are still usable but may have edge bugs.
202 Failing test cases are *always* welcome and point releases are put out rapidly
203 as bugs are found and fixed.
204
205 We do our best to maintain full backwards compatibility for published
206 APIs, since DBIx::Class is used in production in many organisations,
207 and even backwards incompatible changes to non-published APIs will be fixed
208 if they're reported and doing so doesn't cost the codebase anything.
209
210 The test suite is quite substantial, and several developer releases
211 are generally made to CPAN before the branch for the next release is
212 merged back to trunk for a major release.
213
214 =head1 WHERE TO GO NEXT
215
216 L<DBIx::Class::Manual::DocMap> lists each task you might want help on, and
217 the modules where you will find documentation.
218
219 =head1 AUTHOR
220
221 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
222
223 (I mostly consider myself "project founder" these days but the AUTHOR heading
224 is traditional :)
225
226 =head1 CONTRIBUTORS
227
228 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
229
230 aherzog: Adam Herzog <adam@herzogdesigns.com>
231
232 amoore: Andrew Moore <amoore@cpan.org>
233
234 andyg: Andy Grundman <andy@hybridized.org>
235
236 ank: Andres Kievsky
237
238 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
239
240 ash: Ash Berlin <ash@cpan.org>
241
242 bert: Norbert Csongradi <bert@cpan.org>
243
244 blblack: Brandon L. Black <blblack@gmail.com>
245
246 bluefeet: Aran Deltac <bluefeet@cpan.org>
247
248 boghead: Bryan Beeley <cpan@beeley.org>
249
250 bricas: Brian Cassidy <bricas@cpan.org>
251
252 brunov: Bruno Vecchi <vecchi.b@gmail.com>
253
254 caelum: Rafael Kitover <rkitover@cpan.org>
255
256 castaway: Jess Robinson
257
258 claco: Christopher H. Laco
259
260 clkao: CL Kao
261
262 da5id: David Jack Olrik <djo@cpan.org>
263
264 debolaz: Anders Nor Berle <berle@cpan.org>
265
266 dew: Dan Thomas <dan@godders.org>
267
268 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
269
270 dnm: Justin Wheeler <jwheeler@datademons.com>
271
272 dpetrov: Dimitar Petrov <mitakaa@gmail.com>
273
274 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
275
276 dyfrgi: Michael Leuchtenburg <michael@slashhome.org>
277
278 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
279
280 goraxe: Gordon Irving <goraxe@cpan.org>
281
282 gphat: Cory G Watson <gphat@cpan.org>
283
284 groditi: Guillermo Roditi <groditi@cpan.org>
285
286 hobbs: Andrew Rodland <arodland@cpan.org>
287
288 ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
289
290 jasonmay: Jason May <jason.a.may@gmail.com>
291
292 jesper: Jesper Krogh
293
294 jgoulah: John Goulah <jgoulah@cpan.org>
295
296 jguenther: Justin Guenther <jguenther@cpan.org>
297
298 jhannah: Jay Hannah <jay@jays.net>
299
300 jnapiorkowski: John Napiorkowski <jjn1056@yahoo.com>
301
302 jon: Jon Schutz <jjschutz@cpan.org>
303
304 jshirley: J. Shirley <jshirley@gmail.com>
305
306 konobi: Scott McWhirter
307
308 lukes: Luke Saunders <luke.saunders@gmail.com>
309
310 marcus: Marcus Ramberg <mramberg@cpan.org>
311
312 mattlaw: Matt Lawrence
313
314 michaelr: Michael Reddick <michael.reddick@gmail.com>
315
316 ned: Neil de Carteret
317
318 nigel: Nigel Metheringham <nigelm@cpan.org>
319
320 ningu: David Kamholz <dkamholz@cpan.org>
321
322 Nniuq: Ron "Quinn" Straight" <quinnfazigu@gmail.org>
323
324 norbi: Norbert Buchmuller <norbi@nix.hu>
325
326 nuba: Nuba Princigalli <nuba@cpan.org>
327
328 Numa: Dan Sully <daniel@cpan.org>
329
330 ovid: Curtis "Ovid" Poe <ovid@cpan.org>
331
332 oyse: Ã˜ystein Torget <oystein.torget@dnv.com>
333
334 paulm: Paul Makepeace
335
336 penguin: K J Cheetham
337
338 perigrin: Chris Prather <chris@prather.org>
339
340 peter: Peter Collingbourne <peter@pcc.me.uk>
341
342 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
343
344 plu: Johannes Plunien <plu@cpan.org>
345
346 quicksilver: Jules Bean
347
348 rafl: Florian Ragwitz <rafl@debian.org>
349
350 rbuels: Robert Buels <rmb32@cornell.edu>
351
352 rdj: Ryan D Johnson <ryan@innerfence.com>
353
354 ribasushi: Peter Rabbitson <ribasushi@cpan.org>
355
356 rjbs: Ricardo Signes <rjbs@cpan.org>
357
358 robkinyon: Rob Kinyon <rkinyon@cpan.org>
359
360 Roman: Roman Filippov <romanf@cpan.org>
361
362 sc_: Just Another Perl Hacker
363
364 scotty: Scotty Allen <scotty@scottyallen.com>
365
366 semifor: Marc Mims <marc@questright.com>
367
368 solomon: Jared Johnson <jaredj@nmgi.com>
369
370 spb: Stephen Bennett <stephen@freenode.net>
371
372 sszabo: Stephan Szabo <sszabo@bigpanda.com>
373
374 teejay : Aaron Trevena <teejay@cpan.org>
375
376 Todd Lipcon
377
378 Tom Hukins
379
380 triode: Pete Gamache <gamache@cpan.org>
381
382 typester: Daisuke Murase <typester@cpan.org>
383
384 victori: Victor Igumnov <victori@cpan.org>
385
386 wdh: Will Hawes
387
388 willert: Sebastian Willert <willert@cpan.org>
389
390 wreis: Wallace Reis <wreis@cpan.org>
391
392 zamolxes: Bogdan Lucaciu <bogdan@wiz.ro>
393
394 Possum: Daniel LeWarne <possum@cpan.org>
395
396 =head1 COPYRIGHT
397
398 Copyright (c) 2005 - 2010 the DBIx::Class L</AUTHOR> and L</CONTRIBUTORS>
399 as listed above.
400
401 =head1 LICENSE
402
403 This library is free software and may be distributed under the same terms
404 as perl itself.
405
406 =cut