5d8980f8ec8bf9545c9b50211946235693f7fa4a
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Manual / Example.pod
1 =head1 NAME
2
3 DBIx::Class::Manual::Example - Simple CD database example
4
5 =head1 DESCRIPTION
6
7 This tutorial will guide you through the process of setting up and
8 testing a very basic CD database using SQLite, with DBIx::Class::Schema
9 as the database frontend.
10
11 The database consists of the following:
12
13   table 'artist' with columns:  artistid, name
14   table 'cd'     with columns:  cdid, artist, title
15   table 'track'  with columns:  trackid, cd, title
16
17
18 And these rules exists:
19
20   one artist can have many cds
21   one cd belongs to one artist
22   one cd can have many tracks
23   one track belongs to one cd
24
25
26 =head2 Installation
27
28 Install DBIx::Class via CPAN should be sufficient.
29
30 =head3 Create the database/tables
31
32 First make and change the directory:
33
34   mkdir app
35   cd app
36   mkdir db
37   cd db
38
39 This example uses SQLite which is a dependency of DBIx::Class, so you
40 shouldn't have to install extra software.
41
42 Save the following into a example.sql in the directory db
43
44   CREATE TABLE artist (
45     artistid INTEGER PRIMARY KEY,
46     name TEXT NOT NULL
47   );
48
49   CREATE TABLE cd (
50     cdid INTEGER PRIMARY KEY,
51     artist INTEGER NOT NULL REFERENCES artist(artistid),
52     title TEXT NOT NULL
53   );
54
55   CREATE TABLE track (
56     trackid INTEGER PRIMARY KEY,
57     cd INTEGER NOT NULL REFERENCES cd(cdid),
58     title TEXT NOT NULL
59   );
60
61 and create the sqlite database file:
62
63   sqlite3 example.db < example.sql
64
65 =head3 Set up DBIx::Class::Schema
66
67 Change directory back from db to the directory app:
68
69   cd ../
70
71 Now create some more directories:
72
73   mkdir MyDatabase
74   mkdir MyDatabase/Main
75   mkdir MyDatabase/Main/Result
76   mkdir MyDatabase/Main/ResultSet
77
78 Then, create the following DBIx::Class::Schema classes:
79
80 MyDatabase/Main.pm:
81
82   package MyDatabase::Main;
83   use base qw/DBIx::Class::Schema/;
84   __PACKAGE__->load_namespaces;
85
86   1;
87
88
89 MyDatabase/Main/Result/Artist.pm:
90
91   package MyDatabase::Main::Result::Artist;
92   use base qw/DBIx::Class/;
93   __PACKAGE__->load_components(qw/Core/);
94   __PACKAGE__->table('artist');
95   __PACKAGE__->add_columns(qw/ artistid name /);
96   __PACKAGE__->set_primary_key('artistid');
97   __PACKAGE__->has_many('cds' => 'MyDatabase::Main::Result::Cd');
98
99   1;
100
101
102 MyDatabase/Main/Result/Cd.pm:
103
104   package MyDatabase::Main::Result::Cd;
105   use base qw/DBIx::Class/;
106   __PACKAGE__->load_components(qw/Core/);
107   __PACKAGE__->table('cd');
108   __PACKAGE__->add_columns(qw/ cdid artist title/);
109   __PACKAGE__->set_primary_key('cdid');
110   __PACKAGE__->belongs_to('artist' => 'MyDatabase::Main::Result::Artist');
111   __PACKAGE__->has_many('tracks' => 'MyDatabase::Main::Result::Track');
112
113   1;
114
115
116 MyDatabase/Main/Result/Track.pm:
117
118   package MyDatabase::Main::Result::Track;
119   use base qw/DBIx::Class/;
120   __PACKAGE__->load_components(qw/Core/);
121   __PACKAGE__->table('track');
122   __PACKAGE__->add_columns(qw/ trackid cd title/);
123   __PACKAGE__->set_primary_key('trackid');
124   __PACKAGE__->belongs_to('cd' => 'MyDatabase::Main::Result::Cd');
125
126   1;
127
128
129 =head3 Write a script to insert some records
130
131 insertdb.pl
132
133   #!/usr/bin/perl -w
134
135   use MyDatabase::Main;
136   use strict;
137
138   my $schema = MyDatabase::Main->connect('dbi:SQLite:db/example.db');
139
140   #  here's some of the SQL that is going to be generated by the schema
141   #  INSERT INTO artist VALUES (NULL,'Michael Jackson');
142   #  INSERT INTO artist VALUES (NULL,'Eminem');
143
144   my @artists = (['Michael Jackson'], ['Eminem']);
145   $schema->populate('Artist', [
146      [qw/name/],
147      @artists,
148   ]);
149
150   my %albums = (
151     'Thriller' => 'Michael Jackson',
152     'Bad' => 'Michael Jackson',
153     'The Marshall Mathers LP' => 'Eminem',
154   );
155
156   my @cds;
157   foreach my $lp (keys %albums) {
158     my $artist = $schema->resultset('Artist')->find({
159       name => $albums{$lp}
160     });
161     push @cds, [$lp, $artist->id];
162   }
163
164   $schema->populate('Cd', [
165     [qw/title artist/],
166     @cds,
167   ]);
168
169
170   my %tracks = (
171     'Beat It'         => 'Thriller',
172     'Billie Jean'     => 'Thriller',
173     'Dirty Diana'     => 'Bad',
174     'Smooth Criminal' => 'Bad',
175     'Leave Me Alone'  => 'Bad',
176     'Stan'            => 'The Marshall Mathers LP',
177     'The Way I Am'    => 'The Marshall Mathers LP',
178   );
179
180   my @tracks;
181   foreach my $track (keys %tracks) {
182     my $cdname = $schema->resultset('Cd')->find({
183       title => $tracks{$track},
184     });
185     push @tracks, [$cdname->id, $track];
186   }
187
188   $schema->populate('Track',[
189     [qw/cd title/],
190     @tracks,
191   ]);
192
193 =head3 Create and run the test scripts
194
195 testdb.pl:
196
197   #!/usr/bin/perl -w
198
199   use MyDatabase::Main;
200   use strict;
201
202   my $schema = MyDatabase::Main->connect('dbi:SQLite:db/example.db');
203   # for other DSNs, e.g. MySql, see the perldoc for the relevant dbd
204   # driver, e.g perldoc L<DBD::mysql>.
205
206   get_tracks_by_cd('Bad');
207   get_tracks_by_artist('Michael Jackson');
208
209   get_cd_by_track('Stan');
210   get_cds_by_artist('Michael Jackson');
211
212   get_artist_by_track('Dirty Diana');
213   get_artist_by_cd('The Marshall Mathers LP');
214
215
216   sub get_tracks_by_cd {
217     my $cdtitle = shift;
218     print "get_tracks_by_cd($cdtitle):\n";
219     my $rs = $schema->resultset('Track')->search(
220       {
221         'cd.title' => $cdtitle
222       },
223       {
224         join     => [qw/ cd /],
225       }
226     );
227     while (my $track = $rs->next) {
228       print $track->title . "\n";
229     }
230     print "\n";
231   }
232
233   sub get_tracks_by_artist {
234     my $artistname = shift;
235     print "get_tracks_by_artist($artistname):\n";
236     my $rs = $schema->resultset('Track')->search(
237       {
238         'artist.name' => $artistname
239       },
240       {
241         join => {
242           'cd' => 'artist'
243         },
244       }
245     );
246     while (my $track = $rs->next) {
247       print $track->title . "\n";
248     }
249     print "\n";
250   }
251
252
253   sub get_cd_by_track {
254     my $tracktitle = shift;
255     print "get_cd_by_track($tracktitle):\n";
256     my $rs = $schema->resultset('Cd')->search(
257       {
258         'tracks.title' => $tracktitle
259       },
260       {
261         join     => [qw/ tracks /],
262       }
263     );
264     my $cd = $rs->first;
265     print $cd->title . "\n\n";
266   }
267
268   sub get_cds_by_artist {
269     my $artistname = shift;
270     print "get_cds_by_artist($artistname):\n";
271     my $rs = $schema->resultset('Cd')->search(
272       {
273         'artist.name' => $artistname
274       },
275       {
276         join     => [qw/ artist /],
277       }
278     );
279     while (my $cd = $rs->next) {
280       print $cd->title . "\n";
281     }
282     print "\n";
283   }
284
285
286
287   sub get_artist_by_track {
288     my $tracktitle = shift;
289     print "get_artist_by_track($tracktitle):\n";
290     my $rs = $schema->resultset('Artist')->search(
291       {
292         'tracks.title' => $tracktitle
293       },
294       {
295         join => {
296           'cds' => 'tracks'
297         }
298       }
299     );
300     my $artist = $rs->first;
301     print $artist->name . "\n\n";
302   }
303
304   sub get_artist_by_cd {
305     my $cdtitle = shift;
306     print "get_artist_by_cd($cdtitle):\n";
307     my $rs = $schema->resultset('Artist')->search(
308       {
309         'cds.title' => $cdtitle
310       },
311       {
312         join     => [qw/ cds /],
313       }
314     );
315     my $artist = $rs->first;
316     print $artist->name . "\n\n";
317   }
318
319
320
321 It should output:
322
323   get_tracks_by_cd(Bad):
324   Dirty Diana
325   Smooth Criminal
326   Leave Me Alone
327
328   get_tracks_by_artist(Michael Jackson):
329   Beat it
330   Billie Jean
331   Dirty Diana
332   Smooth Criminal
333   Leave Me Alone
334
335   get_cd_by_track(Stan):
336   The Marshall Mathers LP
337
338   get_cds_by_artist(Michael Jackson):
339   Thriller
340   Bad
341
342   get_artist_by_track(Dirty Diana):
343   Michael Jackson
344
345   get_artist_by_cd(The Marshall Mathers LP):
346   Eminem
347
348 =head1 Notes
349
350 A reference implentation of the database and scripts in this example
351 are available in the main distribution for DBIx::Class under the
352 directory F<t/examples/Schema>.
353
354 With these scripts we're relying on @INC looking in the current
355 working directory.  You may want to add the MyDatabase namespaces to
356 @INC in a different way when it comes to deployment.
357
358 The F<testdb.pl> script is an excellent start for testing your database
359 model.
360
361 This example uses L<DBIx::Class::Schema/load_namespaces> to load in the
362 appropriate L<Row|DBIx::Class::Row> classes from the MyDatabase::Main::Result namespace,
363 and any required resultset classes from the MyDatabase::Main::ResultSet
364 namespace (although we created the directory in the directions above we
365 did not add, or need to add, any resultset classes).
366
367 =head1 TODO
368
369 =head1 AUTHOR
370
371   sc_ from irc.perl.org#dbix-class
372   Kieren Diment <kd@totaldatasolution.com>
373   Nigel Metheringham <nigelm@cpan.org>
374
375 =cut