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