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