Fix dubious optimization
[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 Carp::Clan qw/^DBIx::Class/;
9 use DBI;
10 use DBIx::Class::Storage::DBI::Cursor;
11 use DBIx::Class::Storage::Statistics;
12 use Scalar::Util();
13 use List::Util();
14
15 __PACKAGE__->mk_group_accessors('simple' =>
16     qw/_connect_info _dbi_connect_info _dbh _sql_maker _sql_maker_opts
17        _conn_pid _conn_tid transaction_depth _dbh_autocommit savepoints/
18 );
19
20 # the values for these accessors are picked out (and deleted) from
21 # the attribute hashref passed to connect_info
22 my @storage_options = qw/
23   on_connect_do on_disconnect_do disable_sth_caching unsafe auto_savepoint
24 /;
25 __PACKAGE__->mk_group_accessors('simple' => @storage_options);
26
27
28 # default cursor class, overridable in connect_info attributes
29 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
30
31 __PACKAGE__->mk_group_accessors('inherited' => qw/sql_maker_class/);
32 __PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks');
33
34
35 =head1 NAME
36
37 DBIx::Class::Storage::DBI - DBI storage handler
38
39 =head1 SYNOPSIS
40
41   my $schema = MySchema->connect('dbi:SQLite:my.db');
42
43   $schema->storage->debug(1);
44   $schema->dbh_do("DROP TABLE authors");
45
46   $schema->resultset('Book')->search({
47      written_on => $schema->storage->datetime_parser(DateTime->now)
48   });
49
50 =head1 DESCRIPTION
51
52 This class represents the connection to an RDBMS via L<DBI>.  See
53 L<DBIx::Class::Storage> for general information.  This pod only
54 documents DBI-specific methods and behaviors.
55
56 =head1 METHODS
57
58 =cut
59
60 sub new {
61   my $new = shift->next::method(@_);
62
63   $new->transaction_depth(0);
64   $new->_sql_maker_opts({});
65   $new->{savepoints} = [];
66   $new->{_in_dbh_do} = 0;
67   $new->{_dbh_gen} = 0;
68
69   $new;
70 }
71
72 =head2 connect_info
73
74 This method is normally called by L<DBIx::Class::Schema/connection>, which
75 encapsulates its argument list in an arrayref before passing them here.
76
77 The argument list may contain:
78
79 =over
80
81 =item *
82
83 The same 4-element argument set one would normally pass to
84 L<DBI/connect>, optionally followed by
85 L<extra attributes|/DBIx::Class specific connection attributes>
86 recognized by DBIx::Class:
87
88   $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
89
90 =item *
91
92 A single code reference which returns a connected 
93 L<DBI database handle|DBI/connect> optionally followed by 
94 L<extra attributes|/DBIx::Class specific connection attributes> recognized
95 by DBIx::Class:
96
97   $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
98
99 =item *
100
101 A single hashref with all the attributes and the dsn/user/password
102 mixed together:
103
104   $connect_info_args = [{
105     dsn => $dsn,
106     user => $user,
107     password => $pass,
108     %dbi_attributes,
109     %extra_attributes,
110   }];
111
112 This is particularly useful for L<Catalyst> based applications, allowing the 
113 following config (L<Config::General> style):
114
115   <Model::DB>
116     schema_class   App::DB
117     <connect_info>
118       dsn          dbi:mysql:database=test
119       user         testuser
120       password     TestPass
121       AutoCommit   1
122     </connect_info>
123   </Model::DB>
124
125 =back
126
127 Please note that the L<DBI> docs recommend that you always explicitly
128 set C<AutoCommit> to either I<0> or I<1>.  L<DBIx::Class> further
129 recommends that it be set to I<1>, and that you perform transactions
130 via our L<DBIx::Class::Schema/txn_do> method.  L<DBIx::Class> will set it
131 to I<1> if you do not do explicitly set it to zero.  This is the default 
132 for most DBDs. See L</DBIx::Class and AutoCommit> for details.
133
134 =head3 DBIx::Class specific connection attributes
135
136 In addition to the standard L<DBI|DBI/ATTRIBUTES_COMMON_TO_ALL_HANDLES>
137 L<connection|DBI/Database_Handle_Attributes> attributes, DBIx::Class recognizes
138 the following connection options. These options can be mixed in with your other
139 L<DBI> connection attributes, or placed in a seperate hashref
140 (C<\%extra_attributes>) as shown above.
141
142 Every time C<connect_info> is invoked, any previous settings for
143 these options will be cleared before setting the new ones, regardless of
144 whether any options are specified in the new C<connect_info>.
145
146
147 =over
148
149 =item on_connect_do
150
151 Specifies things to do immediately after connecting or re-connecting to
152 the database.  Its value may contain:
153
154 =over
155
156 =item a scalar
157
158 This contains one SQL statement to execute.
159
160 =item an array reference
161
162 This contains SQL statements to execute in order.  Each element contains
163 a string or a code reference that returns a string.
164
165 =item a code reference
166
167 This contains some code to execute.  Unlike code references within an
168 array reference, its return value is ignored.
169
170 =back
171
172 =item on_disconnect_do
173
174 Takes arguments in the same form as L</on_connect_do> and executes them
175 immediately before disconnecting from the database.
176
177 Note, this only runs if you explicitly call L</disconnect> on the
178 storage object.
179
180 =item disable_sth_caching
181
182 If set to a true value, this option will disable the caching of
183 statement handles via L<DBI/prepare_cached>.
184
185 =item limit_dialect 
186
187 Sets the limit dialect. This is useful for JDBC-bridge among others
188 where the remote SQL-dialect cannot be determined by the name of the
189 driver alone. See also L<SQL::Abstract::Limit>.
190
191 =item quote_char
192
193 Specifies what characters to use to quote table and column names. If 
194 you use this you will want to specify L</name_sep> as well.
195
196 C<quote_char> expects either a single character, in which case is it
197 is placed on either side of the table/column name, or an arrayref of length
198 2 in which case the table/column name is placed between the elements.
199
200 For example under MySQL you should use C<< quote_char => '`' >>, and for
201 SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
202
203 =item name_sep
204
205 This only needs to be used in conjunction with C<quote_char>, and is used to 
206 specify the charecter that seperates elements (schemas, tables, columns) from 
207 each other. In most cases this is simply a C<.>.
208
209 The consequences of not supplying this value is that L<SQL::Abstract>
210 will assume DBIx::Class' uses of aliases to be complete column
211 names. The output will look like I<"me.name"> when it should actually
212 be I<"me"."name">.
213
214 =item unsafe
215
216 This Storage driver normally installs its own C<HandleError>, sets
217 C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
218 all database handles, including those supplied by a coderef.  It does this
219 so that it can have consistent and useful error behavior.
220
221 If you set this option to a true value, Storage will not do its usual
222 modifications to the database handle's attributes, and instead relies on
223 the settings in your connect_info DBI options (or the values you set in
224 your connection coderef, in the case that you are connecting via coderef).
225
226 Note that your custom settings can cause Storage to malfunction,
227 especially if you set a C<HandleError> handler that suppresses exceptions
228 and/or disable C<RaiseError>.
229
230 =item auto_savepoint
231
232 If this option is true, L<DBIx::Class> will use savepoints when nesting
233 transactions, making it possible to recover from failure in the inner
234 transaction without having to abort all outer transactions.
235
236 =item cursor_class
237
238 Use this argument to supply a cursor class other than the default
239 L<DBIx::Class::Storage::DBI::Cursor>.
240
241 =back
242
243 Some real-life examples of arguments to L</connect_info> and
244 L<DBIx::Class::Schema/connect>
245
246   # Simple SQLite connection
247   ->connect_info([ 'dbi:SQLite:./foo.db' ]);
248
249   # Connect via subref
250   ->connect_info([ sub { DBI->connect(...) } ]);
251
252   # A bit more complicated
253   ->connect_info(
254     [
255       'dbi:Pg:dbname=foo',
256       'postgres',
257       'my_pg_password',
258       { AutoCommit => 1 },
259       { quote_char => q{"}, name_sep => q{.} },
260     ]
261   );
262
263   # Equivalent to the previous example
264   ->connect_info(
265     [
266       'dbi:Pg:dbname=foo',
267       'postgres',
268       'my_pg_password',
269       { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
270     ]
271   );
272
273   # Same, but with hashref as argument
274   # See parse_connect_info for explanation
275   ->connect_info(
276     [{
277       dsn         => 'dbi:Pg:dbname=foo',
278       user        => 'postgres',
279       password    => 'my_pg_password',
280       AutoCommit  => 1,
281       quote_char  => q{"},
282       name_sep    => q{.},
283     }]
284   );
285
286   # Subref + DBIx::Class-specific connection options
287   ->connect_info(
288     [
289       sub { DBI->connect(...) },
290       {
291           quote_char => q{`},
292           name_sep => q{@},
293           on_connect_do => ['SET search_path TO myschema,otherschema,public'],
294           disable_sth_caching => 1,
295       },
296     ]
297   );
298
299
300
301 =cut
302
303 sub connect_info {
304   my ($self, $info_arg) = @_;
305
306   return $self->_connect_info if !$info_arg;
307
308   my @args = @$info_arg;  # take a shallow copy for further mutilation
309   $self->_connect_info([@args]); # copy for _connect_info
310
311
312   # combine/pre-parse arguments depending on invocation style
313
314   my %attrs;
315   if (ref $args[0] eq 'CODE') {     # coderef with optional \%extra_attributes
316     %attrs = %{ $args[1] || {} };
317     @args = $args[0];
318   }
319   elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
320     %attrs = %{$args[0]};
321     @args = ();
322     for (qw/password user dsn/) {
323       unshift @args, delete $attrs{$_};
324     }
325   }
326   else {                # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
327     %attrs = (
328       % { $args[3] || {} },
329       % { $args[4] || {} },
330     );
331     @args = @args[0,1,2];
332   }
333
334   # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
335   #  the new set of options
336   $self->_sql_maker(undef);
337   $self->_sql_maker_opts({});
338
339   if(keys %attrs) {
340     for my $storage_opt (@storage_options, 'cursor_class') {    # @storage_options is declared at the top of the module
341       if(my $value = delete $attrs{$storage_opt}) {
342         $self->$storage_opt($value);
343       }
344     }
345     for my $sql_maker_opt (qw/limit_dialect quote_char name_sep/) {
346       if(my $opt_val = delete $attrs{$sql_maker_opt}) {
347         $self->_sql_maker_opts->{$sql_maker_opt} = $opt_val;
348       }
349     }
350   }
351
352   %attrs = () if (ref $args[0] eq 'CODE');  # _connect() never looks past $args[0] in this case
353
354   $self->_dbi_connect_info([@args, keys %attrs ? \%attrs : ()]);
355   $self->_connect_info;
356 }
357
358 =head2 on_connect_do
359
360 This method is deprecated in favour of setting via L</connect_info>.
361
362
363 =head2 dbh_do
364
365 Arguments: ($subref | $method_name), @extra_coderef_args?
366
367 Execute the given $subref or $method_name using the new exception-based
368 connection management.
369
370 The first two arguments will be the storage object that C<dbh_do> was called
371 on and a database handle to use.  Any additional arguments will be passed
372 verbatim to the called subref as arguments 2 and onwards.
373
374 Using this (instead of $self->_dbh or $self->dbh) ensures correct
375 exception handling and reconnection (or failover in future subclasses).
376
377 Your subref should have no side-effects outside of the database, as
378 there is the potential for your subref to be partially double-executed
379 if the database connection was stale/dysfunctional.
380
381 Example:
382
383   my @stuff = $schema->storage->dbh_do(
384     sub {
385       my ($storage, $dbh, @cols) = @_;
386       my $cols = join(q{, }, @cols);
387       $dbh->selectrow_array("SELECT $cols FROM foo");
388     },
389     @column_list
390   );
391
392 =cut
393
394 sub dbh_do {
395   my $self = shift;
396   my $code = shift;
397
398   my $dbh = $self->_dbh;
399
400   return $self->$code($dbh, @_) if $self->{_in_dbh_do}
401       || $self->{transaction_depth};
402
403   local $self->{_in_dbh_do} = 1;
404
405   my @result;
406   my $want_array = wantarray;
407
408   eval {
409     $self->_verify_pid if $dbh;
410     if(!$self->_dbh) {
411         $self->_populate_dbh;
412         $dbh = $self->_dbh;
413     }
414
415     if($want_array) {
416         @result = $self->$code($dbh, @_);
417     }
418     elsif(defined $want_array) {
419         $result[0] = $self->$code($dbh, @_);
420     }
421     else {
422         $self->$code($dbh, @_);
423     }
424   };
425
426   my $exception = $@;
427   if(!$exception) { return $want_array ? @result : $result[0] }
428
429   $self->throw_exception($exception) if $self->connected;
430
431   # We were not connected - reconnect and retry, but let any
432   #  exception fall right through this time
433   $self->_populate_dbh;
434   $self->$code($self->_dbh, @_);
435 }
436
437 # This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do.
438 # It also informs dbh_do to bypass itself while under the direction of txn_do,
439 #  via $self->{_in_dbh_do} (this saves some redundant eval and errorcheck, etc)
440 sub txn_do {
441   my $self = shift;
442   my $coderef = shift;
443
444   ref $coderef eq 'CODE' or $self->throw_exception
445     ('$coderef must be a CODE reference');
446
447   return $coderef->(@_) if $self->{transaction_depth} && ! $self->auto_savepoint;
448
449   local $self->{_in_dbh_do} = 1;
450
451   my @result;
452   my $want_array = wantarray;
453
454   my $tried = 0;
455   while(1) {
456     eval {
457       $self->_verify_pid if $self->_dbh;
458       $self->_populate_dbh if !$self->_dbh;
459
460       $self->txn_begin;
461       if($want_array) {
462           @result = $coderef->(@_);
463       }
464       elsif(defined $want_array) {
465           $result[0] = $coderef->(@_);
466       }
467       else {
468           $coderef->(@_);
469       }
470       $self->txn_commit;
471     };
472
473     my $exception = $@;
474     if(!$exception) { return $want_array ? @result : $result[0] }
475
476     if($tried++ > 0 || $self->connected) {
477       eval { $self->txn_rollback };
478       my $rollback_exception = $@;
479       if($rollback_exception) {
480         my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
481         $self->throw_exception($exception)  # propagate nested rollback
482           if $rollback_exception =~ /$exception_class/;
483
484         $self->throw_exception(
485           "Transaction aborted: ${exception}. "
486           . "Rollback failed: ${rollback_exception}"
487         );
488       }
489       $self->throw_exception($exception)
490     }
491
492     # We were not connected, and was first try - reconnect and retry
493     # via the while loop
494     $self->_populate_dbh;
495   }
496 }
497
498 =head2 disconnect
499
500 Our C<disconnect> method also performs a rollback first if the
501 database is not in C<AutoCommit> mode.
502
503 =cut
504
505 sub disconnect {
506   my ($self) = @_;
507
508   if( $self->connected ) {
509     my $connection_do = $self->on_disconnect_do;
510     $self->_do_connection_actions($connection_do) if ref($connection_do);
511
512     $self->_dbh->rollback unless $self->_dbh_autocommit;
513     $self->_dbh->disconnect;
514     $self->_dbh(undef);
515     $self->{_dbh_gen}++;
516   }
517 }
518
519 =head2 with_deferred_fk_checks
520
521 =over 4
522
523 =item Arguments: C<$coderef>
524
525 =item Return Value: The return value of $coderef
526
527 =back
528
529 Storage specific method to run the code ref with FK checks deferred or
530 in MySQL's case disabled entirely.
531
532 =cut
533
534 # Storage subclasses should override this
535 sub with_deferred_fk_checks {
536   my ($self, $sub) = @_;
537
538   $sub->();
539 }
540
541 sub connected {
542   my ($self) = @_;
543
544   if(my $dbh = $self->_dbh) {
545       if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
546           $self->_dbh(undef);
547           $self->{_dbh_gen}++;
548           return;
549       }
550       else {
551           $self->_verify_pid;
552           return 0 if !$self->_dbh;
553       }
554       return ($dbh->FETCH('Active') && $dbh->ping);
555   }
556
557   return 0;
558 }
559
560 # handle pid changes correctly
561 #  NOTE: assumes $self->_dbh is a valid $dbh
562 sub _verify_pid {
563   my ($self) = @_;
564
565   return if defined $self->_conn_pid && $self->_conn_pid == $$;
566
567   $self->_dbh->{InactiveDestroy} = 1;
568   $self->_dbh(undef);
569   $self->{_dbh_gen}++;
570
571   return;
572 }
573
574 sub ensure_connected {
575   my ($self) = @_;
576
577   unless ($self->connected) {
578     $self->_populate_dbh;
579   }
580 }
581
582 =head2 dbh
583
584 Returns the dbh - a data base handle of class L<DBI>.
585
586 =cut
587
588 sub dbh {
589   my ($self) = @_;
590
591   $self->ensure_connected;
592   return $self->_dbh;
593 }
594
595 sub _sql_maker_args {
596     my ($self) = @_;
597     
598     return ( bindtype=>'columns', array_datatypes => 1, limit_dialect => $self->dbh, %{$self->_sql_maker_opts} );
599 }
600
601 sub sql_maker {
602   my ($self) = @_;
603   unless ($self->_sql_maker) {
604     my $sql_maker_class = $self->sql_maker_class;
605     $self->ensure_class_loaded ($sql_maker_class);
606     $self->_sql_maker($sql_maker_class->new( $self->_sql_maker_args ));
607   }
608   return $self->_sql_maker;
609 }
610
611 sub _rebless {}
612
613 sub _populate_dbh {
614   my ($self) = @_;
615   my @info = @{$self->_dbi_connect_info || []};
616   $self->_dbh($self->_connect(@info));
617
618   $self->_conn_pid($$);
619   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
620
621   $self->_determine_driver;
622
623   # Always set the transaction depth on connect, since
624   #  there is no transaction in progress by definition
625   $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
626
627   my $connection_do = $self->on_connect_do;
628   $self->_do_connection_actions($connection_do) if $connection_do;
629 }
630
631 sub _determine_driver {
632   my ($self) = @_;
633
634   if (ref $self eq 'DBIx::Class::Storage::DBI') {
635     my $driver;
636
637     if ($self->_dbh) { # we are connected
638       $driver = $self->_dbh->{Driver}{Name};
639     } else {
640       # try to use dsn to not require being connected, the driver may still
641       # force a connection in _rebless to determine version
642       ($driver) = $self->_dbi_connect_info->[0] =~ /dbi:([^:]+):/i;
643     }
644
645     if ($self->load_optional_class("DBIx::Class::Storage::DBI::${driver}")) {
646       bless $self, "DBIx::Class::Storage::DBI::${driver}";
647       $self->_rebless();
648     }
649   }
650 }
651
652 sub _do_connection_actions {
653   my $self = shift;
654   my $connection_do = shift;
655
656   if (!ref $connection_do) {
657     $self->_do_query($connection_do);
658   }
659   elsif (ref $connection_do eq 'ARRAY') {
660     $self->_do_query($_) foreach @$connection_do;
661   }
662   elsif (ref $connection_do eq 'CODE') {
663     $connection_do->($self);
664   }
665   else {
666     $self->throw_exception (sprintf ("Don't know how to process conection actions of type '%s'", ref $connection_do) );
667   }
668
669   return $self;
670 }
671
672 sub _do_query {
673   my ($self, $action) = @_;
674
675   if (ref $action eq 'CODE') {
676     $action = $action->($self);
677     $self->_do_query($_) foreach @$action;
678   }
679   else {
680     # Most debuggers expect ($sql, @bind), so we need to exclude
681     # the attribute hash which is the second argument to $dbh->do
682     # furthermore the bind values are usually to be presented
683     # as named arrayref pairs, so wrap those here too
684     my @do_args = (ref $action eq 'ARRAY') ? (@$action) : ($action);
685     my $sql = shift @do_args;
686     my $attrs = shift @do_args;
687     my @bind = map { [ undef, $_ ] } @do_args;
688
689     $self->_query_start($sql, @bind);
690     $self->_dbh->do($sql, $attrs, @do_args);
691     $self->_query_end($sql, @bind);
692   }
693
694   return $self;
695 }
696
697 sub _connect {
698   my ($self, @info) = @_;
699
700   $self->throw_exception("You failed to provide any connection info")
701     if !@info;
702
703   my ($old_connect_via, $dbh);
704
705   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
706     $old_connect_via = $DBI::connect_via;
707     $DBI::connect_via = 'connect';
708   }
709
710   eval {
711     if(ref $info[0] eq 'CODE') {
712        $dbh = &{$info[0]}
713     }
714     else {
715        $dbh = DBI->connect(@info);
716     }
717
718     if($dbh && !$self->unsafe) {
719       my $weak_self = $self;
720       Scalar::Util::weaken($weak_self);
721       $dbh->{HandleError} = sub {
722           if ($weak_self) {
723             $weak_self->throw_exception("DBI Exception: $_[0]");
724           }
725           else {
726             croak ("DBI Exception: $_[0]");
727           }
728       };
729       $dbh->{ShowErrorStatement} = 1;
730       $dbh->{RaiseError} = 1;
731       $dbh->{PrintError} = 0;
732     }
733   };
734
735   $DBI::connect_via = $old_connect_via if $old_connect_via;
736
737   $self->throw_exception("DBI Connection failed: " . ($@||$DBI::errstr))
738     if !$dbh || $@;
739
740   $self->_dbh_autocommit($dbh->{AutoCommit});
741
742   $dbh;
743 }
744
745 sub svp_begin {
746   my ($self, $name) = @_;
747
748   $name = $self->_svp_generate_name
749     unless defined $name;
750
751   $self->throw_exception ("You can't use savepoints outside a transaction")
752     if $self->{transaction_depth} == 0;
753
754   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
755     unless $self->can('_svp_begin');
756   
757   push @{ $self->{savepoints} }, $name;
758
759   $self->debugobj->svp_begin($name) if $self->debug;
760   
761   return $self->_svp_begin($name);
762 }
763
764 sub svp_release {
765   my ($self, $name) = @_;
766
767   $self->throw_exception ("You can't use savepoints outside a transaction")
768     if $self->{transaction_depth} == 0;
769
770   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
771     unless $self->can('_svp_release');
772
773   if (defined $name) {
774     $self->throw_exception ("Savepoint '$name' does not exist")
775       unless grep { $_ eq $name } @{ $self->{savepoints} };
776
777     # Dig through the stack until we find the one we are releasing.  This keeps
778     # the stack up to date.
779     my $svp;
780
781     do { $svp = pop @{ $self->{savepoints} } } while $svp ne $name;
782   } else {
783     $name = pop @{ $self->{savepoints} };
784   }
785
786   $self->debugobj->svp_release($name) if $self->debug;
787
788   return $self->_svp_release($name);
789 }
790
791 sub svp_rollback {
792   my ($self, $name) = @_;
793
794   $self->throw_exception ("You can't use savepoints outside a transaction")
795     if $self->{transaction_depth} == 0;
796
797   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
798     unless $self->can('_svp_rollback');
799
800   if (defined $name) {
801       # If they passed us a name, verify that it exists in the stack
802       unless(grep({ $_ eq $name } @{ $self->{savepoints} })) {
803           $self->throw_exception("Savepoint '$name' does not exist!");
804       }
805
806       # Dig through the stack until we find the one we are releasing.  This keeps
807       # the stack up to date.
808       while(my $s = pop(@{ $self->{savepoints} })) {
809           last if($s eq $name);
810       }
811       # Add the savepoint back to the stack, as a rollback doesn't remove the
812       # named savepoint, only everything after it.
813       push(@{ $self->{savepoints} }, $name);
814   } else {
815       # We'll assume they want to rollback to the last savepoint
816       $name = $self->{savepoints}->[-1];
817   }
818
819   $self->debugobj->svp_rollback($name) if $self->debug;
820   
821   return $self->_svp_rollback($name);
822 }
823
824 sub _svp_generate_name {
825     my ($self) = @_;
826
827     return 'savepoint_'.scalar(@{ $self->{'savepoints'} });
828 }
829
830 sub txn_begin {
831   my $self = shift;
832   $self->ensure_connected();
833   if($self->{transaction_depth} == 0) {
834     $self->debugobj->txn_begin()
835       if $self->debug;
836     # this isn't ->_dbh-> because
837     #  we should reconnect on begin_work
838     #  for AutoCommit users
839     $self->dbh->begin_work;
840   } elsif ($self->auto_savepoint) {
841     $self->svp_begin;
842   }
843   $self->{transaction_depth}++;
844 }
845
846 sub txn_commit {
847   my $self = shift;
848   if ($self->{transaction_depth} == 1) {
849     my $dbh = $self->_dbh;
850     $self->debugobj->txn_commit()
851       if ($self->debug);
852     $dbh->commit;
853     $self->{transaction_depth} = 0
854       if $self->_dbh_autocommit;
855   }
856   elsif($self->{transaction_depth} > 1) {
857     $self->{transaction_depth}--;
858     $self->svp_release
859       if $self->auto_savepoint;
860   }
861 }
862
863 sub txn_rollback {
864   my $self = shift;
865   my $dbh = $self->_dbh;
866   eval {
867     if ($self->{transaction_depth} == 1) {
868       $self->debugobj->txn_rollback()
869         if ($self->debug);
870       $self->{transaction_depth} = 0
871         if $self->_dbh_autocommit;
872       $dbh->rollback;
873     }
874     elsif($self->{transaction_depth} > 1) {
875       $self->{transaction_depth}--;
876       if ($self->auto_savepoint) {
877         $self->svp_rollback;
878         $self->svp_release;
879       }
880     }
881     else {
882       die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
883     }
884   };
885   if ($@) {
886     my $error = $@;
887     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
888     $error =~ /$exception_class/ and $self->throw_exception($error);
889     # ensure that a failed rollback resets the transaction depth
890     $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
891     $self->throw_exception($error);
892   }
893 }
894
895 # This used to be the top-half of _execute.  It was split out to make it
896 #  easier to override in NoBindVars without duping the rest.  It takes up
897 #  all of _execute's args, and emits $sql, @bind.
898 sub _prep_for_execute {
899   my ($self, $op, $extra_bind, $ident, $args) = @_;
900
901   if( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
902     $ident = $ident->from();
903   }
904
905   my ($sql, @bind) = $self->sql_maker->$op($ident, @$args);
906
907   unshift(@bind,
908     map { ref $_ eq 'ARRAY' ? $_ : [ '!!dummy', $_ ] } @$extra_bind)
909       if $extra_bind;
910   return ($sql, \@bind);
911 }
912
913
914 sub _fix_bind_params {
915     my ($self, @bind) = @_;
916
917     ### Turn @bind from something like this:
918     ###   ( [ "artist", 1 ], [ "cdid", 1, 3 ] )
919     ### to this:
920     ###   ( "'1'", "'1'", "'3'" )
921     return
922         map {
923             if ( defined( $_ && $_->[1] ) ) {
924                 map { qq{'$_'}; } @{$_}[ 1 .. $#$_ ];
925             }
926             else { q{'NULL'}; }
927         } @bind;
928 }
929
930 sub _query_start {
931     my ( $self, $sql, @bind ) = @_;
932
933     if ( $self->debug ) {
934         @bind = $self->_fix_bind_params(@bind);
935
936         $self->debugobj->query_start( $sql, @bind );
937     }
938 }
939
940 sub _query_end {
941     my ( $self, $sql, @bind ) = @_;
942
943     if ( $self->debug ) {
944         @bind = $self->_fix_bind_params(@bind);
945         $self->debugobj->query_end( $sql, @bind );
946     }
947 }
948
949 sub _dbh_execute {
950   my ($self, $dbh, $op, $extra_bind, $ident, $bind_attributes, @args) = @_;
951
952   my ($sql, $bind) = $self->_prep_for_execute($op, $extra_bind, $ident, \@args);
953
954   $self->_query_start( $sql, @$bind );
955
956   my $sth = $self->sth($sql,$op);
957
958   my $placeholder_index = 1; 
959
960   foreach my $bound (@$bind) {
961     my $attributes = {};
962     my($column_name, @data) = @$bound;
963
964     if ($bind_attributes) {
965       $attributes = $bind_attributes->{$column_name}
966       if defined $bind_attributes->{$column_name};
967     }
968
969     foreach my $data (@data) {
970       my $ref = ref $data;
971       $data = $ref && $ref ne 'ARRAY' ? ''.$data : $data; # stringify args (except arrayrefs)
972
973       $sth->bind_param($placeholder_index, $data, $attributes);
974       $placeholder_index++;
975     }
976   }
977
978   # Can this fail without throwing an exception anyways???
979   my $rv = $sth->execute();
980   $self->throw_exception($sth->errstr) if !$rv;
981
982   $self->_query_end( $sql, @$bind );
983
984   return (wantarray ? ($rv, $sth, @$bind) : $rv);
985 }
986
987 sub _execute {
988     my $self = shift;
989     $self->dbh_do('_dbh_execute', @_)
990 }
991
992 sub insert {
993   my ($self, $source, $to_insert) = @_;
994
995   my $ident = $source->from;
996   my $bind_attributes = $self->source_bind_attributes($source);
997
998   my $updated_cols = {};
999
1000   $self->ensure_connected;
1001   foreach my $col ( $source->columns ) {
1002     if ( !defined $to_insert->{$col} ) {
1003       my $col_info = $source->column_info($col);
1004
1005       if ( $col_info->{auto_nextval} ) {
1006         $updated_cols->{$col} = $to_insert->{$col} = $self->_sequence_fetch( 'nextval', $col_info->{sequence} || $self->_dbh_get_autoinc_seq($self->dbh, $source) );
1007       }
1008     }
1009   }
1010
1011   $self->_execute('insert' => [], $source, $bind_attributes, $to_insert);
1012
1013   return $updated_cols;
1014 }
1015
1016 ## Still not quite perfect, and EXPERIMENTAL
1017 ## Currently it is assumed that all values passed will be "normal", i.e. not 
1018 ## scalar refs, or at least, all the same type as the first set, the statement is
1019 ## only prepped once.
1020 sub insert_bulk {
1021   my ($self, $source, $cols, $data) = @_;
1022   my %colvalues;
1023   my $table = $source->from;
1024   @colvalues{@$cols} = (0..$#$cols);
1025   my ($sql, @bind) = $self->sql_maker->insert($table, \%colvalues);
1026   
1027   $self->_query_start( $sql, @bind );
1028   my $sth = $self->sth($sql);
1029
1030 #  @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
1031
1032   ## This must be an arrayref, else nothing works!
1033   my $tuple_status = [];
1034
1035   ## Get the bind_attributes, if any exist
1036   my $bind_attributes = $self->source_bind_attributes($source);
1037
1038   ## Bind the values and execute
1039   my $placeholder_index = 1; 
1040
1041   foreach my $bound (@bind) {
1042
1043     my $attributes = {};
1044     my ($column_name, $data_index) = @$bound;
1045
1046     if( $bind_attributes ) {
1047       $attributes = $bind_attributes->{$column_name}
1048       if defined $bind_attributes->{$column_name};
1049     }
1050
1051     my @data = map { $_->[$data_index] } @$data;
1052
1053     $sth->bind_param_array( $placeholder_index, [@data], $attributes );
1054     $placeholder_index++;
1055   }
1056   my $rv = eval { $sth->execute_array({ArrayTupleStatus => $tuple_status}) };
1057   if (my $err = $@) {
1058     my $i = 0;
1059     ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i];
1060
1061     $self->throw_exception($sth->errstr || "Unexpected populate error: $err")
1062       if ($i > $#$tuple_status);
1063
1064     require Data::Dumper;
1065     local $Data::Dumper::Terse = 1;
1066     local $Data::Dumper::Indent = 1;
1067     local $Data::Dumper::Useqq = 1;
1068     local $Data::Dumper::Quotekeys = 0;
1069
1070     $self->throw_exception(sprintf "%s for populate slice:\n%s",
1071       $tuple_status->[$i][1],
1072       Data::Dumper::Dumper(
1073         { map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) }
1074       ),
1075     );
1076   }
1077   $self->throw_exception($sth->errstr) if !$rv;
1078
1079   $self->_query_end( $sql, @bind );
1080   return (wantarray ? ($rv, $sth, @bind) : $rv);
1081 }
1082
1083 sub update {
1084   my $self = shift @_;
1085   my $source = shift @_;
1086   my $bind_attributes = $self->source_bind_attributes($source);
1087   
1088   return $self->_execute('update' => [], $source, $bind_attributes, @_);
1089 }
1090
1091
1092 sub delete {
1093   my $self = shift @_;
1094   my $source = shift @_;
1095   
1096   my $bind_attrs = $self->source_bind_attributes($source);
1097   
1098   return $self->_execute('delete' => [], $source, $bind_attrs, @_);
1099 }
1100
1101 # We were sent here because the $rs contains a complex search
1102 # which will require a subquery to select the correct rows
1103 # (i.e. joined or limited resultsets)
1104 #
1105 # Genarating a single PK column subquery is trivial and supported
1106 # by all RDBMS. However if we have a multicolumn PK, things get ugly.
1107 # Look at _multipk_update_delete()
1108 sub _subq_update_delete {
1109   my $self = shift;
1110   my ($rs, $op, $values) = @_;
1111
1112   my $rsrc = $rs->result_source;
1113
1114   # we already check this, but double check naively just in case. Should be removed soon
1115   my $sel = $rs->_resolved_attrs->{select};
1116   $sel = [ $sel ] unless ref $sel eq 'ARRAY';
1117   my @pcols = $rsrc->primary_columns;
1118   if (@$sel != @pcols) {
1119     $self->throw_exception (
1120       'Subquery update/delete can not be called on resultsets selecting a'
1121      .' number of columns different than the number of primary keys'
1122     );
1123   }
1124
1125   if (@pcols == 1) {
1126     return $self->$op (
1127       $rsrc,
1128       $op eq 'update' ? $values : (),
1129       { $pcols[0] => { -in => $rs->as_query } },
1130     );
1131   }
1132
1133   else {
1134     return $self->_multipk_update_delete (@_);
1135   }
1136 }
1137
1138 # ANSI SQL does not provide a reliable way to perform a multicol-PK
1139 # resultset update/delete involving subqueries. So by default resort
1140 # to simple (and inefficient) delete_all style per-row opearations,
1141 # while allowing specific storages to override this with a faster
1142 # implementation.
1143 #
1144 sub _multipk_update_delete {
1145   return shift->_per_row_update_delete (@_);
1146 }
1147
1148 # This is the default loop used to delete/update rows for multi PK
1149 # resultsets, and used by mysql exclusively (because it can't do anything
1150 # else).
1151 #
1152 # We do not use $row->$op style queries, because resultset update/delete
1153 # is not expected to cascade (this is what delete_all/update_all is for).
1154 #
1155 # There should be no race conditions as the entire operation is rolled
1156 # in a transaction.
1157 #
1158 sub _per_row_update_delete {
1159   my $self = shift;
1160   my ($rs, $op, $values) = @_;
1161
1162   my $rsrc = $rs->result_source;
1163   my @pcols = $rsrc->primary_columns;
1164
1165   my $guard = $self->txn_scope_guard;
1166
1167   # emulate the return value of $sth->execute for non-selects
1168   my $row_cnt = '0E0';
1169
1170   my $subrs_cur = $rs->cursor;
1171   while (my @pks = $subrs_cur->next) {
1172
1173     my $cond;
1174     for my $i (0.. $#pcols) {
1175       $cond->{$pcols[$i]} = $pks[$i];
1176     }
1177
1178     $self->$op (
1179       $rsrc,
1180       $op eq 'update' ? $values : (),
1181       $cond,
1182     );
1183
1184     $row_cnt++;
1185   }
1186
1187   $guard->commit;
1188
1189   return $row_cnt;
1190 }
1191
1192 sub _select {
1193   my $self = shift;
1194
1195   # localization is neccessary as
1196   # 1) there is no infrastructure to pass this around (easy to do, but will wait)
1197   # 2) _select_args sets it and _prep_for_execute consumes it
1198   my $sql_maker = $self->sql_maker;
1199   local $sql_maker->{for};
1200
1201   return $self->_execute($self->_select_args(@_));
1202 }
1203
1204 sub _select_args_to_query {
1205   my $self = shift;
1206
1207   # localization is neccessary as
1208   # 1) there is no infrastructure to pass this around (easy to do, but will wait)
1209   # 2) _select_args sets it and _prep_for_execute consumes it
1210   my $sql_maker = $self->sql_maker;
1211   local $sql_maker->{for};
1212
1213   # my ($op, $bind, $ident, $bind_attrs, $select, $cond, $order, $rows, $offset)
1214   #  = $self->_select_args($ident, $select, $cond, $attrs);
1215   my ($op, $bind, $ident, $bind_attrs, @args) =
1216     $self->_select_args(@_);
1217
1218   # my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, [ $select, $cond, $order, $rows, $offset ]);
1219   my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, \@args);
1220   $prepared_bind ||= [];
1221
1222   return wantarray
1223     ? ($sql, $prepared_bind, $bind_attrs)
1224     : \[ "($sql)", @$prepared_bind ]
1225   ;
1226 }
1227
1228 sub _select_args {
1229   my ($self, $ident, $select, $where, $attrs) = @_;
1230
1231   my $sql_maker = $self->sql_maker;
1232   my $alias2source = $self->_resolve_ident_sources ($ident);
1233
1234   # calculate bind_attrs before possible $ident mangling
1235   my $bind_attrs = {};
1236   for my $alias (keys %$alias2source) {
1237     my $bindtypes = $self->source_bind_attributes ($alias2source->{$alias}) || {};
1238     for my $col (keys %$bindtypes) {
1239
1240       my $fqcn = join ('.', $alias, $col);
1241       $bind_attrs->{$fqcn} = $bindtypes->{$col} if $bindtypes->{$col};
1242
1243       # so that unqualified searches can be bound too
1244       $bind_attrs->{$col} = $bind_attrs->{$fqcn} if $alias eq 'me';
1245     }
1246   }
1247
1248   my @limit;
1249   if ($attrs->{software_limit} ||
1250       $sql_maker->_default_limit_syntax eq "GenericSubQ") {
1251         $attrs->{software_limit} = 1;
1252   } else {
1253     $self->throw_exception("rows attribute must be positive if present")
1254       if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
1255
1256     # MySQL actually recommends this approach.  I cringe.
1257     $attrs->{rows} = 2**48 if not defined $attrs->{rows} and defined $attrs->{offset};
1258
1259     if ($attrs->{rows} && keys %{$attrs->{collapse}}) {
1260       ($ident, $select, $where, $attrs)
1261         = $self->_adjust_select_args_for_limited_prefetch ($ident, $select, $where, $attrs);
1262     }
1263     else {
1264       push @limit, $attrs->{rows}, $attrs->{offset};
1265     }
1266   }
1267
1268 ###
1269   # This would be the point to deflate anything found in $where
1270   # (and leave $attrs->{bind} intact). Problem is - inflators historically
1271   # expect a row object. And all we have is a resultsource (it is trivial
1272   # to extract deflator coderefs via $alias2source above).
1273   #
1274   # I don't see a way forward other than changing the way deflators are
1275   # invoked, and that's just bad...
1276 ###
1277
1278   my $order = { map
1279     { $attrs->{$_} ? ( $_ => $attrs->{$_} ) : ()  }
1280     (qw/order_by group_by having _virtual_order_by/ )
1281   };
1282
1283
1284   $sql_maker->{for} = delete $attrs->{for};
1285
1286   return ('select', $attrs->{bind}, $ident, $bind_attrs, $select, $where, $order, @limit);
1287 }
1288
1289 sub _adjust_select_args_for_limited_prefetch {
1290   my ($self, $from, $select, $where, $attrs) = @_;
1291
1292   if ($attrs->{group_by} and @{$attrs->{group_by}}) {
1293     $self->throw_exception ('Prefetch with limit (rows/offset) is not supported on resultsets with a group_by attribute');
1294   }
1295
1296   $self->throw_exception ('Prefetch with limit (rows/offset) is not supported on resultsets with a custom from attribute')
1297     if (ref $from ne 'ARRAY');
1298
1299   # separate attributes
1300   my $sub_attrs = { %$attrs };
1301   delete $attrs->{$_} for qw/where bind rows offset/;
1302   delete $sub_attrs->{$_} for qw/for collapse select order_by/;
1303
1304   my $alias = $attrs->{alias};
1305
1306   # create subquery select list
1307   my $sub_select = [ grep { $_ =~ /^$alias\./ } @{$attrs->{select}} ];
1308
1309   # bring over all non-collapse-induced order_by into the inner query (if any)
1310   # the outer one will have to keep them all
1311   if (my $ord_cnt = @{$attrs->{order_by}} - @{$attrs->{_collapse_order_by}} ) {
1312     $sub_attrs->{order_by} = [
1313       @{$attrs->{order_by}}[ 0 .. ($#{$attrs->{order_by}} - $ord_cnt - 1) ]
1314     ];
1315   }
1316
1317
1318   # mangle the head of the {from}
1319   my $self_ident = shift @$from;
1320
1321   my %join_info = map { $_->[0]{-alias} => $_->[0] } (@$from);
1322
1323   my (%inner_joins);
1324
1325   # decide which parts of the join will remain on the inside
1326   #
1327   # this is not a very viable optimisation, but it was written
1328   # before I realised this, so might as well remain. We can throw
1329   # away _any_ branches of the join tree that are:
1330   # 1) not mentioned in the condition/order
1331   # 2) left-join leaves (or left-join leaf chains)
1332   # Most of the join ocnditions will not satisfy this, but for real
1333   # complex queries some might, and we might make some RDBMS happy.
1334   #
1335   #
1336   # since we do not have introspectable SQLA, we fall back to ugly
1337   # scanning of raw SQL for WHERE, and for pieces of ORDER BY
1338   # in order to determine what goes into %inner_joins
1339   # It may not be very efficient, but it's a reasonable stop-gap
1340   {
1341     # produce stuff unquoted, so it can be scanned
1342     my $sql_maker = $self->sql_maker;
1343     local $sql_maker->{quote_char};
1344
1345     my @order_by = (map
1346       { ref $_ ? $_->[0] : $_ }
1347       $sql_maker->_order_by_chunks ($sub_attrs->{order_by})
1348     );
1349
1350     my $where_sql = $sql_maker->where ($where);
1351
1352     # sort needed joins
1353     for my $alias (keys %join_info) {
1354
1355       # any table alias found on a column name in where or order_by
1356       # gets included in %inner_joins
1357       # Also any parent joins that are needed to reach this particular alias
1358       for my $piece ($where_sql, @order_by ) {
1359         if ($piece =~ /\b$alias\./) {
1360           $inner_joins{$alias} = 1;
1361         }
1362       }
1363     }
1364   }
1365
1366   # scan for non-leaf/non-left joins and mark as needed
1367   # also mark all ancestor joins that are needed to reach this particular alias
1368   # (e.g.  join => { cds => 'tracks' } - tracks will bring cds too )
1369   #
1370   # traverse by the size of the -join_path i.e. reverse depth first
1371   for my $alias (sort { @{$join_info{$b}{-join_path}} <=> @{$join_info{$a}{-join_path}} } (keys %join_info) ) {
1372
1373     my $j = $join_info{$alias};
1374     $inner_joins{$alias} = 1 if (! $j->{-join_type} || ($j->{-join_type} !~ /^left$/i) );
1375
1376     if ($inner_joins{$alias}) {
1377       $inner_joins{$_} = 1 for (@{$j->{-join_path}});
1378     }
1379   }
1380
1381   # construct the inner $from for the subquery
1382   my $inner_from = [ $self_ident ];
1383   if (keys %inner_joins) {
1384     for my $j (@$from) {
1385       push @$inner_from, $j if $inner_joins{$j->[0]{-alias}};
1386     }
1387
1388     # if a multi-type join was needed in the subquery ("multi" is indicated by
1389     # presence in {collapse}) - add a group_by to simulate the collapse in the subq
1390     for my $alias (keys %inner_joins) {
1391
1392       # the dot comes from some weirdness in collapse
1393       # remove after the rewrite
1394       if ($attrs->{collapse}{".$alias"}) {
1395         $sub_attrs->{group_by} = $sub_select;
1396         last;
1397       }
1398     }
1399   }
1400
1401   # generate the subquery
1402   my $subq = $self->_select_args_to_query (
1403     $inner_from,
1404     $sub_select,
1405     $where,
1406     $sub_attrs
1407   );
1408
1409   # put it back in $from
1410   unshift @$from, { $alias => $subq };
1411
1412   # This is totally horrific - the $where ends up in both the inner and outer query
1413   # Unfortunately not much can be done until SQLA2 introspection arrives
1414   #
1415   # OTOH it can be seen as a plus: <ash> (notes that this query would make a DBA cry ;)
1416   return ($from, $select, $where, $attrs);
1417 }
1418
1419 sub _resolve_ident_sources {
1420   my ($self, $ident) = @_;
1421
1422   my $alias2source = {};
1423
1424   # the reason this is so contrived is that $ident may be a {from}
1425   # structure, specifying multiple tables to join
1426   if ( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
1427     # this is compat mode for insert/update/delete which do not deal with aliases
1428     $alias2source->{me} = $ident;
1429   }
1430   elsif (ref $ident eq 'ARRAY') {
1431
1432     for (@$ident) {
1433       my $tabinfo;
1434       if (ref $_ eq 'HASH') {
1435         $tabinfo = $_;
1436       }
1437       if (ref $_ eq 'ARRAY' and ref $_->[0] eq 'HASH') {
1438         $tabinfo = $_->[0];
1439       }
1440
1441       $alias2source->{$tabinfo->{-alias}} = $tabinfo->{-source_handle}->resolve
1442         if ($tabinfo->{-source_handle});
1443     }
1444   }
1445
1446   return $alias2source;
1447 }
1448
1449 sub count {
1450   my ($self, $source, $attrs) = @_;
1451
1452   my $tmp_attrs = { %$attrs };
1453
1454   # take off any limits, record_filter is cdbi, and no point of ordering a count
1455   delete $tmp_attrs->{$_} for (qw/select as rows offset order_by record_filter/);
1456
1457   # overwrite the selector
1458   $tmp_attrs->{select} = { count => '*' };
1459
1460   my $tmp_rs = $source->resultset_class->new($source, $tmp_attrs);
1461   my ($count) = $tmp_rs->cursor->next;
1462
1463   # if the offset/rows attributes are still present, we did not use
1464   # a subquery, so we need to make the calculations in software
1465   $count -= $attrs->{offset} if $attrs->{offset};
1466   $count = $attrs->{rows} if $attrs->{rows} and $attrs->{rows} < $count;
1467   $count = 0 if ($count < 0);
1468
1469   return $count;
1470 }
1471
1472 sub count_grouped {
1473   my ($self, $source, $attrs) = @_;
1474
1475   # copy for the subquery, we need to do some adjustments to it too
1476   my $sub_attrs = { %$attrs };
1477
1478   # these can not go in the subquery, and there is no point of ordering it
1479   delete $sub_attrs->{$_} for qw/collapse select as order_by/;
1480
1481   # if we prefetch, we group_by primary keys only as this is what we would get out of the rs via ->next/->all
1482   # simply deleting group_by suffices, as the code below will re-fill it
1483   # Note: we check $attrs, as $sub_attrs has collapse deleted
1484   if (ref $attrs->{collapse} and keys %{$attrs->{collapse}} ) {
1485     delete $sub_attrs->{group_by};
1486   }
1487
1488   $sub_attrs->{group_by} ||= [ map { "$attrs->{alias}.$_" } ($source->primary_columns) ];
1489   $sub_attrs->{select} = $self->_grouped_count_select ($source, $sub_attrs);
1490
1491   $attrs->{from} = [{
1492     count_subq => $source->resultset_class->new ($source, $sub_attrs )->as_query
1493   }];
1494
1495   # the subquery replaces this
1496   delete $attrs->{$_} for qw/where bind collapse group_by having having_bind rows offset/;
1497
1498   return $self->count ($source, $attrs);
1499 }
1500
1501 #
1502 # Returns a SELECT to go with a supplied GROUP BY
1503 # (caled by count_grouped so a group_by is present)
1504 # Most databases expect them to match, but some
1505 # choke in various ways.
1506 #
1507 sub _grouped_count_select {
1508   my ($self, $source, $rs_args) = @_;
1509   return $rs_args->{group_by};
1510 }
1511
1512 sub source_bind_attributes {
1513   my ($self, $source) = @_;
1514   
1515   my $bind_attributes;
1516   foreach my $column ($source->columns) {
1517   
1518     my $data_type = $source->column_info($column)->{data_type} || '';
1519     $bind_attributes->{$column} = $self->bind_attribute_by_data_type($data_type)
1520      if $data_type;
1521   }
1522
1523   return $bind_attributes;
1524 }
1525
1526 =head2 select
1527
1528 =over 4
1529
1530 =item Arguments: $ident, $select, $condition, $attrs
1531
1532 =back
1533
1534 Handle a SQL select statement.
1535
1536 =cut
1537
1538 sub select {
1539   my $self = shift;
1540   my ($ident, $select, $condition, $attrs) = @_;
1541   return $self->cursor_class->new($self, \@_, $attrs);
1542 }
1543
1544 sub select_single {
1545   my $self = shift;
1546   my ($rv, $sth, @bind) = $self->_select(@_);
1547   my @row = $sth->fetchrow_array;
1548   my @nextrow = $sth->fetchrow_array if @row;
1549   if(@row && @nextrow) {
1550     carp "Query returned more than one row.  SQL that returns multiple rows is DEPRECATED for ->find and ->single";
1551   }
1552   # Need to call finish() to work round broken DBDs
1553   $sth->finish();
1554   return @row;
1555 }
1556
1557 =head2 sth
1558
1559 =over 4
1560
1561 =item Arguments: $sql
1562
1563 =back
1564
1565 Returns a L<DBI> sth (statement handle) for the supplied SQL.
1566
1567 =cut
1568
1569 sub _dbh_sth {
1570   my ($self, $dbh, $sql) = @_;
1571
1572   # 3 is the if_active parameter which avoids active sth re-use
1573   my $sth = $self->disable_sth_caching
1574     ? $dbh->prepare($sql)
1575     : $dbh->prepare_cached($sql, {}, 3);
1576
1577   # XXX You would think RaiseError would make this impossible,
1578   #  but apparently that's not true :(
1579   $self->throw_exception($dbh->errstr) if !$sth;
1580
1581   $sth;
1582 }
1583
1584 sub sth {
1585   my ($self, $sql) = @_;
1586   $self->dbh_do('_dbh_sth', $sql);
1587 }
1588
1589 sub _dbh_columns_info_for {
1590   my ($self, $dbh, $table) = @_;
1591
1592   if ($dbh->can('column_info')) {
1593     my %result;
1594     eval {
1595       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
1596       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
1597       $sth->execute();
1598       while ( my $info = $sth->fetchrow_hashref() ){
1599         my %column_info;
1600         $column_info{data_type}   = $info->{TYPE_NAME};
1601         $column_info{size}      = $info->{COLUMN_SIZE};
1602         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
1603         $column_info{default_value} = $info->{COLUMN_DEF};
1604         my $col_name = $info->{COLUMN_NAME};
1605         $col_name =~ s/^\"(.*)\"$/$1/;
1606
1607         $result{$col_name} = \%column_info;
1608       }
1609     };
1610     return \%result if !$@ && scalar keys %result;
1611   }
1612
1613   my %result;
1614   my $sth = $dbh->prepare($self->sql_maker->select($table, undef, \'1 = 0'));
1615   $sth->execute;
1616   my @columns = @{$sth->{NAME_lc}};
1617   for my $i ( 0 .. $#columns ){
1618     my %column_info;
1619     $column_info{data_type} = $sth->{TYPE}->[$i];
1620     $column_info{size} = $sth->{PRECISION}->[$i];
1621     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
1622
1623     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
1624       $column_info{data_type} = $1;
1625       $column_info{size}    = $2;
1626     }
1627
1628     $result{$columns[$i]} = \%column_info;
1629   }
1630   $sth->finish;
1631
1632   foreach my $col (keys %result) {
1633     my $colinfo = $result{$col};
1634     my $type_num = $colinfo->{data_type};
1635     my $type_name;
1636     if(defined $type_num && $dbh->can('type_info')) {
1637       my $type_info = $dbh->type_info($type_num);
1638       $type_name = $type_info->{TYPE_NAME} if $type_info;
1639       $colinfo->{data_type} = $type_name if $type_name;
1640     }
1641   }
1642
1643   return \%result;
1644 }
1645
1646 sub columns_info_for {
1647   my ($self, $table) = @_;
1648   $self->dbh_do('_dbh_columns_info_for', $table);
1649 }
1650
1651 =head2 last_insert_id
1652
1653 Return the row id of the last insert.
1654
1655 =cut
1656
1657 sub _dbh_last_insert_id {
1658     # All Storage's need to register their own _dbh_last_insert_id
1659     # the old SQLite-based method was highly inappropriate
1660
1661     my $self = shift;
1662     my $class = ref $self;
1663     $self->throw_exception (<<EOE);
1664
1665 No _dbh_last_insert_id() method found in $class.
1666 Since the method of obtaining the autoincrement id of the last insert
1667 operation varies greatly between different databases, this method must be
1668 individually implemented for every storage class.
1669 EOE
1670 }
1671
1672 sub last_insert_id {
1673   my $self = shift;
1674   $self->dbh_do('_dbh_last_insert_id', @_);
1675 }
1676
1677 =head2 sqlt_type
1678
1679 Returns the database driver name.
1680
1681 =cut
1682
1683 sub sqlt_type { shift->dbh->{Driver}->{Name} }
1684
1685 =head2 bind_attribute_by_data_type
1686
1687 Given a datatype from column info, returns a database specific bind
1688 attribute for C<< $dbh->bind_param($val,$attribute) >> or nothing if we will
1689 let the database planner just handle it.
1690
1691 Generally only needed for special case column types, like bytea in postgres.
1692
1693 =cut
1694
1695 sub bind_attribute_by_data_type {
1696     return;
1697 }
1698
1699 =head2 is_datatype_numeric
1700
1701 Given a datatype from column_info, returns a boolean value indicating if
1702 the current RDBMS considers it a numeric value. This controls how
1703 L<DBIx::Class::Row/set_column> decides whether to mark the column as
1704 dirty - when the datatype is deemed numeric a C<< != >> comparison will
1705 be performed instead of the usual C<eq>.
1706
1707 =cut
1708
1709 sub is_datatype_numeric {
1710   my ($self, $dt) = @_;
1711
1712   return 0 unless $dt;
1713
1714   return $dt =~ /^ (?:
1715     numeric | int(?:eger)? | (?:tiny|small|medium|big)int | dec(?:imal)? | real | float | double (?: \s+ precision)? | (?:big)?serial
1716   ) $/ix;
1717 }
1718
1719
1720 =head2 create_ddl_dir (EXPERIMENTAL)
1721
1722 =over 4
1723
1724 =item Arguments: $schema \@databases, $version, $directory, $preversion, \%sqlt_args
1725
1726 =back
1727
1728 Creates a SQL file based on the Schema, for each of the specified
1729 database engines in C<\@databases> in the given directory.
1730 (note: specify L<SQL::Translator> names, not L<DBI> driver names).
1731
1732 Given a previous version number, this will also create a file containing
1733 the ALTER TABLE statements to transform the previous schema into the
1734 current one. Note that these statements may contain C<DROP TABLE> or
1735 C<DROP COLUMN> statements that can potentially destroy data.
1736
1737 The file names are created using the C<ddl_filename> method below, please
1738 override this method in your schema if you would like a different file
1739 name format. For the ALTER file, the same format is used, replacing
1740 $version in the name with "$preversion-$version".
1741
1742 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
1743 The most common value for this would be C<< { add_drop_table => 1 } >>
1744 to have the SQL produced include a C<DROP TABLE> statement for each table
1745 created. For quoting purposes supply C<quote_table_names> and
1746 C<quote_field_names>.
1747
1748 If no arguments are passed, then the following default values are assumed:
1749
1750 =over 4
1751
1752 =item databases  - ['MySQL', 'SQLite', 'PostgreSQL']
1753
1754 =item version    - $schema->schema_version
1755
1756 =item directory  - './'
1757
1758 =item preversion - <none>
1759
1760 =back
1761
1762 By default, C<\%sqlt_args> will have
1763
1764  { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
1765
1766 merged with the hash passed in. To disable any of those features, pass in a 
1767 hashref like the following
1768
1769  { ignore_constraint_names => 0, # ... other options }
1770
1771
1772 Note that this feature is currently EXPERIMENTAL and may not work correctly 
1773 across all databases, or fully handle complex relationships.
1774
1775 WARNING: Please check all SQL files created, before applying them.
1776
1777 =cut
1778
1779 sub create_ddl_dir {
1780   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
1781
1782   if(!$dir || !-d $dir) {
1783     carp "No directory given, using ./\n";
1784     $dir = "./";
1785   }
1786   $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
1787   $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
1788
1789   my $schema_version = $schema->schema_version || '1.x';
1790   $version ||= $schema_version;
1791
1792   $sqltargs = {
1793     add_drop_table => 1, 
1794     ignore_constraint_names => 1,
1795     ignore_index_names => 1,
1796     %{$sqltargs || {}}
1797   };
1798
1799   $self->throw_exception(q{Can't create a ddl file without SQL::Translator 0.09003: '}
1800       . $self->_check_sqlt_message . q{'})
1801           if !$self->_check_sqlt_version;
1802
1803   my $sqlt = SQL::Translator->new( $sqltargs );
1804
1805   $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
1806   my $sqlt_schema = $sqlt->translate({ data => $schema })
1807     or $self->throw_exception ($sqlt->error);
1808
1809   foreach my $db (@$databases) {
1810     $sqlt->reset();
1811     $sqlt->{schema} = $sqlt_schema;
1812     $sqlt->producer($db);
1813
1814     my $file;
1815     my $filename = $schema->ddl_filename($db, $version, $dir);
1816     if (-e $filename && ($version eq $schema_version )) {
1817       # if we are dumping the current version, overwrite the DDL
1818       carp "Overwriting existing DDL file - $filename";
1819       unlink($filename);
1820     }
1821
1822     my $output = $sqlt->translate;
1823     if(!$output) {
1824       carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
1825       next;
1826     }
1827     if(!open($file, ">$filename")) {
1828       $self->throw_exception("Can't open $filename for writing ($!)");
1829       next;
1830     }
1831     print $file $output;
1832     close($file);
1833   
1834     next unless ($preversion);
1835
1836     require SQL::Translator::Diff;
1837
1838     my $prefilename = $schema->ddl_filename($db, $preversion, $dir);
1839     if(!-e $prefilename) {
1840       carp("No previous schema file found ($prefilename)");
1841       next;
1842     }
1843
1844     my $difffile = $schema->ddl_filename($db, $version, $dir, $preversion);
1845     if(-e $difffile) {
1846       carp("Overwriting existing diff file - $difffile");
1847       unlink($difffile);
1848     }
1849     
1850     my $source_schema;
1851     {
1852       my $t = SQL::Translator->new($sqltargs);
1853       $t->debug( 0 );
1854       $t->trace( 0 );
1855
1856       $t->parser( $db )
1857         or $self->throw_exception ($t->error);
1858
1859       my $out = $t->translate( $prefilename )
1860         or $self->throw_exception ($t->error);
1861
1862       $source_schema = $t->schema;
1863
1864       $source_schema->name( $prefilename )
1865         unless ( $source_schema->name );
1866     }
1867
1868     # The "new" style of producers have sane normalization and can support 
1869     # diffing a SQL file against a DBIC->SQLT schema. Old style ones don't
1870     # And we have to diff parsed SQL against parsed SQL.
1871     my $dest_schema = $sqlt_schema;
1872
1873     unless ( "SQL::Translator::Producer::$db"->can('preprocess_schema') ) {
1874       my $t = SQL::Translator->new($sqltargs);
1875       $t->debug( 0 );
1876       $t->trace( 0 );
1877
1878       $t->parser( $db )
1879         or $self->throw_exception ($t->error);
1880
1881       my $out = $t->translate( $filename )
1882         or $self->throw_exception ($t->error);
1883
1884       $dest_schema = $t->schema;
1885
1886       $dest_schema->name( $filename )
1887         unless $dest_schema->name;
1888     }
1889     
1890     my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
1891                                                   $dest_schema,   $db,
1892                                                   $sqltargs
1893                                                  );
1894     if(!open $file, ">$difffile") { 
1895       $self->throw_exception("Can't write to $difffile ($!)");
1896       next;
1897     }
1898     print $file $diff;
1899     close($file);
1900   }
1901 }
1902
1903 =head2 deployment_statements
1904
1905 =over 4
1906
1907 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
1908
1909 =back
1910
1911 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
1912
1913 The L<SQL::Translator> (not L<DBI>) database driver name can be explicitly
1914 provided in C<$type>, otherwise the result of L</sqlt_type> is used as default.
1915
1916 C<$directory> is used to return statements from files in a previously created
1917 L</create_ddl_dir> directory and is optional. The filenames are constructed
1918 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
1919
1920 If no C<$directory> is specified then the statements are constructed on the
1921 fly using L<SQL::Translator> and C<$version> is ignored.
1922
1923 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
1924
1925 =cut
1926
1927 sub deployment_statements {
1928   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
1929   # Need to be connected to get the correct sqlt_type
1930   $self->ensure_connected() unless $type;
1931   $type ||= $self->sqlt_type;
1932   $version ||= $schema->schema_version || '1.x';
1933   $dir ||= './';
1934   my $filename = $schema->ddl_filename($type, $version, $dir);
1935   if(-f $filename)
1936   {
1937       my $file;
1938       open($file, "<$filename") 
1939         or $self->throw_exception("Can't open $filename ($!)");
1940       my @rows = <$file>;
1941       close($file);
1942       return join('', @rows);
1943   }
1944
1945   $self->throw_exception(q{Can't deploy without SQL::Translator 0.09003: '}
1946       . $self->_check_sqlt_message . q{'})
1947           if !$self->_check_sqlt_version;
1948
1949   require SQL::Translator::Parser::DBIx::Class;
1950   eval qq{use SQL::Translator::Producer::${type}};
1951   $self->throw_exception($@) if $@;
1952
1953   # sources needs to be a parser arg, but for simplicty allow at top level 
1954   # coming in
1955   $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
1956       if exists $sqltargs->{sources};
1957
1958   my $tr = SQL::Translator->new(%$sqltargs);
1959   SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
1960   return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
1961 }
1962
1963 sub deploy {
1964   my ($self, $schema, $type, $sqltargs, $dir) = @_;
1965   my $deploy = sub {
1966     my $line = shift;
1967     return if($line =~ /^--/);
1968     return if(!$line);
1969     # next if($line =~ /^DROP/m);
1970     return if($line =~ /^BEGIN TRANSACTION/m);
1971     return if($line =~ /^COMMIT/m);
1972     return if $line =~ /^\s+$/; # skip whitespace only
1973     $self->_query_start($line);
1974     eval {
1975       $self->dbh->do($line); # shouldn't be using ->dbh ?
1976     };
1977     if ($@) {
1978       carp qq{$@ (running "${line}")};
1979     }
1980     $self->_query_end($line);
1981   };
1982   my @statements = $self->deployment_statements($schema, $type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );
1983   if (@statements > 1) {
1984     foreach my $statement (@statements) {
1985       $deploy->( $statement );
1986     }
1987   }
1988   elsif (@statements == 1) {
1989     foreach my $line ( split(";\n", $statements[0])) {
1990       $deploy->( $line );
1991     }
1992   }
1993 }
1994
1995 =head2 datetime_parser
1996
1997 Returns the datetime parser class
1998
1999 =cut
2000
2001 sub datetime_parser {
2002   my $self = shift;
2003   return $self->{datetime_parser} ||= do {
2004     $self->ensure_connected;
2005     $self->build_datetime_parser(@_);
2006   };
2007 }
2008
2009 =head2 datetime_parser_type
2010
2011 Defines (returns) the datetime parser class - currently hardwired to
2012 L<DateTime::Format::MySQL>
2013
2014 =cut
2015
2016 sub datetime_parser_type { "DateTime::Format::MySQL"; }
2017
2018 =head2 build_datetime_parser
2019
2020 See L</datetime_parser>
2021
2022 =cut
2023
2024 sub build_datetime_parser {
2025   my $self = shift;
2026   my $type = $self->datetime_parser_type(@_);
2027   eval "use ${type}";
2028   $self->throw_exception("Couldn't load ${type}: $@") if $@;
2029   return $type;
2030 }
2031
2032 {
2033     my $_check_sqlt_version; # private
2034     my $_check_sqlt_message; # private
2035     sub _check_sqlt_version {
2036         return $_check_sqlt_version if defined $_check_sqlt_version;
2037         eval 'use SQL::Translator "0.09003"';
2038         $_check_sqlt_message = $@ || '';
2039         $_check_sqlt_version = !$@;
2040     }
2041
2042     sub _check_sqlt_message {
2043         _check_sqlt_version if !defined $_check_sqlt_message;
2044         $_check_sqlt_message;
2045     }
2046 }
2047
2048 =head2 is_replicating
2049
2050 A boolean that reports if a particular L<DBIx::Class::Storage::DBI> is set to
2051 replicate from a master database.  Default is undef, which is the result
2052 returned by databases that don't support replication.
2053
2054 =cut
2055
2056 sub is_replicating {
2057     return;
2058     
2059 }
2060
2061 =head2 lag_behind_master
2062
2063 Returns a number that represents a certain amount of lag behind a master db
2064 when a given storage is replicating.  The number is database dependent, but
2065 starts at zero and increases with the amount of lag. Default in undef
2066
2067 =cut
2068
2069 sub lag_behind_master {
2070     return;
2071 }
2072
2073 sub DESTROY {
2074   my $self = shift;
2075   return if !$self->_dbh;
2076   $self->_verify_pid;
2077   $self->_dbh(undef);
2078 }
2079
2080 1;
2081
2082 =head1 USAGE NOTES
2083
2084 =head2 DBIx::Class and AutoCommit
2085
2086 DBIx::Class can do some wonderful magic with handling exceptions,
2087 disconnections, and transactions when you use C<< AutoCommit => 1 >>
2088 combined with C<txn_do> for transaction support.
2089
2090 If you set C<< AutoCommit => 0 >> in your connect info, then you are always
2091 in an assumed transaction between commits, and you're telling us you'd
2092 like to manage that manually.  A lot of the magic protections offered by
2093 this module will go away.  We can't protect you from exceptions due to database
2094 disconnects because we don't know anything about how to restart your
2095 transactions.  You're on your own for handling all sorts of exceptional
2096 cases if you choose the C<< AutoCommit => 0 >> path, just as you would
2097 be with raw DBI.
2098
2099
2100
2101 =head1 AUTHORS
2102
2103 Matt S. Trout <mst@shadowcatsystems.co.uk>
2104
2105 Andy Grundman <andy@hybridized.org>
2106
2107 =head1 LICENSE
2108
2109 You may distribute this code under the same terms as Perl itself.
2110
2111 =cut