DBIx-Custom / lib / DBIx / Custom.pm /
Newer Older
1252 lines | 29.519kb
cleanup
yuki-kimoto authored on 2009-12-22
1
package DBIx::Custom;
2

            
3
use strict;
4
use warnings;
5

            
remove run_transaction().
yuki-kimoto authored on 2010-01-30
6
use base 'Object::Simple';
many change
yuki-kimoto authored on 2010-02-11
7

            
packaging one directory
yuki-kimoto authored on 2009-11-16
8
use Carp 'croak';
9
use DBI;
10
use DBIx::Custom::Result;
11
use DBIx::Custom::SQL::Template;
cleanup
yuki-kimoto authored on 2010-02-11
12
use DBIx::Custom::Query;
many change
yuki-kimoto authored on 2010-02-11
13
use DBIx::Custom::KeyInfo;
packaging one directory
yuki-kimoto authored on 2009-11-16
14

            
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-18
15
__PACKAGE__->attr('dbh');
version 0.0901
yuki-kimoto authored on 2009-12-17
16

            
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-18
17
__PACKAGE__->class_attr(_query_caches     => sub { {} });
18
__PACKAGE__->class_attr(_query_cache_keys => sub { [] });
packaging one directory
yuki-kimoto authored on 2009-11-16
19

            
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-22
20
__PACKAGE__->class_attr('query_cache_max', default => 50,
21
                                           inherit => 'scalar_copy');
22

            
cleanup
yuki-kimoto authored on 2010-04-28
23
__PACKAGE__->attr([qw/user password data_source/]);
24
__PACKAGE__->attr([qw/database host port/]);
cleanup
yuki-kimoto authored on 2010-04-28
25
__PACKAGE__->attr([qw/default_bind_filter default_fetch_filter options/]);
packaging one directory
yuki-kimoto authored on 2009-11-16
26

            
cleanup
yuki-kimoto authored on 2010-04-28
27
__PACKAGE__->dual_attr([qw/ filters formats/],
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-22
28
                       default => sub { {} }, inherit => 'hash_copy');
