Merge 'trunk' into 'DBIx-Class-current'
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
1 package DBIx::Class::Storage::DBI;
2 # -*- mode: cperl; cperl-indent-level: 2 -*-
3
4 use base 'DBIx::Class::Storage';
5
6 use strict;    
7 use warnings;
8 use DBI;
9 use SQL::Abstract::Limit;
10 use DBIx::Class::Storage::DBI::Cursor;
11 use DBIx::Class::Storage::Statistics;
12 use IO::File;
13 use Scalar::Util 'blessed';
14
15 __PACKAGE__->mk_group_accessors(
16   'simple' =>
17     qw/_connect_info _dbh _sql_maker _sql_maker_opts _conn_pid _conn_tid
18        disable_sth_caching cursor on_connect_do transaction_depth/
19 );
20
21 BEGIN {
22
23 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
24
25 use base qw/SQL::Abstract::Limit/;
26
27 # This prevents the caching of $dbh in S::A::L, I believe
28 sub new {
29   my $self = shift->SUPER::new(@_);
30
31   # If limit_dialect is a ref (like a $dbh), go ahead and replace
32   #   it with what it resolves to:
33   $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
34     if ref $self->{limit_dialect};
35
36   $self;
37 }
38
39 sub _RowNumberOver {
40   my ($self, $sql, $order, $rows, $offset ) = @_;
41
42   $offset += 1;
43   my $last = $rows + $offset;
44   my ( $order_by ) = $self->_order_by( $order );
45
46   $sql = <<"";
47 SELECT * FROM
48 (
49    SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
50       $sql
51       $order_by
52    ) Q1
53 ) Q2
54 WHERE ROW_NUM BETWEEN $offset AND $last
55
56   return $sql;
57 }
58
59
60 # While we're at it, this should make LIMIT queries more efficient,
61 #  without digging into things too deeply
62 use Scalar::Util 'blessed';
63 sub _find_syntax {
64   my ($self, $syntax) = @_;
65   my $dbhname = blessed($syntax) ?  $syntax->{Driver}{Name} : $syntax;
66   if(ref($self) && $dbhname && $dbhname eq 'DB2') {
67     return 'RowNumberOver';
68   }
69
70   $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
71 }
72
73 sub select {
74   my ($self, $table, $fields, $where, $order, @rest) = @_;
75   $table = $self->_quote($table) unless ref($table);
76   local $self->{rownum_hack_count} = 1
77     if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
78   @rest = (-1) unless defined $rest[0];
79   die "LIMIT 0 Does Not Compute" if $rest[0] == 0;
80     # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
81   local $self->{having_bind} = [];
82   my ($sql, @ret) = $self->SUPER::select(
83     $table, $self->_recurse_fields($fields), $where, $order, @rest
84   );
85   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
86 }
87
88 sub insert {
89   my $self = shift;
90   my $table = shift;
91   $table = $self->_quote($table) unless ref($table);
92   $self->SUPER::insert($table, @_);
93 }
94
95 sub update {
96   my $self = shift;
97   my $table = shift;
98   $table = $self->_quote($table) unless ref($table);
99   $self->SUPER::update($table, @_);
100 }
101
102 sub delete {
103   my $self = shift;
104   my $table = shift;
105   $table = $self->_quote($table) unless ref($table);
106   $self->SUPER::delete($table, @_);
107 }
108
109 sub _emulate_limit {
110   my $self = shift;
111   if ($_[3] == -1) {
112     return $_[1].$self->_order_by($_[2]);
113   } else {
114     return $self->SUPER::_emulate_limit(@_);
115   }
116 }
117
118 sub _recurse_fields {
119   my ($self, $fields) = @_;
120   my $ref = ref $fields;
121   return $self->_quote($fields) unless $ref;
122   return $$fields if $ref eq 'SCALAR';
123
124   if ($ref eq 'ARRAY') {
125     return join(', ', map {
126       $self->_recurse_fields($_)
127       .(exists $self->{rownum_hack_count}
128          ? ' AS col'.$self->{rownum_hack_count}++
129          : '')
130      } @$fields);
131   } elsif ($ref eq 'HASH') {
132     foreach my $func (keys %$fields) {
133       return $self->_sqlcase($func)
134         .'( '.$self->_recurse_fields($fields->{$func}).' )';
135     }
136   }
137 }
138
139 sub _order_by {
140   my $self = shift;
141   my $ret = '';
142   my @extra;
143   if (ref $_[0] eq 'HASH') {
144     if (defined $_[0]->{group_by}) {
145       $ret = $self->_sqlcase(' group by ')
146                .$self->_recurse_fields($_[0]->{group_by});
147     }
148     if (defined $_[0]->{having}) {
149       my $frag;
150       ($frag, @extra) = $self->_recurse_where($_[0]->{having});
151       push(@{$self->{having_bind}}, @extra);
152       $ret .= $self->_sqlcase(' having ').$frag;
153     }
154     if (defined $_[0]->{order_by}) {
155       $ret .= $self->_order_by($_[0]->{order_by});
156     }
157   } elsif (ref $_[0] eq 'SCALAR') {
158     $ret = $self->_sqlcase(' order by ').${ $_[0] };
159   } elsif (ref $_[0] eq 'ARRAY' && @{$_[0]}) {
160     my @order = @{+shift};
161     $ret = $self->_sqlcase(' order by ')
162           .join(', ', map {
163                         my $r = $self->_order_by($_, @_);
164                         $r =~ s/^ ?ORDER BY //i;
165                         $r;
166                       } @order);
167   } else {
168     $ret = $self->SUPER::_order_by(@_);
169   }
170   return $ret;
171 }
172
173 sub _order_directions {
174   my ($self, $order) = @_;
175   $order = $order->{order_by} if ref $order eq 'HASH';
176   return $self->SUPER::_order_directions($order);
177 }
178
179 sub _table {
180   my ($self, $from) = @_;
181   if (ref $from eq 'ARRAY') {
182     return $self->_recurse_from(@$from);
183   } elsif (ref $from eq 'HASH') {
184     return $self->_make_as($from);
185   } else {
186     return $from; # would love to quote here but _table ends up getting called
187                   # twice during an ->select without a limit clause due to
188                   # the way S::A::Limit->select works. should maybe consider
189                   # bypassing this and doing S::A::select($self, ...) in
190                   # our select method above. meantime, quoting shims have
191                   # been added to select/insert/update/delete here
192   }
193 }
194
195 sub _recurse_from {
196   my ($self, $from, @join) = @_;
197   my @sqlf;
198   push(@sqlf, $self->_make_as($from));
199   foreach my $j (@join) {
200     my ($to, $on) = @$j;
201
202     # check whether a join type exists
203     my $join_clause = '';
204     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
205     if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
206       $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
207     } else {
208       $join_clause = ' JOIN ';
209     }
210     push(@sqlf, $join_clause);
211
212     if (ref $to eq 'ARRAY') {
213       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
214     } else {
215       push(@sqlf, $self->_make_as($to));
216     }
217     push(@sqlf, ' ON ', $self->_join_condition($on));
218   }
219   return join('', @sqlf);
220 }
221
222 sub _make_as {
223   my ($self, $from) = @_;
224   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
225                      reverse each %{$self->_skip_options($from)});
226 }
227
228 sub _skip_options {
229   my ($self, $hash) = @_;
230   my $clean_hash = {};
231   $clean_hash->{$_} = $hash->{$_}
232     for grep {!/^-/} keys %$hash;
233   return $clean_hash;
234 }
235
236 sub _join_condition {
237   my ($self, $cond) = @_;
238   if (ref $cond eq 'HASH') {
239     my %j;
240     for (keys %$cond) {
241       my $v = $cond->{$_};
242       if (ref $v) {
243         # XXX no throw_exception() in this package and croak() fails with strange results
244         Carp::croak(ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
245             if ref($v) ne 'SCALAR';
246         $j{$_} = $v;
247       }
248       else {
249         my $x = '= '.$self->_quote($v); $j{$_} = \$x;
250       }
251     };
252     return scalar($self->_recurse_where(\%j));
253   } elsif (ref $cond eq 'ARRAY') {
254     return join(' OR ', map { $self->_join_condition($_) } @$cond);
255   } else {
256     die "Can't handle this yet!";
257   }
258 }
259
260 sub _quote {
261   my ($self, $label) = @_;
262   return '' unless defined $label;
263   return "*" if $label eq '*';
264   return $label unless $self->{quote_char};
265   if(ref $self->{quote_char} eq "ARRAY"){
266     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
267       if !defined $self->{name_sep};
268     my $sep = $self->{name_sep};
269     return join($self->{name_sep},
270         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
271        split(/\Q$sep\E/,$label));
272   }
273   return $self->SUPER::_quote($label);
274 }
275
276 sub limit_dialect {
277     my $self = shift;
278     $self->{limit_dialect} = shift if @_;
279     return $self->{limit_dialect};
280 }
281
282 sub quote_char {
283     my $self = shift;
284     $self->{quote_char} = shift if @_;
285     return $self->{quote_char};
286 }
287
288 sub name_sep {
289     my $self = shift;
290     $self->{name_sep} = shift if @_;
291     return $self->{name_sep};
292 }
293
294 } # End of BEGIN block
295
296 =head1 NAME
297
298 DBIx::Class::Storage::DBI - DBI storage handler
299
300 =head1 SYNOPSIS
301
302 =head1 DESCRIPTION
303
304 This class represents the connection to an RDBMS via L<DBI>.  See
305 L<DBIx::Class::Storage> for general information.  This pod only
306 documents DBI-specific methods and behaviors.
307
308 =head1 METHODS
309
310 =cut
311
312 sub new {
313   my $new = shift->next::method(@_);
314
315   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
316   $new->transaction_depth(0);
317   $new->_sql_maker_opts({});
318   $new->{_in_dbh_do} = 0;
319   $new->{_dbh_gen} = 0;
320
321   $new;
322 }
323
324 =head2 connect_info
325
326 The arguments of C<connect_info> are always a single array reference.
327
328 This is normally accessed via L<DBIx::Class::Schema/connection>, which
329 encapsulates its argument list in an arrayref before calling
330 C<connect_info> here.
331
332 The arrayref can either contain the same set of arguments one would
333 normally pass to L<DBI/connect>, or a lone code reference which returns
334 a connected database handle.
335
336 In either case, if the final argument in your connect_info happens
337 to be a hashref, C<connect_info> will look there for several
338 connection-specific options:
339
340 =over 4
341
342 =item on_connect_do
343
344 This can be set to an arrayref of literal sql statements, which will
345 be executed immediately after making the connection to the database
346 every time we [re-]connect.
347
348 =item disable_sth_caching
349
350 If set to a true value, this option will disable the caching of
351 statement handles via L<DBI/prepare_cached>.
352
353 =item limit_dialect 
354
355 Sets the limit dialect. This is useful for JDBC-bridge among others
356 where the remote SQL-dialect cannot be determined by the name of the
357 driver alone.
358
359 =item quote_char
360
361 Specifies what characters to use to quote table and column names. If 
362 you use this you will want to specify L<name_sep> as well.
363
364 quote_char expects either a single character, in which case is it is placed
365 on either side of the table/column, or an arrayref of length 2 in which case the
366 table/column name is placed between the elements.
367
368 For example under MySQL you'd use C<quote_char =E<gt> '`'>, and user SQL Server you'd 
369 use C<quote_char =E<gt> [qw/[ ]/]>.
370
371 =item name_sep
372
373 This only needs to be used in conjunction with L<quote_char>, and is used to 
374 specify the charecter that seperates elements (schemas, tables, columns) from 
375 each other. In most cases this is simply a C<.>.
376
377 =back
378
379 These options can be mixed in with your other L<DBI> connection attributes,
380 or placed in a seperate hashref after all other normal L<DBI> connection
381 arguments.
382
383 Every time C<connect_info> is invoked, any previous settings for
384 these options will be cleared before setting the new ones, regardless of
385 whether any options are specified in the new C<connect_info>.
386
387 Important note:  DBIC expects the returned database handle provided by 
388 a subref argument to have RaiseError set on it.  If it doesn't, things
389 might not work very well, YMMV.  If you don't use a subref, DBIC will
390 force this setting for you anyways.  Setting HandleError to anything
391 other than simple exception object wrapper might cause problems too.
392
393 Examples:
394
395   # Simple SQLite connection
396   ->connect_info([ 'dbi:SQLite:./foo.db' ]);
397
398   # Connect via subref
399   ->connect_info([ sub { DBI->connect(...) } ]);
400
401   # A bit more complicated
402   ->connect_info(
403     [
404       'dbi:Pg:dbname=foo',
405       'postgres',
406       'my_pg_password',
407       { AutoCommit => 0 },
408       { quote_char => q{"}, name_sep => q{.} },
409     ]
410   );
411
412   # Equivalent to the previous example
413   ->connect_info(
414     [
415       'dbi:Pg:dbname=foo',
416       'postgres',
417       'my_pg_password',
418       { AutoCommit => 0, quote_char => q{"}, name_sep => q{.} },
419     ]
420   );
421
422   # Subref + DBIC-specific connection options
423   ->connect_info(
424     [
425       sub { DBI->connect(...) },
426       {
427           quote_char => q{`},
428           name_sep => q{@},
429           on_connect_do => ['SET search_path TO myschema,otherschema,public'],
430           disable_sth_caching => 1,
431       },
432     ]
433   );
434
435 =cut
436
437 sub connect_info {
438   my ($self, $info_arg) = @_;
439
440   return $self->_connect_info if !$info_arg;
441
442   # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
443   #  the new set of options
444   $self->_sql_maker(undef);
445   $self->_sql_maker_opts({});
446
447   my $info = [ @$info_arg ]; # copy because we can alter it
448   my $last_info = $info->[-1];
449   if(ref $last_info eq 'HASH') {
450     for my $storage_opt (qw/on_connect_do disable_sth_caching/) {
451       if(my $value = delete $last_info->{$storage_opt}) {
452         $self->$storage_opt($value);
453       }
454     }
455     for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
456       if(my $opt_val = delete $last_info->{$sql_maker_opt}) {
457         $self->_sql_maker_opts->{$sql_maker_opt} = $opt_val;
458       }
459     }
460
461     # Get rid of any trailing empty hashref
462     pop(@$info) if !keys %$last_info;
463   }
464
465   $self->_connect_info($info);
466 }
467
468 =head2 on_connect_do
469
470 This method is deprecated in favor of setting via L</connect_info>.
471
472 =head2 dbh_do
473
474 Arguments: $subref, @extra_coderef_args?
475
476 Execute the given subref using the new exception-based connection management.
477
478 The first two arguments will be the storage object that C<dbh_do> was called
479 on and a database handle to use.  Any additional arguments will be passed
480 verbatim to the called subref as arguments 2 and onwards.
481
482 Using this (instead of $self->_dbh or $self->dbh) ensures correct
483 exception handling and reconnection (or failover in future subclasses).
484
485 Your subref should have no side-effects outside of the database, as
486 there is the potential for your subref to be partially double-executed
487 if the database connection was stale/dysfunctional.
488
489 Example:
490
491   my @stuff = $schema->storage->dbh_do(
492     sub {
493       my ($storage, $dbh, @cols) = @_;
494       my $cols = join(q{, }, @cols);
495       $dbh->selectrow_array("SELECT $cols FROM foo");
496     },
497     @column_list
498   );
499
500 =cut
501
502 sub dbh_do {
503   my $self = shift;
504   my $coderef = shift;
505
506   ref $coderef eq 'CODE' or $self->throw_exception
507     ('$coderef must be a CODE reference');
508
509   return $coderef->($self, $self->_dbh, @_) if $self->{_in_dbh_do};
510   local $self->{_in_dbh_do} = 1;
511
512   my @result;
513   my $want_array = wantarray;
514
515   eval {
516     $self->_verify_pid if $self->_dbh;
517     $self->_populate_dbh if !$self->_dbh;
518     if($want_array) {
519         @result = $coderef->($self, $self->_dbh, @_);
520     }
521     elsif(defined $want_array) {
522         $result[0] = $coderef->($self, $self->_dbh, @_);
523     }
524     else {
525         $coderef->($self, $self->_dbh, @_);
526     }
527   };
528
529   my $exception = $@;
530   if(!$exception) { return $want_array ? @result : $result[0] }
531
532   $self->throw_exception($exception) if $self->connected;
533
534   # We were not connected - reconnect and retry, but let any
535   #  exception fall right through this time
536   $self->_populate_dbh;
537   $coderef->($self, $self->_dbh, @_);
538 }
539
540 # This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do.
541 # It also informs dbh_do to bypass itself while under the direction of txn_do,
542 #  via $self->{_in_dbh_do} (this saves some redundant eval and errorcheck, etc)
543 sub txn_do {
544   my $self = shift;
545   my $coderef = shift;
546
547   ref $coderef eq 'CODE' or $self->throw_exception
548     ('$coderef must be a CODE reference');
549
550   local $self->{_in_dbh_do} = 1;
551
552   my @result;
553   my $want_array = wantarray;
554
555   my $tried = 0;
556   while(1) {
557     eval {
558       $self->_verify_pid if $self->_dbh;
559       $self->_populate_dbh if !$self->_dbh;
560
561       $self->txn_begin;
562       if($want_array) {
563           @result = $coderef->(@_);
564       }
565       elsif(defined $want_array) {
566           $result[0] = $coderef->(@_);
567       }
568       else {
569           $coderef->(@_);
570       }
571       $self->txn_commit;
572     };
573
574     my $exception = $@;
575     if(!$exception) { return $want_array ? @result : $result[0] }
576
577     if($tried++ > 0 || $self->connected) {
578       eval { $self->txn_rollback };
579       my $rollback_exception = $@;
580       if($rollback_exception) {
581         my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
582         $self->throw_exception($exception)  # propagate nested rollback
583           if $rollback_exception =~ /$exception_class/;
584
585         $self->throw_exception(
586           "Transaction aborted: ${exception}. "
587           . "Rollback failed: ${rollback_exception}"
588         );
589       }
590       $self->throw_exception($exception)
591     }
592
593     # We were not connected, and was first try - reconnect and retry
594     # via the while loop
595     $self->_populate_dbh;
596   }
597 }
598
599 =head2 disconnect
600
601 Our C<disconnect> method also performs a rollback first if the
602 database is not in C<AutoCommit> mode.
603
604 =cut
605
606 sub disconnect {
607   my ($self) = @_;
608
609   if( $self->connected ) {
610     $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
611     $self->_dbh->disconnect;
612     $self->_dbh(undef);
613     $self->{_dbh_gen}++;
614   }
615 }
616
617 sub connected {
618   my ($self) = @_;
619
620   if(my $dbh = $self->_dbh) {
621       if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
622           $self->_dbh(undef);
623           $self->{_dbh_gen}++;
624           return;
625       }
626       else {
627           $self->_verify_pid;
628       }
629       return ($dbh->FETCH('Active') && $dbh->ping);
630   }
631
632   return 0;
633 }
634
635 # handle pid changes correctly
636 #  NOTE: assumes $self->_dbh is a valid $dbh
637 sub _verify_pid {
638   my ($self) = @_;
639
640   return if $self->_conn_pid == $$;
641
642   $self->_dbh->{InactiveDestroy} = 1;
643   $self->_dbh(undef);
644   $self->{_dbh_gen}++;
645
646   return;
647 }
648
649 sub ensure_connected {
650   my ($self) = @_;
651
652   unless ($self->connected) {
653     $self->_populate_dbh;
654   }
655 }
656
657 =head2 dbh
658
659 Returns the dbh - a data base handle of class L<DBI>.
660
661 =cut
662
663 sub dbh {
664   my ($self) = @_;
665
666   $self->ensure_connected;
667   return $self->_dbh;
668 }
669
670 sub _sql_maker_args {
671     my ($self) = @_;
672     
673     return ( bindtype=>'columns', limit_dialect => $self->dbh, %{$self->_sql_maker_opts} );
674 }
675
676 sub sql_maker {
677   my ($self) = @_;
678   unless ($self->_sql_maker) {
679     $self->_sql_maker(new DBIC::SQL::Abstract( $self->_sql_maker_args ));
680   }
681   return $self->_sql_maker;
682 }
683
684 sub _populate_dbh {
685   my ($self) = @_;
686   my @info = @{$self->_connect_info || []};
687   $self->_dbh($self->_connect(@info));
688
689   if(ref $self eq 'DBIx::Class::Storage::DBI') {
690     my $driver = $self->_dbh->{Driver}->{Name};
691     if ($self->load_optional_class("DBIx::Class::Storage::DBI::${driver}")) {
692       bless $self, "DBIx::Class::Storage::DBI::${driver}";
693       $self->_rebless() if $self->can('_rebless');
694     }
695   }
696
697   # if on-connect sql statements are given execute them
698   foreach my $sql_statement (@{$self->on_connect_do || []}) {
699     $self->debugobj->query_start($sql_statement) if $self->debug();
700     $self->_dbh->do($sql_statement);
701     $self->debugobj->query_end($sql_statement) if $self->debug();
702   }
703
704   $self->_conn_pid($$);
705   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
706 }
707
708 sub _connect {
709   my ($self, @info) = @_;
710
711   $self->throw_exception("You failed to provide any connection info")
712       if !@info;
713
714   my ($old_connect_via, $dbh);
715
716   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
717       $old_connect_via = $DBI::connect_via;
718       $DBI::connect_via = 'connect';
719   }
720
721   eval {
722     if(ref $info[0] eq 'CODE') {
723        $dbh = &{$info[0]}
724     }
725     else {
726        $dbh = DBI->connect(@info);
727        $dbh->{RaiseError} = 1;
728        $dbh->{PrintError} = 0;
729        $dbh->{PrintWarn} = 0;
730     }
731   };
732
733   $DBI::connect_via = $old_connect_via if $old_connect_via;
734
735   if (!$dbh || $@) {
736     $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
737   }
738
739   $dbh;
740 }
741
742 sub _dbh_txn_begin {
743   my ($self, $dbh) = @_;
744   if ($dbh->{AutoCommit}) {
745     $self->debugobj->txn_begin()
746       if ($self->debug);
747     $dbh->begin_work;
748   }
749 }
750
751 sub txn_begin {
752   my $self = shift;
753   $self->dbh_do($self->can('_dbh_txn_begin'))
754     if $self->{transaction_depth}++ == 0;
755 }
756
757 sub _dbh_txn_commit {
758   my ($self, $dbh) = @_;
759   if ($self->{transaction_depth} == 0) {
760     unless ($dbh->{AutoCommit}) {
761       $self->debugobj->txn_commit()
762         if ($self->debug);
763       $dbh->commit;
764     }
765   }
766   else {
767     if (--$self->{transaction_depth} == 0) {
768       $self->debugobj->txn_commit()
769         if ($self->debug);
770       $dbh->commit;
771     }
772   }
773 }
774
775 sub txn_commit {
776   my $self = shift;
777   $self->dbh_do($self->can('_dbh_txn_commit'));
778 }
779
780 sub _dbh_txn_rollback {
781   my ($self, $dbh) = @_;
782   if ($self->{transaction_depth} == 0) {
783     unless ($dbh->{AutoCommit}) {
784       $self->debugobj->txn_rollback()
785         if ($self->debug);
786       $dbh->rollback;
787     }
788   }
789   else {
790     if (--$self->{transaction_depth} == 0) {
791       $self->debugobj->txn_rollback()
792         if ($self->debug);
793       $dbh->rollback;
794     }
795     else {
796       die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
797     }
798   }
799 }
800
801 sub txn_rollback {
802   my $self = shift;
803
804   eval { $self->dbh_do($self->can('_dbh_txn_rollback')) };
805   if ($@) {
806     my $error = $@;
807     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
808     $error =~ /$exception_class/ and $self->throw_exception($error);
809     $self->{transaction_depth} = 0;          # ensure that a failed rollback
810     $self->throw_exception($error);          # resets the transaction depth
811   }
812 }
813
814 # This used to be the top-half of _execute.  It was split out to make it
815 #  easier to override in NoBindVars without duping the rest.  It takes up
816 #  all of _execute's args, and emits $sql, @bind.
817 sub _prep_for_execute {
818   my ($self, $op, $extra_bind, $ident, @args) = @_;
819
820   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
821   unshift(@bind,
822     map { ref $_ eq 'ARRAY' ? $_ : [ '!!dummy', $_ ] } @$extra_bind)
823       if $extra_bind;
824   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
825
826   return ($sql, @bind);
827 }
828
829 sub _execute {
830   my ($self, $op, $extra_bind, $ident, $bind_attributes, @args) = @_;
831   
832   if( blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
833     $ident = $ident->from();
834   }
835   
836   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
837   unshift(@bind,
838     map { ref $_ eq 'ARRAY' ? $_ : [ '!!dummy', $_ ] } @$extra_bind)
839       if $extra_bind;
840   if ($self->debug) {
841       my @debug_bind =
842         map { defined ($_ && $_->[1]) ? qq{'$_->[1]'} : q{'NULL'} } @bind;
843       $self->debugobj->query_start($sql, @debug_bind);
844   }
845   my $sth = eval { $self->sth($sql,$op) };
846
847   if (!$sth || $@) {
848     $self->throw_exception(
849       'no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql"
850     );
851   }
852
853   my $rv;
854   if ($sth) {
855     my $time = time();
856     $rv = eval {
857       my $placeholder_index = 1; 
858
859       foreach my $bound (@bind) {
860
861         my $attributes = {};
862         my($column_name, @data) = @$bound;
863
864         if( $bind_attributes ) {
865           $attributes = $bind_attributes->{$column_name}
866           if defined $bind_attributes->{$column_name};
867         }
868
869         foreach my $data (@data)
870         {
871           $data = ref $data ? ''.$data : $data; # stringify args
872
873           $sth->bind_param($placeholder_index, $data, $attributes);
874           $placeholder_index++;
875         }
876       }
877       $sth->execute();
878     };
879   
880     if ($@ || !$rv) {
881       $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
882     }
883   } else {
884     $self->throw_exception("'$sql' did not generate a statement.");
885   }
886   if ($self->debug) {
887      my @debug_bind =
888        map { defined ($_ && $_->[1]) ? qq{'$_->[1]'} : q{'NULL'} } @bind; 
889      $self->debugobj->query_end($sql, @debug_bind);
890   }
891   return (wantarray ? ($rv, $sth, @bind) : $rv);
892 }
893
894 sub insert {
895   my ($self, $source, $to_insert) = @_;
896   
897   my $ident = $source->from; 
898   my $bind_attributes = $self->source_bind_attributes($source);
899
900   $self->throw_exception(
901     "Couldn't insert ".join(', ',
902       map "$_ => $to_insert->{$_}", keys %$to_insert
903     )." into ${ident}"
904   ) unless ($self->_execute('insert' => [], $source, $bind_attributes, $to_insert));
905   return $to_insert;
906 }
907
908 ## Still not quite perfect, and EXPERIMENTAL
909 ## Currently it is assumed that all values passed will be "normal", i.e. not 
910 ## scalar refs, or at least, all the same type as the first set, the statement is
911 ## only prepped once.
912 sub insert_bulk {
913   my ($self, $source, $cols, $data) = @_;
914   my %colvalues;
915   my $table = $source->from;
916   @colvalues{@$cols} = (0..$#$cols);
917   my ($sql, @bind) = $self->sql_maker->insert($table, \%colvalues);
918   
919   if ($self->debug) {
920       my @debug_bind = map { defined $_->[1] ? qq{$_->[1]} : q{'NULL'} } @bind;
921       $self->debugobj->query_start($sql, @debug_bind);
922   }
923   my $sth = $self->sth($sql);
924
925 #  @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
926
927   my $rv;
928   
929   ## This must be an arrayref, else nothing works!
930   
931   my $tuple_status = [];
932   
933   ##use Data::Dumper;
934   ##print STDERR Dumper( $data, $sql, [@bind] );
935
936   if ($sth) {
937   
938     my $time = time();
939
940     ## Get the bind_attributes, if any exist
941     my $bind_attributes = $self->source_bind_attributes($source);
942
943     ## Bind the values and execute
944     $rv = eval {
945
946      my $placeholder_index = 1; 
947
948         foreach my $bound (@bind) {
949
950           my $attributes = {};
951           my ($column_name, $data_index) = @$bound;
952
953           if( $bind_attributes ) {
954             $attributes = $bind_attributes->{$column_name}
955             if defined $bind_attributes->{$column_name};
956           }
957
958           my @data = map { $_->[$data_index] } @$data;
959
960           $sth->bind_param_array( $placeholder_index, [@data], $attributes );
961           $placeholder_index++;
962       }
963       $sth->execute_array( {ArrayTupleStatus => $tuple_status} );
964
965     };
966    
967     if ($@ || !defined $rv) {
968       my $errors = '';
969       foreach my $tuple (@$tuple_status) {
970           $errors .= "\n" . $tuple->[1] if(ref $tuple);
971       }
972       $self->throw_exception("Error executing '$sql': ".($@ || $errors));
973     }
974   } else {
975     $self->throw_exception("'$sql' did not generate a statement.");
976   }
977   if ($self->debug) {
978       my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
979       $self->debugobj->query_end($sql, @debug_bind);
980   }
981   return (wantarray ? ($rv, $sth, @bind) : $rv);
982 }
983
984 sub update {
985   my $self = shift @_;
986   my $source = shift @_;
987   my $bind_attributes = $self->source_bind_attributes($source);
988   
989   return $self->_execute('update' => [], $source, $bind_attributes, @_);
990 }
991
992
993 sub delete {
994   my $self = shift @_;
995   my $source = shift @_;
996   
997   my $bind_attrs = {}; ## If ever it's needed...
998   
999   return $self->_execute('delete' => [], $source, $bind_attrs, @_);
1000 }
1001
1002 sub _select {
1003   my ($self, $ident, $select, $condition, $attrs) = @_;
1004   my $order = $attrs->{order_by};
1005   if (ref $condition eq 'SCALAR') {
1006     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
1007   }
1008   if (exists $attrs->{group_by} || $attrs->{having}) {
1009     $order = {
1010       group_by => $attrs->{group_by},
1011       having => $attrs->{having},
1012       ($order ? (order_by => $order) : ())
1013     };
1014   }
1015   my $bind_attrs = {}; ## Future support
1016   my @args = ('select', $attrs->{bind}, $ident, $bind_attrs, $select, $condition, $order);
1017   if ($attrs->{software_limit} ||
1018       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
1019         $attrs->{software_limit} = 1;
1020   } else {
1021     $self->throw_exception("rows attribute must be positive if present")
1022       if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
1023     push @args, $attrs->{rows}, $attrs->{offset};
1024   }
1025   return $self->_execute(@args);
1026 }
1027
1028 sub source_bind_attributes {
1029   my ($self, $source) = @_;
1030   
1031   my $bind_attributes;
1032   foreach my $column ($source->columns) {
1033   
1034     my $data_type = $source->column_info($column)->{data_type} || '';
1035     $bind_attributes->{$column} = $self->bind_attribute_by_data_type($data_type)
1036      if $data_type;
1037   }
1038
1039   return $bind_attributes;
1040 }
1041
1042 =head2 select
1043
1044 =over 4
1045
1046 =item Arguments: $ident, $select, $condition, $attrs
1047
1048 =back
1049
1050 Handle a SQL select statement.
1051
1052 =cut
1053
1054 sub select {
1055   my $self = shift;
1056   my ($ident, $select, $condition, $attrs) = @_;
1057   return $self->cursor->new($self, \@_, $attrs);
1058 }
1059
1060 sub select_single {
1061   my $self = shift;
1062   my ($rv, $sth, @bind) = $self->_select(@_);
1063   my @row = $sth->fetchrow_array;
1064   # Need to call finish() to work round broken DBDs
1065   $sth->finish();
1066   return @row;
1067 }
1068
1069 =head2 sth
1070
1071 =over 4
1072
1073 =item Arguments: $sql
1074
1075 =back
1076
1077 Returns a L<DBI> sth (statement handle) for the supplied SQL.
1078
1079 =cut
1080
1081 sub _dbh_sth {
1082   my ($self, $dbh, $sql) = @_;
1083
1084   # 3 is the if_active parameter which avoids active sth re-use
1085   my $sth = $self->disable_sth_caching
1086     ? $dbh->prepare($sql)
1087     : $dbh->prepare_cached($sql, {}, 3);
1088
1089   $self->throw_exception(
1090     'no sth generated via sql (' . ($@ || $dbh->errstr) . "): $sql"
1091   ) if !$sth;
1092
1093   $sth;
1094 }
1095
1096 sub sth {
1097   my ($self, $sql) = @_;
1098   $self->dbh_do($self->can('_dbh_sth'), $sql);
1099 }
1100
1101 sub _dbh_columns_info_for {
1102   my ($self, $dbh, $table) = @_;
1103
1104   if ($dbh->can('column_info')) {
1105     my %result;
1106     eval {
1107       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
1108       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
1109       $sth->execute();
1110       while ( my $info = $sth->fetchrow_hashref() ){
1111         my %column_info;
1112         $column_info{data_type}   = $info->{TYPE_NAME};
1113         $column_info{size}      = $info->{COLUMN_SIZE};
1114         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
1115         $column_info{default_value} = $info->{COLUMN_DEF};
1116         my $col_name = $info->{COLUMN_NAME};
1117         $col_name =~ s/^\"(.*)\"$/$1/;
1118
1119         $result{$col_name} = \%column_info;
1120       }
1121     };
1122     return \%result if !$@ && scalar keys %result;
1123   }
1124
1125   my %result;
1126   my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0");
1127   $sth->execute;
1128   my @columns = @{$sth->{NAME_lc}};
1129   for my $i ( 0 .. $#columns ){
1130     my %column_info;
1131     my $type_num = $sth->{TYPE}->[$i];
1132     my $type_name;
1133     if(defined $type_num && $dbh->can('type_info')) {
1134       my $type_info = $dbh->type_info($type_num);
1135       $type_name = $type_info->{TYPE_NAME} if $type_info;
1136     }
1137     $column_info{data_type} = $type_name ? $type_name : $type_num;
1138     $column_info{size} = $sth->{PRECISION}->[$i];
1139     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
1140
1141     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
1142       $column_info{data_type} = $1;
1143       $column_info{size}    = $2;
1144     }
1145
1146     $result{$columns[$i]} = \%column_info;
1147   }
1148
1149   return \%result;
1150 }
1151
1152 sub columns_info_for {
1153   my ($self, $table) = @_;
1154   $self->dbh_do($self->can('_dbh_columns_info_for'), $table);
1155 }
1156
1157 =head2 last_insert_id
1158
1159 Return the row id of the last insert.
1160
1161 =cut
1162
1163 sub _dbh_last_insert_id {
1164     my ($self, $dbh, $source, $col) = @_;
1165     # XXX This is a SQLite-ism as a default... is there a DBI-generic way?
1166     $dbh->func('last_insert_rowid');
1167 }
1168
1169 sub last_insert_id {
1170   my $self = shift;
1171   $self->dbh_do($self->can('_dbh_last_insert_id'), @_);
1172 }
1173
1174 =head2 sqlt_type
1175
1176 Returns the database driver name.
1177
1178 =cut
1179
1180 sub sqlt_type { shift->dbh->{Driver}->{Name} }
1181
1182 =head2 bind_attribute_by_data_type
1183
1184 Given a datatype from column info, returns a database specific bind attribute for
1185 $dbh->bind_param($val,$attribute) or nothing if we will let the database planner
1186 just handle it.
1187
1188 Generally only needed for special case column types, like bytea in postgres.
1189
1190 =cut
1191
1192 sub bind_attribute_by_data_type {
1193     return;
1194 }
1195
1196 =head2 create_ddl_dir (EXPERIMENTAL)
1197
1198 =over 4
1199
1200 =item Arguments: $schema \@databases, $version, $directory, $preversion, $sqlt_args
1201
1202 =back
1203
1204 Creates a SQL file based on the Schema, for each of the specified
1205 database types, in the given directory.
1206
1207 Note that this feature is currently EXPERIMENTAL and may not work correctly
1208 across all databases, or fully handle complex relationships.
1209
1210 =cut
1211
1212 sub create_ddl_dir
1213 {
1214   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
1215
1216   if(!$dir || !-d $dir)
1217   {
1218     warn "No directory given, using ./\n";
1219     $dir = "./";
1220   }
1221   $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
1222   $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
1223   $version ||= $schema->VERSION || '1.x';
1224   $sqltargs = { ( add_drop_table => 1 ), %{$sqltargs || {}} };
1225
1226   eval "use SQL::Translator";
1227   $self->throw_exception("Can't create a ddl file without SQL::Translator: $@") if $@;
1228
1229   my $sqlt = SQL::Translator->new({
1230 #      debug => 1,
1231       add_drop_table => 1,
1232   });
1233   foreach my $db (@$databases)
1234   {
1235     $sqlt->reset();
1236     $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
1237 #    $sqlt->parser_args({'DBIx::Class' => $schema);
1238     $sqlt = $self->configure_sqlt($sqlt, $db);
1239     $sqlt->data($schema);
1240     $sqlt->producer($db);
1241
1242     my $file;
1243     my $filename = $schema->ddl_filename($db, $dir, $version);
1244     if(-e $filename)
1245     {
1246       warn("$filename already exists, skipping $db");
1247       next;
1248     }
1249
1250     my $output = $sqlt->translate;
1251     if(!$output)
1252     {
1253       warn("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
1254       next;
1255     }
1256     if(!open($file, ">$filename"))
1257     {
1258         $self->throw_exception("Can't open $filename for writing ($!)");
1259         next;
1260     }
1261     print $file $output;
1262     close($file);
1263
1264     if($preversion)
1265     {
1266       eval "use SQL::Translator::Diff";
1267       if($@)
1268       {
1269         warn("Can't diff versions without SQL::Translator::Diff: $@");
1270         next;
1271       }
1272
1273       my $prefilename = $schema->ddl_filename($db, $dir, $preversion);
1274 #      print "Previous version $prefilename\n";
1275       if(!-e $prefilename)
1276       {
1277         warn("No previous schema file found ($prefilename)");
1278         next;
1279       }
1280       #### We need to reparse the SQLite file we just wrote, so that 
1281       ##   Diff doesnt get all confoosed, and Diff is *very* confused.
1282       ##   FIXME: rip Diff to pieces!
1283 #      my $target_schema = $sqlt->schema;
1284 #      unless ( $target_schema->name ) {
1285 #        $target_schema->name( $filename );
1286 #      }
1287       my @input;
1288       push @input, {file => $prefilename, parser => $db};
1289       push @input, {file => $filename, parser => $db};
1290       my ( $source_schema, $source_db, $target_schema, $target_db ) = map {
1291         my $file   = $_->{'file'};
1292         my $parser = $_->{'parser'};
1293
1294         my $t = SQL::Translator->new;
1295         $t->debug( 0 );
1296         $t->trace( 0 );
1297         $t->parser( $parser )            or die $t->error;
1298         my $out = $t->translate( $file ) or die $t->error;
1299         my $schema = $t->schema;
1300         unless ( $schema->name ) {
1301           $schema->name( $file );
1302         }
1303         ($schema, $parser);
1304       } @input;
1305
1306       my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
1307                                                     $target_schema, $db,
1308                                                     {}
1309                                                    );
1310       my $difffile = $schema->ddl_filename($db, $dir, $version, $preversion);
1311       print STDERR "Diff: $difffile: $db, $dir, $version, $preversion \n";
1312       if(-e $difffile)
1313       {
1314         warn("$difffile already exists, skipping");
1315         next;
1316       }
1317       if(!open $file, ">$difffile")
1318       { 
1319         $self->throw_exception("Can't write to $difffile ($!)");
1320         next;
1321       }
1322       print $file $diff;
1323       close($file);
1324     }
1325   }
1326 }
1327
1328 sub configure_sqlt() {
1329   my $self = shift;
1330   my $tr = shift;
1331   my $db = shift || $self->sqlt_type;
1332   if ($db eq 'PostgreSQL') {
1333     $tr->quote_table_names(0);
1334     $tr->quote_field_names(0);
1335   }
1336   return $tr;
1337 }
1338
1339 =head2 deployment_statements
1340
1341 =over 4
1342
1343 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
1344
1345 =back
1346
1347 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
1348 The database driver name is given by C<$type>, though the value from
1349 L</sqlt_type> is used if it is not specified.
1350
1351 C<$directory> is used to return statements from files in a previously created
1352 L</create_ddl_dir> directory and is optional. The filenames are constructed
1353 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
1354
1355 If no C<$directory> is specified then the statements are constructed on the
1356 fly using L<SQL::Translator> and C<$version> is ignored.
1357
1358 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
1359
1360 =cut
1361
1362 sub deployment_statements {
1363   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
1364   # Need to be connected to get the correct sqlt_type
1365   $self->ensure_connected() unless $type;
1366   $type ||= $self->sqlt_type;
1367   $version ||= $schema->VERSION || '1.x';
1368   $dir ||= './';
1369   my $filename = $schema->ddl_filename($type, $dir, $version);
1370   if(-f $filename)
1371   {
1372       my $file;
1373       open($file, "<$filename") 
1374         or $self->throw_exception("Can't open $filename ($!)");
1375       my @rows = <$file>;
1376       close($file);
1377       return join('', @rows);
1378   }
1379
1380   eval "use SQL::Translator";
1381   if(!$@)
1382   {
1383     eval "use SQL::Translator::Parser::DBIx::Class;";
1384     $self->throw_exception($@) if $@;
1385     eval "use SQL::Translator::Producer::${type};";
1386     $self->throw_exception($@) if $@;
1387
1388     # sources needs to be a parser arg, but for simplicty allow at top level 
1389     # coming in
1390     $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
1391         if exists $sqltargs->{sources};
1392
1393     my $tr = SQL::Translator->new(%$sqltargs);
1394     SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
1395     return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
1396   }
1397
1398   $self->throw_exception("No SQL::Translator, and no Schema file found, aborting deploy");
1399   return;
1400
1401 }
1402
1403 sub deploy {
1404   my ($self, $schema, $type, $sqltargs, $dir) = @_;
1405   foreach my $statement ( $self->deployment_statements($schema, $type, undef, $dir, { no_comments => 1, %{ $sqltargs || {} } } ) ) {
1406     for ( split(";\n", $statement)) {
1407       next if($_ =~ /^--/);
1408       next if(!$_);
1409 #      next if($_ =~ /^DROP/m);
1410       next if($_ =~ /^BEGIN TRANSACTION/m);
1411       next if($_ =~ /^COMMIT/m);
1412       next if $_ =~ /^\s+$/; # skip whitespace only
1413       $self->debugobj->query_start($_) if $self->debug;
1414       $self->dbh->do($_) or warn "SQL was:\n $_"; # XXX exceptions?
1415       $self->debugobj->query_end($_) if $self->debug;
1416     }
1417   }
1418 }
1419
1420 =head2 datetime_parser
1421
1422 Returns the datetime parser class
1423
1424 =cut
1425
1426 sub datetime_parser {
1427   my $self = shift;
1428   return $self->{datetime_parser} ||= $self->build_datetime_parser(@_);
1429 }
1430
1431 =head2 datetime_parser_type
1432
1433 Defines (returns) the datetime parser class - currently hardwired to
1434 L<DateTime::Format::MySQL>
1435
1436 =cut
1437
1438 sub datetime_parser_type { "DateTime::Format::MySQL"; }
1439
1440 =head2 build_datetime_parser
1441
1442 See L</datetime_parser>
1443
1444 =cut
1445
1446 sub build_datetime_parser {
1447   my $self = shift;
1448   my $type = $self->datetime_parser_type(@_);
1449   eval "use ${type}";
1450   $self->throw_exception("Couldn't load ${type}: $@") if $@;
1451   return $type;
1452 }
1453
1454 sub DESTROY {
1455   my $self = shift;
1456   return if !$self->_dbh;
1457   $self->_verify_pid;
1458   $self->_dbh(undef);
1459 }
1460
1461 1;
1462
1463 =head1 SQL METHODS
1464
1465 The module defines a set of methods within the DBIC::SQL::Abstract
1466 namespace.  These build on L<SQL::Abstract::Limit> to provide the
1467 SQL query functions.
1468
1469 The following methods are extended:-
1470
1471 =over 4
1472
1473 =item delete
1474
1475 =item insert
1476
1477 =item select
1478
1479 =item update
1480
1481 =item limit_dialect
1482
1483 See L</connect_info> for details.
1484 For setting, this method is deprecated in favor of L</connect_info>.
1485
1486 =item quote_char
1487
1488 See L</connect_info> for details.
1489 For setting, this method is deprecated in favor of L</connect_info>.
1490
1491 =item name_sep
1492
1493 See L</connect_info> for details.
1494 For setting, this method is deprecated in favor of L</connect_info>.
1495
1496 =back
1497
1498 =head1 AUTHORS
1499
1500 Matt S. Trout <mst@shadowcatsystems.co.uk>
1501
1502 Andy Grundman <andy@hybridized.org>
1503
1504 =head1 LICENSE
1505
1506 You may distribute this code under the same terms as Perl itself.
1507
1508 =cut