3 DBIx::Class::Manual::Intro - Introduction to DBIx::Class
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.
11 =head1 THE DBIx::Class WAY (CLIFF NOTES)
13 Here are a few simple tips that will help you get your bearings with
16 =head2 Tables become Result classes
18 L<DBIC|DBIx::Class> needs to know what your Table structure looks like. You
19 do that by defining L<Result classes|DBIx::Class::Manual::ResultClass>. Each
20 Result class defines one Table, which defines the Columns it has, any
21 L<Relationships|DBIx::Class::Relationship> it has to other tables, and much more.
23 The important thing to understand:
25 A Result class == Table
27 (most of the time, but just bear with my simplification)
29 =head2 It's all about the ResultSet
31 Let's say we defined a L<Result classes|DBIx::Class::Manual::ResultClass> (called
32 C<MyApp::Schema::Result::Artist>) for an C<album> table with three columns:
33 C<albumid>, C<artist>, and C<title>. Any time we want to query this table, we'll
34 be creating a L<ResultSet|DBIx::Class::ResultSet> from its
35 L<Schema|DBIx::Class::Schema>. For example, the results of:
37 SELECT albumid, artist, title FROM album;
39 Would be represented like so:
41 my $rs = $schema->resultset('Album')->search(undef, {
42 columns => [qw{ albumid artist title }]
45 L<DBIC|DBIx::Class> doesn't limit you to creating only simple ResultSets -- if you
46 wanted to do something like:
48 SELECT title FROM album GROUP BY title;
50 You could easily achieve it, like this:
52 my $rs = $schema->resultset('Album')->search(undef, {
54 group_by => ['title'],
57 The important thing to understand:
59 Instead of writing SQL queries manually, you ask a ResultSet object to
62 =head2 Search results are returned as "Rows"
64 Rows of the search from the database are blessed into
65 L<Result objects|DBIx::Class::Manual::ResultClass>. This might seem conflicting,
66 but this is because a Result class is supposed to be customizable "toolset" for
67 both result management and table definition.
69 The important thing to understand:
71 When -defining- a Result class, the purpose of the class is to:
72 * Define the table, columns, and constraints
73 * Define relationships to other tables
75 When -using- a Result object, the purpose of the object is to:
76 * Read data from a result (like a row)
77 * Perform CRUD operations, based on that data
80 =head2 Search is like "prepare"
82 L<DBIC|DBIx::Class> tends to wait until it absolutely must fetch information from the
83 database. If you are returning a L<ResultSet|DBIx::Class::ResultSet>, the
84 query won't execute until you use a method that wants to access the data, such
85 as C<next> or C<first>.
87 # Does not run any SQL statements yet
88 my $rs = $schema->resultset('Album')->search(undef, {
89 columns => [qw{ albumid artist title }]
92 # Will trigger the SQL query once and loop through the results
93 while (my $result = $rs->next) {
94 my $artist = $result->artist;
98 =head1 SETTING UP DBIx::Class
100 Let's look at how you can set and use your first native L<DBIC|DBIx::Class> tree.
102 =head2 Which deployment method to take
104 There are a few different ways to create your L<DBIC|DBIx::Class> tree. Which
105 recommended method to take depends on how your database currently exists:
107 * If you are creating a brand new database, set up the tree manually, and then
108 create the tables via $schema->deploy (or another deployment tool).
109 * If the database already exists, use DBIx::Class::Schema::Loader or another
112 Since L<DBIC|DBIx::Class> first came into the scene, there have been a number of
113 useful deployment tools (schema builders) that ease the process (from oldest to
120 L<DBIx::Class::Schema::Loader> (existing DB only)
124 L<DBIx::Class::Schema::Versioned> (new or existing DB)
128 L<DBIx::Class::DeploymentHandler> (new or existing DB)
132 L<DBIx::Class::Migration> (new or existing DB)
136 This document only covers the manual method and L<DBICSL|/Using
137 DBIx::Class::Schema::Loader>. However, users with complex schemas might want
138 to check out the latest deployment tech to make life easier.
140 =head2 Setting it up manually
144 First, you should create your base schema class, which inherits from
145 L<DBIx::Class::Schema>:
148 use base qw/DBIx::Class::Schema/;
150 In this class, you load your C<result_source> ("table", "model") classes, which
151 we will define later, using the L<load_namespaces|DBIx::Class::Schema/load_namespaces>
154 # load My::Schema::Result::* and their resultset classes
155 __PACKAGE__->load_namespaces();
157 By default, this loads all the L<Result classes|DBIx::Class::Manual::ResultClass>
158 in the C<My::Schema::Result::> namespace, and also any ResultSet classes in the
159 C<My::Schema::ResultSet::> namespace. (If missing, the ResultSets are
160 defaulted to be L<DBIx::Class::ResultSet> objects.) You can change the Result
161 and ResultSet namespaces by using options to the
162 L<load_namespaces|DBIx::Class::Schema/load_namespaces> call.
164 It is also possible to do the same things manually by calling
165 L<load_classes|DBIx::Class::Schema/load_classes> for the
166 L<Result classes|DBIx::Class::Manual::ResultClass> and
167 defining in those classes any required ResultSet classes.
173 Next, create each of the classes you want to load as specified above:
175 package My::Schema::Result::Album;
176 use base qw/DBIx::Class::Core/;
178 Load any additional components you may need with the
179 L<load_components|Class::C3::Componentised/load_components( @comps )> method,
180 and provide component configuration if required. For example, if you want
181 automatic row ordering:
183 __PACKAGE__->load_components(qw/ Ordered /);
184 __PACKAGE__->position_column('rank');
186 (See L<DBIx::Class::Ordered> for more information.)
188 Set the table for your class:
190 __PACKAGE__->table('album');
194 Add columns to your class:
196 __PACKAGE__->add_columns(qw/ albumid artist title rank /);
198 Each column can also be set up with its own accessor, data_type and other pieces
199 of information that it may be useful to have -- just pass C<add_columns> a hash:
201 __PACKAGE__->add_columns(
204 data_type => 'integer',
207 is_auto_increment => 1,
210 data_type => 'integer',
215 data_type => 'varchar',
220 data_type => 'integer',
227 L<DBIC|DBIx::Class> doesn't directly use most of this data yet, but various
228 related modules, such as L<HTML::FormHandler::Model::DBIC>, make use of it. Also,
229 it allows you to create your database tables from your Schema, instead of the
230 other way around. See L<DBIx::Class::Schema/deploy> for details.
232 See L<DBIx::Class::ResultSource/add_columns> for more details of the possible column
235 Accessors are created for each column automatically, so C<My::Schema::Result::Album>
236 will have C<albumid> (or C<album>, when using the accessor shown above), C<artist>
237 and C<title> methods.
241 Define a primary key for your class:
243 __PACKAGE__->set_primary_key('albumid');
245 If you have a multi-column primary key, just pass a list instead:
247 __PACKAGE__->set_primary_key( qw/ albumid artistid / );
251 Define this class' relationships with other classes using either
252 L<belongs_to|DBIx::Class::Relationship/belongs_to> to describe a column which
253 contains an ID of another Table, or
254 L<has_many|DBIx::Class::Relationship/has_many> to make a predefined accessor for
255 fetching objects that contain this Table's foreign key:
257 # in My::Schema::Result::Artist
258 __PACKAGE__->has_many('albums', 'My::Schema::Result::Album', 'artist');
260 See L<DBIx::Class::Relationship> for more information about the various types of
261 available relationships and how you can design your own.
263 =head2 Using DBIx::Class::Schema::Loader
265 L<DBICSL|DBIx::Class::Schema::Loader> is an external module, and not part
266 of the L<DBIC|DBIx::Class> distribution. It inspects your database, and
267 automatically creates classes for all the tables in your schema.
269 The simplest way to use it is via the L<dbicdump> script from the
270 L<DBIx::Class::Schema::Loader> distribution. For example:
272 $ dbicdump -o dump_directory=./lib \
273 -o components='["InflateColumn::DateTime"]' \
274 MyApp::Schema dbi:mysql:mydb user pass
276 If you have a mixed-case database, use the C<preserve_case> option, e.g.:
278 $ dbicdump -o dump_directory=./lib -o preserve_case=1 \
279 -o components='["InflateColumn::DateTime"]' \
280 MyApp::Schema dbi:mysql:mydb user pass
282 If you are using L<Catalyst>, then you can use the helper that comes with
283 L<Catalyst::Model::DBIC::Schema>:
285 $ script/myapp_create.pl model MyDB DBIC::Schema MyDB::Schema \
286 create=static moniker_map='{ foo => "FOO" }' dbi:SQLite:./myapp.db \
287 on_connect_do='PRAGMA foreign_keys=ON' quote_char='"'
289 See L<Catalyst::Helper::Model::DBIC::Schema> for more information on this
292 See the L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>
293 documentation for more information on the many loader options.
297 To connect to your Schema, you need to provide the connection details or a
300 =head3 Via connection details
302 The arguments are the same as for L<DBI/connect>:
304 my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
306 You can create as many different schema instances as you need. So if you have a
307 second database you want to access:
309 my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
311 Note that L<DBIx::Class::Schema> does not cache connections for you. If you use
312 multiple connections, you need to do this manually.
314 To execute some SQL statements on every connect you can add them as an option in
315 a special fifth argument to connect:
317 my $another_schema = My::Schema->connect(
322 { on_connect_do => \@on_connect_sql_statments }
325 See L<DBIx::Class::Storage::DBI/connect_info> for more information about
326 this and other special C<connect>-time options.
328 =head3 Via a database handle
330 The supplied coderef is expected to return a single connected database handle
331 (e.g. a L<DBI> C<$dbh>)
333 my $schema = My::Schema->connect (
334 sub { Some::DBH::Factory->connect },
340 Once you've defined the basic classes, either manually or using
341 L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
343 To access your database using your $schema object, you can fetch a
344 L<DBIx::Class::Manual::Glossary/"ResultSet"> representing each of your tables by
345 calling the C<resultset> method.
347 The simplest way to get a record is by primary key:
349 my $album = $schema->resultset('Album')->find(14);
351 This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause, and
352 return an instance of C<My::Schema::Result::Album> that represents this row. Once you
353 have that row, you can access and update columns:
355 $album->title('Physical Graffiti');
356 my $title = $album->title; # $title holds 'Physical Graffiti'
358 If you prefer, you can use the C<set_column> and C<get_column> accessors
361 $album->set_column('title', 'Presence');
362 $title = $album->get_column('title');
364 Just like with L<Class::DBI>, you call C<update> to save your changes to the
365 database (by executing the actual C<UPDATE> statement):
369 If needed, you can throw away your local changes:
371 $album->discard_changes if $album->is_changed;
373 As you can see, C<is_changed> allows you to check if there are local changes to
376 =head2 Adding and removing rows
378 To create a new record in the database, you can use the C<create> method. It
379 returns an instance of C<My::Schema::Result::Album> that can be used to access the data
382 my $new_album = $schema->resultset('Album')->create({
383 title => 'Wish You Were Here',
384 artist => 'Pink Floyd'
387 Now you can add data to the new record:
389 $new_album->label('Capitol');
390 $new_album->year('1975');
393 Likewise, you can remove it from the database:
397 You can also remove records without retrieving them first, by calling delete
398 directly on a ResultSet object.
400 # Delete all of Falco's albums
401 $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
403 =head2 Finding your objects
405 L<DBIC|DBIx::Class> provides a few different ways to retrieve data from your
406 database. Here's one example:
408 # Find all of Santana's albums
409 my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
411 In scalar context, as above, C<search> returns a L<DBIx::Class::ResultSet>
412 object. It can be used to peek at the first album returned by the database:
414 my $album = $rs->first;
417 You can loop over the albums and update each one:
419 while (my $album = $rs->next) {
420 print $album->artist . ' - ' . $album->title;
425 Or, you can update them all at once:
427 $rs->update({ year => 2001 });
429 In list context, the C<search> method returns all of the matching rows:
431 # Fetch immediately all of Carlos Santana's albums
432 my @albums = $schema->resultset('Album')->search(
433 { artist => 'Carlos Santana' }
435 foreach my $album (@albums) {
436 print $album->artist . ' - ' . $album->title;
439 We also provide a handy shortcut for doing a C<LIKE> search:
441 # Find albums whose artist starts with 'Jimi'
442 my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
444 Or you can provide your own C<WHERE> clause:
446 # Find Peter Frampton albums from the year 1986
447 my $where = 'artist = ? AND year = ?';
448 my @bind = ( 'Peter Frampton', 1986 );
449 my $rs = $schema->resultset('Album')->search_literal( $where, @bind );
451 The preferred way to generate complex queries is to provide a L<SQL::Abstract>
452 construct to C<search>:
454 my $rs = $schema->resultset('Album')->search({
455 artist => { '!=', 'Janis Joplin' },
456 year => { '<' => 1980 },
457 albumid => { '-in' => [ 1, 14, 15, 65, 43 ] }
460 This results in something like the following C<WHERE> clause:
462 WHERE artist != 'Janis Joplin'
464 AND albumid IN (1, 14, 15, 65, 43)
466 For more examples of complex queries, see L<DBIx::Class::Manual::Cookbook>.
468 The search can also be modified by passing another hash with
471 my @albums = My::Schema->resultset('Album')->search(
472 { artist => 'Bob Marley' },
473 { rows => 2, order_by => { -desc => 'year' } }
476 C<@albums> then holds the two most recent Bob Marley albums.
478 For more information on what you can do with a L<DBIx::Class::ResultSet>, see
479 L<DBIx::Class::ResultSet/METHODS>.
481 For a complete overview of the available attributes, see
482 L<DBIx::Class::ResultSet/ATTRIBUTES>.
486 =head2 The Significance and Importance of Primary Keys
488 The concept of a L<primary key|DBIx::Class::ResultSource/set_primary_key> in
489 L<DBIC|DBIx::Class> warrants special discussion. The formal definition (which somewhat
490 resembles that of a classic RDBMS) is I<a unique constraint that is least
491 likely to change after initial row creation>. However, this is where the
492 similarity ends. Any time you call a CRUD operation on a row (e.g.
493 L<delete|DBIx::Class::Row/delete>,
494 L<update|DBIx::Class::Row/update>,
495 L<discard_changes|DBIx::Class::Row/discard_changes>,
496 etc.), L<DBIC|DBIx::Class> will use the values of of the
497 L<primary key|DBIx::Class::ResultSource/set_primary_key> columns to populate
498 the C<WHERE> clause necessary to accomplish the operation. This is why it is
499 important to declare a L<primary key|DBIx::Class::ResultSource/set_primary_key>
500 on all your result sources B<even if the underlying RDBMS does not have one>.
501 In a pinch, one can always declare each row identifiable by all its columns:
503 __PACKAGE__->set_primary_key(__PACKAGE__->columns);
505 Note that L<DBIC|DBIx::Class> is smart enough to store a copy of the PK values before
506 any row-object changes take place, so even if you change the values of PK
507 columns, the C<WHERE> clause will remain correct.
509 If you elect not to declare a C<primary key>, L<DBIC|DBIx::Class> will behave correctly
510 by throwing exceptions on any row operation that relies on unique identifiable
511 rows. If you inherited datasets with multiple identical rows in them, you can
512 still operate with such sets provided you only utilize
513 L<DBIx::Class::ResultSet> CRUD methods:
514 L<search|DBIx::Class::ResultSet/search>,
515 L<update|DBIx::Class::ResultSet/update>,
516 L<delete|DBIx::Class::ResultSet/delete>
518 For example, the following would not work (assuming C<People> does not have
521 my $row = $schema->resultset('People')
522 ->search({ last_name => 'Dantes' })
524 $row->update({ children => 2 }); # <-- exception thrown because $row isn't
527 So, instead the following should be done:
529 $schema->resultset('People')
530 ->search({ last_name => 'Dantes' })
531 ->update({ children => 2 }); # <-- update's ALL Dantes to have children of 2
533 =head2 Problems on RHEL5/CentOS5
535 There used to be an issue with the system perl on Red Hat Enterprise
536 Linux 5, some versions of Fedora and derived systems. Further
537 information on this can be found in L<DBIx::Class::Manual::Troubleshooting>
543 =item * L<DBIx::Class::Manual::Cookbook>
545 =item * L<DBIx::Class::Manual::ResultClass>