packaging one directory
yuki-kimoto authored on 2009-11-16
29

            
cleanup
yuki-kimoto authored on 2010-04-28
30
__PACKAGE__->attr(result_class => 'DBIx::Custom::Result');
31
__PACKAGE__->attr(sql_tmpl => sub { DBIx::Custom::SQL::Template->new });
packaging one directory
yuki-kimoto authored on 2009-11-16
32

            
33
sub add_filter {
34
    my $invocant = shift;
35
    
update document
yuki-kimoto authored on 2010-01-30
36
    # Add filter
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-18
37
    my $filters = ref $_[0] eq 'HASH' ? $_[0] : {@_};
38
    $invocant->filters({%{$invocant->filters}, %$filters});
39
    
packaging one directory
yuki-kimoto authored on 2009-11-16
40
    return $invocant;
41
}
42

            
43
sub add_format{
44
    my $invocant = shift;
45
    
update document
yuki-kimoto authored on 2010-01-30
46
    # Add format
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-18
47
    my $formats = ref $_[0] eq 'HASH' ? $_[0] : {@_};
48
    $invocant->formats({%{$invocant->formats}, %$formats});
49

            
packaging one directory
yuki-kimoto authored on 2009-11-16
50
    return $invocant;
51
}
52

            
53
sub _auto_commit {
54
    my $self = shift;
55
    
update document
yuki-kimoto authored on 2010-01-30
56
    # Not connected
packaging one directory
yuki-kimoto authored on 2009-11-16
57
    croak("Not yet connect to database") unless $self->dbh;
58
    
59
    if (@_) {
update document
yuki-kimoto authored on 2010-01-30
60
        
61
        # Set AutoCommit
packaging one directory
yuki-kimoto authored on 2009-11-16
62
        $self->dbh->{AutoCommit} = $_[0];
update document
yuki-kimoto authored on 2010-01-30
63
        
packaging one directory
yuki-kimoto authored on 2009-11-16
64
        return $self;
65
    }
66
    return $self->dbh->{AutoCommit};
67
}
68

            
69
sub connect {
70
    my $self = shift;
update document
yuki-kimoto authored on 2010-01-30
71
    
72
    # Information
packaging one directory
yuki-kimoto authored on 2009-11-16
73
    my $data_source = $self->data_source;
74
    my $user        = $self->user;
75
    my $password    = $self->password;
version 0.0901
yuki-kimoto authored on 2009-12-17
76
    my $options     = $self->options;
packaging one directory
yuki-kimoto authored on 2009-11-16
77
    
update document
yuki-kimoto authored on 2010-01-30
78
    # Connect
packaging one directory
yuki-kimoto authored on 2009-11-16
79
    my $dbh = eval{DBI->connect(
80
        $data_source,
81
        $user,
82
        $password,
83
        {
84
            RaiseError => 1,
85
            PrintError => 0,
86
            AutoCommit => 1,
version 0.0901
yuki-kimoto authored on 2009-12-17
87
            %{$options || {} }
packaging one directory
yuki-kimoto authored on 2009-11-16
88
        }
89
    )};
90
    
update document
yuki-kimoto authored on 2010-01-30
91
    # Connect error
packaging one directory
yuki-kimoto authored on 2009-11-16
92
    croak $@ if $@;
93
    
update document
yuki-kimoto authored on 2010-01-30
94
    # Database handle
packaging one directory
yuki-kimoto authored on 2009-11-16
95
    $self->dbh($dbh);
update document
yuki-kimoto authored on 2010-01-30
96
    
packaging one directory
yuki-kimoto authored on 2009-11-16
97
    return $self;
98
}
99

            
100
sub DESTROY {
101
    my $self = shift;
update document
yuki-kimoto authored on 2010-01-30
102
    
103
    # Disconnect
packaging one directory
yuki-kimoto authored on 2009-11-16
104
    $self->disconnect if $self->connected;
105
}
106

            
update document
yuki-kimoto authored on 2010-01-30
107
sub connected { ref shift->{dbh} eq 'DBI::db' }
packaging one directory
yuki-kimoto authored on 2009-11-16
108

            
109
sub disconnect {
110
    my $self = shift;
update document
yuki-kimoto authored on 2010-01-30
111
    
packaging one directory
yuki-kimoto authored on 2009-11-16
112
    if ($self->connected) {
update document
yuki-kimoto authored on 2010-01-30
113
        
114
        # Disconnect
packaging one directory
yuki-kimoto authored on 2009-11-16
115
        $self->dbh->disconnect;
116
        delete $self->{dbh};
117
    }
update document
yuki-kimoto authored on 2010-01-30
118
    
119
    return $self;
packaging one directory
yuki-kimoto authored on 2009-11-16
120
}
121

            
122
sub reconnect {
123
    my $self = shift;
update document
yuki-kimoto authored on 2010-01-30
124
    
125
    # Reconnect
packaging one directory
yuki-kimoto authored on 2009-11-16
126
    $self->disconnect if $self->connected;
127
    $self->connect;
update document
yuki-kimoto authored on 2010-01-30
128
    
129
    return $self;
packaging one directory
yuki-kimoto authored on 2009-11-16
130
}
131

            
132
sub prepare {
133
    my ($self, $sql) = @_;
134
    
135
    # Connect if not
136
    $self->connect unless $self->connected;
137
    
138
    # Prepare
139
    my $sth = eval{$self->dbh->prepare($sql)};
140
    
141
    # Error
142
    croak("$@<Your SQL>\n$sql") if $@;
143
    
144
    return $sth;
145
}
146

            
147
sub do{
148
    my ($self, $sql, @bind_values) = @_;
149
    
150
    # Connect if not
151
    $self->connect unless $self->connected;
152
    
153
    # Do
version 0.0901
yuki-kimoto authored on 2009-12-17
154
    my $affected = eval{$self->dbh->do($sql, @bind_values)};
packaging one directory
yuki-kimoto authored on 2009-11-16
155
    
156
    # Error
157
    if ($@) {
158
        my $error = $@;
159
        require Data::Dumper;
160
        
161
        my $bind_value_dump
162
          = Data::Dumper->Dump([\@bind_values], ['*bind_valuds']);
163
        
164
        croak("$error<Your SQL>\n$sql\n<Your bind values>\n$bind_value_dump\n");
165
    }
version 0.0901
yuki-kimoto authored on 2009-12-17
166
    
167
    return $affected;
packaging one directory
yuki-kimoto authored on 2009-11-16
168
}
169

            
170
sub create_query {
171
    my ($self, $template) = @_;
cleanup
yuki-kimoto authored on 2010-02-11
172
    
packaging one directory
yuki-kimoto authored on 2009-11-16
173
    my $class = ref $self;
174
    
cleanup
yuki-kimoto authored on 2010-02-11
175
    my $table = '';
176
    if (ref $template eq 'ARRAY') {
Simplify key search
yuki-kimoto authored on 2010-02-11
177
        $table    = $template->[0] if $template->[0];
cleanup
yuki-kimoto authored on 2010-02-11
178
        $template = $template->[1];
179
    }
180
    
packaging one directory
yuki-kimoto authored on 2009-11-16
181
    # Create query from SQL template
version 0.0901
yuki-kimoto authored on 2009-12-17
182
    my $sql_tmpl = $self->sql_tmpl;
packaging one directory
yuki-kimoto authored on 2009-11-16
183
    
184
    # Try to get cached query
cleanup
yuki-kimoto authored on 2010-02-11
185
    my $cached_query = $class->_query_caches->{"$table$template"};
packaging one directory
yuki-kimoto authored on 2009-11-16
186
    
187
    # Create query
fix timeformat tests
yuki-kimoto authored on 2009-11-23
188
    my $query;
cleanup
yuki-kimoto authored on 2010-02-11
189
    if ($cached_query) {
190
        $query = DBIx::Custom::Query->new(
191
            sql       => $cached_query->sql,
192
            key_infos => $cached_query->key_infos
193
        );
fix timeformat tests
yuki-kimoto authored on 2009-11-23
194
    }
195
    else {
Simplify key search
yuki-kimoto authored on 2010-02-11
196
        $sql_tmpl->table($table);
197
        $query = eval{$sql_tmpl->create_query($template)};
packaging one directory
yuki-kimoto authored on 2009-11-16
198
        croak($@) if $@;
199
        
Simplify key search
yuki-kimoto authored on 2010-02-11
200
        $class->_add_query_cache("$table$template", $query);
packaging one directory
yuki-kimoto authored on 2009-11-16
201
    }
202
    
203
    # Connect if not
204
    $self->connect unless $self->connected;
205
    
206
    # Prepare statement handle
207
    my $sth = $self->prepare($query->{sql});
208
    
209
    # Set statement handle
210
    $query->sth($sth);
211
    
212
    # Set bind filter
cleanup
yuki-kimoto authored on 2010-04-28
213
    $query->bind_filter($self->default_bind_filter);
packaging one directory
yuki-kimoto authored on 2009-11-16
214
    
215
    # Set fetch filter
cleanup
yuki-kimoto authored on 2010-04-28
216
    $query->fetch_filter($self->default_fetch_filter);
packaging one directory
yuki-kimoto authored on 2009-11-16
217
    
218
    return $query;
219
}
220

            
version 0.0901
yuki-kimoto authored on 2009-12-17
221
sub query{
Simplify key search
yuki-kimoto authored on 2010-02-11
222
    my ($self, $query, $params, $query_edit_cb)  = @_;
packaging one directory
yuki-kimoto authored on 2009-11-16
223
    $params ||= {};
224
    
225
    # First argument is SQL template
Simplify key search
yuki-kimoto authored on 2010-02-11
226
    unless (ref $query eq 'DBIx::Custom::Query') {
227
        my $table;
228
        my $template;
229
        
230
        if (ref $query eq 'ARRAY') {
231
            $table    = $query->[0];
232
            $template = $query->[1];
233
        }
234
        else { $template = $query }
235
        
236
        $query = $self->create_query([$table, $template]);
packaging one directory
yuki-kimoto authored on 2009-11-16
237
        $query_edit_cb->($query) if ref $query_edit_cb eq 'CODE';
238
    }
239
    
240
    # Create bind value
241
    my $bind_values = $self->_build_bind_values($query, $params);
242
    
243
    # Execute
version 0.0901
yuki-kimoto authored on 2009-12-17
244
    my $sth      = $query->sth;
245
    my $affected = eval{$sth->execute(@$bind_values)};
packaging one directory
yuki-kimoto authored on 2009-11-16
246
    
247
    # Execute error
248
    if (my $execute_error = $@) {
249
        require Data::Dumper;
250
        my $sql              = $query->{sql} || '';
251
        my $key_infos_dump   = Data::Dumper->Dump([$query->key_infos], ['*key_infos']);
252
        my $params_dump      = Data::Dumper->Dump([$params], ['*params']);
253
        
254
        croak("$execute_error" . 
255
              "<Your SQL>\n$sql\n" . 
256
              "<Your parameters>\n$params_dump");
257
    }
258
    
259
    # Return resultset if select statement is executed
260
    if ($sth->{NUM_OF_FIELDS}) {
261
        
262
        # Get result class
263
        my $result_class = $self->result_class;
264
        
265
        # Create result
266
        my $result = $result_class->new({
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
267
            _dbi             => $self,
packaging one directory
yuki-kimoto authored on 2009-11-16
268
            sth              => $sth,
269
            fetch_filter     => $query->fetch_filter,
270
        });
271
        return $result;
272
    }
version 0.0901
yuki-kimoto authored on 2009-12-17
273
    return $affected;
packaging one directory
yuki-kimoto authored on 2009-11-16
274
}
275

            
276
sub _build_bind_values {
277
    my ($self, $query, $params) = @_;
Simplify key search
yuki-kimoto authored on 2010-02-11
278
    my $key_infos  = $query->key_infos;
279
    my $filter     = $query->bind_filter;
packaging one directory
yuki-kimoto authored on 2009-11-16
280
    
281
    # binding values
282
    my @bind_values;
283
    
Simplify key search
yuki-kimoto authored on 2010-02-11
284
    # Build bind values
packaging one directory
yuki-kimoto authored on 2009-11-16
285
    foreach my $key_info (@$key_infos) {
Simplify key search
yuki-kimoto authored on 2010-02-11
286
        my $table        = $key_info->table;
287
        my $column       = $key_info->column;
288
        my $id           = $key_info->id;
289
        my $pos          = $key_info->pos;
packaging one directory
yuki-kimoto authored on 2009-11-16
290
        
Simplify key search
yuki-kimoto authored on 2010-02-11
291
        # Value
many change
yuki-kimoto authored on 2010-02-11
292
        my $value = $id && defined $pos ? $params->{$id}->{$column}->[$pos]
293
                  : $id                 ? $params->{$id}->{$column}
294
                  : defined $pos        ? $params->{$column}->[$pos]
Simplify key search
yuki-kimoto authored on 2010-02-11
295
                  : $params->{$column};
packaging one directory
yuki-kimoto authored on 2009-11-16
296
        
Simplify key search
yuki-kimoto authored on 2010-02-11
297
        # Filter
298
        push @bind_values, 
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
299
             $filter ? $filter->($value, $table, $column, $self)
Simplify key search
yuki-kimoto authored on 2010-02-11
300
                     : $value;
cleanup
yuki-kimoto authored on 2010-02-11
301
    }
302
    
Simplify key search
yuki-kimoto authored on 2010-02-11
303
    return \@bind_values;
cleanup
yuki-kimoto authored on 2010-02-11
304
}
305

            
remove run_transaction().
yuki-kimoto authored on 2010-01-30
306
sub transaction { DBIx::Custom::Transaction->new(dbi => shift) }
packaging one directory
yuki-kimoto authored on 2009-11-16
307

            
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
308
sub run_transaction {
309
    my ($self, $transaction) = @_;
310
    
311
    # Shorcut
many change
yuki-kimoto authored on 2010-02-11
312
    return unless $self;
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
313
    
314
    # Check auto commit
315
    croak("AutoCommit must be true before transaction start")
many change
yuki-kimoto authored on 2010-02-11
316
      unless $self->_auto_commit;
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
317
    
318
    # Auto commit off
many change
yuki-kimoto authored on 2010-02-11
319
    $self->_auto_commit(0);
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
320
    
321
    # Run transaction
322
    eval {$transaction->()};
323
    
324
    # Tranzaction error
325
    my $transaction_error = $@;
326
    
327
    # Tranzaction is failed.
328
    if ($transaction_error) {
329
        # Rollback
many change
yuki-kimoto authored on 2010-02-11
330
        eval{$self->dbh->rollback};
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
331
        
332
        # Rollback error
333
        my $rollback_error = $@;
334
        
335
        # Auto commit on
many change
yuki-kimoto authored on 2010-02-11
336
        $self->_auto_commit(1);
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
337
        
338
        if ($rollback_error) {
339
            # Rollback is failed
340
            croak("${transaction_error}Rollback is failed : $rollback_error");
341
        }
342
        else {
343
            # Rollback is success
344
            croak("${transaction_error}Rollback is success");
345
        }
346
    }
347
    # Tranzaction is success
348
    else {
349
        # Commit
many change
yuki-kimoto authored on 2010-02-11
350
        eval{$self->dbh->commit};
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
351
        my $commit_error = $@;
352
        
353
        # Auto commit on
many change
yuki-kimoto authored on 2010-02-11
354
        $self->_auto_commit(1);
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
355
        
356
        # Commit is failed
357
        croak($commit_error) if $commit_error;
358
    }
359
}
360

            
version 0.0901
yuki-kimoto authored on 2009-12-17
361
sub create_table {
362
    my ($self, $table, @column_definitions) = @_;
363
    
364
    # Create table
rename fetch_first to fetch_...
yuki-kimoto authored on 2010-01-29
365
    my $sql = "create table $table (";
version 0.0901
yuki-kimoto authored on 2009-12-17
366
    
367
    # Column definitions
368
    foreach my $column_definition (@column_definitions) {
rename fetch_first to fetch_...
yuki-kimoto authored on 2010-01-29
369
        $sql .= "$column_definition,";
version 0.0901
yuki-kimoto authored on 2009-12-17
370
    }
rename fetch_first to fetch_...
yuki-kimoto authored on 2010-01-29
371
    $sql =~ s/,$//;
version 0.0901
yuki-kimoto authored on 2009-12-17
372
    
373
    # End
rename fetch_first to fetch_...
yuki-kimoto authored on 2010-01-29
374
    $sql .= ");";
version 0.0901
yuki-kimoto authored on 2009-12-17
375
    
376
    # Do query
377
    return $self->do($sql);
378
}
379

            
380
sub drop_table {
381
    my ($self, $table) = @_;
382
    
383
    # Drop table
384
    my $sql = "drop table $table;";
385

            
386
    # Do query
387
    return $self->do($sql);
388
}
389

            
cleanup insert
yuki-kimoto authored on 2010-04-28
390
our %VALID_INSERT_ARGS = map { $_ => 1 } qw/append query_edit_cb/;
391

            
packaging one directory
yuki-kimoto authored on 2009-11-16
392
sub insert {
cleanup insert
yuki-kimoto authored on 2010-04-28
393
    my ($self, $table, $insert_params, $args) = @_;
394
    
395
    # Table
396
    $table ||= '';
397
    
398
    # Insert params
399
    $insert_params ||= {};
400
    
401
    # Arguments
402
    $args ||= {};
403
    
404
    # Check arguments
405
    foreach my $name (keys %$args) {
406
        croak "\"$name\" is invalid name"
407
          unless $VALID_INSERT_ARGS{$name};
408
    }
409
    
410
    my $append_statement = $args->{append} || '';
411
    my $query_edit_cb    = $args->{query_edit_cb};
packaging one directory
yuki-kimoto authored on 2009-11-16
412
    
413
    # Insert keys
414
    my @insert_keys = keys %$insert_params;
415
    
416
    # Not exists insert keys
417
    croak("Key-value pairs for insert must be specified to 'insert' second argument")
418
      unless @insert_keys;
419
    
420
    # Templte for insert
421
    my $template = "insert into $table {insert " . join(' ', @insert_keys) . '}';
insert, update, delete appnd...
yuki-kimoto authored on 2009-11-16
422
    $template .= " $append_statement" if $append_statement;
packaging one directory
yuki-kimoto authored on 2009-11-16
423
    # Create query
Simplify key search
yuki-kimoto authored on 2010-02-11
424
    my $query = $self->create_query([$table, $template]);
packaging one directory
yuki-kimoto authored on 2009-11-16
425
    
426
    # Query edit callback must be code reference
427
    croak("Query edit callback must be code reference")
428
      if $query_edit_cb && ref $query_edit_cb ne 'CODE';
429
    
430
    # Query edit if need
431
    $query_edit_cb->($query) if $query_edit_cb;
432
    
433
    # Execute query
version 0.0901
yuki-kimoto authored on 2009-12-17
434
    my $ret_val = $self->query($query, $insert_params);
packaging one directory
yuki-kimoto authored on 2009-11-16
435
    
436
    return $ret_val;
437
}
438

            
cleanup update and update_al...
yuki-kimoto authored on 2010-04-28
439
our %VALID_UPDATE_ARGS
440
  = map { $_ => 1 } qw/where append query_edit_cb allow_update_all/;
