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