examples
[dbsrgits/dbix-class-introduction-presentation.git] / slideshow.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
4 <html xmlns="http://www.w3.org/1999/xhtml">
5
6 <head>
7 <title>DBIx::Class (aka DBIC)</title>
8 <!-- metadata -->
9 <meta name="contributor" content="youcan[64]netzgesta[46]de" />
10 <meta name="publisher" content="s5.netzgesta.de" />
11 <meta name="description" content="S5 1.3 is a very flexible and lightweight slide show system available for anyone to use (including transitions and scalable fonts and images)" />
12 <meta name="keywords" content="S5, version 1.3, slide show, presentation-mode, projection-mode, powerpoint-like, scala-like, keynote-like, incremental display, scalable fonts, scalable images, transitions, notes, osf, xoxo, css, javascript, xhtml, public domain" />
13
14 <meta name="generator" content="S5" />
15 <meta name="version" content="1" />
16 <meta name="subject" content="DBIx::Class" />
17 <meta name="author" content="See first slide" />
18 <meta name="company" content="N/A" />
19 <meta name="robots" content="index, follow" />
20 <meta name="revisit-after" content="7 days" />
21 <!-- meta additionally -->
22 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
23 <meta http-equiv="Content-Script-Type" content="text/javascript" />
24 <meta http-equiv="Content-Style-Type" content="text/css" /><!-- configuration parameters -->
25 <meta name="defaultView" content="slideshow" />
26 <meta name="controlVis" content="hidden" />
27 <!-- configuration transition extension -->
28 <meta name="tranSitions" content="true" />
29 <meta name="fadeDuration" content="500" />
30 <meta name="incrDuration" content="250" />
31 <!-- configuration autoplay extension -->
32 <meta name="autoMatic" content="false" />
33 <meta name="playLoop" content="true" />
34 <meta name="playDelay" content="10" />
35 <!-- configuration audio extension -->
36 <meta name="audioSupport" content="false" />
37 <meta name="audioVolume" content="0" />
38 <meta name="audioError" content="false" />
39 <!-- configuration audio debug -->
40 <meta name="audioDebug" content="false" />
41 <!-- style sheet links -->
42 <link rel="stylesheet" href="ui/scala_utf/slides.css" type="text/css" media="projection" id="slideProj" />
43 <link rel="stylesheet" href="ui/scala_utf/outline.css" type="text/css" media="screen" id="outlineStyle" />
44 <link rel="stylesheet" href="ui/scala_utf/print.css" type="text/css" media="print" id="slidePrint" />
45 <link rel="stylesheet" href="ui/scala_utf/opera.css" type="text/css" media="projection" id="operaFix" />
46 <!-- embedded styles -->
47 <style type="text/css" media="all">
48 .imgcon {width: 100%; margin: 0 auto; padding: 0; text-align: center;}
49 #anim {width: 33%; height: 320px; position: relative;}
50 #anim img {position: absolute; top: 0px; left: 0px;}
51 .red {color: red;}
52 .grey {color: gray;}
53 </style>
54 <!-- S5 JS -->
55 <script src="ui/scala_utf/slides.js" type="text/javascript"></script>
56 </head>
57 <body>
58
59 <div class="layout">
60    <div id="controls"><!-- DO NOT EDIT --></div>
61    <div id="currentSlide"><!-- DO NOT EDIT --></div>
62    <div id="header"></div>
63    <div id="footer">
64       <h1>DBIx::Class Introduction</h1>
65       <h2>YAPC::NA 2010</h2>
66    </div>
67 </div>
68
69 <div class="presentation">
70
71    <div class="slide">
72       <h1>DBIX::Class (aka DBIC)</h1>
73       <h3>for (advanced) beginners</h3>
74    </div>
75
76    <div class="slide">
77       <h1>Authors</h1>
78       <h4>Originally Leo Lapworth @ LPW 2009</h4>
79       <h4>Amiri Barksdale</h4>
80       <h4>Justin D. Hunter</h4>
81       <h4>Arthur Axel "fREW" Schmidt</h4>
82    </div>
83
84    <div class="slide">
85       <h1>What's up guys?</h1>
86       <div class="notes">
87          <ul>
88             <li>How many people have used any ORM?<ul>
89                <li>In Perl?<ul>
90                   <li>DBIC?</li>
91                   <li>Class::DBI?</li>
92                   <li>Rose::DB?</li>
93                   <li>Fey?</li>
94                   <li>Others?</li>
95                </ul></li>
96                <li>AR?</li>
97                <li>DataMapper?</li>
98                <li>(N)Hibernate?</li>
99             </ul></li>
100          </ul>
101       </div>
102    </div>
103
104    <div class="slide">
105       <h1>Purpose</h1>
106       <p>The purpose of this talk is to show you as many features of
107       DBIx::Class in 40 minutes so that when you need to do something with
108       it later you will know what's possible</p>
109    </div>
110
111    <div class="slide">
112       <h1>DBIx::Class?</h1>
113       <ul>
114          <li>ORM (object relational mapper)</li>
115          <li>SQL &lt;-&gt; OO (using objects instead of SQL)</li>
116          <li>There are many ORMs, DBIx::Class just happens to be the best in Perl (personal opinion)</li>
117       </ul>
118    </div>
119
120    <div class="slide">
121       <h1>Meta</h1>
122       <p>These are reasons that are not technical or inherent to
123       the code of DBIC, but are totally awesome things about it.</p>
124    </div>
125
126    <div class="slide">
127       <h1>Large Community</h1>
128       <p>Currently there are 88 people listed as contributors to DBIC.  That
129       ranges from documentation help, to test help, to added features,
130       to entire database support.</p>
131    </div>
132
133    <div class="slide">
134       <h1>Active Community</h1>
135       <p>Currently (June 9, 2010) 6 active branches (commited to in the last two weeks) in git.  Last release (0.08122) had 14 new features, and 16 bug fixes.  Of course that <a href="http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git;a=blob;f=Changes">ebbs and flows</a>.</p>
136    </div>
137
138    <div class="slide">
139       <h1>Responsive Community</h1>
140       <ul class="incremental">
141          <li>needed MSSQL Order by support, they helped me add support</li>
142          <li>generally very welcoming of people willing to help</li>
143       </ul>
144    </div>
145
146    <div class="slide">
147       <h1>General ORM</h1>
148       <p>These are things that are in most other ORMs, but are still reasons
149       to use DBIC over raw SQL.</p>
150    </div>
151
152    <div class="slide">
153       <h1>Cross DB</h1>
154       <p>The vast majority of code should run on all databases without needing tweaking</p>
155    </div>
156
157    <div class="slide">
158       <h1>Basic CRUD</h1>
159       <ul class="incremental">
160          <li><strong>C</strong> - Create</li>
161          <li><strong>R</strong> - Read</li>
162          <li><strong>U</strong> - Update</li>
163          <li><strong>D</strong> - Delete</li>
164       </ul>
165    </div>
166
167    <div class="slide">
168       <h1>SQL: Create</h1>
169 <pre>my $sth = $dbh-&gt;prepare('
170    INSERT INTO books
171    (title, author_id)
172    values (?,?)
173 ');
174
175 $sth-&gt;execute(
176   'A book title', $author_id
177 );</pre>
178    </div>
179
180    <div class="slide">
181       <h1>DBIC: Create</h1>
182 <pre>my $book = $book_rs-&gt;create({
183    title     =&gt; 'A book title',
184    author_id =&gt; $author_id,
185 });</pre>
186       <ul class="incremental">
187          <li>No need to pair placeholders and values</li>
188          <li>Automatically gets autoincremented id for you</li>
189          <li>Transparrently uses INSERT ... RETURNING for databases that support it</li>
190       </ul>
191    </div>
192
193    <div class="slide">
194       <h1>SQL: Read</h1>
195 <pre>my $sth = $dbh-&gt;prepare('
196    SELECT title,
197    authors.name as author_name
198    FROM books, authors
199    WHERE books.author = authors.id
200 ');</pre>
201    </div>
202
203    <div class="slide">
204       <h1>SQL: Read</h1>
205 <pre>while( my $book = $sth-&gt;fetchrow_hashref() ) {
206   print 'Author of '
207      . $book-&gt;{title}
208      . ' is '
209      . $book-&gt;{author_name}
210      . "\n";
211 }</pre>
212    </div>
213
214    <div class="slide">
215       <h1>DBIC: Read</h1>
216 <pre>my $book = $book_rs-&gt;find($book_id);
217
218 my $book = $book_rs-&gt;search({
219    title =&gt; 'A book title',
220 }, { rows =&gt; 1 })-&gt;next;
221
222 my @books = $book_rs-&gt;search({
223    author =&gt; $author_id,
224 })-&gt;all;</pre>
225       <ul class="incremental">
226          <li>TMTOWTDI</li>
227       </ul>
228    </div>
229
230    <div class="slide">
231       <h1>DBIC: Read</h1>
232 <pre>while( my $book = $books_rs-&gt;next ) {
233  print 'Author of '
234     . $book-&gt;title
235     . ' is '
236     . $book-&gt;author-&gt;name
237     . "\n";
238 }</pre>
239    </div>
240
241    <div class="slide">
242       <h1>SQL: Update</h1>
243 <pre>my $update = $dbh-&gt;prepare('
244    UPDATE books
245    SET title = ?
246    WHERE id = ?
247 ');
248
249 $update-&gt;execute(
250   'New title',<strong>$book_id</strong>
251 );</pre>
252    </div>
253
254    <div class="slide">
255       <h1>DBIC: Update</h1>
256 <pre>$book-&gt;update({
257   title =&gt; 'New title',
258 });</pre>
259       <ul class="incremental">
260          <li>Lazy Update</li>
261       </ul>
262    </div>
263
264    <div class="slide">
265       <h1>SQL: Delete</h1>
266 <pre>my $delete = $dbh-&gt;prepare('
267    DELETE FROM books
268    WHERE id = ?
269 ');
270
271 $delete-&gt;execute(<strong>$book_id</strong>);</pre>
272    </div>
273
274    <div class="slide">
275       <h1>DBIC: Delete</h1>
276 <pre>$book-&gt;delete;</pre>
277    </div>
278
279    <div class="slide">
280       <h1>OO Overidability</h1>
281       <ul class="incremental">
282          <li>Override new if you want to do validation</li>
283          <li>Override delete if you want to disable deletion</li>
284          <li>and on and on</li>
285       </ul>
286       <div class="notes">
287          <p>I got yelled at about this before by people, so
288          we don't get EVERYTHING from OO, but we do get a lot
289          so :-P</p>
290       </div>
291    </div>
292
293    <div class="slide">
294       <h1>Convenience Methods</h1>
295       <ul class="incremental">
296          <li>find_or_create</li>
297          <li>create_or_update</li>
298       </ul>
299    </div>
300
301    <div class="slide">
302       <h1>Non-column methods</h1>
303       <p>Need a method to get a user's gravatar URL?  Add a
304       gravatar_url method to their Result class</p>
305    </div>
306
307    <div class="slide">
308       <h1>RELATIONSHIPS</h1>
309       <ul class="incremental">
310          <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship#belongs_to">belongs_to</a></li>
311          <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship#has_many">has_many</a></li>
312          <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship#might_have">might_have</a></li>
313          <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship#has_one">has_one</a></li>
314          <li><a href="http://search.cpan.org/perldoc?DBIx::Class::Relationship#many_to_many">many_to_many</a> (technically not a relationship)</li>
315          <li>SET AND FORGET</li>
316       </ul>
317    </div>
318
319    <div class="slide">
320       <h1>DBIx::Class Specific Features</h1>
321       <p>These things may be in other ORM's, but they are very specific, so doubtful</p>
322    </div>
323
324    <div class="slide">
325       <h1>-&gt;deploy</h1>
326       <p>Perl -&gt; DB</p>
327 <pre>my $schema = Foo::Schema-&gt;connect($dsn, $user, $pass);
328 $schema-&gt;deploy
329 </pre>
330 <p>See also: <a href="http://search.cpan.org/perldoc?DBIx::Class::DeploymentHandler">DBIx::Class::DeploymentHandler</a></p>
331    </div>
332
333    <div class="slide">
334       <h1>Schema::Loader</h1>
335       <p>DB -&gt; Perl</p>
336 <pre>package Foo::Schema;
337 use strict; use warnings;
338 use base 'DBIx::Class::Schema::Loader';
339 __PACKAGE__-&gt;loader_options({
340    naming =&gt; 'v7',
341    debug  =&gt; $ENV{DBIC_TRACE},
342 });
343 1;
344
345 # elsewhere...
346
347 my $schema = Foo::Schema-&gt;connect($dsn, $user, $pass);
348 </pre>
349    </div>
350
351    <div class="slide">
352       <h1>Populate</h1>
353       <p>Made for inserting lots of rows very quicky into database</p>
354 <pre>$schema-&gt;populate([ Users =&gt;
355    [qw( username password )],
356    [qw( frew &gt;=4char$  )],
357    [qw(      ...          )],
358    [qw(      ...          )],
359 );
360 </pre>
361       <ul class="incremental">
362          <li>I use this to <a href="http://blog.afoolishmanifesto.com/archives/1255">export our whole (200M~) db to SQLite</a></li>
363       </ul>
364    </div>
365
366    <div class="slide">
367       <h1>Multicreate</h1>
368       <p>Create an object and all of it's related objects all at once</p>
369 <pre>$schema-&gt;resultset('Author')-&gt;create({
370    name =&gt; 'Stephen King',
371    books =&gt; [{ title =&gt; 'The Dark Tower' }],
372    address =&gt; {
373       street =&gt; '123 Turtle Back Lane',
374       state  =&gt; { abbreviation =&gt; 'ME' },
375       city   =&gt; { name =&gt; 'Lowell' },
376    },
377 });
378 </pre>
379       <div class="notes">
380          <ul>
381             <li>books is a has_many</li>
382             <li>address is a belongs_to which in turn belongs to state and city each</li>
383             <li>for this to work right state and city must mark abbreviation and name as unique</li>
384          </ul>
385       </div>
386    </div>
387
388    <div class="slide">
389       <h1>Extensible</h1>
390       <p>DBIx::Class helped pioneer fast MI in Perl 5 with Class::C3, so it is made
391       to allow extensions to nearly every part of it.</p>
392    </div>
393
394    <div class="slide">
395       <h1>Extensible: DBIC::Helpers</h1>
396       <ul class="incremental">
397          <li>DBIx::Class::Helper::ResultSet::IgnoreWantarray</li>
398          <li>DBIx::Class::Helper::ResultSet::Random</li>
399          <li>DBIx::Class::Helper::ResultSet::SetOperations</li>
400          <li>DBIx::Class::Helper::Row::JoinTable</li>
401          <li>DBIx::Class::Helper::Row::NumifyGet</li>
402          <li>DBIx::Class::Helper::Row::SubClass</li>
403          <li>DBIx::Class::Helper::Row::ToJSON</li>
404       </ul>
405    </div>
406
407    <div class="slide">
408       <h1>Extensible: DBIC::TimeStamp</h1>
409       <ul class="incremental">
410          <li>Cross DB</li>
411          <li>set_on_create</li>
412          <li>set_on_update</li>
413       </ul>
414    </div>
415
416    <div class="slide">
417       <h1>Extensible: DBIx::Class::Schema::KiokuDB</h1>
418       <ul class="incremental">
419          <li>Kioku is the new hotness</li>
420          <li>Mix RDBMS with Object DB</li>
421          <li>beta ( == sexy )</li>
422       </ul>
423    </div>
424
425    <div class="slide">
426       <h1>SQL::Abstract</h1>
427 <pre>my $resultset = $book_rs-&gt;search({
428    name =&gt; { -like =&gt; "%$nick%" },
429 });</pre>
430       <ul class="incremental">
431          <li>(kinda) introspectible</li>
432          <li>Prettier than SQL</li>
433       </ul>
434    </div>
435
436    <div class="slide">
437       <h1>Result vs ResultSet</h1>
438          <ul class="incremental">
439             <li>Result == Row</li>
440             <li>ResultSet == Query Plan<ul class="incremental">
441                <li>Internal Join Optimizer for all DB's (!!!)</li>
442             </ul></li>
443             <li>(less important but...)</li>
444             <li>ResultSource == Table</li>
445             <li>Storage == Database</li>
446          </ul>
447    </div>
448
449    <div class="slide">
450       <h1>ResultSet methods</h1>
451 <pre>package MyApp::Schema::ResultSet::Book;
452 use base 'DBIx::Class::ResultSet';
453 sub good {
454    $_[0]-&gt;search({
455       rating =&gt; { '&gt;=' =&gt; 4 },
456    })
457 };
458 sub cheap {
459    $_[0]-&gt;search({
460       price =&gt; { '&lt;=' =&gt; 5}
461    })
462 };
463 # ...
464 1;
465       </pre>
466       <ul class="incremental">
467          <li>All searches should be ResultSet methods</li>
468          <li>Name has obvious meaning</li>
469       </ul>
470    </div>
471
472    <div class="slide">
473       <h1>ResultSet method in Action</h1>
474       <pre>$schema-&gt;resultset('Book')-&gt;good</pre>
475    </div>
476
477    <div class="slide">
478       <h1>ResultSet Chaining</h1>
479 <pre>$schema-&gt;resultset('Book')
480    -&gt;good
481    -&gt;cheap
482    -&gt;recent
483 </pre>
484    </div>
485
486    <div class="slide">
487       <h1>search_related</h1>
488 <pre>my @test_rs = ($schema-&gt;resultset('User')-&gt;search({'me.userid' =&gt; 'marial'})
489    -&gt;related_resultset('access')
490    -&gt;related_resultset('mgmt')
491    -&gt;related_resultset('orders')-&gt;search({'orders.reporttype' =&gt; 0})
492    -&gt;related_resultset('shops')-&gt;search({'shops.status' =&gt; 'Completed', 'shops.datecompleted' =&gt; {-between =&gt; ['2009-10-01','2009-10-08']}})
493    -&gt;related_resultset('rpt_score')-&gt;get_column('raw_scores')-&gt;first);
494 </pre>
495    </div>
496
497    <div class="slide">
498       <h1>related_resultset</h1>
499 <pre>my @screens = $user-&gt;roles
500    -&gt;related_resultset('role_permissions')
501    -&gt;related_resultset('permission')
502    -&gt;related_resultset('permission_screens')
503    -&gt;related_resultset('screen')
504    -&gt;search(undef, { distinct =&gt; 1 })-&gt;all;</pre>
505    </div>
506
507    <div class="slide">
508       <h1>bonus rel methods</h1>
509 <pre>my $book = $author-&gt;create_related(
510   <strong>books</strong> =&gt; {
511    title =&gt; 'Another Discworld book',
512 });
513
514 my $book2 = $pratchett-&gt;add_to_<strong>books</strong>({
515    title =&gt; 'MOAR Discworld book',
516 });</pre>
517       <ul class="incremental">
518          <li>Automaticaly fills in foreign key for you</li>
519       </ul>
520    </div>
521
522    <div class="slide">
523       <h1>Excellent Transaction Support</h1>
524 <pre>$schema-&gt;txn_do(sub {
525    ...
526 });
527
528 my $guard = $schema-&gt;txn_scope_guard;
529 # ...
530 $guard-&gt;commit;
531
532 $schema-&gt;txn_begin; # &lt;-- low level
533 # ...
534 $schema-&gt;txn_commit;
535 </pre>
536    </div>
537
538    <div class="slide">
539       <h1>InflateColumn</h1>
540 <pre>package Foo::Schema::Result::Book;
541 use base 'DBIx::Class::Core';
542 # Result code here
543 __PACKAGE__-&gt;load_components('InflateColumn');
544 use DateTime::Format::MySQL;
545 __PACKAGE__-&gt;<strong>inflate_column</strong>(
546    <strong>date_published</strong> =&gt; {
547       inflate =&gt; sub { DateTime::Format::MySQL-&gt;parse_date(shift) },
548       deflate =&gt; sub { shift-&gt;ymd},
549    },
550 );
551 # Automatic see: DBIx::Class::InflateColumn::DateTime</pre>
552    </div>
553
554    <div class="slide">
555       <h1>InflateColumn: deflation</h1>
556 <pre>$book-&gt;date_published(DateTime-&gt;now);
557 $book-&gt;update;</pre>
558    </div>
559
560    <div class="slide">
561       <h1>InflateColumn: inflation</h1>
562 <pre>my $date_published = $book-&gt;date_published;
563 print $date_published-&gt;month_abbr;</pre>
564
565 <strong><em>Nov</em></strong>
566    </div>
567
568    <div class="slide">
569       <h1>FilterColumn</h1>
570 <pre>package Foo::Schema::Result::Book;
571 use base 'DBIx::Class::Core';
572 # Result code here
573 __PACKAGE__-&gt;load_components('FilterColumn');
574
575 __PACKAGE__-&gt;<strong>filter_column</strong>(
576    <strong>length</strong> =&gt; {
577       to_storage   =&gt; 'to_metric',
578       from_storage =&gt; 'to_imperial',
579    },
580 );
581
582 sub to_metric   { $_[1] * .305 }
583 sub to_imperial { $_[1] * 3.28 }
584 # Automatic see: DBIx::Class::InflateColumn::DateTime</pre>
585    </div>
586
587    <div class="slide">
588       <h1>ResultSetColumn</h1>
589 <pre>my $rsc = $schema-&gt;resultset('Book')-&gt;get_column('price');
590 $rsc-&gt;min;
591 $rsc-&gt;max;
592 $rsc-&gt;sum;
593 </pre>
594    </div>
595
596    <div class="slide">
597       <h1>Aggregates</h1>
598 <pre>my @res = $rs-&gt;search({}, {
599    select   =&gt; [qw(price genre), { max =&gt; price }, { avg =&gt; price }],
600    as       =&gt; [qw(price genre max_price avg_price)],
601    group_by =&gt; [qw(price genre)],
602 });
603 for (@res) {
604    say $_-&gt;price . ' ' . $_-&gt;genre;
605    say $_-&gt;get_column('max_price');
606    say $_-&gt;get_column('min_price');
607 }</pre>
608       <ul class="incremental">
609          <li>Careful, get_column can basicaly mean THREE things</li>
610          <li>private for get what you should use an accessor for</li>
611          <li>public for what there is no accessor for</li>
612          <li>public for get resultset column (prev slide)</li>
613       </ul>
614    </div>
615
616    <div class="slide">
617       <h1>HRI</h1>
618 <pre>$rs-&gt;search({}, {
619    result_class =&gt; 'DBIx::Class::ResultClass::HashRefInflator',
620 });</pre>
621       <ul class="incremental">
622          <li>Easy on memory</li>
623          <li>Mega fast</li>
624          <li>Great for quick debugging</li>
625          <li>Great for performance tuning (we went from 2m to &lt; 3s)</li>
626       </ul>
627    </div>
628
629    <div class="slide">
630       <h1>Subquery Support</h1>
631 <pre>  my $inside_rs = $schema-&gt;resultset('Artist')-&gt;search({
632     name =&gt; [ 'Billy Joel', 'Brittany Spears' ],
633 });
634
635 my $rs = $schema-&gt;resultset('CD')-&gt;search({
636     artist_id =&gt; { -in =&gt; $inside_rs-&gt;get_column('id')-&gt;as_query },
637 });</pre>
638    </div>
639
640    <div class="slide">
641       <h1>Bare SQL w/ Placeholders</h1>
642 <pre>$rs-&gt;update({
643    price =&gt; \"price + $inc", # !!! SQL INJECTION VECTOR
644 });
645
646 $rs-&gt;update({
647    price =&gt; \['price + ?', [inc =&gt; $inc]],
648 });
649 </pre>
650    </div>
651
652    <div class="slide">
653       <h1>Questions?</h1>
654    </div>
655
656    <div class="slide">
657       <h1>END</h1>
658    </div>
659 </div>
660 </body>
661 </html>