441

            
packaging one directory
yuki-kimoto authored on 2009-11-16
442
sub update {
cleanup update and update_al...
yuki-kimoto authored on 2010-04-28
443
    my ($self, $table, $update_params, $args) = @_;
444
    
445
    # Check arguments
446
    foreach my $name (keys %$args) {
447
        croak "\"$name\" is invalid name"
448
          unless $VALID_UPDATE_ARGS{$name};
449
    }
450
    
451
    # Arguments
452
    my $where_params     = $args->{where} || {};
453
    my $append_statement = $args->{append} || '';
454
    my $query_edit_cb    = $args->{query_edit_cb};
455
    my $allow_update_all = $args->{allow_update_all};
packaging one directory
yuki-kimoto authored on 2009-11-16
456
    
457
    # Update keys
458
    my @update_keys = keys %$update_params;
459
    
460
    # Not exists update kyes
461
    croak("Key-value pairs for update must be specified to 'update' second argument")
462
      unless @update_keys;
463
    
464
    # Where keys
465
    my @where_keys = keys %$where_params;
466
    
467
    # Not exists where keys
468
    croak("Key-value pairs for where clause must be specified to 'update' third argument")
cleanup update and update_al...
yuki-kimoto authored on 2010-04-28
469
      if !@where_keys && !$allow_update_all;
packaging one directory
yuki-kimoto authored on 2009-11-16
470
    
471
    # Update clause
472
    my $update_clause = '{update ' . join(' ', @update_keys) . '}';
473
    
474
    # Where clause
475
    my $where_clause = '';
476
    if (@where_keys) {
477
        $where_clause = 'where ';
478
        foreach my $where_key (@where_keys) {
many change
yuki-kimoto authored on 2010-02-11
479
            my $key_info = DBIx::Custom::KeyInfo->new($where_key);
480
            
481
            my $table_new = $key_info->table || $table;
482
            my $column = $table_new . '.' . $key_info->column
483
                         . '#@where';
484

            
485
            $where_clause .= "{= $column} and ";
packaging one directory
yuki-kimoto authored on 2009-11-16
486
        }
487
        $where_clause =~ s/ and $//;
488
    }
489
    
490
    # Template for update
491
    my $template = "update $table $update_clause $where_clause";
insert, update, delete appnd...
yuki-kimoto authored on 2009-11-16
492
    $template .= " $append_statement" if $append_statement;
packaging one directory
yuki-kimoto authored on 2009-11-16
493
    
494
    # Create query
Simplify key search
yuki-kimoto authored on 2010-02-11
495
    my $query = $self->create_query([$table, $template]);
packaging one directory
yuki-kimoto authored on 2009-11-16
496
    
497
    # Query edit callback must be code reference
498
    croak("Query edit callback must be code reference")
499
      if $query_edit_cb && ref $query_edit_cb ne 'CODE';
500
    
501
    # Query edit if need
502
    $query_edit_cb->($query) if $query_edit_cb;
503
    
504
    # Rearrange parammeters
many change
yuki-kimoto authored on 2010-02-11
505
    my $params = {%$update_params, '@where' => $where_params};
packaging one directory
yuki-kimoto authored on 2009-11-16
506
    
507
    # Execute query
version 0.0901
yuki-kimoto authored on 2009-12-17
508
    my $ret_val = $self->query($query, $params);
packaging one directory
yuki-kimoto authored on 2009-11-16
509
    
510
    return $ret_val;
511
}
512

            
513
sub update_all {
cleanup update and update_al...
yuki-kimoto authored on 2010-04-28
514
    my ($self, $table, $update_params, $args) = @_;
515
    
516
    $args ||= {};
517
    
518
    $args->{allow_update_all} = 1;
insert, update, delete appnd...
yuki-kimoto authored on 2009-11-16
519
    
update document
yuki-kimoto authored on 2010-01-30
520
    # Update all rows
cleanup update and update_al...
yuki-kimoto authored on 2010-04-28
521
    return $self->update($table, $update_params, $args);
packaging one directory
yuki-kimoto authored on 2009-11-16
522
}
523

            
refactoring delete and delet...
yuki-kimoto authored on 2010-04-28
524
our %VALID_DELETE_ARGS
525
  = map { $_ => 1 } qw/where append query_edit_cb allow_delete_all/;
