Newer Older
515 lines | 13.688kb
added DBIx::Custom::Guides
yuki-kimoto authored on 2010-10-17
1
=head1 NAME
2

            
3
DBIx::Custom::Guides - DBIx::Custom Guides
4

            
5
=head1 GUIDES
6

            
7
=head2 1. Connect to the database
8

            
9
C<connect()> method create a new L<DBIx::Custom>
10
object and connect to the database.
11

            
12
    use DBIx::Custom;
13
    my $dbi = DBIx::Custom->connect(data_source => "dbi:mysql:database=dbname",
14
                                    user => 'ken', password => '!LFKD%$&');
15

            
16
If database is SQLite, use L<DBIx::Custom::SQLite> instead.
17
you connect database easily.
18

            
19
    use DBIx::Custom::SQLite;
20
    my $dbi = DBIx::Custom::SQLite->connect(database => 'dbname');
21
    
22
If database is  MySQL, use L<DBIx::Custom::MySQL>.
23

            
24
    use DBIx::Custom::MySQL;
25
    my $dbi = DBIx::Custom::MySQL->connect(
26
        database => 'dbname',
27
        user     => 'ken',
28
        password => '!LFKD%$&'
29
    );
30

            
31
=head2 2. Suger methods
32

            
33
L<DBIx::Custom> has suger methods, such as C<insert()>, C<update()>,
34
C<delete()> or C<select()>. If you want to do small works,
35
You don't have to create SQL statements.
36

            
37
=head3 insert()
38

            
39
Execute insert statement.
40

            
41
    $dbi->insert(table  => 'books',
42
                 param  => {title => 'Perl', author => 'Ken'});
43

            
44
The following SQL is executed.
45

            
46
    insert into (title, author) values (?, ?);
47

            
48
The values of C<title> and C<author> is embedded into the placeholders.
49

            
50
C<append> and C<filter> argument can be specified.
51
See also "METHODS" section.
52

            
53
=head3 update()
54

            
55
Execute update statement.
56

            
57
    $dbi->update(table  => 'books', 
58
                 param  => {title => 'Perl', author => 'Ken'}, 
59
                 where  => {id => 5});
60

            
61
The following SQL is executed.
62

            
63
    update books set title = ?, author = ?;
64

            
65
The values of C<title> and C<author> is embedded into the placeholders.
66

            
67
C<append> and C<filter> argument can be specified.
68
See also "METHOD" section.
69

            
70
If you want to update all rows, use C<update_all()> method.
71

            
72
=head3 delete()
73

            
74
Execute delete statement.
75

            
76
    $dbi->delete(table  => 'books',
77
                 where  => {author => 'Ken'});
78

            
79
The following SQL is executed.
80

            
81
    delete from books where id = ?;
82

            
83
The value of C<id> is embedded into the placehodler.
84

            
85
C<append> and C<filter> argument can be specified.
86
see also "METHODS" section.
87

            
88
If you want to delete all rows, use C<delete_all()> method.
89

            
90
=head3 select()
91

            
92
Execute select statement, only C<table> argument specified :
93

            
94
    my $result = $dbi->select(table => 'books');
95

            
96
The following SQL is executed.
97

            
98
    select * from books;
99

            
100
the result of C<select()> method is L<DBIx::Custom::Result> object.
101
You can fetch a row by C<fetch()> method.
102

            
103
    while (my $row = $result->fetch) {
104
        my $title  = $row->[0];
105
        my $author = $row->[1];
106
    }
107

            
108
L<DBIx::Custom::Result> has various methods to fetch row.
109
See "3. Fetch row".
110

            
111
C<column> and C<where> arguments specified.
112

            
113
    my $result = $dbi->select(
114
        table  => 'books',
115
        column => [qw/author title/],
116
        where  => {author => 'Ken'}
117
    );
118

            
119
The following SQL is executed.
120

            
121
    select author, title from books where author = ?;
122

            
123
the value of C<author> is embdded into the placeholder.
124

            
125
If you want to join tables, specify C<relation> argument. 
126

            
127
    my $result = $dbi->select(
128
        table    => ['books', 'rental'],
129
        column   => ['books.name as book_name']
130
        relation => {'books.id' => 'rental.book_id'}
131
    );
