4bd95d5f9a34a7f22a0079d57a814226090bd1eb
[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_classes() method. You can specify which
90 classes to load manually: 
91
92   # load My::Schema::Album and My::Schema::Artist
93   __PACKAGE__->load_classes(qw/ Album Artist /);
94
95 Or load classes by namespace:
96
97   # load My::Schema::Album, My::Schema::Artist and My::OtherSchema::LinerNotes
98   __PACKAGE__->load_classes(
99     {
100       'My::Schema' => [qw/ Album Artist /],
101       'My::OtherSchema' => [qw/ LinerNotes /]
102     }
103   );
104
105 Or let your schema class load all classes in its namespace automatically:
106
107    # load My::Schema::*
108   __PACKAGE__->load_classes();
109
110 Next, create each of the classes you want to load as specified above:
111
112   package My::Schema::Album;
113   use base qw/DBIx::Class/;
114
115 Load any components required by each class with the load_components() method.
116 This should consist of "Core" plus any additional components you want to use.
117 For example, if you want serial/auto-incrementing primary keys:
118
119   __PACKAGE__->load_components(qw/ PK::Auto Core /);
120
121 C<PK::Auto> is supported for many databases; see L<DBIx::Class::Storage::DBI>
122 for more information.
123
124 Set the table for your class:
125
126   __PACKAGE__->table('album');
127
128 Add columns to your class:
129
130   __PACKAGE__->add_columns(qw/ albumid artist title /);
131
132 Each column can also be set up with its own accessor, data_type and other pieces
133 of information that it may be useful to have -- just pass C<add_columns> a hash:
134
135   __PACKAGE__->add_columns(albumid =>
136                             { accessor  => 'album',
137                               data_type => 'integer',
138                               size      => 16,
139                               is_nullable => 0,
140                               is_auto_increment => 1,
141                               default_value => '',
142                             },
143                           artist =>
144                             { data_type => 'integer',
145                               size      => 16,
146                               is_nullable => 0,
147                               is_auto_increment => 0,
148                               default_value => '',
149                             },
150                           title  => 
151                             { data_type => 'varchar',
152                               size      => 256,
153                               is_nullable => 0,
154                               is_auto_increment => 0,
155                               default_value => '',
156                             }
157                          );
158
159 DBIx::Class doesn't directly use most of this data yet, but various related
160 modules such as L<DBIx::Class::WebForm> make use of it. Also it allows you to
161 create your database tables from your Schema, instead of the other way around.
162 See L<SQL::Translator> for details.
163
164 See L<DBIx::Class::ResultSource> for more details of the possible column
165 attributes.
166
167 Accessors are created for each column automatically, so My::Schema::Album will
168 have albumid() (or album(), when using the accessor), artist() and title()
169 methods.
170
171 Define a primary key for your class:
172
173   __PACKAGE__->set_primary_key('albumid');
174
175 If you have a multi-column primary key, just pass a list instead:
176
177   __PACKAGE__->set_primary_key( qw/ albumid artistid / );
178
179 Define this class' relationships with other classes using either C<belongs_to>
180 to describe a column which contains an ID of another Table, or C<has_many> to
181 make a predefined accessor for fetching objects that contain this Table's
182 foreign key:
183
184   __PACKAGE__->has_many('albums', 'My::Schema::Artist', 'album_id');
185
186 See L<DBIx::Class::Relationship> for more information about the various types of
187 available relationships and how you can design your own.
188
189 =head2 Using L<DBIx::Class::Schema::Loader>
190
191 This is an external module, and not part of the L<DBIx::Class> distribution.
192 Like L<Class::DBI::Loader>, it inspects your database, and automatically creates
193 classes for all the tables in your database.  Here's a simple setup:
194
195   package My::Schema;
196   use base qw/DBIx::Class::Schema::Loader/;
197
198   __PACKAGE__->loader_options( relationships => 1 );
199
200   1;
201
202 The actual autoloading process will occur when you create a connected instance
203 of your schema below.
204
205 See the L<DBIx::Class::Schema::Loader> documentation for more information on its
206 many options.
207
208 =head2 Connecting
209
210 To connect to your Schema, you need to provide the connection details.  The
211 arguments are the same as for L<DBI/connect>:
212
213   my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
214
215 You can create as many different schema instances as you need. So if you have a
216 second database you want to access:
217
218   my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
219
220 Note that L<DBIx::Class::Schema> does not cache connections for you. If you use
221 multiple connections, you need to do this manually.
222
223 To execute some sql statements on every connect you can add them as an option in
224 a special fifth argument to connect:
225
226   my $another_schema = My::Schema->connect(
227       $dsn,
228       $user,
229       $password,
230       $attrs,
231       { on_connect_do => \@on_connect_sql_statments }
232   );
233
234 See L<DBIx::Class::Schema::Storage::DBI/connect_info> for more information about
235 this and other special C<connect>-time options.
236
237 =head2 Basic usage
238
239 Once you've defined the basic classes, either manually or using
240 L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
241
242 To access your database using your $schema object, you can fetch a
243 L<DBIx::Class::Manual::Glossary/"ResultSet"> representing each of your tables by
244 calling the C<resultset> method.
245
246 The simplest way to get a record is by primary key:
247
248   my $album = $schema->resultset('Album')->find(14);
249
250 This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause, and
251 return an instance of C<My::Schema::Album> that represents this row.  Once you
252 have that row, you can access and update columns:
253
254   $album->title('Physical Graffiti');
255   my $title = $album->title; # $title holds 'Physical Graffiti'
256
257 If you prefer, you can use the C<set_column> and C<get_column> accessors
258 instead:
259
260   $album->set_column('title', 'Presence');
261   $title = $album->get_column('title');
262
263 Just like with L<Class::DBI>, you call C<update> to commit your changes to the
264 database:
265
266   $album->update;
267
268 If needed, you can throw away your local changes:
269
270   $album->discard_changes if $album->is_changed;
271
272 As you can see, C<is_changed> allows you to check if there are local changes to
273 your object.
274
275 =head2 Adding and removing rows
276
277 To create a new record in the database, you can use the C<create> method.  It
278 returns an instance of C<My::Schema::Album> that can be used to access the data
279 in the new record:
280
281   my $new_album = $schema->resultset('Album')->create({ 
282     title  => 'Wish You Were Here',
283     artist => 'Pink Floyd'
284   });
285
286 Now you can add data to the new record:
287
288   $new_album->label('Capitol');
289   $new_album->year('1975');
290   $new_album->update;
291
292 Likewise, you can remove it from the database:
293
294   $new_album->delete;
295
296 You can also remove records without retrieving them first, by calling delete
297 directly on a ResultSet object.
298
299   # Delete all of Falco's albums
300   $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
301
302 =head2 Finding your objects
303
304 L<DBIx::Class> provides a few different ways to retrieve data from your
305 database.  Here's one example:
306
307   # Find all of Santana's albums
308   my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
309
310 In scalar context, as above, C<search> returns a L<DBIx::Class::ResultSet>
311 object.  It can be used to peek at the first album returned by the database:
312
313   my $album = $rs->first;
314   print $album->title;
315
316 You can loop over the albums and update each one:
317
318   while (my $album = $rs->next) {
319     print $album->artist . ' - ' . $album->title;
320     $album->year(2001);
321     $album->update;
322   }
323
324 Or, you can update them all at once:
325
326   $rs->update({ year => 2001 });
327
328 In list context, the C<search> method returns all of the matching rows:
329
330   # Fetch immediately all of Carlos Santana's albums
331   my @albums = $schema->resultset('Album')->search(
332     { artist => 'Carlos Santana' }
333   );
334   foreach my $album (@albums) {
335     print $album->artist . ' - ' . $album->title;
336   }
337
338 We also provide a handy shortcut for doing a C<LIKE> search:
339
340   # Find albums whose artist starts with 'Jimi'
341   my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
342
343 Or you can provide your own C<WHERE> clause:
344
345   # Find Peter Frampton albums from the year 1986
346   my $where = 'artist = ? AND year = ?';
347   my @bind  = ( 'Peter Frampton', 1986 );
348   my $rs    = $schema->resultset('Album')->search_literal( $where, @bind );
349
350 The preferred way to generate complex queries is to provide a L<SQL::Abstract>
351 construct to C<search>:
352
353   my $rs = $schema->resultset('Album')->search({
354     artist  => { '!=', 'Janis Joplin' },
355     year    => { '<' => 1980 },
356     albumid => { '-in' => [ 1, 14, 15, 65, 43 ] }
357   });
358
359 This results in something like the following C<WHERE> clause:
360
361   WHERE artist != 'Janis Joplin'
362     AND year < 1980
363     AND albumid IN (1, 14, 15, 65, 43)
364
365 For more examples of complex queries, see L<DBIx::Class::Manual::Cookbook>.
366
367 The search can also be modified by passing another hash with
368 attributes:
369
370   my @albums = My::Schema->resultset('Album')->search(
371     { artist => 'Bob Marley' },
372     { rows => 2, order_by => 'year DESC' }
373   );
374
375 C<@albums> then holds the two most recent Bob Marley albums.
376
377 For more information on what you can do with a L<DBIx::Class::ResultSet>, see
378 L<DBIx::Class::ResultSet/METHODS>.
379
380 For a complete overview of the available attributes, see
381 L<DBIx::Class::ResultSet/ATTRIBUTES>.
382
383 =head1 NOTES
384
385 =head2 Problems on RHEL5/CentOS5
386
387 There is a problem with slow performance of certain DBIx::Class operations in
388 perl-5.8.8-10 and later on RedHat and related systems, due to a bad backport of
389 a "use overload" related bug.  The problem is in the Perl binary itself, not in
390 DBIx::Class.  If your system has this problem, you will see a warning on
391 startup, with some options as to what to do about it.
392
393 =head1 SEE ALSO
394
395 =over 4
396
397 =item * L<DBIx::Class::Manual::Cookbook>
398
399 =back
400
401 =cut