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