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