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