More FAQs!
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / Intro.pod
CommitLineData
9c82c181 1=head1 NAME
2
3b44ccc6 3DBIx::Class::Manual::Intro - Introduction to DBIx::Class
9c82c181 4
40dbc108 5=head1 INTRODUCTION
076652e8 6
40dbc108 7So, you are bored with SQL, and want a native Perl interface for your
8database? Or you've been doing this for a while with L<Class::DBI>,
35d4fe78 9and think there's a better way? You've come to the right place.
4b0779f4 10
11=head1 THE DBIx::Class WAY
12
13Here are a few simple tips that will help you get your bearings
14with DBIx::Class.
15
16=head2 Tables become ResultSources
17
18DBIx::Class needs to know what your Table structure looks like. You do that
19by defining L<DBIx::Class::ResultSource>s. Each table get's a ResultSource,
20which defines the Columns it has, along with any Relationships it has to
21other tables. (And oh, so much more besides) The important thing to
22understand:
23
24 A ResultSource == Table
25
26(most of the time, but just bear with my simplification)
27
28=head2 It's all about the ResultSet
29
30So, we've got some ResultSources defined. Now, we want to actually use
31those definitions to help us translate the queries we need into
32handy perl objects!
33
34Let's say we defined a ResultSource for an "album" table with three
35columns: "albumid", "artist", and "title". Any time we want to query
36this table, we'll be creating a L<DBIx::Class::ResultSet> from it's
37ResultSource. For example, the results of:
38
39 SELECT albumid, artist, title FROM album;
40
41Would be retrieved by creating a ResultSet object from the album
42table's ResultSource, likely by using the "search" method.
43
44DBIx::Class doesn't limit you to creating only simple ResultSets --
45if you wanted to do something like:
46
47 SELECT title FROM album GROUP BY title;
48
49You could easily achieve it.
50
51The 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
58DBIx::Class tends to wait until it absolutely must fetch information
59from the database. If you are returning a ResultSet, the query won't
60execute until you use a method that wants to access the data. (Such
61as "next", or "first")
62
63The important thing to understand:
64
65 Setting up a ResultSet does not execute the query; retrieving
66 the data does.
67
68=head1 SETTING UP DBIx::Class
69
35d4fe78 70Let's look at how you can set and use your first native L<DBIx::Class>
71tree.
076652e8 72
35d4fe78 73First we'll see how you can set up your classes yourself. If you want
40dbc108 74them to be auto-discovered, just skip to the next section, which shows
5cc9fa32 75you how to use L<DBIx::Class::Schema::Loader>.
076652e8 76
77=head2 Setting it up manually
78
5cc9fa32 79First, you should create your base schema class, which inherits from
80L<DBIx::Class::Schema>:
076652e8 81
5cc9fa32 82 package My::Schema;
83 use base qw/DBIx::Class::Schema/;
84
85In this class you load your result_source ("table", "model") classes, which
86we will define later, using the load_classes() method. You can specify which
87classes to load manually:
076652e8 88
5cc9fa32 89 # load My::Schema::Album and My::Schema::Artist
90 __PACKAGE__->load_classes(qw/ Album Artist /);
076652e8 91
5cc9fa32 92Or load classes by namespace:
076652e8 93
5cc9fa32 94 # load My::Schema::Album, My::Schema::Artist and My::OtherSchema::LinerNotes
95 __PACKAGE__->load_classes(
96 {
97 'My::Schema' => [qw/ Album Artist /],
98 'My::OtherSchema' => [qw/ LinerNotes /]
99 }
100 );
101
102Or let your schema class load all classes in its namespace automatically:
076652e8 103
5cc9fa32 104 # load My::Schema::*
105 __PACKAGE__->load_classes();
076652e8 106
5cc9fa32 107Next, create each of the classes you want to load as specified above:
076652e8 108
5cc9fa32 109 package My::Schema::Album;
110 use base qw/DBIx::Class/;
35d4fe78 111
5cc9fa32 112Load any components required by each class with the load_components() method.
113This should consist of "Core" plus any additional components you want to use.
114For example, if you want serial/auto-incrementing primary keys:
076652e8 115
5cc9fa32 116 __PACKAGE__->load_components(qw/ PK::Auto Core /);
076652e8 117
5cc9fa32 118C<PK::Auto> is supported for many databases; see
119L<DBIx::Class::Storage::DBI> for more information.
076652e8 120
5cc9fa32 121Set the table for your class:
076652e8 122
35d4fe78 123 __PACKAGE__->table('album');
076652e8 124
5cc9fa32 125Add columns to your class:
126
127 __PACKAGE__->add_columns(qw/ albumid artist title /);
128
129Each column can also be set up with its own accessor, data_type and other
130pieces of information that it may be useful to have, just pass C<add_columns>
131a hash such as:
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 );
156
157Most of this data isn't yet used directly by DBIx::Class, but various related
158modules such as L<DBIx::Class::WebForm> make use of it. Also it allows you
159to create your database tables from your Schema, instead of the other way
160around. See L<SQL::Translator> for details.
161
162See L<DBIx::Class::ResultSource> for more details of the possible column
163attributes.
164
165Accessors are created for each column automatically, so My::Schema::Album will
166have albumid() (or album(), when using the accessor), artist() and title()
167methods.
168
169Define a primary key for your class:
076652e8 170
5cc9fa32 171 __PACKAGE__->set_primary_key('albumid');
076652e8 172
5cc9fa32 173If you have a multi-column primary key, just pass a list instead:
076652e8 174
5cc9fa32 175 __PACKAGE__->set_primary_key( qw/ albumid artistid / );
076652e8 176
5cc9fa32 177Define relationships that the class has with any other classes by using
178either C<belongs_to> to describe a column which contains an ID of another
179table, or C<has_many> to make a predefined accessor for fetching objects
180that contain this tables foreign key in one of their columns:
181
182 __PACKAGE__->has_many('albums', 'My::Schema::Artist', 'album_id');
076652e8 183
5cc9fa32 184More information about the various types of relationships available, and
185how you can design your own, can be found in L<DBIx::Class::Relationship>.
076652e8 186
076652e8 187
5cc9fa32 188=head2 Using L<DBIx::Class::Schema::Loader>
076652e8 189
5cc9fa32 190This is an external module, and not part of the L<DBIx::Class>
40dbc108 191distribution. Like L<Class::DBI::Loader>, it inspects your database,
35d4fe78 192and automatically creates classes for all the tables in your database.
193Here's a simple setup:
076652e8 194
24d34a80 195 package My::Schema;
196 use base qw/DBIx::Class::Schema::Loader/;
40dbc108 197
24d34a80 198 __PACKAGE__->load_from_connection(
199 connect_info = [ 'dbi:SQLite:/home/me/myapp/my.db' ]
35d4fe78 200 );
076652e8 201
35d4fe78 202 1;
076652e8 203
35d4fe78 204This should be equivalent to the manual setup in the section above.
5cc9fa32 205L<DBIx::Class::Schema::Loader> takes lots of other options. For more
40dbc108 206information, consult its documentation.
076652e8 207
5cc9fa32 208=head2 Connecting
209
210L<DBIx::Class::Schema::Loader> already contains the connection info for the
211database, so to get started all you need to do is create an instance of your
212class:
213
24d34a80 214 my $schema = My::Schema->new();
5cc9fa32 215
216To connect to your manually created Schema, you also need to provide the
217connection details:
218
219 my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
220
221You can create as many different schema instances as you need. So if you have
222a second database you want to access:
223
224 my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
225
880a1a0c 226Note that L<DBIx::Class::Schema> does not cache connections for you. If you
5cc9fa32 227use multiple connections, you need to do this manually.
228
229To execute some sql statements on every connect you can pass them to your schema after the connect:
230
231 $schema->storage->on_connect_do(\@on_connect_sql_statments);
232
40dbc108 233=head2 Basic usage
076652e8 234
35d4fe78 235Once you've defined the basic classes, either manually or using
5cc9fa32 236L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
237
238To access your database using your $schema object, you can fetch a L<DBIx::Class::Manual::Glossary/"ResultSet">
239representing each of your tables by calling the ->resultset method.
240
35d4fe78 241The simplest way to get a record is by primary key:
076652e8 242
5cc9fa32 243 my $album = $schema->resultset('Album')->find(14);
076652e8 244
35d4fe78 245This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause,
24d34a80 246and return an instance of C<My::Schema::Album> that represents this
35d4fe78 247row. Once you have that row, you can access and update columns:
076652e8 248
35d4fe78 249 $album->title('Physical Graffiti');
250 my $title = $album->title; # $title holds 'Physical Graffiti'
076652e8 251
40dbc108 252If you prefer, you can use the C<set_column> and C<get_column>
253accessors instead:
076652e8 254
35d4fe78 255 $album->set_column('title', 'Presence');
256 $title = $album->get_column('title');
076652e8 257
5cc9fa32 258Just like with L<Class::DBI>, you call C<update> to commit your
40dbc108 259changes to the database:
260
35d4fe78 261 $album->update;
076652e8 262
35d4fe78 263If needed, you can throw away your local changes like this:
076652e8 264
35d4fe78 265 $album->discard_changes if $album->is_changed;
076652e8 266
40dbc108 267As you can see, C<is_changed> allows you to check if there are local
268changes to your object.
076652e8 269
40dbc108 270=head2 Adding and removing rows
076652e8 271
40dbc108 272To create a new record in the database, you can use the C<create>
24d34a80 273method. It returns an instance of C<My::Schema::Album> that can be
35d4fe78 274used to access the data in the new record:
076652e8 275
5cc9fa32 276 my $new_album = $schema->resultset('Album')->create({
35d4fe78 277 title => 'Wish You Were Here',
278 artist => 'Pink Floyd'
279 });
dfeba824 280
281Now you can add data to the new record:
282
35d4fe78 283 $new_album->label('Capitol');
284 $new_album->year('1975');
285 $new_album->update;
076652e8 286
35d4fe78 287Likewise, you can remove it from the database like this:
076652e8 288
35d4fe78 289 $new_album->delete;
076652e8 290
5cc9fa32 291You can also remove records without retrieving them first, by calling
292delete directly on a ResultSet object.
076652e8 293
35d4fe78 294 # Delete all of Falco's albums
5cc9fa32 295 $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
076652e8 296
40dbc108 297=head2 Finding your objects
076652e8 298
40dbc108 299L<DBIx::Class> provides a few different ways to retrieve data from
35d4fe78 300your database. Here's one example:
301
302 # Find all of Santana's albums
5cc9fa32 303 my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
35d4fe78 304
305In scalar context, as above, C<search> returns a
306L<DBIx::Class::ResultSet> object. It can be used to peek at the first
307album returned by the database:
308
309 my $album = $rs->first;
310 print $album->title;
076652e8 311
5cc9fa32 312You can loop over the albums and update each one:
076652e8 313
35d4fe78 314 while (my $album = $rs->next) {
315 print $album->artist . ' - ' . $album->title;
316 $album->year(2001);
317 $album->update;
318 }
a3c5e7e3 319
5cc9fa32 320Or, you can update them all at once:
321
322 $rs->update({ year => 2001 });
323
35d4fe78 324For more information on what you can do with a
325L<DBIx::Class::ResultSet>, see L<DBIx::Class::ResultSet/METHODS>.
a3c5e7e3 326
35d4fe78 327In list context, the C<search> method returns all of the matching
a3c5e7e3 328rows:
329
35d4fe78 330 # Fetch immediately all of Carlos Santana's albums
5cc9fa32 331 my @albums = $schema->resultset('Album')->search(
332 { artist => 'Carlos Santana' }
333 );
35d4fe78 334 foreach my $album (@albums) {
335 print $album->artist . ' - ' . $album->title;
336 }
076652e8 337
40dbc108 338We also provide a handy shortcut for doing a C<LIKE> search:
076652e8 339
35d4fe78 340 # Find albums whose artist starts with 'Jimi'
24d34a80 341 my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
076652e8 342
5cc9fa32 343Or you can provide your own C<WHERE> clause, like:
35d4fe78 344
345 # Find Peter Frampton albums from the year 1986
346 my $where = 'artist = ? AND year = ?';
347 my @bind = ( 'Peter Frampton', 1986 );
5cc9fa32 348 my $rs = $schema->resultset('Album')->search_literal( $where, @bind );
40dbc108 349
350The preferred way to generate complex queries is to provide a
351L<SQL::Abstract> construct to C<search>:
352
5cc9fa32 353 my $rs = $schema->resultset('Album')->search({
35d4fe78 354 artist => { '!=', 'Janis Joplin' },
355 year => { '<' => 1980 },
356 albumid => [ 1, 14, 15, 65, 43 ]
357 });
358
359This results in something like the following C<WHERE> clause:
40dbc108 360
35d4fe78 361 WHERE artist != 'Janis Joplin'
362 AND year < 1980
363 AND albumid IN (1, 14, 15, 65, 43)
364
365For more examples of complex queries, see
40dbc108 366L<DBIx::Class::Manual::Cookbook>.
367
368The search can also be modified by passing another hash with
369attributes:
370
24d34a80 371 my @albums = My::Schema->resultset('Album')->search(
35d4fe78 372 { artist => 'Bob Marley' },
373 { rows => 2, order_by => 'year DESC' }
374 );
375
376C<@albums> then holds the two most recent Bob Marley albums.
40dbc108 377
378For a complete overview of the available attributes, see
379L<DBIx::Class::ResultSet/ATTRIBUTES>.
076652e8 380
40dbc108 381=head1 SEE ALSO
076652e8 382
40dbc108 383=over 4
076652e8 384
40dbc108 385=item * L<DBIx::Class::Manual::Cookbook>
076652e8 386
40dbc108 387=back
076652e8 388
389=cut