cd8b0917a461106299c956835a3d2ca3603a165e
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / Intro.pod
1 =head1 NAME
2
3 DBIx::Class::Manual::Intro - Introduction to DBIx::Class
4
5 =head1 INTRODUCTION
6
7 You're bored with SQL, and want a native Perl interface for your database?  Or
8 you've been doing this for a while with L<Class::DBI>, and think there's a
9 better way?  You've come to the right place.
10
11 =head1 THE DBIx::Class WAY
12
13 Here are a few simple tips that will help you get your bearings with
14 DBIx::Class.
15
16 =head2 Tables become Result classes
17
18 DBIx::Class needs to know what your Table structure looks like.  You
19 do that by defining Result classes. Result classes are defined by
20 calling methods proxied to L<DBIx::Class::ResultSource>.  Each Result
21 class defines one Table, which defines the Columns it has, along with
22 any Relationships it has to other tables.  (And oh, so much more
23 besides) The important thing to understand:
24
25   A Result class == Table
26
27 (most of the time, but just bear with my simplification)
28
29 =head2 It's all about the ResultSet
30
31 So, we've got some ResultSources defined.  Now, we want to actually use those
32 definitions to help us translate the queries we need into handy perl objects!
33
34 Let's say we defined a ResultSource for an "album" table with three columns:
35 "albumid", "artist", and "title".  Any time we want to query this table, we'll
36 be creating a L<DBIx::Class::ResultSet> from its ResultSource.  For example, the
37 results of:
38
39   SELECT albumid, artist, title FROM album;
40
41 Would be retrieved by creating a ResultSet object from the album table's
42 ResultSource, likely by using the "search" method.
43
44 DBIx::Class doesn't limit you to creating only simple ResultSets -- if you
45 wanted to do something like:
46
47   SELECT title FROM album GROUP BY title;
48
49 You could easily achieve it.
50
51 The important thing to understand:
52
53   Any time you would reach for a SQL query in DBI, you are
54   creating a DBIx::Class::ResultSet.
55
56 =head2 Search is like "prepare"
57
58 DBIx::Class tends to wait until it absolutely must fetch information from the
59 database.  If you are returning a ResultSet, the query won't execute until you
60 use a method that wants to access the data. (Such as "next", or "first")
61
62 The important thing to understand:
63
64   Setting up a ResultSet does not execute the query; retrieving
65   the data does.
66
67 =head2 Search results are returned as Rows
68
69 Rows of the search from the database are blessed into
70 L<DBIx::Class::Row> objects.
71
72 =head1 SETTING UP DBIx::Class
73
74 Let's look at how you can set and use your first native L<DBIx::Class> tree.
75
76 First we'll see how you can set up your classes yourself.  If you want them to
77 be auto-discovered, just skip to the next section, which shows you how to use
78 L<DBIx::Class::Schema::Loader>.
79
80 =head2 Setting it up manually
81
82 First, you should create your base schema class, which inherits from
83 L<DBIx::Class::Schema>:
84
85   package My::Schema;
86   use base qw/DBIx::Class::Schema/;
87
88 In this class you load your result_source ("table", "model") classes, which we
89 will define later, using the load_namespaces() method:
90
91   # load My::Schema::Result::* and their resultset classes
92   __PACKAGE__->load_namespaces();
93
94 By default this loads all the Result (Row) classes in the
95 My::Schema::Result:: namespace, and also any resultset classes in the
96 My::Schema::ResultSet:: namespace (if missing, the resultsets are
97 defaulted to be DBIx::Class::ResultSet objects). You can change the
98 result and resultset namespaces by using options to the
99 L<DBIx::Class::Schema/load_namespaces> call.
100
101 It is also possible to do the same things manually by calling
102 C<load_classes> for the Row classes and defining in those classes any
103 required resultset classes.
104
105 Next, create each of the classes you want to load as specified above:
106
107   package My::Schema::Result::Album;
108   use base qw/DBIx::Class::Core/;
109
110 Load any additional components you may need with the load_components() method,
111 and provide component configuration if required. For example, if you want
112 automatic row ordering:
113
114   __PACKAGE__->load_components(qw/ Ordered /);
115   __PACKAGE__->position_column('rank');
116
117 Ordered will refer to a field called 'position' unless otherwise directed.  Here you are defining
118 the ordering field to be named 'rank'.  (NOTE: Insert errors may occur if you use the Ordered 
119 component, but have not defined a position column or have a 'position' field in your row.)
120
121 Set the table for your class:
122
123   __PACKAGE__->table('album');
124
125 Add columns to your class:
126
127   __PACKAGE__->add_columns(qw/ albumid artist title rank /);
128
129 Each column can also be set up with its own accessor, data_type and other pieces
130 of information that it may be useful to have -- just pass C<add_columns> a hash:
131
132   __PACKAGE__->add_columns(albumid =>
133                             { accessor  => 'album',
134                               data_type => 'integer',
135                               size      => 16,
136                               is_nullable => 0,
137                               is_auto_increment => 1,
138                               default_value => '',
139                             },
140                           artist =>
141                             { data_type => 'integer',
142                               size      => 16,
143                               is_nullable => 0,
144                               is_auto_increment => 0,
145                               default_value => '',
146                             },
147                           title  =>
148                             { data_type => 'varchar',
149                               size      => 256,
150                               is_nullable => 0,
151                               is_auto_increment => 0,
152                               default_value => '',
153                             },
154                           rank =>
155                             { data_type => 'integer',
156                               size      => 16,
157                               is_nullable => 0,
158                               is_auto_increment => 0,
159                               default_value => '',
160                             }
161                          );
162
163 DBIx::Class doesn't directly use most of this data yet, but various related
164 modules such as L<DBIx::Class::WebForm> make use of it. Also it allows you to
165 create your database tables from your Schema, instead of the other way around.
166 See L<DBIx::Class::Schema/deploy> for details.
167
168 See L<DBIx::Class::ResultSource> for more details of the possible column
169 attributes.
170
171 Accessors are created for each column automatically, so My::Schema::Result::Album will
172 have albumid() (or album(), when using the accessor), artist() and title()
173 methods.
174
175 Define a primary key for your class:
176
177   __PACKAGE__->set_primary_key('albumid');
178
179 If you have a multi-column primary key, just pass a list instead:
180
181   __PACKAGE__->set_primary_key( qw/ albumid artistid / );
182
183 Define this class' relationships with other classes using either C<belongs_to>
184 to describe a column which contains an ID of another Table, or C<has_many> to
185 make a predefined accessor for fetching objects that contain this Table's
186 foreign key:
187
188   # in My::Schema::Result::Artist
189   __PACKAGE__->has_many('albums', 'My::Schema::Result::Album', 'artist');
190
191 See L<DBIx::Class::Relationship> for more information about the various types of
192 available relationships and how you can design your own.
193
194 =head2 Using L<DBIx::Class::Schema::Loader>
195
196 This is an external module, and not part of the L<DBIx::Class> distribution.
197 Like L<Class::DBI::Loader>, it inspects your database, and automatically creates
198 classes for all the tables in your database.  Here's a simple setup:
199
200   package My::Schema;
201   use base qw/DBIx::Class::Schema::Loader/;
202
203   __PACKAGE__->loader_options( relationships => 1 );
204
205   1;
206
207 The actual autoloading process will occur when you create a connected instance
208 of your schema below.
209
210 See the L<DBIx::Class::Schema::Loader> documentation for more information on its
211 many options.
212
213 =head2 Connecting
214
215 To connect to your Schema, you need to provide the connection details or a
216 database handle.
217
218 =head3 Via connection details
219
220 The arguments are the same as for L<DBI/connect>:
221
222   my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
223
224 You can create as many different schema instances as you need. So if you have a
225 second database you want to access:
226
227   my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
228
229 Note that L<DBIx::Class::Schema> does not cache connections for you. If you use
230 multiple connections, you need to do this manually.
231
232 To execute some SQL statements on every connect you can add them as an option in
233 a special fifth argument to connect:
234
235   my $another_schema = My::Schema->connect(
236       $dsn,
237       $user,
238       $password,
239       $attrs,
240       { on_connect_do => \@on_connect_sql_statments }
241   );
242
243 See L<DBIx::Class::Storage::DBI/connect_info> for more information about
244 this and other special C<connect>-time options.
245
246 =head3 Via a database handle
247
248 The supplied coderef is expected to return a single connected database handle
249 (e.g. a L<DBI> C<$dbh>)
250
251   my $schema = My::Schema->connect (
252     sub { Some::DBH::Factory->connect },
253     \%extra_attrs,
254   );
255
256 =head2 Basic usage
257
258 Once you've defined the basic classes, either manually or using
259 L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
260
261 To access your database using your $schema object, you can fetch a
262 L<DBIx::Class::Manual::Glossary/"ResultSet"> representing each of your tables by
263 calling the C<resultset> method.
264
265 The simplest way to get a record is by primary key:
266
267   my $album = $schema->resultset('Album')->find(14);
268
269 This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause, and
270 return an instance of C<My::Schema::Result::Album> that represents this row.  Once you
271 have that row, you can access and update columns:
272
273   $album->title('Physical Graffiti');
274   my $title = $album->title; # $title holds 'Physical Graffiti'
275
276 If you prefer, you can use the C<set_column> and C<get_column> accessors
277 instead:
278
279   $album->set_column('title', 'Presence');
280   $title = $album->get_column('title');
281
282 Just like with L<Class::DBI>, you call C<update> to save your changes to the
283 database (by executing the actual C<UPDATE> statement):
284
285   $album->update;
286
287 If needed, you can throw away your local changes:
288
289   $album->discard_changes if $album->is_changed;
290
291 As you can see, C<is_changed> allows you to check if there are local changes to
292 your object.
293
294 =head2 Adding and removing rows
295
296 To create a new record in the database, you can use the C<create> method.  It
297 returns an instance of C<My::Schema::Result::Album> that can be used to access the data
298 in the new record:
299
300   my $new_album = $schema->resultset('Album')->create({
301     title  => 'Wish You Were Here',
302     artist => 'Pink Floyd'
303   });
304
305 Now you can add data to the new record:
306
307   $new_album->label('Capitol');
308   $new_album->year('1975');
309   $new_album->update;
310
311 Likewise, you can remove it from the database:
312
313   $new_album->delete;
314
315 You can also remove records without retrieving them first, by calling delete
316 directly on a ResultSet object.
317
318   # Delete all of Falco's albums
319   $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
320
321 =head2 Finding your objects
322
323 L<DBIx::Class> provides a few different ways to retrieve data from your
324 database.  Here's one example:
325
326   # Find all of Santana's albums
327   my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
328
329 In scalar context, as above, C<search> returns a L<DBIx::Class::ResultSet>
330 object.  It can be used to peek at the first album returned by the database:
331
332   my $album = $rs->first;
333   print $album->title;
334
335 You can loop over the albums and update each one:
336
337   while (my $album = $rs->next) {
338     print $album->artist . ' - ' . $album->title;
339     $album->year(2001);
340     $album->update;
341   }
342
343 Or, you can update them all at once:
344
345   $rs->update({ year => 2001 });
346
347 In list context, the C<search> method returns all of the matching rows:
348
349   # Fetch immediately all of Carlos Santana's albums
350   my @albums = $schema->resultset('Album')->search(
351     { artist => 'Carlos Santana' }
352   );
353   foreach my $album (@albums) {
354     print $album->artist . ' - ' . $album->title;
355   }
356
357 We also provide a handy shortcut for doing a C<LIKE> search:
358
359   # Find albums whose artist starts with 'Jimi'
360   my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
361
362 Or you can provide your own C<WHERE> clause:
363
364   # Find Peter Frampton albums from the year 1986
365   my $where = 'artist = ? AND year = ?';
366   my @bind  = ( 'Peter Frampton', 1986 );
367   my $rs    = $schema->resultset('Album')->search_literal( $where, @bind );
368
369 The preferred way to generate complex queries is to provide a L<SQL::Abstract>
370 construct to C<search>:
371
372   my $rs = $schema->resultset('Album')->search({
373     artist  => { '!=', 'Janis Joplin' },
374     year    => { '<' => 1980 },
375     albumid => { '-in' => [ 1, 14, 15, 65, 43 ] }
376   });
377
378 This results in something like the following C<WHERE> clause:
379
380   WHERE artist != 'Janis Joplin'
381     AND year < 1980
382     AND albumid IN (1, 14, 15, 65, 43)
383
384 For more examples of complex queries, see L<DBIx::Class::Manual::Cookbook>.
385
386 The search can also be modified by passing another hash with
387 attributes:
388
389   my @albums = My::Schema->resultset('Album')->search(
390     { artist => 'Bob Marley' },
391     { rows => 2, order_by => 'year DESC' }
392   );
393
394 C<@albums> then holds the two most recent Bob Marley albums.
395
396 For more information on what you can do with a L<DBIx::Class::ResultSet>, see
397 L<DBIx::Class::ResultSet/METHODS>.
398
399 For a complete overview of the available attributes, see
400 L<DBIx::Class::ResultSet/ATTRIBUTES>.
401
402 =head1 NOTES
403
404 =head2 The Significance and Importance of Primary Keys
405
406 The concept of a L<primary key|DBIx::Class::ResultSource/set_primary_key> in
407 DBIx::Class warrants special discussion. The formal definition (which somewhat
408 resembles that of a classic RDBMS) is I<a unique constraint that is least
409 likely to change after initial row creation>. However this is where the
410 similarity ends. Any time you call a CRUD operation on a row (e.g.
411 L<delete|DBIx::Class::Row/delete>,
412 L<update|DBIx::Class::Row/update>,
413 L<discard_changes|DBIx::Class::Row/discard_changes>,
414 etc.) DBIx::Class will use the values of of the
415 L<primary key|DBIx::Class::ResultSource/set_primary_key> columns to populate
416 the C<WHERE> clause necessary to accomplish the operation. This is why it is
417 important to declare a L<primary key|DBIx::Class::ResultSource/set_primary_key>
418 on all your result sources B<even if the underlying RDBMS does not have one>.
419 In a pinch one can always declare each row identifiable by all its columns:
420
421  __PACKAGE__->set_primary_keys (__PACKAGE__->columns);
422
423 Note that DBIx::Class is smart enough to store a copy of the PK values before
424 any row-object changes take place, so even if you change the values of PK
425 columns the C<WHERE> clause will remain correct.
426
427 If you elect not to declare a C<primary key>, DBIx::Class will behave correctly
428 by throwing exceptions on any row operation that relies on unique identifiable
429 rows. If you inherited datasets with multiple identical rows in them, you can
430 still operate with such sets provided you only utilize
431 L<DBIx::Class::ResultSet> CRUD methods:
432 L<search|DBIx::Class::ResultSet/search>,
433 L<update|DBIx::Class::ResultSet/update>,
434 L<delete|DBIx::Class::ResultSet/delete>
435
436 For example, the following would not work (assuming C<People> does not have
437 a declared PK):
438
439  my $row = $schema->resultset('People')
440                    ->search({ last_name => 'Dantes' })
441                     ->next;
442  $row->update({ children => 2 }); # <-- exception thrown because $row isn't
443                                   # necessarily unique
444
445 So instead the following should be done:
446
447  $schema->resultset('People')
448          ->search({ last_name => 'Dantes' })
449           ->update({ children => 2 }); # <-- update's ALL Dantes to have children of 2
450
451 =head2 Problems on RHEL5/CentOS5
452
453 There used to be an issue with the system perl on Red Hat Enterprise
454 Linux 5, some versions of Fedora and derived systems. Further
455 information on this can be found in L<DBIx::Class::Manual::Troubleshooting>
456
457 =head1 SEE ALSO
458
459 =over 4
460
461 =item * L<DBIx::Class::Manual::Cookbook>
462
463 =back
464
465 =cut