Added startup checks to warn loudly if we appear to be running on RedHat systems...
[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
14DBIx::Class.
4b0779f4 15
16=head2 Tables become ResultSources
17
d53178fd 18DBIx::Class needs to know what your Table structure looks like. You do that by
19defining L<DBIx::Class::ResultSource>s. Each table gets a ResultSource, which
20defines the Columns it has, along with any Relationships it has to other tables.
21(And oh, so much more besides) The important thing to understand:
22
4b0779f4 23 A ResultSource == Table
d53178fd 24
4b0779f4 25(most of the time, but just bear with my simplification)
26
27=head2 It's all about the ResultSet
28
d53178fd 29So, we've got some ResultSources defined. Now, we want to actually use those
30definitions to help us translate the queries we need into handy perl objects!
31
32Let's say we defined a ResultSource for an "album" table with three columns:
33"albumid", "artist", and "title". Any time we want to query this table, we'll
34be creating a L<DBIx::Class::ResultSet> from its ResultSource. For example, the
35results of:
4b0779f4 36
d53178fd 37 SELECT albumid, artist, title FROM album;
4b0779f4 38
d53178fd 39Would be retrieved by creating a ResultSet object from the album table's
40ResultSource, likely by using the "search" method.
4b0779f4 41
d53178fd 42DBIx::Class doesn't limit you to creating only simple ResultSets -- if you
43wanted to do something like:
44
45 SELECT title FROM album GROUP BY title;
4b0779f4 46
4b0779f4 47You could easily achieve it.
48
49The important thing to understand:
50
d53178fd 51 Any time you would reach for a SQL query in DBI, you are
52 creating a DBIx::Class::ResultSet.
4b0779f4 53
54=head2 Search is like "prepare"
55
d53178fd 56DBIx::Class tends to wait until it absolutely must fetch information from the
57database. If you are returning a ResultSet, the query won't execute until you
58use a method that wants to access the data. (Such as "next", or "first")
4b0779f4 59
60The important thing to understand:
61
d53178fd 62 Setting up a ResultSet does not execute the query; retrieving
63 the data does.
4b0779f4 64
65=head1 SETTING UP DBIx::Class
66
d53178fd 67Let's look at how you can set and use your first native L<DBIx::Class> tree.
076652e8 68
d53178fd 69First we'll see how you can set up your classes yourself. If you want them to
70be auto-discovered, just skip to the next section, which shows you how to use
71L<DBIx::Class::Schema::Loader>.
076652e8 72
73=head2 Setting it up manually
74
5cc9fa32 75First, you should create your base schema class, which inherits from
76L<DBIx::Class::Schema>:
076652e8 77
5cc9fa32 78 package My::Schema;
79 use base qw/DBIx::Class::Schema/;
80
d53178fd 81In this class you load your result_source ("table", "model") classes, which we
82will define later, using the load_classes() method. You can specify which
5cc9fa32 83classes to load manually:
076652e8 84
5cc9fa32 85 # load My::Schema::Album and My::Schema::Artist
86 __PACKAGE__->load_classes(qw/ Album Artist /);
076652e8 87
5cc9fa32 88Or load classes by namespace:
076652e8 89
5cc9fa32 90 # load My::Schema::Album, My::Schema::Artist and My::OtherSchema::LinerNotes
91 __PACKAGE__->load_classes(
92 {
93 'My::Schema' => [qw/ Album Artist /],
94 'My::OtherSchema' => [qw/ LinerNotes /]
95 }
96 );
97
98Or let your schema class load all classes in its namespace automatically:
076652e8 99
5cc9fa32 100 # load My::Schema::*
101 __PACKAGE__->load_classes();
076652e8 102
5cc9fa32 103Next, create each of the classes you want to load as specified above:
076652e8 104
5cc9fa32 105 package My::Schema::Album;
106 use base qw/DBIx::Class/;
35d4fe78 107
5cc9fa32 108Load any components required by each class with the load_components() method.
109This should consist of "Core" plus any additional components you want to use.
110For example, if you want serial/auto-incrementing primary keys:
076652e8 111
5cc9fa32 112 __PACKAGE__->load_components(qw/ PK::Auto Core /);
076652e8 113
d53178fd 114C<PK::Auto> is supported for many databases; see L<DBIx::Class::Storage::DBI>
115for more information.
076652e8 116
5cc9fa32 117Set the table for your class:
076652e8 118
35d4fe78 119 __PACKAGE__->table('album');
076652e8 120
5cc9fa32 121Add columns to your class:
122
123 __PACKAGE__->add_columns(qw/ albumid artist title /);
124
d53178fd 125Each column can also be set up with its own accessor, data_type and other pieces
126of information that it may be useful to have -- just pass C<add_columns> a hash:
5cc9fa32 127
128 __PACKAGE__->add_columns(albumid =>
129 { accessor => 'album',
130 data_type => 'integer',
131 size => 16,
132 is_nullable => 0,
133 is_auto_increment => 1,
134 default_value => '',
135 },
136 artist =>
137 { data_type => 'integer',
138 size => 16,
139 is_nullable => 0,
140 is_auto_increment => 0,
141 default_value => '',
142 },
143 title =>
144 { data_type => 'varchar',
145 size => 256,
146 is_nullable => 0,
147 is_auto_increment => 0,
148 default_value => '',
149 }
150 );
151
d53178fd 152DBIx::Class doesn't directly use most of this data yet, but various related
153modules such as L<DBIx::Class::WebForm> make use of it. Also it allows you to
154create your database tables from your Schema, instead of the other way around.
155See L<SQL::Translator> for details.
5cc9fa32 156
157See L<DBIx::Class::ResultSource> for more details of the possible column
158attributes.
159
160Accessors are created for each column automatically, so My::Schema::Album will
161have albumid() (or album(), when using the accessor), artist() and title()
162methods.
163
164Define a primary key for your class:
076652e8 165
5cc9fa32 166 __PACKAGE__->set_primary_key('albumid');
076652e8 167
5cc9fa32 168If you have a multi-column primary key, just pass a list instead:
076652e8 169
5cc9fa32 170 __PACKAGE__->set_primary_key( qw/ albumid artistid / );
076652e8 171
d53178fd 172Define this class' relationships with other classes using either C<belongs_to>
173to describe a column which contains an ID of another Table, or C<has_many> to
174make a predefined accessor for fetching objects that contain this Table's
175foreign key:
5cc9fa32 176
177 __PACKAGE__->has_many('albums', 'My::Schema::Artist', 'album_id');
076652e8 178
d53178fd 179See L<DBIx::Class::Relationship> for more information about the various types of
180available relationships and how you can design your own.
076652e8 181
5cc9fa32 182=head2 Using L<DBIx::Class::Schema::Loader>
076652e8 183
d53178fd 184This is an external module, and not part of the L<DBIx::Class> distribution.
185Like L<Class::DBI::Loader>, it inspects your database, and automatically creates
186classes for all the tables in your database. Here's a simple setup:
076652e8 187
24d34a80 188 package My::Schema;
189 use base qw/DBIx::Class::Schema::Loader/;
40dbc108 190
3f073ddf 191 __PACKAGE__->loader_options( relationships => 1 );
076652e8 192
35d4fe78 193 1;
076652e8 194
d53178fd 195The actual autoloading process will occur when you create a connected instance
196of your schema below.
3f073ddf 197
d53178fd 198See the L<DBIx::Class::Schema::Loader> documentation for more information on its
199many options.
076652e8 200
5cc9fa32 201=head2 Connecting
202
d53178fd 203To connect to your Schema, you need to provide the connection details. The
204arguments are the same as for L<DBI/connect>:
5cc9fa32 205
206 my $schema = My::Schema->connect('dbi:SQLite:/home/me/myapp/my.db');
207
d53178fd 208You can create as many different schema instances as you need. So if you have a
209second database you want to access:
5cc9fa32 210
211 my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
212
d53178fd 213Note that L<DBIx::Class::Schema> does not cache connections for you. If you use
214multiple connections, you need to do this manually.
5cc9fa32 215
d53178fd 216To execute some sql statements on every connect you can add them as an option in
217a special fifth argument to connect:
3f073ddf 218
219 my $another_schema = My::Schema->connect(
220 $dsn,
221 $user,
222 $password,
223 $attrs,
224 { on_connect_do => \@on_connect_sql_statments }
225 );
5cc9fa32 226
d53178fd 227See L<DBIx::Class::Schema::Storage::DBI/connect_info> for more information about
228this and other special C<connect>-time options.
5cc9fa32 229
40dbc108 230=head2 Basic usage
076652e8 231
35d4fe78 232Once you've defined the basic classes, either manually or using
5cc9fa32 233L<DBIx::Class::Schema::Loader>, you can start interacting with your database.
234
d53178fd 235To access your database using your $schema object, you can fetch a
236L<DBIx::Class::Manual::Glossary/"ResultSet"> representing each of your tables by
237calling the C<resultset> method.
5cc9fa32 238
35d4fe78 239The simplest way to get a record is by primary key:
076652e8 240
5cc9fa32 241 my $album = $schema->resultset('Album')->find(14);
076652e8 242
d53178fd 243This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause, and
244return an instance of C<My::Schema::Album> that represents this row. Once you
245have that row, you can access and update columns:
076652e8 246
35d4fe78 247 $album->title('Physical Graffiti');
248 my $title = $album->title; # $title holds 'Physical Graffiti'
076652e8 249
d53178fd 250If you prefer, you can use the C<set_column> and C<get_column> accessors
251instead:
076652e8 252
35d4fe78 253 $album->set_column('title', 'Presence');
254 $title = $album->get_column('title');
076652e8 255
d53178fd 256Just like with L<Class::DBI>, you call C<update> to commit your changes to the
257database:
40dbc108 258
35d4fe78 259 $album->update;
076652e8 260
d53178fd 261If needed, you can throw away your local changes:
076652e8 262
35d4fe78 263 $album->discard_changes if $album->is_changed;
076652e8 264
d53178fd 265As you can see, C<is_changed> allows you to check if there are local changes to
266your object.
076652e8 267
40dbc108 268=head2 Adding and removing rows
076652e8 269
d53178fd 270To create a new record in the database, you can use the C<create> method. It
271returns an instance of C<My::Schema::Album> that can be used to access the data
272in the new record:
076652e8 273
5cc9fa32 274 my $new_album = $schema->resultset('Album')->create({
35d4fe78 275 title => 'Wish You Were Here',
276 artist => 'Pink Floyd'
277 });
dfeba824 278
279Now you can add data to the new record:
280
35d4fe78 281 $new_album->label('Capitol');
282 $new_album->year('1975');
283 $new_album->update;
076652e8 284
d53178fd 285Likewise, you can remove it from the database:
076652e8 286
35d4fe78 287 $new_album->delete;
076652e8 288
d53178fd 289You can also remove records without retrieving them first, by calling delete
290directly on a ResultSet object.
076652e8 291
35d4fe78 292 # Delete all of Falco's albums
5cc9fa32 293 $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
076652e8 294
40dbc108 295=head2 Finding your objects
076652e8 296
d53178fd 297L<DBIx::Class> provides a few different ways to retrieve data from your
298database. Here's one example:
35d4fe78 299
300 # Find all of Santana's albums
5cc9fa32 301 my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
35d4fe78 302
d53178fd 303In scalar context, as above, C<search> returns a L<DBIx::Class::ResultSet>
304object. It can be used to peek at the first album returned by the database:
35d4fe78 305
306 my $album = $rs->first;
307 print $album->title;
076652e8 308
5cc9fa32 309You can loop over the albums and update each one:
076652e8 310
35d4fe78 311 while (my $album = $rs->next) {
312 print $album->artist . ' - ' . $album->title;
313 $album->year(2001);
314 $album->update;
315 }
a3c5e7e3 316
5cc9fa32 317Or, you can update them all at once:
318
319 $rs->update({ year => 2001 });
320
d53178fd 321In list context, the C<search> method returns all of the matching rows:
a3c5e7e3 322
35d4fe78 323 # Fetch immediately all of Carlos Santana's albums
5cc9fa32 324 my @albums = $schema->resultset('Album')->search(
325 { artist => 'Carlos Santana' }
326 );
35d4fe78 327 foreach my $album (@albums) {
328 print $album->artist . ' - ' . $album->title;
329 }
076652e8 330
40dbc108 331We also provide a handy shortcut for doing a C<LIKE> search:
076652e8 332
35d4fe78 333 # Find albums whose artist starts with 'Jimi'
24d34a80 334 my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
076652e8 335
d53178fd 336Or you can provide your own C<WHERE> clause:
35d4fe78 337
338 # Find Peter Frampton albums from the year 1986
339 my $where = 'artist = ? AND year = ?';
340 my @bind = ( 'Peter Frampton', 1986 );
5cc9fa32 341 my $rs = $schema->resultset('Album')->search_literal( $where, @bind );
40dbc108 342
d53178fd 343The preferred way to generate complex queries is to provide a L<SQL::Abstract>
344construct to C<search>:
40dbc108 345
5cc9fa32 346 my $rs = $schema->resultset('Album')->search({
35d4fe78 347 artist => { '!=', 'Janis Joplin' },
348 year => { '<' => 1980 },
1aec4bac 349 albumid => { '-in' => [ 1, 14, 15, 65, 43 ] }
35d4fe78 350 });
351
352This results in something like the following C<WHERE> clause:
40dbc108 353
35d4fe78 354 WHERE artist != 'Janis Joplin'
355 AND year < 1980
356 AND albumid IN (1, 14, 15, 65, 43)
357
d53178fd 358For more examples of complex queries, see L<DBIx::Class::Manual::Cookbook>.
40dbc108 359
360The search can also be modified by passing another hash with
361attributes:
362
24d34a80 363 my @albums = My::Schema->resultset('Album')->search(
35d4fe78 364 { artist => 'Bob Marley' },
365 { rows => 2, order_by => 'year DESC' }
366 );
367
368C<@albums> then holds the two most recent Bob Marley albums.
40dbc108 369
d53178fd 370For more information on what you can do with a L<DBIx::Class::ResultSet>, see
371L<DBIx::Class::ResultSet/METHODS>.
372
40dbc108 373For a complete overview of the available attributes, see
374L<DBIx::Class::ResultSet/ATTRIBUTES>.
076652e8 375
11736b4c 376=head1 NOTES
377
378=head2 Problems on RHEL5/CentOS5
379
380There is a problem with slow performance of certain DBIx::Class operations in
381perl-5.8.8-10 and later on RedHat and related systems, due to a bad backport of
382a "use overload" related bug. The problem is in the Perl binary itself, not in
383DBIx::Class. If your system has this problem, you will see a warning on
384startup, with some options as to what to do about it.
385
40dbc108 386=head1 SEE ALSO
076652e8 387
40dbc108 388=over 4
076652e8 389
40dbc108 390=item * L<DBIx::Class::Manual::Cookbook>
076652e8 391
40dbc108 392=back
076652e8 393
394=cut