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