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