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