526

            
packaging one directory
yuki-kimoto authored on 2009-11-16
527
sub delete {
refactoring delete and delet...
yuki-kimoto authored on 2010-04-28
528
    my ($self, $table, $args) = @_;
529
    
530
    # Table
531
    $table            ||= '';
532

            
533
    # Check arguments
534
    foreach my $name (keys %$args) {
535
        croak "\"$name\" is invalid name"
536
          unless $VALID_DELETE_ARGS{$name};
537
    }
538
    
539
    # Arguments
540
    my $where_params     = $args->{where} || {};
541
    my $append_statement = $args->{append};
542
    my $query_edit_cb    = $args->{query_edit_cb};
543
    my $allow_delete_all = $args->{allow_delete_all};
packaging one directory
yuki-kimoto authored on 2009-11-16
544
    
545
    # Where keys
546
    my @where_keys = keys %$where_params;
547
    
548
    # Not exists where keys
549
    croak("Key-value pairs for where clause must be specified to 'delete' second argument")
refactoring delete and delet...
yuki-kimoto authored on 2010-04-28
550
      if !@where_keys && !$allow_delete_all;
packaging one directory
yuki-kimoto authored on 2009-11-16
551
    
552
    # Where clause
553
    my $where_clause = '';
554
    if (@where_keys) {
555
        $where_clause = 'where ';
556
        foreach my $where_key (@where_keys) {
557
            $where_clause .= "{= $where_key} and ";
558
        }
559
        $where_clause =~ s/ and $//;
560
    }
561
    
562
    # Template for delete
563
    my $template = "delete from $table $where_clause";
insert, update, delete appnd...
yuki-kimoto authored on 2009-11-16
564
    $template .= " $append_statement" if $append_statement;
packaging one directory
yuki-kimoto authored on 2009-11-16
565
    
566
    # Create query
Simplify key search
yuki-kimoto authored on 2010-02-11
567
    my $query = $self->create_query([$table, $template]);
packaging one directory
yuki-kimoto authored on 2009-11-16
568
    
569
    # Query edit callback must be code reference
570
    croak("Query edit callback must be code reference")
571
      if $query_edit_cb && ref $query_edit_cb ne 'CODE';
572
    
573
    # Query edit if need
574
    $query_edit_cb->($query) if $query_edit_cb;
575
    
576
    # Execute query
version 0.0901
yuki-kimoto authored on 2009-12-17
577
    my $ret_val = $self->query($query, $where_params);
packaging one directory
yuki-kimoto authored on 2009-11-16
578
    
579
    return $ret_val;
580
}
581

            
582
sub delete_all {
refactoring delete and delet...
yuki-kimoto authored on 2010-04-28
583
    my ($self, $table, $args) = @_;
584
    
585
    $args ||= {};
586
    
587
    $args->{allow_delete_all} = 1;
insert, update, delete appnd...
yuki-kimoto authored on 2009-11-16
588
    
update document
yuki-kimoto authored on 2010-01-30
589
    # Delete all rows
refactoring delete and delet...
yuki-kimoto authored on 2010-04-28
590
    return $self->delete($table, $args);
packaging one directory
yuki-kimoto authored on 2009-11-16
591
}
592

            
593
sub _select_usage { return << 'EOS' }
594
Your select arguments is wrong.
595
select usage:
596
$dbi->select(
cleanup
yuki-kimoto authored on 2010-02-11
597
    $table,                # String or array ref
598
    [@$columns],           # Array reference. this can be ommited
599
    {%$where_params},      # Hash reference.  this can be ommited
600
    $append_statement,     # String.          this can be ommited
601
    $query_edit_callback   # Sub reference.   this can be ommited
packaging one directory
yuki-kimoto authored on 2009-11-16
602
);
603
EOS
604

            
605
sub select {
606
    my $self = shift;
607
    
608
    # Check argument
609
    croak($self->_select_usage) unless @_;
610
    
611
    # Arguments
612
    my $tables = shift || '';
613
    $tables    = [$tables] unless ref $tables;
614
    
615
    my $columns          = ref $_[0] eq 'ARRAY' ? shift : [];
616
    my $where_params     = ref $_[0] eq 'HASH'  ? shift : {};
617
    my $append_statement = $_[0] && !ref $_[0]  ? shift : '';
618
    my $query_edit_cb    = shift if ref $_[0] eq 'CODE';
619
    
620
    # Check rest argument
621
    croak($self->_select_usage) if @_;
622
    
623
    # SQL template for select statement
624
    my $template = 'select ';
625
    
626
    # Join column clause
627
    if (@$columns) {
628
        foreach my $column (@$columns) {
629
            $template .= "$column, ";
630
        }
631
        $template =~ s/, $/ /;
632
    }
633
    else {
634
        $template .= '* ';
635
    }
636
    
637
    # Join table
638
    $template .= 'from ';
639
    foreach my $table (@$tables) {
640
        $template .= "$table, ";
641
    }
642
    $template =~ s/, $/ /;
643
    
644
    # Where clause keys
645
    my @where_keys = keys %$where_params;
646
    
many change
yuki-kimoto authored on 2010-02-11
647
    my $where_params_new = {};
648
    
packaging one directory
yuki-kimoto authored on 2009-11-16
649
    # Join where clause
650
    if (@where_keys) {
651
        $template .= 'where ';
652
        foreach my $where_key (@where_keys) {
many change
yuki-kimoto authored on 2010-02-11
653
            my $key_info = DBIx::Custom::KeyInfo->new($where_key);
654
            
655
            my $table_new = $key_info->table || $tables->[0];
656
            my $column = $table_new . '.' . $key_info->column
657
                         . '#' . $table_new;
658
                      
659
            $template .= "{= $column} and ";
660
            
661
            $where_params_new->{$table_new} ||= {};
662
            $where_params_new->{$table_new}->{$key_info->column}
663
              = $where_params->{$where_key};
packaging one directory
yuki-kimoto authored on 2009-11-16
664
        }
665
    }
666
    $template =~ s/ and $//;
667
    
668
    # Append something to last of statement
669
    if ($append_statement =~ s/^where //) {
670
        if (@where_keys) {
671
            $template .= " and $append_statement";
672
        }
673
        else {
674
            $template .= " where $append_statement";
675
        }
676
    }
677
    else {
678
        $template .= " $append_statement";
679
    }
680
    
681
    # Create query
Simplify key search
yuki-kimoto authored on 2010-02-11
682
    my $query = $self->create_query([$tables->[0], $template]);
packaging one directory
yuki-kimoto authored on 2009-11-16
683
    
684
    # Query edit
685
    $query_edit_cb->($query) if $query_edit_cb;
686
    
687
    # Execute query
many change
yuki-kimoto authored on 2010-02-11
688
    my $result = $self->query($query, $where_params_new);
packaging one directory
yuki-kimoto authored on 2009-11-16
689
    
690
    return $result;
691
}
692

            
693
sub _add_query_cache {
694
    my ($class, $template, $query) = @_;
update document
yuki-kimoto authored on 2010-01-30
695
    
696
    # Query information
packaging one directory
yuki-kimoto authored on 2009-11-16
697
    my $query_cache_keys = $class->_query_cache_keys;
698
    my $query_caches     = $class->_query_caches;
699
    
update document
yuki-kimoto authored on 2010-01-30
700
    # Already cached
packaging one directory
yuki-kimoto authored on 2009-11-16
701
    return $class if $query_caches->{$template};
702
    
update document
yuki-kimoto authored on 2010-01-30
703
    # Cache
packaging one directory
yuki-kimoto authored on 2009-11-16
704
    $query_caches->{$template} = $query;
705
    push @$query_cache_keys, $template;
706
    
update document
yuki-kimoto authored on 2010-01-30
707
    # Check cache overflow
packaging one directory
yuki-kimoto authored on 2009-11-16
708
    my $overflow = @$query_cache_keys - $class->query_cache_max;
709
    for (my $i = 0; $i < $overflow; $i++) {
710
        my $template = shift @$query_cache_keys;
711
        delete $query_caches->{$template};
712
    }
713
    
714
    return $class;
715
}
716

            
717
=head1 NAME
718

            
version 0.0901
yuki-kimoto authored on 2009-12-17
719
DBIx::Custom - Customizable DBI
packaging one directory
yuki-kimoto authored on 2009-11-16
720

            
version 0.0901
yuki-kimoto authored on 2009-12-17
721
=head1 VERSION
packaging one directory
yuki-kimoto authored on 2009-11-16
722

            
many change
yuki-kimoto authored on 2010-02-11
723
Version 0.1201
catch up with Object::Simple...
yuki-kimoto authored on 2010-01-18
724

            
725
=cut
726

            
many change
yuki-kimoto authored on 2010-02-11
727
our $VERSION = '0.1201';
packaging one directory
yuki-kimoto authored on 2009-11-16
728

            
cleanup
yuki-kimoto authored on 2010-02-11
729
=head1 STATE
730

            
731
This module is not stable. Method name and functionality will be change.
732

            
version 0.0901
yuki-kimoto authored on 2009-12-17
733
=head1 SYNOPSYS
734
    
