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