missed a couple things
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
1 package DBIx::Class::Storage::DBI;
2
3 use base 'DBIx::Class::Storage';
4
5 use strict;
6 use warnings;
7 use DBI;
8 use SQL::Abstract::Limit;
9 use DBIx::Class::Storage::DBI::Cursor;
10 use IO::File;
11 use Carp::Clan qw/DBIx::Class/;
12
13 BEGIN {
14
15 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
16
17 use base qw/SQL::Abstract::Limit/;
18
19 sub select {
20   my ($self, $table, $fields, $where, $order, @rest) = @_;
21   @rest = (-1) unless defined $rest[0];
22   local $self->{having_bind} = [];
23   my ($sql, @ret) = $self->SUPER::select(
24     $table, $self->_recurse_fields($fields), $where, $order, @rest
25   );
26   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
27 }
28
29 sub _emulate_limit {
30   my $self = shift;
31   if ($_[3] == -1) {
32     return $_[1].$self->_order_by($_[2]);
33   } else {
34     return $self->SUPER::_emulate_limit(@_);
35   }
36 }
37
38 sub _recurse_fields {
39   my ($self, $fields) = @_;
40   my $ref = ref $fields;
41   return $self->_quote($fields) unless $ref;
42   return $$fields if $ref eq 'SCALAR';
43
44   if ($ref eq 'ARRAY') {
45     return join(', ', map { $self->_recurse_fields($_) } @$fields);
46   } elsif ($ref eq 'HASH') {
47     foreach my $func (keys %$fields) {
48       return $self->_sqlcase($func)
49         .'( '.$self->_recurse_fields($fields->{$func}).' )';
50     }
51   }
52 }
53
54 sub _order_by {
55   my $self = shift;
56   my $ret = '';
57   my @extra;
58   if (ref $_[0] eq 'HASH') {
59     if (defined $_[0]->{group_by}) {
60       $ret = $self->_sqlcase(' group by ')
61                .$self->_recurse_fields($_[0]->{group_by});
62     }
63     if (defined $_[0]->{having}) {
64       my $frag;
65       ($frag, @extra) = $self->_recurse_where($_[0]->{having});
66       push(@{$self->{having_bind}}, @extra);
67       $ret .= $self->_sqlcase(' having ').$frag;
68     }
69     if (defined $_[0]->{order_by}) {
70       $ret .= $self->SUPER::_order_by($_[0]->{order_by});
71     }
72   } elsif(ref $_[0] eq 'SCALAR') {
73     $ret = $self->_sqlcase(' order by ').${ $_[0] };
74   } else {
75     $ret = $self->SUPER::_order_by(@_);
76   }
77   return $ret;
78 }
79
80 sub _order_directions {
81   my ($self, $order) = @_;
82   $order = $order->{order_by} if ref $order eq 'HASH';
83   return $self->SUPER::_order_directions($order);
84 }
85
86 sub _table {
87   my ($self, $from) = @_;
88   if (ref $from eq 'ARRAY') {
89     return $self->_recurse_from(@$from);
90   } elsif (ref $from eq 'HASH') {
91     return $self->_make_as($from);
92   } else {
93     return $from;
94   }
95 }
96
97 sub _recurse_from {
98   my ($self, $from, @join) = @_;
99   my @sqlf;
100   push(@sqlf, $self->_make_as($from));
101   foreach my $j (@join) {
102     my ($to, $on) = @$j;
103
104     # check whether a join type exists
105     my $join_clause = '';
106     if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
107       $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
108     } else {
109       $join_clause = ' JOIN ';
110     }
111     push(@sqlf, $join_clause);
112
113     if (ref $to eq 'ARRAY') {
114       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
115     } else {
116       push(@sqlf, $self->_make_as($to));
117     }
118     push(@sqlf, ' ON ', $self->_join_condition($on));
119   }
120   return join('', @sqlf);
121 }
122
123 sub _make_as {
124   my ($self, $from) = @_;
125   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
126                      reverse each %{$self->_skip_options($from)});
127 }
128
129 sub _skip_options {
130   my ($self, $hash) = @_;
131   my $clean_hash = {};
132   $clean_hash->{$_} = $hash->{$_}
133     for grep {!/^-/} keys %$hash;
134   return $clean_hash;
135 }
136
137 sub _join_condition {
138   my ($self, $cond) = @_;
139   if (ref $cond eq 'HASH') {
140     my %j;
141     for (keys %$cond) {
142       my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
143     };
144     return $self->_recurse_where(\%j);
145   } elsif (ref $cond eq 'ARRAY') {
146     return join(' OR ', map { $self->_join_condition($_) } @$cond);
147   } else {
148     die "Can't handle this yet!";
149   }
150 }
151
152 sub _quote {
153   my ($self, $label) = @_;
154   return '' unless defined $label;
155   return "*" if $label eq '*';
156   return $label unless $self->{quote_char};
157   if(ref $self->{quote_char} eq "ARRAY"){
158     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
159       if !defined $self->{name_sep};
160     my $sep = $self->{name_sep};
161     return join($self->{name_sep},
162         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
163        split(/\Q$sep\E/,$label));
164   }
165   return $self->SUPER::_quote($label);
166 }
167
168 sub _RowNum {
169    my $self = shift;
170    my $c;
171    $_[0] =~ s/SELECT (.*?) FROM/
172      'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
173    $self->SUPER::_RowNum(@_);
174 }
175
176 # Accessor for setting limit dialect. This is useful
177 # for JDBC-bridge among others where the remote SQL-dialect cannot
178 # be determined by the name of the driver alone.
179 #
180 sub limit_dialect {
181     my $self = shift;
182     $self->{limit_dialect} = shift if @_;
183     return $self->{limit_dialect};
184 }
185
186 sub quote_char {
187     my $self = shift;
188     $self->{quote_char} = shift if @_;
189     return $self->{quote_char};
190 }
191
192 sub name_sep {
193     my $self = shift;
194     $self->{name_sep} = shift if @_;
195     return $self->{name_sep};
196 }
197
198
199
200
201 package DBIx::Class::Storage::DBI::DebugCallback;
202
203 sub print {
204   my ($self, $string) = @_;
205   $string =~ m/^(\w+)/;
206   ${$self}->($1, $string);
207 }
208
209 } # End of BEGIN block
210
211 use base qw/DBIx::Class/;
212
213 __PACKAGE__->load_components(qw/AccessorGroup/);
214
215 __PACKAGE__->mk_group_accessors('simple' =>
216   qw/connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
217      cursor on_connect_do transaction_depth/);
218
219 sub new {
220   my $new = bless({}, ref $_[0] || $_[0]);
221   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
222   $new->transaction_depth(0);
223   if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
224      ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
225     $new->debugfh(IO::File->new($1, 'w'))
226       or $new->throw_exception("Cannot open trace file $1");
227   } else {
228     $new->debugfh(IO::File->new('>&STDERR'));
229   }
230   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
231   return $new;
232 }
233
234 sub throw_exception {
235   my ($self, $msg) = @_;
236   croak($msg);
237 }
238
239 =head1 NAME 
240
241 DBIx::Class::Storage::DBI - DBI storage handler
242
243 =head1 SYNOPSIS
244
245 =head1 DESCRIPTION
246
247 This class represents the connection to the database
248
249 =head1 METHODS
250
251 =cut
252
253 =head2 on_connect_do
254
255 Executes the sql statements given as a listref on every db connect.
256
257 =head2 debug
258
259 Causes SQL trace information to be emitted on C<debugfh> filehandle
260 (or C<STDERR> if C<debugfh> has not specifically been set).
261
262 =head2 debugfh
263
264 Sets or retrieves the filehandle used for trace/debug output.  This
265 should be an IO::Handle compatible object (only the C<print> method is
266 used).  Initially set to be STDERR - although see information on the
267 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
268
269 =head2 debugcb
270
271 Sets a callback to be executed each time a statement is run; takes a sub
272 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
273 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
274 be printed.
275
276 =cut
277
278 sub debugcb {
279   my ($self, $cb) = @_;
280   my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
281   $self->debugfh($cb_obj);
282 }
283
284 sub disconnect {
285   my ($self) = @_;
286
287   if( $self->connected ) {
288     $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
289     $self->_dbh->disconnect;
290     $self->_dbh(undef);
291   }
292 }
293
294 sub connected {
295   my ($self) = @_;
296
297   if(my $dbh = $self->_dbh) {
298       if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
299           $self->_sql_maker(undef);
300           return $self->_dbh(undef);
301       }
302       elsif($self->_conn_pid != $$) {
303           $self->_dbh->{InactiveDestroy} = 1;
304           $self->_sql_maker(undef);
305           return $self->_dbh(undef)
306       }
307       return ($dbh->FETCH('Active') && $dbh->ping);
308   }
309
310   return 0;
311 }
312
313 sub ensure_connected {
314   my ($self) = @_;
315
316   unless ($self->connected) {
317     $self->_populate_dbh;
318   }
319 }
320
321 sub dbh {
322   my ($self) = @_;
323
324   $self->ensure_connected;
325   return $self->_dbh;
326 }
327
328 sub sql_maker {
329   my ($self) = @_;
330   unless ($self->_sql_maker) {
331     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
332   }
333   return $self->_sql_maker;
334 }
335
336 sub _populate_dbh {
337   my ($self) = @_;
338   my @info = @{$self->connect_info || []};
339   $self->_dbh($self->_connect(@info));
340   my $driver = $self->_dbh->{Driver}->{Name};
341   eval "require DBIx::Class::Storage::DBI::${driver}";
342   unless ($@) {
343     bless $self, "DBIx::Class::Storage::DBI::${driver}";
344   }
345   # if on-connect sql statements are given execute them
346   foreach my $sql_statement (@{$self->on_connect_do || []}) {
347     $self->_dbh->do($sql_statement);
348   }
349
350   $self->_conn_pid($$);
351   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
352 }
353
354 sub _connect {
355   my ($self, @info) = @_;
356
357   $self->throw_exception("You failed to provide any connection info")
358       if !@info;
359
360   my ($old_connect_via, $dbh);
361
362   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
363       $old_connect_via = $DBI::connect_via;
364       $DBI::connect_via = 'connect';
365   }
366
367   if(ref $info[0] eq 'CODE') {
368       $dbh = &{$info[0]};
369   }
370   else {
371       $dbh = DBI->connect(@info);
372   }
373
374   $DBI::connect_via = $old_connect_via if $old_connect_via;
375
376   $self->throw_exception("DBI Connection failed: $DBI::errstr")
377       unless $dbh;
378
379   $dbh;
380 }
381
382 =head2 txn_begin
383
384 Calls begin_work on the current dbh.
385
386 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
387 an entire code block to be executed transactionally.
388
389 =cut
390
391 sub txn_begin {
392   my $self = shift;
393   $self->dbh->begin_work
394     if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
395 }
396
397 =head2 txn_commit
398
399 Issues a commit against the current dbh.
400
401 =cut
402
403 sub txn_commit {
404   my $self = shift;
405   if ($self->{transaction_depth} == 0) {
406     $self->dbh->commit unless $self->dbh->{AutoCommit};
407   }
408   else {
409     $self->dbh->commit if --$self->{transaction_depth} == 0;    
410   }
411 }
412
413 =head2 txn_rollback
414
415 Issues a rollback against the current dbh. A nested rollback will
416 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
417 which allows the rollback to propagate to the outermost transaction.
418
419 =cut
420
421 sub txn_rollback {
422   my $self = shift;
423
424   eval {
425     if ($self->{transaction_depth} == 0) {
426       $self->dbh->rollback unless $self->dbh->{AutoCommit};
427     }
428     else {
429       --$self->{transaction_depth} == 0 ?
430         $self->dbh->rollback :
431         die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
432     }
433   };
434
435   if ($@) {
436     my $error = $@;
437     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
438     $error =~ /$exception_class/ and $self->throw_exception($error);
439     $self->{transaction_depth} = 0;          # ensure that a failed rollback
440     $self->throw_exception($error);          # resets the transaction depth
441   }
442 }
443
444 sub _execute {
445   my ($self, $op, $extra_bind, $ident, @args) = @_;
446   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
447   unshift(@bind, @$extra_bind) if $extra_bind;
448   if ($self->debug) {
449       my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
450       $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
451   }
452   my $sth = $self->sth($sql,$op);
453   $self->throw_exception("no sth generated via sql: $sql") unless $sth;
454   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
455   my $rv;
456   if ($sth) {  
457     $rv = $sth->execute(@bind)
458       or $self->throw_exception("Error executing '$sql': " . $sth->errstr);
459   } else { 
460     $self->throw_exception("'$sql' did not generate a statement.");
461   }
462   return (wantarray ? ($rv, $sth, @bind) : $rv);
463 }
464
465 sub insert {
466   my ($self, $ident, $to_insert) = @_;
467   $self->throw_exception(
468     "Couldn't insert ".join(', ',
469       map "$_ => $to_insert->{$_}", keys %$to_insert
470     )." into ${ident}"
471   ) unless ($self->_execute('insert' => [], $ident, $to_insert));
472   return $to_insert;
473 }
474
475 sub update {
476   return shift->_execute('update' => [], @_);
477 }
478
479 sub delete {
480   return shift->_execute('delete' => [], @_);
481 }
482
483 sub _select {
484   my ($self, $ident, $select, $condition, $attrs) = @_;
485   my $order = $attrs->{order_by};
486   if (ref $condition eq 'SCALAR') {
487     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
488   }
489   if (exists $attrs->{group_by} || $attrs->{having}) {
490     $order = {
491       group_by => $attrs->{group_by},
492       having => $attrs->{having},
493       ($order ? (order_by => $order) : ())
494     };
495   }
496   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
497   if ($attrs->{software_limit} ||
498       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
499         $attrs->{software_limit} = 1;
500   } else {
501     push @args, $attrs->{rows}, $attrs->{offset};
502   }
503   return $self->_execute(@args);
504 }
505
506 sub select {
507   my $self = shift;
508   my ($ident, $select, $condition, $attrs) = @_;
509   return $self->cursor->new($self, \@_, $attrs);
510 }
511
512 # Need to call finish() to work round broken DBDs
513
514 sub select_single {
515   my $self = shift;
516   my ($rv, $sth, @bind) = $self->_select(@_);
517   my @row = $sth->fetchrow_array;
518   $sth->finish();
519   return @row;
520 }
521
522 sub sth {
523   my ($self, $sql) = @_;
524   # 3 is the if_active parameter which avoids active sth re-use
525   return $self->dbh->prepare_cached($sql, {}, 3);
526 }
527
528 =head2 columns_info_for
529
530 Returns database type info for a given table columns.
531
532 =cut
533
534 sub columns_info_for {
535   my ($self, $table) = @_;
536
537   if ($self->dbh->can('column_info')) {
538     my %result;
539     my $old_raise_err = $self->dbh->{RaiseError};
540     my $old_print_err = $self->dbh->{PrintError};
541     $self->dbh->{RaiseError} = 1;
542     $self->dbh->{PrintError} = 0;
543     eval {
544       my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
545       $sth->execute();
546       while ( my $info = $sth->fetchrow_hashref() ){
547         my %column_info;
548         $column_info{data_type}   = $info->{TYPE_NAME};
549         $column_info{size}      = $info->{COLUMN_SIZE};
550         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
551         $column_info{default_value} = $info->{COLUMN_DEF};
552
553         $result{$info->{COLUMN_NAME}} = \%column_info;
554       }
555     };
556     $self->dbh->{RaiseError} = $old_raise_err;
557     $self->dbh->{PrintError} = $old_print_err;
558     return \%result if !$@;
559   }
560
561   my %result;
562   my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
563   $sth->execute;
564   my @columns = @{$sth->{NAME_lc}};
565   for my $i ( 0 .. $#columns ){
566     my %column_info;
567     my $type_num = $sth->{TYPE}->[$i];
568     my $type_name;
569     if(defined $type_num && $self->dbh->can('type_info')) {
570       my $type_info = $self->dbh->type_info($type_num);
571       $type_name = $type_info->{TYPE_NAME} if $type_info;
572     }
573     $column_info{data_type} = $type_name ? $type_name : $type_num;
574     $column_info{size} = $sth->{PRECISION}->[$i];
575     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
576
577     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
578       $column_info{data_type} = $1;
579       $column_info{size}    = $2;
580     }
581
582     $result{$columns[$i]} = \%column_info;
583   }
584
585   return \%result;
586 }
587
588 sub last_insert_id {
589   my ($self, $row) = @_;
590     
591   return $self->dbh->func('last_insert_rowid');
592
593 }
594
595 sub sqlt_type { shift->dbh->{Driver}->{Name} }
596
597 sub deployment_statements {
598   my ($self, $schema, $type, $sqltargs) = @_;
599   $type ||= $self->sqlt_type;
600   eval "use SQL::Translator";
601   $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
602   eval "use SQL::Translator::Parser::DBIx::Class;";
603   $self->throw_exception($@) if $@; 
604   eval "use SQL::Translator::Producer::${type};";
605   $self->throw_exception($@) if $@;
606   my $tr = SQL::Translator->new(%$sqltargs);
607   SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
608   return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
609 }
610
611 sub deploy {
612   my ($self, $schema, $type, $sqltargs) = @_;
613   my @statements = $self->deployment_statements($schema, $type, $sqltargs);
614   foreach(split(";\n", @statements)) {
615     $self->debugfh->print("$_\n") if $self->debug;
616     $self->dbh->do($_) or warn "SQL was:\n $_";
617   } 
618 }
619
620 sub DESTROY { shift->disconnect }
621
622 1;
623
624 =head1 ENVIRONMENT VARIABLES
625
626 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
627
628 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
629 is produced (as when the L<debug> method is set).
630
631 If the value is of the form C<1=/path/name> then the trace output is
632 written to the file C</path/name>.
633
634 =head1 AUTHORS
635
636 Matt S. Trout <mst@shadowcatsystems.co.uk>
637
638 Andy Grundman <andy@hybridized.org>
639
640 =head1 LICENSE
641
642 You may distribute this code under the same terms as Perl itself.
643
644 =cut
645