735
    # New
736
    my $dbi = DBIx::Custom->new(data_source => "dbi:mysql:database=books"
737
                                user => 'ken', password => '!LFKD%$&');
738
    
739
    # Query
740
    $dbi->query("select title from books");
741
    
742
    # Query with parameters
743
    $dbi->query("select id from books where {= author} && {like title}",
744
                {author => 'ken', title => '%Perl%'});
745
    
746
    # Insert 
747
    $dbi->insert('books', {title => 'perl', author => 'Ken'});
748
    
749
    # Update 
750
    $dbi->update('books', {title => 'aaa', author => 'Ken'}, {id => 5});
751
    
752
    # Delete
753
    $dbi->delete('books', {author => 'Ken'});
754
    
755
    # Select
756
    $dbi->select('books');
757
    $dbi->select('books', {author => 'taro'}); 
758
    $dbi->select('books', [qw/author title/], {author => 'Ken'});
759
    $dbi->select('books', [qw/author title/], {author => 'Ken'},
760
                 'order by id limit 1');
packaging one directory
yuki-kimoto authored on 2009-11-16
761

            
update document
yuki-kimoto authored on 2010-01-30
762
=head1 ATTRIBUTES
packaging one directory
yuki-kimoto authored on 2009-11-16
763

            
764
=head2 user
765

            
update document
yuki-kimoto authored on 2010-01-30
766
Database user name
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
767
    
version 0.0901
yuki-kimoto authored on 2009-12-17
768
    $dbi  = $dbi->user('Ken');
769
    $user = $dbi->user;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
770
    
packaging one directory
yuki-kimoto authored on 2009-11-16
771
=head2 password
772

            
update document
yuki-kimoto authored on 2010-01-30
773
Database password
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
774
    
version 0.0901
yuki-kimoto authored on 2009-12-17
775
    $dbi      = $dbi->password('lkj&le`@s');
776
    $password = $dbi->password;
packaging one directory
yuki-kimoto authored on 2009-11-16
777

            
778
=head2 data_source
779

            
update document
yuki-kimoto authored on 2010-01-30
780
Database data source
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
781
    
version 0.0901
yuki-kimoto authored on 2009-12-17
782
    $dbi         = $dbi->data_source("dbi:mysql:dbname=$database");
783
    $data_source = $dbi->data_source;
packaging one directory
yuki-kimoto authored on 2009-11-16
784
    