132

            
133
The following SQL is executed.
134

            
135
    select books.name as book_name from books, rental
136
    where books.id = rental.book_id;
137

            
138
If you want to add some string to the end of SQL statement,
139
use C<append> argument.
140

            
141
    my $result = $dbi->select(
142
        table  => 'books',
143
        where  => {author => 'Ken'},
144
        append => 'order by price limit 5',
145
    );
146

            
147
The following SQL is executed.
148

            
149
    select * books where author = ? order by price limit 5;
150

            
151
C<filter> argument can be specified.
152
see also "METHODS" section.
153

            
154
=head2 3. Fetch row
155

            
156
C<select()> method return L<DBIx::Custom::Result> object.
157
You can fetch row by various methods.
158
Note that in this section, array means array reference,
159
and hash meanse hash reference.
160

            
161
Fetch row into array.
162
    
163
    while (my $row = $result->fetch) {
164
        my $author = $row->[0];
165
        my $title  = $row->[1];
166
        
167
    }
168

            
169
Fetch only a first row into array.
170

            
171
    my $row = $result->fetch_first;
172

            
173
Fetch multiple rows into array of array.
174

            
175
    while (my $rows = $result->fetch_multi(5)) {
176
        my $first_author  = $rows->[0][0];
177
        my $first_title   = $rows->[0][1];
178
        my $second_author = $rows->[1][0];
179
        my $second_value  = $rows->[1][1];
180
    
181
    }
182
    
183
Fetch all rows into array of array.
184

            
185
    my $rows = $result->fetch_all;
186

            
187
Fetch row into hash.
188

            
189
    # Fetch a row into hash
190
    while (my $row = $result->fetch_hash) {
191
        my $title  = $row->{title};
192
        my $author = $row->{author};
193
        
194
    }
195

            
196
Fetch only a first row into hash
197

            
198
    my $row = $result->fetch_hash_first;
199
    
200
Fetch multiple rows into array of hash
201

            
202
    while (my $rows = $result->fetch_hash_multi(5)) {
203
        my $first_title   = $rows->[0]{title};
204
        my $first_author  = $rows->[0]{author};
205
        my $second_title  = $rows->[1]{title};
206
        my $second_author = $rows->[1]{author};
207
    
208
    }
209
    
210
Fetch all rows into array of hash
211

            
212
    my $rows = $result->fetch_hash_all;
213

            
214
If you want to access statement handle of L<DBI>, use C<sth> attribute.
215

            
216
    my $sth = $result->sth;
217

            
218
=head2 4. Hash parameter binding
219

            
220
L<DBIx::Custom> provides hash parameter binding.
221

            
222
At frist, I show normal parameter binding.
223

            
224
    use DBI;
225
    my $dbh = DBI->connect(...);
226
    my $sth = $dbh->prepare(
227
        "select * from books where author = ? and title like ?;"
228
    );
229
    $sth->execute('Ken', '%Perl%');
230

            
231
This is very good way because database system can enable SQL caching,
232
and parameter is quoted automatically. this is secure.
233

            
234
L<DBIx::Custom> hash parameter binding system improve
235
normal parameter binding to use hash parameter.
236

            
237
    my $result = $dbi->execute(
238
        "select * from books where {= author} and {like title};"
239
        param => {author => 'Ken', title => '%Perl%'}
240
    );
241

            
242
This is same as the normal way, execpt that the parameter is hash.
243
{= author} and {like title} is called C<tag>.
244
tag is expand to placeholder string internally.
245

            
246
    select * from books where {= author} and {like title}
247
      -> select * from books where author = ? and title like ?;
248

            
249
The following tags is available.
250

            
251
    [TAG]                       [REPLACED]
252
    {? NAME}               ->   ?
253
    {= NAME}               ->   NAME = ?
254
    {<> NAME}              ->   NAME <> ?
255
    
256
    {< NAME}               ->   NAME < ?
257
    {> NAME}               ->   NAME > ?
258
    {>= NAME}              ->   NAME >= ?
