doc tweaks, failing test from jcs
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / SchemaIntro.pod
CommitLineData
8292706e 1=head1 NAME
2
3DBIx::Class::Manual::SchemaIntro - Introduction to DBIx::Class::Schema
4
5=head1 INTRODUCTION
6
7This document describes how to set up DBIx::Class using the recommended
8schema-based approach.
9
10=head2 Setup
11
12First, you should create your base schema class, which inherits from
13L<DBIx::Class::Schema>:
14
15 package My::Schema;
16 use base qw/DBIx::Class::Schema/;
17
80c90f5d 18In this class you load your result_source ("table", "model") classes, which
8292706e 19we will define later, using the load_classes() method. You can specify which
20classes to load manually:
21
22 # load My::Schema::Album and My::Schema::Artist
23 __PACKAGE__->load_classes(qw/ Album Artist /);
24
25Or load classes by namespace:
26
27 # load My::Schema::Album, My::Schema::Artist and My::OtherSchema::LinerNotes
28 __PACKAGE__->load_classes(
29 {
86a42388 30 'My::Schema' => [qw/ Album Artist /],
31 'My::OtherSchema' => [qw/ LinerNotes /]
8292706e 32 }
33 );
34
35Or let your schema class load all classes in its namespace automatically:
36
37 # load My::Schema::*
38 __PACKAGE__->load_classes();
39
40Next, create each of the classes you want to load as specified above:
41
42 package My::Schema::Album;
43 use base qw/DBIx::Class/;
44
45Load any components required by each class with the load_components() method.
46This should consist of "Core" plus any additional components you want to use.
47For example, if you use SQLite and want serial/auto-incrementing primary keys:
48
49 __PACKAGE__->load_components(qw/ PK::Auto::SQLite Core /);
50
51C<PK::Auto> classes exist for many databases; see
52L<DBIx::Class::PK::Auto> for more information.
53
54Set the table for your class:
55
56 __PACKAGE__->table('album');
57
58Add columns to your class:
59
60 __PACKAGE__->add_columns(qw/ albumid artist title /);
61
62Accessors are created for each column automatically, so My::Schema::Album will
63have albumid(), artist() and title() methods.
64
65Define a primary key for your class:
66
67 __PACKAGE__->set_primary_key('albumid');
68
69If you have a multi-column primary key, just pass a list instead:
70
71 __PACKAGE__->set_primary_key( qw/ albumid artistid / );
72
f109ee4a 73=begin hide
74
8292706e 75You can define relationships for any of your classes. L<DBIx::Class> will
76automatically fill in the correct namespace, so if you want to say
77"a My::Schema::Album object belongs to a My::Schema::Artist object" you do not
78need to include the namespace when declaring the relationship:
79
80 __PACKAGE__->belongs_to('artist' => 'Artist');
81
f109ee4a 82=end hide
83
8292706e 84That's all you need in terms of setup.
85
86=head2 Usage
87
88In your application code, you should first create a connected schema object:
89
90 my $schema = My::Schema->connect( $dsn, $user, $password, $attrs );
91
92You can create as many different schema instances as you need. So if you have
93a second database you want to access:
94
95 my $other_schema = My::Schema->connect( $dsn, $user, $password, $attrs );
96
97Note that L<DBIx::Class::Schema> does not cache connnections for you. If you
98use multiple connections, you need to do this manually.
99
d7c4c15c 100To execute some sql statements on every connect you can pass them to your schema after the connect:
101
102 $schema->storage->on_connect_do(\@on_connect_sql_statments);
103
8292706e 104The simplest way to get a record is by primary key:
105
106 my $schema = My::Schema->connect( ... );
107 my $album = $schema->resultset('Album')->find(14);
108
109This will run a C<SELECT> with C<albumid = 14> in the C<WHERE> clause,
110and return an instance of C<My::Schema::Album> that represents this
111row. Once you have that row, you can access and update columns:
112
84e7c3de 113 $album->title('Physical Graffiti');
8292706e 114 my $title = $album->title; # holds 'Physical Graffiti'
115
116If you prefer, you can use the C<set_column> and C<get_column>
117accessors instead:
118
119 $album->set_column('title', 'Presence');
120 $title = $album->get_column('title');
121
122You use C<update> to commit your changes to the database:
123
124 $album->update();
125
126If needed, you can throw away your local changes like this:
127
128 $album->discard_changes() if $album->is_changed();
129
130As you can see, C<is_changed> allows you to check if there are local
131changes to your object.
132
133=head2 Adding and removing rows
134
135To create a new record in the database, you can use the C<create>
136method. It returns an instance of C<My::Schema::Album> that can be
137used to access the data in the new record:
138
139 my $new_album = $schema->resultset('Album')->create({
140 title => 'Wish You Were Here',
141 artist => 'Pink Floyd'
142 });
143
144Now you can add data to the new record:
145
146 $new_album->label('Capitol');
147 $new_album->year('1975');
148 $new_album->update;
149
150Likewise, you can remove it from the database like this:
151
152 $new_album->delete;
153
c5e2c462 154You can also remove records without retrieving them first, by calling
155delete directly on a ResultSet object.
8292706e 156
157 # Delete all of Falco's albums
c5e2c462 158 $schema->resultset('Album')->search({ artist => 'Falco' })->delete;
8292706e 159
160=head2 Finding your objects
161
162L<DBIx::Class> provides a few different ways to retrieve data from
163your database. Here's one example:
164
165 # Find all of Santana's albums
166 my $rs = $schema->resultset('Album')->search({ artist => 'Santana' });
167
168In scalar context, as above, C<search> returns a
169L<DBIx::Class::ResultSet> object. It can be used to peek at the first
170album returned by the database:
171
172 my $album = $rs->first;
173 print $album->title;
174
175Or, you can loop over the albums and update each one:
176
177 while (my $album = $rs->next) {
178 print $album->artist . ' - ' . $album->title;
179 $album->year(2001);
180 $album->update;
181 }
182
183For more information on what you can do with a
184L<DBIx::Class::ResultSet>, see L<DBIx::Class::ResultSet/METHODS>.
185
186In list context, the C<search> method returns all of the matching
187rows:
188
189 # Fetch immediately all of Carlos Santana's albums
190 my @albums = @{ $schema->resultset('Album')->search(
191 { artist => 'Carlos Santana' }
192 ) };
193 foreach my $album (@albums) {
194 print $album->artist . ' - ' . $album->title;
195 }
196
197We also provide a handy shortcut for doing a C<LIKE> search:
198
199 # Find albums whose artist starts with 'Jimi'
c31f8021 200 my $rs = $schema->resultset('Album')->search_like({ artist => 'Jimi%' });
8292706e 201
202Or you can provide your own handmade C<WHERE> clause, like:
203
204 # Find Peter Frampton albums from the year 1986
205 my $where = 'artist = ? AND year = ?';
206 my @bind = ( 'Peter Frampton', 1986 );
207 my $rs = $schema->resultset('Album')->search_literal( $where, @bind );
208
209The preferred way to generate complex queries is to provide a
210L<SQL::Abstract> construct to C<search>:
211
212 my $rs = $schema->resultset('Album')->search({
213 artist => { '!=', 'Janis Joplin' },
214 year => { '<' => 1980 },
215 albumid => [ 1, 14, 15, 65, 43 ]
216 });
217
218This results in something like the following C<WHERE> clause:
219
220 WHERE artist != 'Janis Joplin'
221 AND year < 1980
222 AND albumid IN (1, 14, 15, 65, 43)
223
224For more examples of complex queries, see
225L<DBIx::Class::Manual::Cookbook>.
226
227The search can also be modified by passing another hash with
228attributes:
229
230 my @albums = $schema->resultset('Album')->search(
231 { artist => 'Bob Marley' },
232 { rows => 2, order_by => 'year DESC' }
233 );
234
235C<@albums> then holds the two most recent Bob Marley albums.
236
237For a complete overview of the available attributes, see
238L<DBIx::Class::ResultSet/ATTRIBUTES>.
239
240=head1 SEE ALSO
241
242=over 4
243
244=item * L<DBIx::Class::Manual::Cookbook>
245
246=item * L<DBIx::Class::Manual::FAQ>
247
248=back
249
250=cut