Clean up of "DBIx::Class" references to "DBIC"
[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
7b35a32e 11=head1 THE DBIx::Class WAY (CLIFF NOTES)
4b0779f4 12
d53178fd 13Here are a few simple tips that will help you get your bearings with
7b35a32e 14L<DBIC|DBIx::Class>.
4b0779f4 15
2f0790c4 16=head2 Tables become Result classes
4b0779f4 17
7b35a32e 18L<DBIC|DBIx::Class> needs to know what your Table structure looks like. You
19do that by defining L<Result classes|DBIx::Class::Manual::ResultClass>. Each
20Result class defines one Table, which defines the Columns it has, any
21L<Relationships|DBIx::Class::Relationship> it has to other tables, and much more.
22
23The 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
7b35a32e 31Let's say we defined a L<Result classes|DBIx::Class::Manual::ResultClass> (called
32C<MyApp::Schema::Result::Artist>) for an C<album> table with three columns:
33C<albumid>, C<artist>, and C<title>. Any time we want to query this table, we'll
34be creating a L<ResultSet|DBIx::Class::ResultSet> from its
35L<Schema|DBIx::Class::Schema>. For example, the results of:
4b0779f4 36
d53178fd 37 SELECT albumid, artist, title FROM album;
4b0779f4 38
7b35a32e 39Would be represented like so:
4b0779f4 40
7b35a32e 41 my $rs = $schema->resultset('Album')->search(undef, {
42 columns => [qw{ albumid artist title }]
43 });
44
45L<DBIC|DBIx::Class> doesn't limit you to creating only simple ResultSets -- if you
d53178fd 46wanted to do something like:
47
48 SELECT title FROM album GROUP BY title;
4b0779f4 49
7b35a32e 50You could easily achieve it, like this:
51
52 my $rs = $schema->resultset('Album')->search(undef, {
53 columns => ['title'],
54 group_by => ['title'],
55 });
4b0779f4 56
d56c3191 57The important thing to understand:
4b0779f4 58
7b35a32e 59 Instead of writing SQL queries manually, you ask a ResultSet object to
60 generate them.
4b0779f4 61
7b35a32e 62=head2 Search results are returned as "Rows"
4b0779f4 63
7b35a32e 64Rows of the search from the database are blessed into
65L<Result objects|DBIx::Class::Manual::ResultClass>. This might seem conflicting,
66but this is because a Result class is supposed to be customizable "toolset" for
67both result management and table definition.
4b0779f4 68
69The important thing to understand:
70
7b35a32e 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
4b0779f4 74
7b35a32e 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
78 * "Inflate" columns
2f0790c4 79
7b35a32e 80=head2 Search is like "prepare"
81
82L<DBIC|DBIx::Class> tends to wait until it absolutely must fetch information from the
83database. If you are returning a L<ResultSet|DBIx::Class::ResultSet>, the
84query won't execute until you use a method that wants to access the data, such
85as C<next> or C<first>.
86
87 # Does not run any SQL statements yet
88 my $rs = $schema->resultset('Album')->search(undef, {
89 columns => [qw{ albumid artist title }]
90 });
91
92 # Will trigger the SQL query once and loop through the results
93 while (my $result = $rs->next) {
94 my $artist = $result->artist;
95 ...
96 }
2f0790c4 97
4b0779f4 98=head1 SETTING UP DBIx::Class
99
7b35a32e 100Let's look at how you can set and use your first native L<DBIC|DBIx::Class> tree.
101
102=head2 Which deployment method to take
103
104There are a few different ways to create your L<DBIC|DBIx::Class> tree. Which
105recommended method to take depends on how your database currently exists:
106
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
110 schema builder.
111
112Since L<DBIC|DBIx::Class> first came into the scene, there have been a number of
113useful deployment tools (schema builders) that ease the process (from oldest to
114newest):
115
116=over
076652e8 117
7b35a32e 118=item *
119
120L<DBIx::Class::Schema::Loader> (existing DB only)
121
122=item *
123
124L<DBIx::Class::Schema::Versioned> (new or existing DB)
125
126=item *
127
128L<DBIx::Class::DeploymentHandler> (new or existing DB)
129
130=item *
131
132L<DBIx::Class::Migration> (new or existing DB)
133
134=back
135
136This document only covers the manual method and L<DBICSL|/Using
137DBIx::Class::Schema::Loader>. However, users with complex schemas might want
138to check out the latest deployment tech to make life easier.
076652e8 139
140=head2 Setting it up manually
141
7b35a32e 142=head3 Schema
143
5cc9fa32 144First, you should create your base schema class, which inherits from
145L<DBIx::Class::Schema>:
076652e8 146
5cc9fa32 147 package My::Schema;
148 use base qw/DBIx::Class::Schema/;
149
7b35a32e 150In this class, you load your C<result_source> ("table", "model") classes, which
151we will define later, using the L<load_namespaces|DBIx::Class::Schema/load_namespaces>
152method:
076652e8 153
da7372ac 154 # load My::Schema::Result::* and their resultset classes
155 __PACKAGE__->load_namespaces();
076652e8 156
7b35a32e 157By default, this loads all the L<Result classes|DBIx::Class::Manual::ResultClass>
158in the C<My::Schema::Result::> namespace, and also any ResultSet classes in the
159C<My::Schema::ResultSet::> namespace. (If missing, the ResultSets are
160defaulted to be L<DBIx::Class::ResultSet> objects.) You can change the Result
161and ResultSet namespaces by using options to the
162L<load_namespaces|DBIx::Class::Schema/load_namespaces> call.
076652e8 163
da7372ac 164It is also possible to do the same things manually by calling
7b35a32e 165L<load_classes|DBIx::Class::Schema/load_classes> for the
166L<Result classes|DBIx::Class::Manual::ResultClass> and
167defining in those classes any required ResultSet classes.
168
169=head3 Result class
170
171=head4 Header
076652e8 172
5cc9fa32 173Next, create each of the classes you want to load as specified above:
076652e8 174
da7372ac 175 package My::Schema::Result::Album;
d88ecca6 176 use base qw/DBIx::Class::Core/;
35d4fe78 177
7b35a32e 178Load any additional components you may need with the
179L<load_components|Class::C3::Componentised/load_components( @comps )> method,
180and provide component configuration if required. For example, if you want
d88ecca6 181automatic row ordering:
076652e8 182
d88ecca6 183 __PACKAGE__->load_components(qw/ Ordered /);
184 __PACKAGE__->position_column('rank');
076652e8 185
7b35a32e 186(See L<DBIx::Class::Ordered> for more information.)
81aa4300 187
5cc9fa32 188Set the table for your class:
076652e8 189
35d4fe78 190 __PACKAGE__->table('album');
076652e8 191
7b35a32e 192=head4 Columns
193
5cc9fa32 194Add columns to your class:
195
d88ecca6 196 __PACKAGE__->add_columns(qw/ albumid artist title rank /);
5cc9fa32 197
d53178fd 198Each column can also be set up with its own accessor, data_type and other pieces
199of information that it may be useful to have -- just pass C<add_columns> a hash:
5cc9fa32 200
7b35a32e 201 __PACKAGE__->add_columns(
202 albumid => {
203 accessor => 'album',
204 data_type => 'integer',
205 size => 16,
206 is_nullable => 0,
207 is_auto_increment => 1,
208 },
209 artist => {
210 data_type => 'integer',
211 size => 16,
212 is_nullable => 0,
213 },
214 title => {
215 data_type => 'varchar',
216 size => 256,
217 is_nullable => 0,
218 },
219 rank => {
220 data_type => 'integer',
221 size => 16,
222 is_nullable => 0,
223 default_value => 0,
224 },
225 );
226
227L<DBIC|DBIx::Class> doesn't directly use most of this data yet, but various
228related modules, such as L<HTML::FormHandler::Model::DBIC>, make use of it. Also,
229it allows you to create your database tables from your Schema, instead of the
230other way around. See L<DBIx::Class::Schema/deploy> for details.
231
232See L<DBIx::Class::ResultSource/add_columns> for more details of the possible column
5cc9fa32 233attributes.
234
7b35a32e 235Accessors are created for each column automatically, so C<My::Schema::Result::Album>
236will have C<albumid> (or C<album>, when using the accessor shown above), C<artist>
237and C<title> methods.
238
239=head4 Primary Key
5cc9fa32 240
241Define a primary key for your class:
076652e8 242
5cc9fa32 243 __PACKAGE__->set_primary_key('albumid');
076652e8 244
5cc9fa32 245If you have a multi-column primary key, just pass a list instead:
076652e8 246
5cc9fa32 247 __PACKAGE__->set_primary_key( qw/ albumid artistid / );
076652e8 248
7b35a32e 249=head4 Relationships
250
251Define this class' relationships with other classes using either
252L<belongs_to|DBIx::Class::Relationship/belongs_to> to describe a column which
253contains an ID of another Table, or
254L<has_many|DBIx::Class::Relationship/has_many> to make a predefined accessor for
255fetching objects that contain this Table's foreign key:
5cc9fa32 256
4ae94ded 257 # in My::Schema::Result::Artist
258 __PACKAGE__->has_many('albums', 'My::Schema::Result::Album', 'artist');
076652e8 259
d53178fd 260See L<DBIx::Class::Relationship> for more information about the various types of
261available relationships and how you can design your own.
076652e8 262
cab77187 263=head2 Using DBIx::Class::Schema::Loader
076652e8 264
7b35a32e 265L<DBICSL|DBIx::Class::Schema::Loader> is an external module, and not part
266of the L<DBIC|DBIx::Class> distribution. It inspects your database, and
267automatically creates classes for all the tables in your schema.
076652e8 268
5fe8a42e 269The simplest way to use it is via the L<dbicdump> script from the
270L<DBIx::Class::Schema::Loader> distribution. For example:
271
cab77187 272 $ dbicdump -o dump_directory=./lib \
273 -o components='["InflateColumn::DateTime"]' \
274 MyApp::Schema dbi:mysql:mydb user pass
5fe8a42e 275
276If you have a mixed-case database, use the C<preserve_case> option, e.g.:
277
cab77187 278 $ dbicdump -o dump_directory=./lib -o preserve_case=1 \
279 -o components='["InflateColumn::DateTime"]' \
280 MyApp::Schema dbi:mysql:mydb user pass
40dbc108 281
5fe8a42e 282If you are using L<Catalyst>, then you can use the helper that comes with
283L<Catalyst::Model::DBIC::Schema>:
076652e8 284
5fe8a42e 285 $ script/myapp_create.pl model MyDB DBIC::Schema MyDB::Schema \
286 create=static moniker_map='{ foo => "FOO" }' dbi:SQLite:./myapp.db \
03535356 287 on_connect_do='PRAGMA foreign_keys=ON' quote_char='"'
076652e8 288
5fe8a42e 289See L<Catalyst::Helper::Model::DBIC::Schema> for more information on this
290helper.
3f073ddf 291
5fe8a42e 292See the L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>
293documentation for more information on the many loader options.
076652e8 294
5cc9fa32 295=head2 Connecting
296
6ba55998 297To connect to your Schema, you need to provide the connection details or a
298database handle.
299
300=head3 Via connection details
301
302The arguments are the same as for L<DBI/connect>:
5cc9fa32 303
304 my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
305
d53178fd 306You can create as many different schema instances as you need. So if you have a
307second database you want to access:
5cc9fa32 308
309 my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
310
d53178fd 311Note that L<DBIx::Class::Schema> does not cache connections for you. If you use
312multiple connections, you need to do this manually.
5cc9fa32 313
48580715 314To execute some SQL statements on every connect you can add them as an option in
d53178fd 315a special fifth argument to connect:
3f073ddf 316
317 my $another_schema = My::Schema->connect(
318 $dsn,
319 $user,
320 $password,
321 $attrs,
322 { on_connect_do => \@on_connect_sql_statments }
323 );
5cc9fa32 324
e0b505d4 325See L<DBIx::Class::Storage::DBI/connect_info> for more information about
d53178fd 326this and other special C<connect>-time options.
5cc9fa32 327
6ba55998 328=head3 Via a database handle
329
330The supplied coderef is expected to return a single connected database handle
331(e.g. a L<DBI> C<$dbh>)
332
333 my $schema = My::Schema->connect (
334 sub { Some::DBH::Factory->connect },
335 \%extra_attrs,
336 );
337
40dbc108 338=head2 Basic usage
076652e8 339
35d4fe78 340Once you've defined the basic classes, either manually or using
5cc9fa32 341L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
342
d53178fd 343To access your database using your $schema object, you can fetch a
344L<DBIx::Class::Manual::Glossary/"ResultSet"> representing each of your tables by
345calling the C<resultset> method.
5cc9fa32 346
35d4fe78 347The simplest way to get a record is by primary key:
076652e8 348
5cc9fa32 349 my $album = $schema->resultset('Album')->find(14);
076652e8 350
d53178fd 351This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause, and
da7372ac 352return an instance of C<My::Schema::Result::Album> that represents this row. Once you
d53178fd 353have that row, you can access and update columns:
076652e8 354
35d4fe78 355 $album->title('Physical Graffiti');
356 my $title = $album->title; # $title holds 'Physical Graffiti'
076652e8 357
d53178fd 358If you prefer, you can use the C<set_column> and C<get_column> accessors
359instead:
076652e8 360
35d4fe78 361 $album->set_column('title', 'Presence');
362 $title = $album->get_column('title');
076652e8 363
18bb9eca 364Just like with L<Class::DBI>, you call C<update> to save your changes to the
365database (by executing the actual C<UPDATE> statement):
40dbc108 366
35d4fe78 367 $album->update;
076652e8 368
d53178fd 369If needed, you can throw away your local changes:
076652e8 370
35d4fe78 371 $album->discard_changes if $album->is_changed;
076652e8 372
d53178fd 373As you can see, C<is_changed> allows you to check if there are local changes to
374your object.
076652e8 375
40dbc108 376=head2 Adding and removing rows
076652e8 377
d53178fd 378To create a new record in the database, you can use the C<create> method. It
da7372ac 379returns an instance of C<My::Schema::Result::Album> that can be used to access the data
d53178fd 380in the new record:
076652e8 381
d56c3191 382 my $new_album = $schema->resultset('Album')->create({
35d4fe78 383 title => 'Wish You Were Here',
384 artist => 'Pink Floyd'
385 });
dfeba824 386
387Now you can add data to the new record:
388
35d4fe78 389 $new_album->label('Capitol');
390 $new_album->year('1975');
391 $new_album->update;
076652e8 392
d53178fd 393Likewise, you can remove it from the database:
076652e8 394
35d4fe78 395 $new_album->delete;
076652e8 396
d53178fd 397You can also remove records without retrieving them first, by calling delete
398directly on a ResultSet object.
076652e8 399
35d4fe78 400 # Delete all of Falco's albums
5cc9fa32 401 $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
076652e8 402
40dbc108 403=head2 Finding your objects
076652e8 404
7b35a32e 405L<DBIC|DBIx::Class> provides a few different ways to retrieve data from your
d53178fd 406database. Here's one example:
35d4fe78 407
408 # Find all of Santana's albums
5cc9fa32 409 my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
35d4fe78 410
d53178fd 411In scalar context, as above, C<search> returns a L<DBIx::Class::ResultSet>
412object. It can be used to peek at the first album returned by the database:
35d4fe78 413
414 my $album = $rs->first;
415 print $album->title;
076652e8 416
5cc9fa32 417You can loop over the albums and update each one:
076652e8 418
35d4fe78 419 while (my $album = $rs->next) {
420 print $album->artist . ' - ' . $album->title;
421 $album->year(2001);
422 $album->update;
423 }
a3c5e7e3 424
5cc9fa32 425Or, you can update them all at once:
426
427 $rs->update({ year => 2001 });
428
d53178fd 429In list context, the C<search> method returns all of the matching rows:
a3c5e7e3 430
35d4fe78 431 # Fetch immediately all of Carlos Santana's albums
5cc9fa32 432 my @albums = $schema->resultset('Album')->search(
433 { artist => 'Carlos Santana' }
434 );
35d4fe78 435 foreach my $album (@albums) {
436 print $album->artist . ' - ' . $album->title;
437 }
076652e8 438
40dbc108 439We also provide a handy shortcut for doing a C<LIKE> search:
076652e8 440
35d4fe78 441 # Find albums whose artist starts with 'Jimi'
24d34a80 442 my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
076652e8 443
d53178fd 444Or you can provide your own C<WHERE> clause:
35d4fe78 445
446 # Find Peter Frampton albums from the year 1986
447 my $where = 'artist = ? AND year = ?';
448 my @bind = ( 'Peter Frampton', 1986 );
5cc9fa32 449 my $rs = $schema->resultset('Album')->search_literal( $where, @bind );
40dbc108 450
d53178fd 451The preferred way to generate complex queries is to provide a L<SQL::Abstract>
452construct to C<search>:
40dbc108 453
5cc9fa32 454 my $rs = $schema->resultset('Album')->search({
35d4fe78 455 artist => { '!=', 'Janis Joplin' },
456 year => { '<' => 1980 },
1aec4bac 457 albumid => { '-in' => [ 1, 14, 15, 65, 43 ] }
35d4fe78 458 });
459
460This results in something like the following C<WHERE> clause:
40dbc108 461
35d4fe78 462 WHERE artist != 'Janis Joplin'
463 AND year < 1980
464 AND albumid IN (1, 14, 15, 65, 43)
465
d53178fd 466For more examples of complex queries, see L<DBIx::Class::Manual::Cookbook>.
40dbc108 467
468The search can also be modified by passing another hash with
469attributes:
470
24d34a80 471 my @albums = My::Schema->resultset('Album')->search(
35d4fe78 472 { artist => 'Bob Marley' },
4e11ba0a 473 { rows => 2, order_by => { -desc => 'year' } }
35d4fe78 474 );
475
476C<@albums> then holds the two most recent Bob Marley albums.
40dbc108 477
d53178fd 478For more information on what you can do with a L<DBIx::Class::ResultSet>, see
479L<DBIx::Class::ResultSet/METHODS>.
480
40dbc108 481For a complete overview of the available attributes, see
482L<DBIx::Class::ResultSet/ATTRIBUTES>.
076652e8 483
11736b4c 484=head1 NOTES
485
ef8f6e19 486=head2 The Significance and Importance of Primary Keys
487
488The concept of a L<primary key|DBIx::Class::ResultSource/set_primary_key> in
7b35a32e 489L<DBIC|DBIx::Class> warrants special discussion. The formal definition (which somewhat
ef8f6e19 490resembles that of a classic RDBMS) is I<a unique constraint that is least
7b35a32e 491likely to change after initial row creation>. However, this is where the
492similarity ends. Any time you call a CRUD operation on a row (e.g.
ef8f6e19 493L<delete|DBIx::Class::Row/delete>,
494L<update|DBIx::Class::Row/update>,
495L<discard_changes|DBIx::Class::Row/discard_changes>,
7b35a32e 496etc.), L<DBIC|DBIx::Class> will use the values of of the
ef8f6e19 497L<primary key|DBIx::Class::ResultSource/set_primary_key> columns to populate
7b35a32e 498the C<WHERE> clause necessary to accomplish the operation. This is why it is
d6988be8 499important to declare a L<primary key|DBIx::Class::ResultSource/set_primary_key>
500on all your result sources B<even if the underlying RDBMS does not have one>.
7b35a32e 501In a pinch, one can always declare each row identifiable by all its columns:
ef8f6e19 502
a5d797bb 503 __PACKAGE__->set_primary_key(__PACKAGE__->columns);
ef8f6e19 504
7b35a32e 505Note that L<DBIC|DBIx::Class> is smart enough to store a copy of the PK values before
d6988be8 506any row-object changes take place, so even if you change the values of PK
7b35a32e 507columns, the C<WHERE> clause will remain correct.
d6988be8 508
7b35a32e 509If you elect not to declare a C<primary key>, L<DBIC|DBIx::Class> will behave correctly
ef8f6e19 510by throwing exceptions on any row operation that relies on unique identifiable
7b35a32e 511rows. If you inherited datasets with multiple identical rows in them, you can
ef8f6e19 512still operate with such sets provided you only utilize
513L<DBIx::Class::ResultSet> CRUD methods:
514L<search|DBIx::Class::ResultSet/search>,
515L<update|DBIx::Class::ResultSet/update>,
516L<delete|DBIx::Class::ResultSet/delete>
517
d6988be8 518For example, the following would not work (assuming C<People> does not have
519a declared PK):
63ec9705 520
521 my $row = $schema->resultset('People')
d6988be8 522 ->search({ last_name => 'Dantes' })
523 ->next;
63ec9705 524 $row->update({ children => 2 }); # <-- exception thrown because $row isn't
525 # necessarily unique
526
7b35a32e 527So, instead the following should be done:
63ec9705 528
d6988be8 529 $schema->resultset('People')
530 ->search({ last_name => 'Dantes' })
531 ->update({ children => 2 }); # <-- update's ALL Dantes to have children of 2
ef8f6e19 532
11736b4c 533=head2 Problems on RHEL5/CentOS5
534
dc253b77 535There used to be an issue with the system perl on Red Hat Enterprise
536Linux 5, some versions of Fedora and derived systems. Further
537information on this can be found in L<DBIx::Class::Manual::Troubleshooting>
11736b4c 538
40dbc108 539=head1 SEE ALSO
076652e8 540
40dbc108 541=over 4
076652e8 542
40dbc108 543=item * L<DBIx::Class::Manual::Cookbook>
076652e8 544
7b35a32e 545=item * L<DBIx::Class::Manual::ResultClass>
546
784b08ba 547=head1 AUTHOR AND CONTRIBUTORS
076652e8 548
784b08ba 549See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class