259
    {<= NAME}              ->   NAME <= ?
260
    
261
    {like NAME}            ->   NAME like ?
262
    {in NAME COUNT}        ->   NAME in [?, ?, ..]
263
    
264
    {insert_param NAME1 NAME2}   ->   (NAME1, NAME2) values (?, ?)
265
    {update_param NAME1 NAME2}   ->   set NAME1 = ?, NAME2 = ?
266

            
267
See also L<DBIx::Custom::QueryBuilder>.
268

            
269
C<{> and C<}> is reserved. If you use these charactors,
270
you must escape them using '\'. Note that '\' is
271
already perl escaped charactor, so you must write '\\'. 
272

            
273
    'select * from books \\{ something statement \\}'
274

            
275
=head2 5. Filtering
276

            
277
Usually, Perl string is kept as internal string.
278
If you want to save the string to database, You must encode the string.
279
Filtering system help you to convert a data to another data
280
when you save to the data and get the data form database.
281

            
282
If you want to register filter, use C<register_filter()> method.
283

            
284
    $dbi->register_filter(
285
        to_upper_case => sub {
286
            my $value = shift;
287
            return uc $value;
288
        }
289
    );
290

            
291
C<encode_utf8> and C<decode_utf8> filter is registerd by default.
292

            
293
You can specify these filters to C<filter> argument of C<execute()> method.
294

            
295
    my $result = $dbi->execute(
296
        "select * from books where {= author} and {like title};"
297
        param  => {author => 'Ken', title => '%Perl%'},
298
        filter => {author => 'to_upper_case, title => 'encode_utf8'}
299
    );
300

            
301
C<filter> argument can be specified to suger methods, such as
302
C<insert()>, C<update()>, C<update_all()>,
303
C<delete()>, C<delete_all()>, C<select()>.
304

            
305
    # insert(), having filter argument
306
    $dbi->insert(table  => 'books',
307
                 param  => {title => 'Perl', author => 'Ken'},
308
                 filter => {title => 'encode_utf8'});
309
    
310
    # select(), having filter argument
311
    my $result = $dbi->select(
312
        table  => 'books',
313
        column => [qw/author title/],
314
        where  => {author => 'Ken'},
315
        append => 'order by id limit 1',
316
        filter => {title => 'encode_utf8'}
317
    );
318

            
319
Filter works each parmeter, but you prepare default filter for all parameters.
320

            
321
    $dbi->default_bind_filter('encode_utf8');
322

            
323
C<filter()> argument overwrites this default filter.
324
    
325
    $dbi->default_bind_filter('encode_utf8');
326
    $dbi->insert(
327
        table  => 'books',
328
        param  => {title => 'Perl', author => 'Ken', price => 1000},
329
        filter => {author => 'to_upper_case', price => undef}
330
    );
331

            
332
This is same as the following example.
333

            
334
    $dbi->insert(
335
        table  => 'books',
336
        param  => {title => 'Perl', author => 'Ken', price => 1000},
337
        filter => {title => 'encode_uft8' author => 'to_upper_case'}
338
    );
339

            
340
You can also specify filter when the row is fetched. This is reverse of bind filter.
341

            
342
    my $result = $dbi->select(table => 'books');
343
    $result->filter({title => 'decode_utf8', author => 'to_upper_case'});
344

            
345
Filter works each column value, but you prepare a default filter
346
for all clumn value.
347

            
348
    $dbi->default_fetch_filter('decode_utf8');
349

            
350
C<filter()> method of L<DBIx::Custom::Result>
351
overwrites this default filter.
352

            
353
    $dbi->default_fetch_filter('decode_utf8');
354
    my $result = $dbi->select(
355
        table => 'books',
356
        columns => ['title', 'author', 'price']
357
    );
358
    $result->filter({author => 'to_upper_case', price => undef});
359

            
360
This is same as the following one.
361

            
362
    my $result = $dbi->select(
363
        table => 'books',
364
        columns => ['title', 'author', 'price']
365
    );
366
    $result->filter({title => 'decode_utf8', author => 'to_upper_case'});
367

            
368
Note that in fetch filter, column names must be lower case
369
even if the column name conatains upper case charactors.
370
This is requirment not to depend database systems.
371

            
372
=head2 6. Get high performance
373

            
374
=head3 Disable filter checking
375

            
376
Filter checking is executed by default.
377
This is done to check right filter name is specified,
378
but sometimes damage performance.
379

            
380
If you disable this filter checking,
381
Set C<filter_check> attribute to 0.
382

            
383
    $dbi->filter_check(0);
384

            
385
=head3 Use execute() method instead suger methods
386

            
387
If you execute insert statement by C<insert()> method,
388
you sometimes can't get required performance.
389

            
390
C<insert()> method is a little slow because SQL statement and statement handle
391
is created every time.
392

            
393
In that case, you can prepare a query by C<create_query()> method.
394
    
395
    my $query = $dbi->create_query(
396
        "insert into books {insert_param title author};"
397
    );
398

            
399
Return value of C<create_query()> is L<DBIx::Custom::Query> object.
400
This keep the information of SQL and column names.
401

            
402
    {
403
        sql     => 'insert into books (title, author) values (?, ?);',
404
        columns => ['title', 'author']
405
    }
406

            
407
Execute query repeatedly.
408
    
409
    my $inputs = [
410
        {title => 'Perl',      author => 'Ken'},
411
        {title => 'Good days', author => 'Mike'}
412
    ];
413
    
414
    foreach my $input (@$inputs) {
415
        $dbi->execute($query, $input);
416
    }
417

            
418
This is faster than C<insert()> method.
419

            
420
=head3 caching
421

            
422
C<execute()> method caches the parsed result of the source of SQL.
423
Default to 1
424

            
425
    $dbi->cache(1);
426

            
427
Caching is on memory, but you can change this by C<cache_method()>.
428
First argument is L<DBIx::Custom> object.
429
Second argument is a source of SQL,
430
such as "select * from books where {= title} and {= author};";
431
Third argument is parsed result, such as
432
{sql => "select * from books where title = ? and author = ?",
433
 columns => ['title', 'author']}, this is hash reference.
434
If arguments is more than two, this method is called to set cache.
435
If not, this method is called to get cache.
436

            
437
    $dbi->cache_method(sub {
438
        sub {
439
            my $self = shift;
440
            
441
            $self->{_cached} ||= {};
442
            
443
            # Set cache
444
            if (@_ > 1) {
445
                $self->{_cached}{$_[0]} = $_[1] 
446
            }
447
            
448
            # Get cache
449
            else {
450
                return $self->{_cached}{$_[0]}
451
            }
452
        }
453
    });
454

            
455
=head2 7. More features
456

            
457
=head3 Get DBI object
458

            
459
You can get L<DBI> object and call any method of L<DBI>.
460

            
461
    $dbi->dbh->begin_work;
462
    $dbi->dbh->commit;
463
    $dbi->dbh->rollback;
464

            
465
=head3 Change Result class
466

            
467
You can change Result class if you need.
468

            
469
    package Your::Result;
470
    use base 'DBIx::Custom::Result';
471
    
472
    sub some_method { ... }
473

            
474
    1;
475
    
476
    package main;
477
    
478
    use Your::Result;
479
    
480
    my $dbi = DBIx::Custom->connect(...);
481
    $dbi->result_class('Your::Result');
482

            
483
=head3 Custamize SQL builder object
484

            
485
You can custamize SQL builder object
486

            
487
    my $dbi = DBIx::Custom->connect(...);
488
    $dbi->query_builder->register_tag_processor(
489
        name => sub {
490
           ...
491
        }
492
    );
493

            
494
=head3 Resister helper method
495

            
496
You can resiter helper method.
497

            
498
    $dbi->helper(
499
        update_or_insert => sub {
500
            my $self = shift;
501
            # do something
502
        },
503
        find_or_create   => sub {
504
            my $self = shift;
505
            # do something
506
        }
507
    );
508

            
509
Register helper methods.
510
These method can be called from L<DBIx::Custom> object directory.
511

            
512
    $dbi->update_or_insert;
513
    $dbi->find_or_create;
514

            
515
=cut