version 0.0901
yuki-kimoto authored on 2009-12-17
785
If you know data source more, See also L<DBI>.
786

            
packaging one directory
yuki-kimoto authored on 2009-11-16
787
=head2 database
788

            
update document
yuki-kimoto authored on 2010-01-30
789
Database name
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
790

            
version 0.0901
yuki-kimoto authored on 2009-12-17
791
    $dbi      = $dbi->database('books');
792
    $database = $dbi->database;
packaging one directory
yuki-kimoto authored on 2009-11-16
793

            
add port and host method
yuki-kimoto authored on 2009-11-16
794
=head2 host
795

            
update document
yuki-kimoto authored on 2010-01-30
796
Host name
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
797

            
version 0.0901
yuki-kimoto authored on 2009-12-17
798
    $dbi  = $dbi->host('somehost.com');
799
    $host = $dbi->host;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
800

            
version 0.0901
yuki-kimoto authored on 2009-12-17
801
You can also set IP address like '127.03.45.12'.
add port and host method
yuki-kimoto authored on 2009-11-16
802

            
803
=head2 port
804

            
update document
yuki-kimoto authored on 2010-01-30
805
Port number
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
806

            
version 0.0901
yuki-kimoto authored on 2009-12-17
807
    $dbi  = $dbi->port(1198);
808
    $port = $dbi->port;
add port and host method
yuki-kimoto authored on 2009-11-16
809

            
version 0.0901
yuki-kimoto authored on 2009-12-17
810
=head2 options
packaging one directory
yuki-kimoto authored on 2009-11-16
811

            
update document
yuki-kimoto authored on 2010-01-30
812
DBI options
packaging one directory
yuki-kimoto authored on 2009-11-16
813

            
version 0.0901
yuki-kimoto authored on 2009-12-17
814
    $dbi     = $dbi->options({PrintError => 0, RaiseError => 1});
815
    $options = $dbi->options;
packaging one directory
yuki-kimoto authored on 2009-11-16
816

            
version 0.0901
yuki-kimoto authored on 2009-12-17
817
=head2 sql_tmpl
packaging one directory
yuki-kimoto authored on 2009-11-16
818

            
update document
yuki-kimoto authored on 2010-01-30
819
SQL::Template object
packaging one directory
yuki-kimoto authored on 2009-11-16
820

            
version 0.0901
yuki-kimoto authored on 2009-12-17
821
    $dbi      = $dbi->sql_tmpl(DBIx::Cutom::SQL::Template->new);
822
    $sql_tmpl = $dbi->sql_tmpl;
packaging one directory
yuki-kimoto authored on 2009-11-16
823

            
version 0.0901
yuki-kimoto authored on 2009-12-17
824
See also L<DBIx::Custom::SQL::Template>.
packaging one directory
yuki-kimoto authored on 2009-11-16
825

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
826
=head2 filters
packaging one directory
yuki-kimoto authored on 2009-11-16
827

            
update document
yuki-kimoto authored on 2010-01-30
828
Filters
packaging one directory
yuki-kimoto authored on 2009-11-16
829

            
version 0.0901
yuki-kimoto authored on 2009-12-17
830
    $dbi     = $dbi->filters({filter1 => sub { }, filter2 => sub {}});
831
    $filters = $dbi->filters;
packaging one directory
yuki-kimoto authored on 2009-11-16
832
    
version 0.0901
yuki-kimoto authored on 2009-12-17
833
This method is generally used to get a filter.
834

            
835
    $filter = $dbi->filters->{encode_utf8};
836

            
837
If you add filter, use add_filter method.
packaging one directory
yuki-kimoto authored on 2009-11-16
838

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
839
=head2 formats
packaging one directory
yuki-kimoto authored on 2009-11-16
840

            
update document
yuki-kimoto authored on 2010-01-30
841
Formats
packaging one directory
yuki-kimoto authored on 2009-11-16
842

            
version 0.0901
yuki-kimoto authored on 2009-12-17
843
    $dbi     = $dbi->formats({format1 => sub { }, format2 => sub {}});
844
    $formats = $dbi->formats;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
845

            
version 0.0901
yuki-kimoto authored on 2009-12-17
846
This method is generally used to get a format.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
847

            
version 0.0901
yuki-kimoto authored on 2009-12-17
848
    $filter = $dbi->formats->{datetime};
849

            
850
If you add format, use add_format method.
packaging one directory
yuki-kimoto authored on 2009-11-16
851

            
cleanup
yuki-kimoto authored on 2010-04-28
852
=head2 default_bind_filter
packaging one directory
yuki-kimoto authored on 2009-11-16
853

            
update document
yuki-kimoto authored on 2010-01-30
854
Binding filter
packaging one directory
yuki-kimoto authored on 2009-11-16
855

            
cleanup
yuki-kimoto authored on 2010-04-28
856
    $dbi                 = $dbi->default_bind_filter($default_bind_filter);
857
    $default_bind_filter = $dbi->default_bind_filter
packaging one directory
yuki-kimoto authored on 2009-11-16
858

            
version 0.0901
yuki-kimoto authored on 2009-12-17
859
The following is bind filter sample
cleanup
yuki-kimoto authored on 2010-04-28
860
    
861
    $dbi->add_filter(encode_utf8 => sub {
862
        my $value = shift;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
863
        
cleanup
yuki-kimoto authored on 2010-04-28
864
        require Encode 'encode_utf8';
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
865
        
cleanup
yuki-kimoto authored on 2010-04-28
866
        return encode_utf8($value);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
867
    });
cleanup
yuki-kimoto authored on 2010-04-28
868
    
869
    $dbi->default_bind_filter('encode_utf8')
packaging one directory
yuki-kimoto authored on 2009-11-16
870

            
version 0.0901
yuki-kimoto authored on 2009-12-17
871
Bind filter arguemts is
872

            
873
    1. $value : Value
874
    2. $key   : Key
875
    3. $dbi   : DBIx::Custom object
876
    4. $infos : {table => $table, column => $column}
877

            
cleanup
yuki-kimoto authored on 2010-04-28
878
=head2 default_fetch_filter
packaging one directory
yuki-kimoto authored on 2009-11-16
879

            
update document
yuki-kimoto authored on 2010-01-30
880
Fetching filter
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
881

            
cleanup
yuki-kimoto authored on 2010-04-28
882
    $dbi                  = $dbi->default_fetch_filter($default_fetch_filter);
883
    $default_fetch_filter = $dbi->default_fetch_filter;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
884

            
version 0.0901
yuki-kimoto authored on 2009-12-17
885
The following is fetch filter sample
packaging one directory
yuki-kimoto authored on 2009-11-16
886

            
cleanup
yuki-kimoto authored on 2010-04-28
887
    $dbi->add_filter(decode_utf8 => sub {
888
        my $value = shift;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
889
        
cleanup
yuki-kimoto authored on 2010-04-28
890
        require Encode 'decode_utf8';
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
891
        
cleanup
yuki-kimoto authored on 2010-04-28
892
        return decode_utf8($value);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
893
    });
packaging one directory
yuki-kimoto authored on 2009-11-16
894

            
cleanup
yuki-kimoto authored on 2010-04-28
895
    $dbi->default_fetch_filter('decode_utf8');
896

            
version 0.0901
yuki-kimoto authored on 2009-12-17
897
Bind filter arguemts is
898

            
899
    1. $value : Value
900
    2. $key   : Key
901
    3. $dbi   : DBIx::Custom object
902
    4. $infos : {type => $table, sth => $sth, index => $index}
