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