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