903

            
packaging one directory
yuki-kimoto authored on 2009-11-16
904
=head2 result_class
905

            
update document
yuki-kimoto authored on 2010-01-30
906
Resultset class
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
907

            
version 0.0901
yuki-kimoto authored on 2009-12-17
908
    $dbi          = $dbi->result_class('DBIx::Custom::Result');
packaging one directory
yuki-kimoto authored on 2009-11-16
909
    $result_class = $dbi->result_class;
910

            
update document
yuki-kimoto authored on 2010-01-30
911
Default is L<DBIx::Custom::Result>
912

            
packaging one directory
yuki-kimoto authored on 2009-11-16
913
=head2 dbh
914

            
update document
yuki-kimoto authored on 2010-01-30
915
Database handle
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
916
    
version 0.0901
yuki-kimoto authored on 2009-12-17
917
    $dbi = $dbi->dbh($dbh);
918
    $dbh = $dbi->dbh;
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
919
    
920
=head2 query_cache_max
921

            
update document
yuki-kimoto authored on 2010-01-30
922
Query cache max
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
923

            
version 0.0901
yuki-kimoto authored on 2009-12-17
924
    $class           = DBIx::Custom->query_cache_max(50);
925
    $query_cache_max = DBIx::Custom->query_cache_max;
926

            
927
Default value is 50
928

            
update document
yuki-kimoto authored on 2010-01-30
929
=head1 METHODS
930

            
931
This class is L<Object::Simple> subclass.
932
You can use all methods of L<Object::Simple>
packaging one directory
yuki-kimoto authored on 2009-11-16
933

            
934
=head2 connect
935

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
936
Connect to database
937

            
packaging one directory
yuki-kimoto authored on 2009-11-16
938
    $dbi->connect;
939

            
940
=head2 disconnect
941

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
942
Disconnect database
943

            
packaging one directory
yuki-kimoto authored on 2009-11-16
944
    $dbi->disconnect;
945

            
version 0.0901
yuki-kimoto authored on 2009-12-17
946
If database is already disconnected, this method do nothing.
packaging one directory
yuki-kimoto authored on 2009-11-16
947

            
948
=head2 reconnect
949

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
950
Reconnect to database
951

            
packaging one directory
yuki-kimoto authored on 2009-11-16
952
    $dbi->reconnect;
953

            
954
=head2 connected
955

            
version 0.0901
yuki-kimoto authored on 2009-12-17
956
Check if database is connected.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
957
    
version 0.0901
yuki-kimoto authored on 2009-12-17
958
    $is_connected = $dbi->connected;
packaging one directory
yuki-kimoto authored on 2009-11-16
959
    
960
=head2 add_filter
961

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
962
Resist filter
packaging one directory
yuki-kimoto authored on 2009-11-16
963
    
version 0.0901
yuki-kimoto authored on 2009-12-17
964
    $dbi->add_filter($fname1 => $filter1, $fname => $filter2);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
965
    
version 0.0901
yuki-kimoto authored on 2009-12-17
966
The following is add_filter sample
967

            
packaging one directory
yuki-kimoto authored on 2009-11-16
968
    $dbi->add_filter(
969
        encode_utf8 => sub {
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
970
            my ($value, $key, $dbi, $infos) = @_;
971
            utf8::upgrade($value) unless Encode::is_utf8($value);
972
            return encode('UTF-8', $value);
packaging one directory
yuki-kimoto authored on 2009-11-16
973
        },
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
974
        decode_utf8 => sub {
975
            my ($value, $key, $dbi, $infos) = @_;
976
            return decode('UTF-8', $value)
packaging one directory
yuki-kimoto authored on 2009-11-16
977
        }
978
    );
979

            
980
=head2 add_format
981

            
version 0.0901
yuki-kimoto authored on 2009-12-17
982
Add format
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
983

            
version 0.0901
yuki-kimoto authored on 2009-12-17
984
    $dbi->add_format($fname1 => $format, $fname2 => $format2);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
985
    
version 0.0901
yuki-kimoto authored on 2009-12-17
986
The following is add_format sample.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
987

            
version 0.0901
yuki-kimoto authored on 2009-12-17
988
    $dbi->add_format(date => '%Y:%m:%d', datetime => '%Y-%m-%d %H:%M:%S');
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
989

            
version 0.0901
yuki-kimoto authored on 2009-12-17
990
=head2 create_query
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
991
    
version 0.0901
yuki-kimoto authored on 2009-12-17
992
Create Query object parsing SQL template
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
993

            
version 0.0901
yuki-kimoto authored on 2009-12-17
994
    my $query = $dbi->create_query("select * from authors where {= name} and {= age}");
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
995

            
version 0.0901
yuki-kimoto authored on 2009-12-17
996
$query is <DBIx::Query> object. This is executed by query method as the following
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
997

            
version 0.0901
yuki-kimoto authored on 2009-12-17
998
    $dbi->query($query, $params);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
999

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1000
If you know SQL template, see also L<DBIx::Custom::SQL::Template>.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1001

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1002
=head2 query
packaging one directory
yuki-kimoto authored on 2009-11-16
1003

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1004
Query
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1005

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1006
    $result = $dbi->query($template, $params);
packaging one directory
yuki-kimoto authored on 2009-11-16
1007

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1008
The following is query sample
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1009

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1010
    $result = $dbi->query("select * from authors where {= name} and {= age}", 
1011
                          {author => 'taro', age => 19});
1012
    
1013
    while (my @row = $result->fetch) {
1014
        # do something
1015
    }
1016

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1017
If you now syntax of template, See also L<DBIx::Custom::SQL::Template>
1018

            
1019
Return value of query method is L<DBIx::Custom::Result> object
1020

            
1021
See also L<DBIx::Custom::Result>.
packaging one directory
yuki-kimoto authored on 2009-11-16
1022

            
remove run_transaction().
yuki-kimoto authored on 2010-01-30
1023
=head2 transaction
packaging one directory
yuki-kimoto authored on 2009-11-16
1024

            
remove run_transaction().
yuki-kimoto authored on 2010-01-30
1025
Get L<DBIx::Custom::Transaction> object, and you run a transaction.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1026

            
remove run_transaction().
yuki-kimoto authored on 2010-01-30
1027
    $dbi->transaction->run(sub {
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1028
        my $dbi = shift;
1029
        
packaging one directory
yuki-kimoto authored on 2009-11-16
1030
        # do something
1031
    });
1032

            
1033
If transaction is success, commit is execute. 
1034
If tranzation is died, rollback is execute.
1035

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1036
=head2 create_table
1037

            
1038
Create table
1039

            
1040
    $dbi->create_table(
1041
        'books',
1042
        'name char(255)',
1043
        'age  int'
1044
    );
1045

            
1046
First argument is table name. Rest arguments is column definition.
1047

            
1048
=head2 drop_table
1049

            
1050
Drop table
1051

            
1052
    $dbi->drop_table('books');
1053

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1054
=head2 insert
1055

            
update document
yuki-kimoto authored on 2009-11-19
1056
Insert row
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1057

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1058
    $affected = $dbi->insert($table, \%$insert_params);
1059
    $affected = $dbi->insert($table, \%$insert_params, $append);
update document
yuki-kimoto authored on 2009-11-19
1060

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1061
Retrun value is affected rows count
packaging one directory
yuki-kimoto authored on 2009-11-16
1062
    
version 0.0901
yuki-kimoto authored on 2009-12-17
1063
The following is insert sample.
1064

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1065
    $dbi->insert('books', {title => 'Perl', author => 'Taro'});
