Expand the c3 mro test from d009cb7d
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class.pm
CommitLineData
ea2e61bf 1package DBIx::Class;
2
95b76469 3# important to load early
4use DBIx::Class::_Util;
5
5d283305 6use strict;
7use warnings;
8
f9cc85ce 9our $VERSION;
10# Always remember to do all digits for the version even if they're 0
11# i.e. first release of 0.XX *must* be 0.XX000. This avoids fBSD ports
12# brain damage and presumably various other packaging systems too
13
14# $VERSION declaration must stay up here, ahead of any other package
15# declarations, as to not confuse various modules attempting to determine
16# this ones version, whether that be s.c.o. or Module::Metadata, etc
c6b73be9 17$VERSION = '0.082899_15';
f9cc85ce 18
19$VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
20
d38cd95c 21use mro 'c3';
329d7385 22
db29433c 23use base qw/DBIx::Class::Componentised DBIx::Class::AccessorGroup/;
f9080e45 24use DBIx::Class::Exception;
3e110410 25
7bd921c0 26use DBIx::Class::_Util qw( uniq refdesc visit_namespaces );
27use Scalar::Util qw( weaken refaddr );
28use namespace::clean;
29
70c28808 30__PACKAGE__->mk_group_accessors(inherited => '_skip_namespace_frames');
8b60b921 31__PACKAGE__->_skip_namespace_frames('^DBIx::Class|^SQL::Abstract|^Try::Tiny|^Class::Accessor::Grouped|^Context::Preserve|^Moose::Meta::');
70c28808 32
e1d9e578 33# FIXME - this is not really necessary, and is in
34# fact going to slow things down a bit
35# However it is the right thing to do in order to get
36# various install bases to highlight their brokenness
37# Remove at some unknown point in the future
5f74ed3a 38#
39# The oddball BEGIN is there for... reason unknown
40# It does make non-segfaulty difference on pre-5.8.5 perls, so shrug
41BEGIN {
42 sub DESTROY { &DBIx::Class::_Util::detected_reinvoked_destructor };
43}
e1d9e578 44
d009cb7d 45sub component_base_class { 'DBIx::Class' }
77d518d1 46
7bd921c0 47
48my $cref_registry;
49sub DBIx::Class::__Attr_iThreads_handler__::CLONE {
50
51 # this is disgusting, but the best we can do without even more surgery
52 visit_namespaces( action => sub {
53 my $pkg = shift;
54
55 # skip dangerous namespaces
56 return 1 if $pkg =~ /^ (?:
57 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
58 ) $/x;
59
60 no strict 'refs';
61
62 if (
63 exists ${"${pkg}::"}{__cag___attr_cache}
64 and
65 ref( my $attr_stash = ${"${pkg}::__cag___attr_cache"} ) eq 'HASH'
66 ) {
67 $attr_stash->{ $cref_registry->{$_} } = delete $attr_stash->{$_}
68 for keys %$attr_stash;
69 }
70
71 return 1;
72 })
73}
74
f0750722 75sub MODIFY_CODE_ATTRIBUTES {
b5d2c57f 76 my ($class,$code,@attrs) = @_;
e5053694 77 $class->mk_classaccessor('__attr_cache' => {})
b5d2c57f 78 unless $class->can('__attr_cache');
7bd921c0 79
80 # compaction step
81 defined $cref_registry->{$_} or delete $cref_registry->{$_}
82 for keys %$cref_registry;
83
84 # The original API used stringification instead of refaddr - can't change that now
85 if( $cref_registry->{$code} ) {
86 Carp::confess( sprintf
87 "Coderefs '%s' and '%s' stringify to the same value '%s': nothing will work",
88 refdesc($code),
89 refdesc($cref_registry->{$code}),
90 "$code"
91 ) if refaddr($cref_registry->{$code}) != refaddr($code);
92 }
93 else {
94 weaken( $cref_registry->{$code} = $code )
95 }
96
97 $class->__attr_cache->{$code} = [ sort( uniq(
98 @{ $class->__attr_cache->{$code} || [] },
99 @attrs,
100 ))];
101
102 # FIXME - DBIC essentially gobbles up any attribute it can lay its hands on:
103 # decidedly not cool
104 #
105 # There should be some sort of warning on unrecognized attributes or
106 # somesuch... OTOH people do use things in the wild hence the plan of action
107 # is anything but clear :/
108 #
109 # https://metacpan.org/source/ZIGOROU/DBIx-Class-Service-0.02/lib/DBIx/Class/Service.pm#L93-110
110 # https://metacpan.org/source/ZIGOROU/DBIx-Class-Service-0.02/t/lib/DBIC/Test/Service/User.pm#L29
111 # https://metacpan.org/source/ZIGOROU/DBIx-Class-Service-0.02/t/lib/DBIC/Test/Service/User.pm#L36
112 #
b5d2c57f 113 return ();
f0750722 114}
115
140bcb6a 116sub FETCH_CODE_ATTRIBUTES {
117 my ($class,$code) = @_;
118 @{ $class->_attr_cache->{$code} || [] }
119}
120
da95b45f 121sub _attr_cache {
b5d2c57f 122 my $self = shift;
7bd921c0 123 +{
124 %{ $self->can('__attr_cache') ? $self->__attr_cache : {} },
9780718f 125 %{ $self->maybe::next::method || {} },
20674fcd 126 };
da95b45f 127}
128
d095c62d 129# *DO NOT* change this URL nor the identically named =head1 below
130# it is linked throughout the ecosystem
131sub DBIx::Class::_ENV_::HELP_URL () {
132 'http://p3rl.org/DBIx::Class#GETTING_HELP/SUPPORT'
133}
134
ea2e61bf 1351;
34d52be2 136
d095c62d 137__END__
138
75d07914 139=head1 NAME
34d52be2 140
7e4b2f59 141DBIx::Class - Extensible and flexible object <-> relational mapper.
34d52be2 142
06752a03 143=head1 WHERE TO START READING
3b1c2bbd 144
06752a03 145See L<DBIx::Class::Manual::DocMap> for an overview of the exhaustive documentation.
146To get the most out of DBIx::Class with the least confusion it is strongly
147recommended to read (at the very least) the
148L<Manuals|DBIx::Class::Manual::DocMap/Manuals> in the order presented there.
149
32250d01 150=cut
151
32250d01 152=head1 GETTING HELP/SUPPORT
06752a03 153
32250d01 154Due to the sheer size of its problem domain, DBIx::Class is a relatively
06752a03 155complex framework. After you start using DBIx::Class questions will inevitably
156arise. If you are stuck with a problem or have doubts about a particular
32250d01 157approach do not hesitate to contact us via any of the following options (the
158list is sorted by "fastest response time"):
3b1c2bbd 159
a06e1181 160=over
3b1c2bbd 161
c6fdaf2a 162=item * IRC: irc.perl.org#dbix-class
163
164=for html
e1ddfc8a 165<a href="https://chat.mibbit.com/#dbix-class@irc.perl.org">(click for instant chatroom login)</a>
3b1c2bbd 166
a06e1181 167=item * Mailing list: L<http://lists.scsys.co.uk/mailman/listinfo/dbix-class>
3b1c2bbd 168
e1ddfc8a 169=item * RT Bug Tracker: L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=DBIx-Class>
86a23587 170
e1ddfc8a 171=item * Twitter: L<https://www.twitter.com/dbix_class>
86a23587 172
86a23587 173=item * Web Site: L<http://www.dbix-class.org/>
a06e1181 174
86a23587 175=back
176
34d52be2 177=head1 SYNOPSIS
178
113e8d16 179For the very impatient: L<DBIx::Class::Manual::QuickStart>
180
181This code in the next step can be generated automatically from an existing
182database, see L<dbicdump> from the distribution C<DBIx-Class-Schema-Loader>.
183
5b56d1ac 184=head2 Schema classes preparation
185
53aa53f3 186Create a schema class called F<MyApp/Schema.pm>:
34d52be2 187
03460bef 188 package MyApp::Schema;
a0638a7b 189 use base qw/DBIx::Class::Schema/;
34d52be2 190
f0bb26f3 191 __PACKAGE__->load_namespaces();
daec44b8 192
a0638a7b 193 1;
daec44b8 194
30e1753a 195Create a result class to represent artists, who have many CDs, in
53aa53f3 196F<MyApp/Schema/Result/Artist.pm>:
daec44b8 197
30e1753a 198See L<DBIx::Class::ResultSource> for docs on defining result classes.
199
03460bef 200 package MyApp::Schema::Result::Artist;
d88ecca6 201 use base qw/DBIx::Class::Core/;
daec44b8 202
a0638a7b 203 __PACKAGE__->table('artist');
204 __PACKAGE__->add_columns(qw/ artistid name /);
205 __PACKAGE__->set_primary_key('artistid');
326dacbf 206 __PACKAGE__->has_many(cds => 'MyApp::Schema::Result::CD', 'artistid');
daec44b8 207
a0638a7b 208 1;
daec44b8 209
30e1753a 210A result class to represent a CD, which belongs to an artist, in
53aa53f3 211F<MyApp/Schema/Result/CD.pm>:
39fe0e65 212
03460bef 213 package MyApp::Schema::Result::CD;
d88ecca6 214 use base qw/DBIx::Class::Core/;
39fe0e65 215
d88ecca6 216 __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
a0638a7b 217 __PACKAGE__->table('cd');
bd077b47 218 __PACKAGE__->add_columns(qw/ cdid artistid title year /);
a0638a7b 219 __PACKAGE__->set_primary_key('cdid');
03460bef 220 __PACKAGE__->belongs_to(artist => 'MyApp::Schema::Result::Artist', 'artistid');
39fe0e65 221
a0638a7b 222 1;
39fe0e65 223
5b56d1ac 224=head2 API usage
225
a0638a7b 226Then you can use these classes in your application's code:
39fe0e65 227
a0638a7b 228 # Connect to your database.
03460bef 229 use MyApp::Schema;
230 my $schema = MyApp::Schema->connect($dbi_dsn, $user, $pass, \%dbi_params);
a0638a7b 231
232 # Query for all artists and put them in an array,
233 # or retrieve them as a result set object.
30e1753a 234 # $schema->resultset returns a DBIx::Class::ResultSet
2053ab2a 235 my @all_artists = $schema->resultset('Artist')->all;
236 my $all_artists_rs = $schema->resultset('Artist');
126042ee 237
30e1753a 238 # Output all artists names
4e8ffded 239 # $artist here is a DBIx::Class::Row, which has accessors
16ccb4fe 240 # for all its columns. Rows are also subclasses of your Result class.
85067746 241 foreach $artist (@all_artists) {
30e1753a 242 print $artist->name, "\n";
243 }
244
a0638a7b 245 # Create a result set to search for artists.
86beca1d 246 # This does not query the DB.
2053ab2a 247 my $johns_rs = $schema->resultset('Artist')->search(
6576ef54 248 # Build your WHERE using an SQL::Abstract structure:
2053ab2a 249 { name => { like => 'John%' } }
a0638a7b 250 );
39fe0e65 251
2053ab2a 252 # Execute a joined query to get the cds.
a0638a7b 253 my @all_john_cds = $johns_rs->search_related('cds')->all;
448c8424 254
f0bb26f3 255 # Fetch the next available row.
a0638a7b 256 my $first_john = $johns_rs->next;
448c8424 257
2053ab2a 258 # Specify ORDER BY on the query.
a0638a7b 259 my $first_john_cds_by_title_rs = $first_john->cds(
260 undef,
261 { order_by => 'title' }
262 );
448c8424 263
bd077b47 264 # Create a result set that will fetch the artist data
2053ab2a 265 # at the same time as it fetches CDs, using only one query.
884559b1 266 my $millennium_cds_rs = $schema->resultset('CD')->search(
a0638a7b 267 { year => 2000 },
268 { prefetch => 'artist' }
269 );
448c8424 270
880a1a0c 271 my $cd = $millennium_cds_rs->next; # SELECT ... FROM cds JOIN artists ...
bd077b47 272 my $cd_artist_name = $cd->artist->name; # Already has the data so no 2nd query
076652e8 273
4b0a90fd 274 # new() makes a Result object but doesn't insert it into the DB.
264f1571 275 # create() is the same as new() then insert().
884559b1 276 my $new_cd = $schema->resultset('CD')->new({ title => 'Spoon' });
f183eccd 277 $new_cd->artist($cd->artist);
f183eccd 278 $new_cd->insert; # Auto-increment primary key filled in after INSERT
f183eccd 279 $new_cd->title('Fork');
280
884559b1 281 $schema->txn_do(sub { $new_cd->update }); # Runs the update in a transaction
f183eccd 282
bd077b47 283 # change the year of all the millennium CDs at once
284 $millennium_cds_rs->update({ year => 2002 });
f183eccd 285
286=head1 DESCRIPTION
287
288This is an SQL to OO mapper with an object API inspired by L<Class::DBI>
bd077b47 289(with a compatibility layer as a springboard for porting) and a resultset API
f183eccd 290that allows abstract encapsulation of database operations. It aims to make
291representing queries in your code as perl-ish as possible while still
a0638a7b 292providing access to as many of the capabilities of the database as possible,
f183eccd 293including retrieving related records from multiple tables in a single query,
53aa53f3 294C<JOIN>, C<LEFT JOIN>, C<COUNT>, C<DISTINCT>, C<GROUP BY>, C<ORDER BY> and
295C<HAVING> support.
f183eccd 296
297DBIx::Class can handle multi-column primary and foreign keys, complex
298queries and database-level paging, and does its best to only query the
75d07914 299database in order to return something you've directly asked for. If a
300resultset is used as an iterator it only fetches rows off the statement
301handle as requested in order to minimise memory usage. It has auto-increment
2053ab2a 302support for SQLite, MySQL, PostgreSQL, Oracle, SQL Server and DB2 and is
303known to be used in production on at least the first four, and is fork-
ec6415a9 304and thread-safe out of the box (although
9361b05d 305L<your DBD may not be|DBI/Threads and Thread Safety>).
f183eccd 306
dfccde48 307This project is still under rapid development, so large new features may be
53aa53f3 308marked B<experimental> - such APIs are still usable but may have edge bugs.
309Failing test cases are I<always> welcome and point releases are put out rapidly
dfccde48 310as bugs are found and fixed.
311
312We do our best to maintain full backwards compatibility for published
313APIs, since DBIx::Class is used in production in many organisations,
314and even backwards incompatible changes to non-published APIs will be fixed
315if they're reported and doing so doesn't cost the codebase anything.
316
264f1571 317The test suite is quite substantial, and several developer releases
318are generally made to CPAN before the branch for the next release is
319merged back to trunk for a major release.
f183eccd 320
6ed05cfd 321=head1 HOW TO CONTRIBUTE
322
323Contributions are always welcome, in all usable forms (we especially
324welcome documentation improvements). The delivery methods include git-
325or unified-diff formatted patches, GitHub pull requests, or plain bug
326reports either via RT or the Mailing list. Contributors are generally
cb32addc 327granted access to the official repository after their first several
328patches pass successful review. Don't hesitate to
329L<contact|/GETTING HELP/SUPPORT> either of the L</CAT HERDERS> with
330any further questions you may have.
6ed05cfd 331
332=for comment
333FIXME: Getty, frew and jnap need to get off their asses and finish the contrib section so we can link it here ;)
334
335This project is maintained in a git repository. The code and related tools are
336accessible at the following locations:
337
338=over
339
340=item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
341
342=item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
343
344=item * GitHub mirror: L<https://github.com/dbsrgits/DBIx-Class>
345
346=item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/DBIx-Class.git>
347
348=item * Travis-CI log: L<https://travis-ci.org/dbsrgits/dbix-class/builds>
349
350=for html
33d0570d 351&#x21AA; Bleeding edge dev CI status: <img src="https://secure.travis-ci.org/dbsrgits/dbix-class.png?branch=master"></img>
6ed05cfd 352
353=back
354
3440100b 355=head1 AUTHORS
34d52be2 356
3440100b 357Even though a large portion of the source I<appears> to be written by just a
358handful of people, this library continues to remain a collaborative effort -
359perhaps one of the most successful such projects on L<CPAN|http://cpan.org>.
360It is important to remember that ideas do not always result in a direct code
361contribution, but deserve acknowledgement just the same. Time and time again
362the seemingly most insignificant questions and suggestions have been shown
363to catalyze monumental improvements in consistency, accuracy and performance.
34d52be2 364
3440100b 365=for comment this line is replaced with the author list at dist-building time
dfccde48 366
3440100b 367The canonical source of authors and their details is the F<AUTHORS> file at
368the root of this distribution (or repository). The canonical source of
369per-line authorship is the L<git repository|/HOW TO CONTRIBUTE> history
370itself.
f9139687 371
cb32addc 372=head1 CAT HERDERS
373
374The fine folks nudging the project in a particular direction:
375
376=over
377
f06eb015 378B<ribasushi>: Peter Rabbitson <ribasushi@cpan.org>
cb32addc 379(present day maintenance and controlled evolution)
380
f06eb015 381B<castaway>: Jess Robinson <castaway@desert-island.me.uk>
cb32addc 382(lions share of the reference documentation and manuals)
383
f06eb015 384B<mst>: Matt S Trout <mst@shadowcat.co.uk> (project founder -
cb32addc 385original idea, architecture and implementation)
386
387=back
388
a2bd3796 389=head1 COPYRIGHT AND LICENSE
b38e10bd 390
a2bd3796 391Copyright (c) 2005 by mst, castaway, ribasushi, and other DBIx::Class
392L</AUTHORS> as listed above and in F<AUTHORS>.
96154ef7 393
394This library is free software and may be distributed under the same terms
a2bd3796 395as perl5 itself. See F<LICENSE> for the complete licensing terms.