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