41eacb1789e1c127906179e25363d81a824791fb
[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
15 sub mk_classdata {
16   shift->mk_classaccessor(@_);
17 }
18
19 sub mk_classaccessor {
20   my $self = shift;
21   $self->mk_group_accessors('inherited', $_[0]);
22   $self->set_inherited(@_) if @_ > 1;
23 }
24
25 sub component_base_class { 'DBIx::Class' }
26
27 # Always remember to do all digits for the version even if they're 0
28 # i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
29 # brain damage and presumably various other packaging systems too
30 $VERSION = '0.08124';
31
32 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
33
34 sub MODIFY_CODE_ATTRIBUTES {
35   my ($class,$code,@attrs) = @_;
36   $class->mk_classdata('__attr_cache' => {})
37     unless $class->can('__attr_cache');
38   $class->__attr_cache->{$code} = [@attrs];
39   return ();
40 }
41
42 sub _attr_cache {
43   my $self = shift;
44   my $cache = $self->can('__attr_cache') ? $self->__attr_cache : {};
45
46   return {
47     %$cache,
48     %{ $self->maybe::next::method || {} },
49   };
50 }
51
52 1;
53
54 =head1 NAME
55
56 DBIx::Class - Extensible and flexible object <-> relational mapper.
57
58 =head1 GETTING HELP/SUPPORT
59
60 The community can be found via:
61
62 =over
63
64 =item * IRC: irc.perl.org#dbix-class
65
66 =for html
67 <a href="http://chat.mibbit.com/#dbix-class@irc.perl.org">(click for instant chatroom login)</a>
68
69 =item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
70
71 =item * RT Bug Tracker: L<https://rt.cpan.org/Dist/Display.html?Queue=DBIx-Class>
72
73 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
74
75 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
76
77 =item * twitter L<http://www.twitter.com/dbix_class>
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
199 L<your DBD may not be|DBI/Threads_and_Thread_Safety>).
200
201 This project is still under rapid development, so large new features may be
202 marked EXPERIMENTAL - such APIs are still usable but may have edge bugs.
203 Failing test cases are *always* welcome and point releases are put out rapidly
204 as bugs are found and fixed.
205
206 We do our best to maintain full backwards compatibility for published
207 APIs, since DBIx::Class is used in production in many organisations,
208 and even backwards incompatible changes to non-published APIs will be fixed
209 if they're reported and doing so doesn't cost the codebase anything.
210
211 The test suite is quite substantial, and several developer releases
212 are generally made to CPAN before the branch for the next release is
213 merged back to trunk for a major release.
214
215 =head1 WHERE TO GO NEXT
216
217 L<DBIx::Class::Manual::DocMap> lists each task you might want help on, and
218 the modules where you will find documentation.
219
220 =head1 AUTHOR
221
222 mst: Matt S. Trout <mst@shadowcatsystems.co.uk>
223
224 (I mostly consider myself "project founder" these days but the AUTHOR heading
225 is traditional :)
226
227 =head1 CONTRIBUTORS
228
229 abraxxa: Alexander Hartmaier <abraxxa@cpan.org>
230
231 aherzog: Adam Herzog <adam@herzogdesigns.com>
232
233 Alexander Keusch <cpan@keusch.at>
234
235 amiri: Amiri Barksdale <amiri@metalabel.com>
236
237 amoore: Andrew Moore <amoore@cpan.org>
238
239 andyg: Andy Grundman <andy@hybridized.org>
240
241 ank: Andres Kievsky
242
243 arc: Aaron Crane <arc@cpan.org>
244
245 arcanez: Justin Hunter <justin.d.hunter@gmail.com>
246
247 ash: Ash Berlin <ash@cpan.org>
248
249 bert: Norbert Csongradi <bert@cpan.org>
250
251 blblack: Brandon L. Black <blblack@gmail.com>
252
253 bluefeet: Aran Deltac <bluefeet@cpan.org>
254
255 boghead: Bryan Beeley <cpan@beeley.org>
256
257 bricas: Brian Cassidy <bricas@cpan.org>
258
259 brunov: Bruno Vecchi <vecchi.b@gmail.com>
260
261 caelum: Rafael Kitover <rkitover@cpan.org>
262
263 castaway: Jess Robinson
264
265 claco: Christopher H. Laco
266
267 clkao: CL Kao
268
269 da5id: David Jack Olrik <djo@cpan.org>
270
271 debolaz: Anders Nor Berle <berle@cpan.org>
272
273 dew: Dan Thomas <dan@godders.org>
274
275 dkubb: Dan Kubb <dan.kubb-cpan@onautopilot.com>
276
277 dnm: Justin Wheeler <jwheeler@datademons.com>
278
279 dpetrov: Dimitar Petrov <mitakaa@gmail.com>
280
281 dwc: Daniel Westermann-Clark <danieltwc@cpan.org>
282
283 dyfrgi: Michael Leuchtenburg <michael@slashhome.org>
284
285 frew: Arthur Axel "fREW" Schmidt <frioux@gmail.com>
286
287 goraxe: Gordon Irving <goraxe@cpan.org>
288
289 gphat: Cory G Watson <gphat@cpan.org>
290
291 groditi: Guillermo Roditi <groditi@cpan.org>
292
293 Haarg: Graham Knop <haarg@haarg.org>
294
295 hobbs: Andrew Rodland <arodland@cpan.org>
296
297 ilmari: Dagfinn Ilmari MannsE<aring>ker <ilmari@ilmari.org>
298
299 initself: Mike Baas <mike@initselftech.com>
300
301 jasonmay: Jason May <jason.a.may@gmail.com>
302
303 jesper: Jesper Krogh
304
305 jgoulah: John Goulah <jgoulah@cpan.org>
306
307 jguenther: Justin Guenther <jguenther@cpan.org>
308
309 jhannah: Jay Hannah <jay@jays.net>
310
311 jnapiorkowski: John Napiorkowski <jjn1056@yahoo.com>
312
313 jon: Jon Schutz <jjschutz@cpan.org>
314
315 jshirley: J. Shirley <jshirley@gmail.com>
316
317 konobi: Scott McWhirter
318
319 lukes: Luke Saunders <luke.saunders@gmail.com>
320
321 marcus: Marcus Ramberg <mramberg@cpan.org>
322
323 mattlaw: Matt Lawrence
324
325 michaelr: Michael Reddick <michael.reddick@gmail.com>
326
327 ned: Neil de Carteret
328
329 nigel: Nigel Metheringham <nigelm@cpan.org>
330
331 ningu: David Kamholz <dkamholz@cpan.org>
332
333 Nniuq: Ron "Quinn" Straight" <quinnfazigu@gmail.org>
334
335 norbi: Norbert Buchmuller <norbi@nix.hu>
336
337 nuba: Nuba Princigalli <nuba@cpan.org>
338
339 Numa: Dan Sully <daniel@cpan.org>
340
341 ovid: Curtis "Ovid" Poe <ovid@cpan.org>
342
343 oyse: Ã˜ystein Torget <oystein.torget@dnv.com>
344
345 paulm: Paul Makepeace
346
347 penguin: K J Cheetham
348
349 perigrin: Chris Prather <chris@prather.org>
350
351 peter: Peter Collingbourne <peter@pcc.me.uk>
352
353 phaylon: Robert Sedlacek <phaylon@dunkelheit.at>
354
355 plu: Johannes Plunien <plu@cpan.org>
356
357 Possum: Daniel LeWarne <possum@cpan.org>
358
359 quicksilver: Jules Bean
360
361 rafl: Florian Ragwitz <rafl@debian.org>
362
363 rainboxx: Matthias Dietrich <perl@rb.ly>
364
365 rbo: Robert Bohne <rbo@cpan.org>
366
367 rbuels: Robert Buels <rmb32@cornell.edu>
368
369 rdj: Ryan D Johnson <ryan@innerfence.com>
370
371 ribasushi: Peter Rabbitson <ribasushi@cpan.org>
372
373 rjbs: Ricardo Signes <rjbs@cpan.org>
374
375 robkinyon: Rob Kinyon <rkinyon@cpan.org>
376
377 Roman: Roman Filippov <romanf@cpan.org>
378
379 sc_: Just Another Perl Hacker
380
381 scotty: Scotty Allen <scotty@scottyallen.com>
382
383 semifor: Marc Mims <marc@questright.com>
384
385 solomon: Jared Johnson <jaredj@nmgi.com>
386
387 spb: Stephen Bennett <stephen@freenode.net>
388
389 sszabo: Stephan Szabo <sszabo@bigpanda.com>
390
391 teejay : Aaron Trevena <teejay@cpan.org>
392
393 Todd Lipcon
394
395 Tom Hukins
396
397 tonvoon: Ton Voon <tonvoon@cpan.org>
398
399 triode: Pete Gamache <gamache@cpan.org>
400
401 typester: Daisuke Murase <typester@cpan.org>
402
403 victori: Victor Igumnov <victori@cpan.org>
404
405 wdh: Will Hawes
406
407 willert: Sebastian Willert <willert@cpan.org>
408
409 wreis: Wallace Reis <wreis@cpan.org>
410
411 yrlnry: Mark Jason Dominus <mjd@plover.com>
412
413 zamolxes: Bogdan Lucaciu <bogdan@wiz.ro>
414
415 =head1 COPYRIGHT
416
417 Copyright (c) 2005 - 2010 the DBIx::Class L</AUTHOR> and L</CONTRIBUTORS>
418 as listed above.
419
420 =head1 LICENSE
421
422 This library is free software and may be distributed under the same terms
423 as perl itself.
424
425 =cut