Release v0.082840
[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.082840';
15
16 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
17
18 use DBIx::Class::_Util;
19 use mro 'c3';
20
21 use DBIx::Class::Optional::Dependencies;
22
23 use base qw/DBIx::Class::Componentised DBIx::Class::AccessorGroup/;
24 use DBIx::Class::StartupCheck;
25 use DBIx::Class::Exception;
26
27 __PACKAGE__->mk_group_accessors(inherited => '_skip_namespace_frames');
28 __PACKAGE__->_skip_namespace_frames('^DBIx::Class|^SQL::Abstract|^Try::Tiny|^Class::Accessor::Grouped|^Context::Preserve');
29
30 # FIXME - this is not really necessary, and is in
31 # fact going to slow things down a bit
32 # However it is the right thing to do in order to get
33 # various install bases to highlight their brokenness
34 # Remove at some unknown point in the future
35 sub DESTROY { &DBIx::Class::_Util::detected_reinvoked_destructor }
36
37 sub mk_classdata {
38   shift->mk_classaccessor(@_);
39 }
40
41 sub mk_classaccessor {
42   my $self = shift;
43   $self->mk_group_accessors('inherited', $_[0]);
44   $self->set_inherited(@_) if @_ > 1;
45 }
46
47 sub component_base_class { 'DBIx::Class' }
48
49 sub MODIFY_CODE_ATTRIBUTES {
50   my ($class,$code,@attrs) = @_;
51   $class->mk_classdata('__attr_cache' => {})
52     unless $class->can('__attr_cache');
53   $class->__attr_cache->{$code} = [@attrs];
54   return ();
55 }
56
57 sub _attr_cache {
58   my $self = shift;
59   my $cache = $self->can('__attr_cache') ? $self->__attr_cache : {};
60
61   return {
62     %$cache,
63     %{ $self->maybe::next::method || {} },
64   };
65 }
66
67 # *DO NOT* change this URL nor the identically named =head1 below
68 # it is linked throughout the ecosystem
69 sub DBIx::Class::_ENV_::HELP_URL () {
70   'http://p3rl.org/DBIx::Class#GETTING_HELP/SUPPORT'
71 }
72
73 1;
74
75 __END__
76
77 =head1 NAME
78
79 DBIx::Class - Extensible and flexible object <-> relational mapper.
80
81 =head1 WHERE TO START READING
82
83 See L<DBIx::Class::Manual::DocMap> for an overview of the exhaustive documentation.
84 To get the most out of DBIx::Class with the least confusion it is strongly
85 recommended to read (at the very least) the
86 L<Manuals|DBIx::Class::Manual::DocMap/Manuals> in the order presented there.
87
88 =cut
89
90 =head1 GETTING HELP/SUPPORT
91
92 Due to the sheer size of its problem domain, DBIx::Class is a relatively
93 complex framework. After you start using DBIx::Class questions will inevitably
94 arise. If you are stuck with a problem or have doubts about a particular
95 approach do not hesitate to contact us via any of the following options (the
96 list is sorted by "fastest response time"):
97
98 =over
99
100 =item * IRC: irc.perl.org#dbix-class
101
102 =for html
103 <a href="https://chat.mibbit.com/#dbix-class@irc.perl.org">(click for instant chatroom login)</a>
104
105 =item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
106
107 =item * RT Bug Tracker: L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=DBIx-Class>
108
109 =item * Twitter: L<https://www.twitter.com/dbix_class>
110
111 =item * Web Site: L<http://www.dbix-class.org/>
112
113 =back
114
115 =head1 SYNOPSIS
116
117 For the very impatient: L<DBIx::Class::Manual::QuickStart>
118
119 This code in the next step can be generated automatically from an existing
120 database, see L<dbicdump> from the distribution C<DBIx-Class-Schema-Loader>.
121
122 =head2 Schema classes preparation
123
124 Create a schema class called F<MyApp/Schema.pm>:
125
126   package MyApp::Schema;
127   use base qw/DBIx::Class::Schema/;
128
129   __PACKAGE__->load_namespaces();
130
131   1;
132
133 Create a result class to represent artists, who have many CDs, in
134 F<MyApp/Schema/Result/Artist.pm>:
135
136 See L<DBIx::Class::ResultSource> for docs on defining result classes.
137
138   package MyApp::Schema::Result::Artist;
139   use base qw/DBIx::Class::Core/;
140
141   __PACKAGE__->table('artist');
142   __PACKAGE__->add_columns(qw/ artistid name /);
143   __PACKAGE__->set_primary_key('artistid');
144   __PACKAGE__->has_many(cds => 'MyApp::Schema::Result::CD', 'artistid');
145
146   1;
147
148 A result class to represent a CD, which belongs to an artist, in
149 F<MyApp/Schema/Result/CD.pm>:
150
151   package MyApp::Schema::Result::CD;
152   use base qw/DBIx::Class::Core/;
153
154   __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
155   __PACKAGE__->table('cd');
156   __PACKAGE__->add_columns(qw/ cdid artistid title year /);
157   __PACKAGE__->set_primary_key('cdid');
158   __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Result::Artist', 'artistid');
159
160   1;
161
162 =head2 API usage
163
164 Then you can use these classes in your application's code:
165
166   # Connect to your database.
167   use MyApp::Schema;
168   my $schema = MyApp::Schema->connect($dbi_dsn, $user, $pass, \%dbi_params);
169
170   # Query for all artists and put them in an array,
171   # or retrieve them as a result set object.
172   # $schema->resultset returns a DBIx::Class::ResultSet
173   my @all_artists = $schema->resultset('Artist')->all;
174   my $all_artists_rs = $schema->resultset('Artist');
175
176   # Output all artists names
177   # $artist here is a DBIx::Class::Row, which has accessors
178   # for all its columns. Rows are also subclasses of your Result class.
179   foreach $artist (@all_artists) {
180     print $artist->name, "\n";
181   }
182
183   # Create a result set to search for artists.
184   # This does not query the DB.
185   my $johns_rs = $schema->resultset('Artist')->search(
186     # Build your WHERE using an SQL::Abstract structure:
187     { name => { like => 'John%' } }
188   );
189
190   # Execute a joined query to get the cds.
191   my @all_john_cds = $johns_rs->search_related('cds')->all;
192
193   # Fetch the next available row.
194   my $first_john = $johns_rs->next;
195
196   # Specify ORDER BY on the query.
197   my $first_john_cds_by_title_rs = $first_john->cds(
198     undef,
199     { order_by => 'title' }
200   );
201
202   # Create a result set that will fetch the artist data
203   # at the same time as it fetches CDs, using only one query.
204   my $millennium_cds_rs = $schema->resultset('CD')->search(
205     { year => 2000 },
206     { prefetch => 'artist' }
207   );
208
209   my $cd = $millennium_cds_rs->next; # SELECT ... FROM cds JOIN artists ...
210   my $cd_artist_name = $cd->artist->name; # Already has the data so no 2nd query
211
212   # new() makes a Result object but doesn't insert it into the DB.
213   # create() is the same as new() then insert().
214   my $new_cd = $schema->resultset('CD')->new({ title => 'Spoon' });
215   $new_cd->artist($cd->artist);
216   $new_cd->insert; # Auto-increment primary key filled in after INSERT
217   $new_cd->title('Fork');
218
219   $schema->txn_do(sub { $new_cd->update }); # Runs the update in a transaction
220
221   # change the year of all the millennium CDs at once
222   $millennium_cds_rs->update({ year => 2002 });
223
224 =head1 DESCRIPTION
225
226 This is an SQL to OO mapper with an object API inspired by L<Class::DBI>
227 (with a compatibility layer as a springboard for porting) and a resultset API
228 that allows abstract encapsulation of database operations. It aims to make
229 representing queries in your code as perl-ish as possible while still
230 providing access to as many of the capabilities of the database as possible,
231 including retrieving related records from multiple tables in a single query,
232 C<JOIN>, C<LEFT JOIN>, C<COUNT>, C<DISTINCT>, C<GROUP BY>, C<ORDER BY> and
233 C<HAVING> support.
234
235 DBIx::Class can handle multi-column primary and foreign keys, complex
236 queries and database-level paging, and does its best to only query the
237 database in order to return something you've directly asked for. If a
238 resultset is used as an iterator it only fetches rows off the statement
239 handle as requested in order to minimise memory usage. It has auto-increment
240 support for SQLite, MySQL, PostgreSQL, Oracle, SQL Server and DB2 and is
241 known to be used in production on at least the first four, and is fork-
242 and thread-safe out of the box (although
243 L<your DBD may not be|DBI/Threads and Thread Safety>).
244
245 This project is still under rapid development, so large new features may be
246 marked B<experimental> - such APIs are still usable but may have edge bugs.
247 Failing test cases are I<always> welcome and point releases are put out rapidly
248 as bugs are found and fixed.
249
250 We do our best to maintain full backwards compatibility for published
251 APIs, since DBIx::Class is used in production in many organisations,
252 and even backwards incompatible changes to non-published APIs will be fixed
253 if they're reported and doing so doesn't cost the codebase anything.
254
255 The test suite is quite substantial, and several developer releases
256 are generally made to CPAN before the branch for the next release is
257 merged back to trunk for a major release.
258
259 =head1 HOW TO CONTRIBUTE
260
261 Contributions are always welcome, in all usable forms (we especially
262 welcome documentation improvements). The delivery methods include git-
263 or unified-diff formatted patches, GitHub pull requests, or plain bug
264 reports either via RT or the Mailing list. Contributors are generally
265 granted access to the official repository after their first several
266 patches pass successful review. Don't hesitate to
267 L<contact|/GETTING HELP/SUPPORT> either of the L</CAT HERDERS> with
268 any further questions you may have.
269
270 =for comment
271 FIXME: Getty, frew and jnap need to get off their asses and finish the contrib section so we can link it here ;)
272
273 This project is maintained in a git repository. The code and related tools are
274 accessible at the following locations:
275
276 =over
277
278 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
279
280 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
281
282 =item * GitHub mirror: L<https://github.com/dbsrgits/DBIx-Class>
283
284 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/DBIx-Class.git>
285
286 =item * Travis-CI log: L<https://travis-ci.org/dbsrgits/dbix-class/builds>
287
288 =back
289
290 =head1 AUTHORS
291
292 Even though a large portion of the source I<appears> to be written by just a
293 handful of people, this library continues to remain a collaborative effort -
294 perhaps one of the most successful such projects on L<CPAN|http://cpan.org>.
295 It is important to remember that ideas do not always result in a direct code
296 contribution, but deserve acknowledgement just the same. Time and time again
297 the seemingly most insignificant questions and suggestions have been shown
298 to catalyze monumental improvements in consistency, accuracy and performance.
299
300 =for comment this line is replaced with the author list at dist-building time
301
302 The canonical source of authors and their details is the F<AUTHORS> file at
303 the root of this distribution (or repository). The canonical source of
304 per-line authorship is the L<git repository|/HOW TO CONTRIBUTE> history
305 itself.
306
307 =head1 CAT HERDERS
308
309 The fine folks nudging the project in a particular direction:
310
311 =over
312
313 B<ribasushi>: Peter Rabbitson <ribasushi@cpan.org>
314 (present day maintenance and controlled evolution)
315
316 B<castaway>: Jess Robinson <castaway@desert-island.me.uk>
317 (lions share of the reference documentation and manuals)
318
319 B<mst>: Matt S Trout <mst@shadowcat.co.uk> (project founder -
320 original idea, architecture and implementation)
321
322 =back
323
324 =head1 COPYRIGHT AND LICENSE
325
326 Copyright (c) 2005 by mst, castaway, ribasushi, and other DBIx::Class
327 L</AUTHORS> as listed above and in F<AUTHORS>.
328
329 This library is free software and may be distributed under the same terms
330 as perl5 itself. See F<LICENSE> for the complete licensing terms.