1066

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1067
You can add statement.
1068

            
1069
    $dbi->insert('books', {title => 'Perl', author => 'Taro'}, "some statement");
1070

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1071
=head2 update
1072

            
update document
yuki-kimoto authored on 2009-11-19
1073
Update rows
1074

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1075
    $affected = $dbi->update($table, \%update_params, \%where);
1076
    $affected = $dbi->update($table, \%update_params, \%where, $append);
1077

            
1078
Retrun value is affected rows count
update document
yuki-kimoto authored on 2009-11-19
1079

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1080
The following is update sample.
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1081

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1082
    $dbi->update('books', {title => 'Perl', author => 'Taro'}, {id => 5});
1083

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1084
You can add statement.
1085

            
1086
    $dbi->update('books', {title => 'Perl', author => 'Taro'},
1087
                 {id => 5}, "some statement");
1088

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1089
=head2 update_all
1090

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1091
Update all rows
1092

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1093
    $affected = $dbi->update_all($table, \%updat_params);
update document
yuki-kimoto authored on 2009-11-19
1094

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1095
Retrun value is affected rows count
1096

            
1097
The following is update_all sample.
update document
yuki-kimoto authored on 2009-11-19
1098

            
1099
    $dbi->update_all('books', {author => 'taro'});
packaging one directory
yuki-kimoto authored on 2009-11-16
1100

            
1101
=head2 delete
1102

            
update document
yuki-kimoto authored on 2009-11-19
1103
Delete rows
1104

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1105
    $affected = $dbi->delete($table, \%where);
1106
    $affected = $dbi->delete($table, \%where, $append);
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1107

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1108
Retrun value is affected rows count
packaging one directory
yuki-kimoto authored on 2009-11-16
1109
    
version 0.0901
yuki-kimoto authored on 2009-12-17
1110
The following is delete sample.
1111

            
update document
yuki-kimoto authored on 2009-11-19
1112
    $dbi->delete('books', {id => 5});
packaging one directory
yuki-kimoto authored on 2009-11-16
1113

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1114
You can add statement.
1115

            
1116
    $dbi->delete('books', {id => 5}, "some statement");
1117

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1118
=head2 delete_all
1119

            
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1120
Delete all rows
1121

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1122
    $affected = $dbi->delete_all($table);
packaging one directory
yuki-kimoto authored on 2009-11-16
1123

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1124
Retrun value is affected rows count
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1125

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1126
The following is delete_all sample.
1127

            
1128
    $dbi->delete_all('books');
packaging one directory
yuki-kimoto authored on 2009-11-16
1129

            
1130
=head2 select
1131
    
update document
yuki-kimoto authored on 2009-11-19
1132
Select rows
bind_filter argument is chan...
yuki-kimoto authored on 2009-11-19
1133

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1134
    $resut = $dbi->select(
packaging one directory
yuki-kimoto authored on 2009-11-16
1135
        $table,                # must be string or array;
version 0.0901
yuki-kimoto authored on 2009-12-17
1136
        \@$columns,            # must be array reference. this can be ommited
1137
        \%$where_params,       # must be hash reference.  this can be ommited
1138
        $append_statement,     # must be string.          this can be ommited
1139
        $query_edit_callback   # must be code reference.  this can be ommited
packaging one directory
yuki-kimoto authored on 2009-11-16
1140
    );
update document
yuki-kimoto authored on 2009-11-19
1141

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1142
$reslt is L<DBIx::Custom::Result> object
update document
yuki-kimoto authored on 2009-11-19
1143

            
1144
The following is some select samples
1145

            
1146
    # select * from books;
1147
    $result = $dbi->select('books');
packaging one directory
yuki-kimoto authored on 2009-11-16
1148
    
update document
yuki-kimoto authored on 2009-11-19
1149
    # select * from books where title = 'Perl';
1150
    $result = $dbi->select('books', {title => 1});
1151
    
1152
    # select title, author from books where id = 1 for update;
1153
    $result = $dbi->select(
1154
        'books',              # table
1155
        ['title', 'author'],  # columns
1156
        {id => 1},            # where clause
1157
        'for update',         # append statement
1158
    );
1159

            
1160
You can join multi tables
1161
    
1162
    $result = $dbi->select(
1163
        ['table1', 'table2'],                # tables
1164
        ['table1.id as table1_id', 'title'], # columns (alias is ok)
1165
        {table1.id => 1},                    # where clase
1166
        "where table1.id = table2.id",       # join clause (must start 'where')
1167
    );
1168

            
1169
You can also edit query
1170
        
packaging one directory
yuki-kimoto authored on 2009-11-16
1171
    $dbi->select(
update document
yuki-kimoto authored on 2009-11-19
1172
        'books',
1173
        # column, where clause, append statement,
packaging one directory
yuki-kimoto authored on 2009-11-16
1174
        sub {
1175
            my $query = shift;
1176
            $query->bind_filter(sub {
1177
                # ...
1178
            });
1179
        }
update document
yuki-kimoto authored on 2009-11-19
1180
    }
1181

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1182
=head2 prepare
1183

            
1184
Prepare statement handle.
1185

            
1186
    $sth = $dbi->prepare('select * from books;');
1187

            
1188
This method is same as DBI prepare method.
1189

            
1190
See also L<DBI>.
1191

            
1192
=head2 do
1193

            
1194
Execute SQL
1195

            
1196
    $affected = $dbi->do('insert into books (title, author) values (?, ?)',
1197
                        'Perl', 'taro');
1198

            
1199
Retrun value is affected rows count.
1200

            
1201
This method is same as DBI do method.
1202

            
1203
See also L<DBI>
1204

            
remove DBIx::Custom::Transac...
yuki-kimoto authored on 2010-02-11
1205
=head2 run_transaction
1206

            
1207

            
1208

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1209
=head1 DBIx::Custom default configuration
packaging one directory
yuki-kimoto authored on 2009-11-16
1210

            
update document
yuki-kimoto authored on 2009-11-19
1211
DBIx::Custom have DBI object.
packaging one directory
yuki-kimoto authored on 2009-11-16
1212
This module is work well in the following DBI condition.
1213

            
1214
    1. AutoCommit is true
1215
    2. RaiseError is true
1216

            
1217
By default, Both AutoCommit and RaiseError is true.
1218
You must not change these mode not to damage your data.
1219

            
1220
If you change these mode, 
1221
you cannot get correct error message, 
1222
or run_transaction may fail.
1223

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1224
=head1 Inheritance of DBIx::Custom
1225

            
1226
DBIx::Custom is customizable DBI.
1227
You can inherit DBIx::Custom and custumize attributes.
1228

            
1229
    package DBIx::Custom::Yours;
1230
    use base DBIx::Custom;
1231
    
1232
    my $class = __PACKAGE__;
1233
    
1234
    $class->user('your_name');
1235
    $class->password('your_password');
1236

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1237
=head1 AUTHOR
1238

            
1239
Yuki Kimoto, C<< <kimoto.yuki at gmail.com> >>
1240

            
1241
Github L<http://github.com/yuki-kimoto>
1242

            
version 0.0901
yuki-kimoto authored on 2009-12-17
1243
I develope this module L<http://github.com/yuki-kimoto/DBIx-Custom>
1244

            
packaging one directory
yuki-kimoto authored on 2009-11-16
1245
=head1 COPYRIGHT & LICENSE
1246

            
1247
Copyright 2009 Yuki Kimoto, all rights reserved.
1248

            
1249
This program is free software; you can redistribute it and/or modify it
1250
under the same terms as Perl itself.
1251

            
1252
=cut