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