s/_get_server_info/_populate_server_info/
[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 strict;
5 use warnings;
6
7 use base qw/DBIx::Class::Storage::DBIHacks DBIx::Class::Storage/;
8 use mro 'c3';
9
10 use Carp::Clan qw/^DBIx::Class/;
11 use DBI;
12 use DBIx::Class::Storage::DBI::Cursor;
13 use DBIx::Class::Storage::Statistics;
14 use Scalar::Util();
15 use List::Util();
16 use Data::Dumper::Concise();
17 use Sub::Name ();
18
19 __PACKAGE__->mk_group_accessors('simple' =>
20   qw/_connect_info _dbi_connect_info _dbh _sql_maker _sql_maker_opts _conn_pid
21      _conn_tid transaction_depth _dbh_autocommit _driver_determined savepoints
22      _server_info/
23 );
24
25 # the values for these accessors are picked out (and deleted) from
26 # the attribute hashref passed to connect_info
27 my @storage_options = qw/
28   on_connect_call on_disconnect_call on_connect_do on_disconnect_do
29   disable_sth_caching unsafe auto_savepoint
30 /;
31 __PACKAGE__->mk_group_accessors('simple' => @storage_options);
32
33
34 # default cursor class, overridable in connect_info attributes
35 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
36
37 __PACKAGE__->mk_group_accessors('inherited' => qw/
38   sql_maker_class
39   can_insert_returning
40 /);
41 __PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks');
42
43
44 # Each of these methods need _determine_driver called before itself
45 # in order to function reliably. This is a purely DRY optimization
46 my @rdbms_specific_methods = qw/
47   deployment_statements
48   sqlt_type
49   build_datetime_parser
50   datetime_parser_type
51
52   insert
53   insert_bulk
54   update
55   delete
56   select
57   select_single
58 /;
59
60 for my $meth (@rdbms_specific_methods) {
61
62   my $orig = __PACKAGE__->can ($meth)
63     or next;
64
65   no strict qw/refs/;
66   no warnings qw/redefine/;
67   *{__PACKAGE__ ."::$meth"} = Sub::Name::subname $meth => sub {
68     if (not $_[0]->_driver_determined) {
69       $_[0]->_determine_driver;
70       goto $_[0]->can($meth);
71     }
72     $orig->(@_);
73   };
74 }
75
76
77 =head1 NAME
78
79 DBIx::Class::Storage::DBI - DBI storage handler
80
81 =head1 SYNOPSIS
82
83   my $schema = MySchema->connect('dbi:SQLite:my.db');
84
85   $schema->storage->debug(1);
86
87   my @stuff = $schema->storage->dbh_do(
88     sub {
89       my ($storage, $dbh, @args) = @_;
90       $dbh->do("DROP TABLE authors");
91     },
92     @column_list
93   );
94
95   $schema->resultset('Book')->search({
96      written_on => $schema->storage->datetime_parser(DateTime->now)
97   });
98
99 =head1 DESCRIPTION
100
101 This class represents the connection to an RDBMS via L<DBI>.  See
102 L<DBIx::Class::Storage> for general information.  This pod only
103 documents DBI-specific methods and behaviors.
104
105 =head1 METHODS
106
107 =cut
108
109 sub new {
110   my $new = shift->next::method(@_);
111
112   $new->transaction_depth(0);
113   $new->_sql_maker_opts({});
114   $new->{savepoints} = [];
115   $new->{_in_dbh_do} = 0;
116   $new->{_dbh_gen} = 0;
117
118   $new;
119 }
120
121 =head2 connect_info
122
123 This method is normally called by L<DBIx::Class::Schema/connection>, which
124 encapsulates its argument list in an arrayref before passing them here.
125
126 The argument list may contain:
127
128 =over
129
130 =item *
131
132 The same 4-element argument set one would normally pass to
133 L<DBI/connect>, optionally followed by
134 L<extra attributes|/DBIx::Class specific connection attributes>
135 recognized by DBIx::Class:
136
137   $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
138
139 =item *
140
141 A single code reference which returns a connected
142 L<DBI database handle|DBI/connect> optionally followed by
143 L<extra attributes|/DBIx::Class specific connection attributes> recognized
144 by DBIx::Class:
145
146   $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
147
148 =item *
149
150 A single hashref with all the attributes and the dsn/user/password
151 mixed together:
152
153   $connect_info_args = [{
154     dsn => $dsn,
155     user => $user,
156     password => $pass,
157     %dbi_attributes,
158     %extra_attributes,
159   }];
160
161   $connect_info_args = [{
162     dbh_maker => sub { DBI->connect (...) },
163     %dbi_attributes,
164     %extra_attributes,
165   }];
166
167 This is particularly useful for L<Catalyst> based applications, allowing the
168 following config (L<Config::General> style):
169
170   <Model::DB>
171     schema_class   App::DB
172     <connect_info>
173       dsn          dbi:mysql:database=test
174       user         testuser
175       password     TestPass
176       AutoCommit   1
177     </connect_info>
178   </Model::DB>
179
180 The C<dsn>/C<user>/C<password> combination can be substituted by the
181 C<dbh_maker> key whose value is a coderef that returns a connected
182 L<DBI database handle|DBI/connect>
183
184 =back
185
186 Please note that the L<DBI> docs recommend that you always explicitly
187 set C<AutoCommit> to either I<0> or I<1>.  L<DBIx::Class> further
188 recommends that it be set to I<1>, and that you perform transactions
189 via our L<DBIx::Class::Schema/txn_do> method.  L<DBIx::Class> will set it
190 to I<1> if you do not do explicitly set it to zero.  This is the default
191 for most DBDs. See L</DBIx::Class and AutoCommit> for details.
192
193 =head3 DBIx::Class specific connection attributes
194
195 In addition to the standard L<DBI|DBI/ATTRIBUTES_COMMON_TO_ALL_HANDLES>
196 L<connection|DBI/Database_Handle_Attributes> attributes, DBIx::Class recognizes
197 the following connection options. These options can be mixed in with your other
198 L<DBI> connection attributes, or placed in a separate hashref
199 (C<\%extra_attributes>) as shown above.
200
201 Every time C<connect_info> is invoked, any previous settings for
202 these options will be cleared before setting the new ones, regardless of
203 whether any options are specified in the new C<connect_info>.
204
205
206 =over
207
208 =item on_connect_do
209
210 Specifies things to do immediately after connecting or re-connecting to
211 the database.  Its value may contain:
212
213 =over
214
215 =item a scalar
216
217 This contains one SQL statement to execute.
218
219 =item an array reference
220
221 This contains SQL statements to execute in order.  Each element contains
222 a string or a code reference that returns a string.
223
224 =item a code reference
225
226 This contains some code to execute.  Unlike code references within an
227 array reference, its return value is ignored.
228
229 =back
230
231 =item on_disconnect_do
232
233 Takes arguments in the same form as L</on_connect_do> and executes them
234 immediately before disconnecting from the database.
235
236 Note, this only runs if you explicitly call L</disconnect> on the
237 storage object.
238
239 =item on_connect_call
240
241 A more generalized form of L</on_connect_do> that calls the specified
242 C<connect_call_METHOD> methods in your storage driver.
243
244   on_connect_do => 'select 1'
245
246 is equivalent to:
247
248   on_connect_call => [ [ do_sql => 'select 1' ] ]
249
250 Its values may contain:
251
252 =over
253
254 =item a scalar
255
256 Will call the C<connect_call_METHOD> method.
257
258 =item a code reference
259
260 Will execute C<< $code->($storage) >>
261
262 =item an array reference
263
264 Each value can be a method name or code reference.
265
266 =item an array of arrays
267
268 For each array, the first item is taken to be the C<connect_call_> method name
269 or code reference, and the rest are parameters to it.
270
271 =back
272
273 Some predefined storage methods you may use:
274
275 =over
276
277 =item do_sql
278
279 Executes a SQL string or a code reference that returns a SQL string. This is
280 what L</on_connect_do> and L</on_disconnect_do> use.
281
282 It can take:
283
284 =over
285
286 =item a scalar
287
288 Will execute the scalar as SQL.
289
290 =item an arrayref
291
292 Taken to be arguments to L<DBI/do>, the SQL string optionally followed by the
293 attributes hashref and bind values.
294
295 =item a code reference
296
297 Will execute C<< $code->($storage) >> and execute the return array refs as
298 above.
299
300 =back
301
302 =item datetime_setup
303
304 Execute any statements necessary to initialize the database session to return
305 and accept datetime/timestamp values used with
306 L<DBIx::Class::InflateColumn::DateTime>.
307
308 Only necessary for some databases, see your specific storage driver for
309 implementation details.
310
311 =back
312
313 =item on_disconnect_call
314
315 Takes arguments in the same form as L</on_connect_call> and executes them
316 immediately before disconnecting from the database.
317
318 Calls the C<disconnect_call_METHOD> methods as opposed to the
319 C<connect_call_METHOD> methods called by L</on_connect_call>.
320
321 Note, this only runs if you explicitly call L</disconnect> on the
322 storage object.
323
324 =item disable_sth_caching
325
326 If set to a true value, this option will disable the caching of
327 statement handles via L<DBI/prepare_cached>.
328
329 =item limit_dialect
330
331 Sets the limit dialect. This is useful for JDBC-bridge among others
332 where the remote SQL-dialect cannot be determined by the name of the
333 driver alone. See also L<SQL::Abstract::Limit>.
334
335 =item quote_char
336
337 Specifies what characters to use to quote table and column names. If
338 you use this you will want to specify L</name_sep> as well.
339
340 C<quote_char> expects either a single character, in which case is it
341 is placed on either side of the table/column name, or an arrayref of length
342 2 in which case the table/column name is placed between the elements.
343
344 For example under MySQL you should use C<< quote_char => '`' >>, and for
345 SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
346
347 =item name_sep
348
349 This only needs to be used in conjunction with C<quote_char>, and is used to
350 specify the character that separates elements (schemas, tables, columns) from
351 each other. In most cases this is simply a C<.>.
352
353 The consequences of not supplying this value is that L<SQL::Abstract>
354 will assume DBIx::Class' uses of aliases to be complete column
355 names. The output will look like I<"me.name"> when it should actually
356 be I<"me"."name">.
357
358 =item unsafe
359
360 This Storage driver normally installs its own C<HandleError>, sets
361 C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
362 all database handles, including those supplied by a coderef.  It does this
363 so that it can have consistent and useful error behavior.
364
365 If you set this option to a true value, Storage will not do its usual
366 modifications to the database handle's attributes, and instead relies on
367 the settings in your connect_info DBI options (or the values you set in
368 your connection coderef, in the case that you are connecting via coderef).
369
370 Note that your custom settings can cause Storage to malfunction,
371 especially if you set a C<HandleError> handler that suppresses exceptions
372 and/or disable C<RaiseError>.
373
374 =item auto_savepoint
375
376 If this option is true, L<DBIx::Class> will use savepoints when nesting
377 transactions, making it possible to recover from failure in the inner
378 transaction without having to abort all outer transactions.
379
380 =item cursor_class
381
382 Use this argument to supply a cursor class other than the default
383 L<DBIx::Class::Storage::DBI::Cursor>.
384
385 =back
386
387 Some real-life examples of arguments to L</connect_info> and
388 L<DBIx::Class::Schema/connect>
389
390   # Simple SQLite connection
391   ->connect_info([ 'dbi:SQLite:./foo.db' ]);
392
393   # Connect via subref
394   ->connect_info([ sub { DBI->connect(...) } ]);
395
396   # Connect via subref in hashref
397   ->connect_info([{
398     dbh_maker => sub { DBI->connect(...) },
399     on_connect_do => 'alter session ...',
400   }]);
401
402   # A bit more complicated
403   ->connect_info(
404     [
405       'dbi:Pg:dbname=foo',
406       'postgres',
407       'my_pg_password',
408       { AutoCommit => 1 },
409       { quote_char => q{"}, name_sep => q{.} },
410     ]
411   );
412
413   # Equivalent to the previous example
414   ->connect_info(
415     [
416       'dbi:Pg:dbname=foo',
417       'postgres',
418       'my_pg_password',
419       { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
420     ]
421   );
422
423   # Same, but with hashref as argument
424   # See parse_connect_info for explanation
425   ->connect_info(
426     [{
427       dsn         => 'dbi:Pg:dbname=foo',
428       user        => 'postgres',
429       password    => 'my_pg_password',
430       AutoCommit  => 1,
431       quote_char  => q{"},
432       name_sep    => q{.},
433     }]
434   );
435
436   # Subref + DBIx::Class-specific connection options
437   ->connect_info(
438     [
439       sub { DBI->connect(...) },
440       {
441           quote_char => q{`},
442           name_sep => q{@},
443           on_connect_do => ['SET search_path TO myschema,otherschema,public'],
444           disable_sth_caching => 1,
445       },
446     ]
447   );
448
449
450
451 =cut
452
453 sub connect_info {
454   my ($self, $info) = @_;
455
456   return $self->_connect_info if !$info;
457
458   $self->_connect_info($info); # copy for _connect_info
459
460   $info = $self->_normalize_connect_info($info)
461     if ref $info eq 'ARRAY';
462
463   for my $storage_opt (keys %{ $info->{storage_options} }) {
464     my $value = $info->{storage_options}{$storage_opt};
465
466     $self->$storage_opt($value);
467   }
468
469   # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
470   #  the new set of options
471   $self->_sql_maker(undef);
472   $self->_sql_maker_opts({});
473
474   for my $sql_maker_opt (keys %{ $info->{sql_maker_options} }) {
475     my $value = $info->{sql_maker_options}{$sql_maker_opt};
476
477     $self->_sql_maker_opts->{$sql_maker_opt} = $value;
478   }
479
480   my %attrs = (
481     %{ $self->_default_dbi_connect_attributes || {} },
482     %{ $info->{attributes} || {} },
483   );
484
485   my @args = @{ $info->{arguments} };
486
487   $self->_dbi_connect_info([@args,
488     %attrs && !(ref $args[0] eq 'CODE') ? \%attrs : ()]);
489
490   return $self->_connect_info;
491 }
492
493 sub _normalize_connect_info {
494   my ($self, $info_arg) = @_;
495   my %info;
496
497   my @args = @$info_arg;  # take a shallow copy for further mutilation
498
499   # combine/pre-parse arguments depending on invocation style
500
501   my %attrs;
502   if (ref $args[0] eq 'CODE') {     # coderef with optional \%extra_attributes
503     %attrs = %{ $args[1] || {} };
504     @args = $args[0];
505   }
506   elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
507     %attrs = %{$args[0]};
508     @args = ();
509     if (my $code = delete $attrs{dbh_maker}) {
510       @args = $code;
511
512       my @ignored = grep { delete $attrs{$_} } (qw/dsn user password/);
513       if (@ignored) {
514         carp sprintf (
515             'Attribute(s) %s in connect_info were ignored, as they can not be applied '
516           . "to the result of 'dbh_maker'",
517
518           join (', ', map { "'$_'" } (@ignored) ),
519         );
520       }
521     }
522     else {
523       @args = delete @attrs{qw/dsn user password/};
524     }
525   }
526   else {                # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
527     %attrs = (
528       % { $args[3] || {} },
529       % { $args[4] || {} },
530     );
531     @args = @args[0,1,2];
532   }
533
534   $info{arguments} = \@args;
535
536   my @storage_opts = grep exists $attrs{$_},
537     @storage_options, 'cursor_class';
538
539   @{ $info{storage_options} }{@storage_opts} =
540     delete @attrs{@storage_opts} if @storage_opts;
541
542   my @sql_maker_opts = grep exists $attrs{$_},
543     qw/limit_dialect quote_char name_sep/;
544
545   @{ $info{sql_maker_options} }{@sql_maker_opts} =
546     delete @attrs{@sql_maker_opts} if @sql_maker_opts;
547
548   $info{attributes} = \%attrs if %attrs;
549
550   return \%info;
551 }
552
553 sub _default_dbi_connect_attributes {
554   return {
555     AutoCommit => 1,
556     RaiseError => 1,
557     PrintError => 0,
558   };
559 }
560
561 =head2 on_connect_do
562
563 This method is deprecated in favour of setting via L</connect_info>.
564
565 =cut
566
567 =head2 on_disconnect_do
568
569 This method is deprecated in favour of setting via L</connect_info>.
570
571 =cut
572
573 sub _parse_connect_do {
574   my ($self, $type) = @_;
575
576   my $val = $self->$type;
577   return () if not defined $val;
578
579   my @res;
580
581   if (not ref($val)) {
582     push @res, [ 'do_sql', $val ];
583   } elsif (ref($val) eq 'CODE') {
584     push @res, $val;
585   } elsif (ref($val) eq 'ARRAY') {
586     push @res, map { [ 'do_sql', $_ ] } @$val;
587   } else {
588     $self->throw_exception("Invalid type for $type: ".ref($val));
589   }
590
591   return \@res;
592 }
593
594 =head2 dbh_do
595
596 Arguments: ($subref | $method_name), @extra_coderef_args?
597
598 Execute the given $subref or $method_name using the new exception-based
599 connection management.
600
601 The first two arguments will be the storage object that C<dbh_do> was called
602 on and a database handle to use.  Any additional arguments will be passed
603 verbatim to the called subref as arguments 2 and onwards.
604
605 Using this (instead of $self->_dbh or $self->dbh) ensures correct
606 exception handling and reconnection (or failover in future subclasses).
607
608 Your subref should have no side-effects outside of the database, as
609 there is the potential for your subref to be partially double-executed
610 if the database connection was stale/dysfunctional.
611
612 Example:
613
614   my @stuff = $schema->storage->dbh_do(
615     sub {
616       my ($storage, $dbh, @cols) = @_;
617       my $cols = join(q{, }, @cols);
618       $dbh->selectrow_array("SELECT $cols FROM foo");
619     },
620     @column_list
621   );
622
623 =cut
624
625 sub dbh_do {
626   my $self = shift;
627   my $code = shift;
628
629   my $dbh = $self->_get_dbh;
630
631   return $self->$code($dbh, @_) if $self->{_in_dbh_do}
632       || $self->{transaction_depth};
633
634   local $self->{_in_dbh_do} = 1;
635
636   my @result;
637   my $want_array = wantarray;
638
639   eval {
640
641     if($want_array) {
642         @result = $self->$code($dbh, @_);
643     }
644     elsif(defined $want_array) {
645         $result[0] = $self->$code($dbh, @_);
646     }
647     else {
648         $self->$code($dbh, @_);
649     }
650   };
651
652   # ->connected might unset $@ - copy
653   my $exception = $@;
654   if(!$exception) { return $want_array ? @result : $result[0] }
655
656   $self->throw_exception($exception) if $self->connected;
657
658   # We were not connected - reconnect and retry, but let any
659   #  exception fall right through this time
660   carp "Retrying $code after catching disconnected exception: $exception"
661     if $ENV{DBIC_DBIRETRY_DEBUG};
662   $self->_populate_dbh;
663   $self->$code($self->_dbh, @_);
664 }
665
666 # This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do.
667 # It also informs dbh_do to bypass itself while under the direction of txn_do,
668 #  via $self->{_in_dbh_do} (this saves some redundant eval and errorcheck, etc)
669 sub txn_do {
670   my $self = shift;
671   my $coderef = shift;
672
673   ref $coderef eq 'CODE' or $self->throw_exception
674     ('$coderef must be a CODE reference');
675
676   return $coderef->(@_) if $self->{transaction_depth} && ! $self->auto_savepoint;
677
678   local $self->{_in_dbh_do} = 1;
679
680   my @result;
681   my $want_array = wantarray;
682
683   my $tried = 0;
684   while(1) {
685     eval {
686       $self->_get_dbh;
687
688       $self->txn_begin;
689       if($want_array) {
690           @result = $coderef->(@_);
691       }
692       elsif(defined $want_array) {
693           $result[0] = $coderef->(@_);
694       }
695       else {
696           $coderef->(@_);
697       }
698       $self->txn_commit;
699     };
700
701     # ->connected might unset $@ - copy
702     my $exception = $@;
703     if(!$exception) { return $want_array ? @result : $result[0] }
704
705     if($tried++ || $self->connected) {
706       eval { $self->txn_rollback };
707       my $rollback_exception = $@;
708       if($rollback_exception) {
709         my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
710         $self->throw_exception($exception)  # propagate nested rollback
711           if $rollback_exception =~ /$exception_class/;
712
713         $self->throw_exception(
714           "Transaction aborted: ${exception}. "
715           . "Rollback failed: ${rollback_exception}"
716         );
717       }
718       $self->throw_exception($exception)
719     }
720
721     # We were not connected, and was first try - reconnect and retry
722     # via the while loop
723     carp "Retrying $coderef after catching disconnected exception: $exception"
724       if $ENV{DBIC_DBIRETRY_DEBUG};
725     $self->_populate_dbh;
726   }
727 }
728
729 =head2 disconnect
730
731 Our C<disconnect> method also performs a rollback first if the
732 database is not in C<AutoCommit> mode.
733
734 =cut
735
736 sub disconnect {
737   my ($self) = @_;
738
739   if( $self->_dbh ) {
740     my @actions;
741
742     push @actions, ( $self->on_disconnect_call || () );
743     push @actions, $self->_parse_connect_do ('on_disconnect_do');
744
745     $self->_do_connection_actions(disconnect_call_ => $_) for @actions;
746
747     $self->_dbh_rollback unless $self->_dbh_autocommit;
748
749     %{ $self->_dbh->{CachedKids} } = ();
750     $self->_dbh->disconnect;
751     $self->_dbh(undef);
752     $self->{_dbh_gen}++;
753   }
754 }
755
756 =head2 with_deferred_fk_checks
757
758 =over 4
759
760 =item Arguments: C<$coderef>
761
762 =item Return Value: The return value of $coderef
763
764 =back
765
766 Storage specific method to run the code ref with FK checks deferred or
767 in MySQL's case disabled entirely.
768
769 =cut
770
771 # Storage subclasses should override this
772 sub with_deferred_fk_checks {
773   my ($self, $sub) = @_;
774   $sub->();
775 }
776
777 =head2 connected
778
779 =over
780
781 =item Arguments: none
782
783 =item Return Value: 1|0
784
785 =back
786
787 Verifies that the current database handle is active and ready to execute
788 an SQL statement (e.g. the connection did not get stale, server is still
789 answering, etc.) This method is used internally by L</dbh>.
790
791 =cut
792
793 sub connected {
794   my $self = shift;
795   return 0 unless $self->_seems_connected;
796
797   #be on the safe side
798   local $self->_dbh->{RaiseError} = 1;
799
800   return $self->_ping;
801 }
802
803 sub _seems_connected {
804   my $self = shift;
805
806   my $dbh = $self->_dbh
807     or return 0;
808
809   if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
810     $self->_dbh(undef);
811     $self->{_dbh_gen}++;
812     return 0;
813   }
814   else {
815     $self->_verify_pid;
816     return 0 if !$self->_dbh;
817   }
818
819   return $dbh->FETCH('Active');
820 }
821
822 sub _ping {
823   my $self = shift;
824
825   my $dbh = $self->_dbh or return 0;
826
827   return $dbh->ping;
828 }
829
830 # handle pid changes correctly
831 #  NOTE: assumes $self->_dbh is a valid $dbh
832 sub _verify_pid {
833   my ($self) = @_;
834
835   return if defined $self->_conn_pid && $self->_conn_pid == $$;
836
837   $self->_dbh->{InactiveDestroy} = 1;
838   $self->_dbh(undef);
839   $self->{_dbh_gen}++;
840
841   return;
842 }
843
844 sub ensure_connected {
845   my ($self) = @_;
846
847   unless ($self->connected) {
848     $self->_populate_dbh;
849   }
850 }
851
852 =head2 dbh
853
854 Returns a C<$dbh> - a data base handle of class L<DBI>. The returned handle
855 is guaranteed to be healthy by implicitly calling L</connected>, and if
856 necessary performing a reconnection before returning. Keep in mind that this
857 is very B<expensive> on some database engines. Consider using L</dbh_do>
858 instead.
859
860 =cut
861
862 sub dbh {
863   my ($self) = @_;
864
865   if (not $self->_dbh) {
866     $self->_populate_dbh;
867   } else {
868     $self->ensure_connected;
869   }
870   return $self->_dbh;
871 }
872
873 # this is the internal "get dbh or connect (don't check)" method
874 sub _get_dbh {
875   my $self = shift;
876   $self->_verify_pid if $self->_dbh;
877   $self->_populate_dbh unless $self->_dbh;
878   return $self->_dbh;
879 }
880
881 sub _sql_maker_args {
882     my ($self) = @_;
883
884     return (
885       bindtype=>'columns',
886       array_datatypes => 1,
887       limit_dialect => $self->_get_dbh,
888       %{$self->_sql_maker_opts}
889     );
890 }
891
892 sub sql_maker {
893   my ($self) = @_;
894   unless ($self->_sql_maker) {
895     my $sql_maker_class = $self->sql_maker_class;
896     $self->ensure_class_loaded ($sql_maker_class);
897     $self->_sql_maker($sql_maker_class->new( $self->_sql_maker_args ));
898   }
899   return $self->_sql_maker;
900 }
901
902 # nothing to do by default
903 sub _rebless {}
904 sub _init {}
905
906 sub _populate_dbh {
907   my ($self) = @_;
908
909   my @info = @{$self->_dbi_connect_info || []};
910   $self->_dbh(undef); # in case ->connected failed we might get sent here
911   $self->_dbh($self->_connect(@info));
912
913   $self->_conn_pid($$);
914   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
915
916   $self->_determine_driver;
917
918   # Always set the transaction depth on connect, since
919   #  there is no transaction in progress by definition
920   $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
921
922   $self->_run_connection_actions unless $self->{_in_determine_driver};
923
924   $self->_populate_server_info;
925 }
926
927 sub _run_connection_actions {
928   my $self = shift;
929   my @actions;
930
931   push @actions, ( $self->on_connect_call || () );
932   push @actions, $self->_parse_connect_do ('on_connect_do');
933
934   $self->_do_connection_actions(connect_call_ => $_) for @actions;
935 }
936
937 sub _populate_server_info {
938   my $self = shift;
939   my %info;
940
941   my $dbms_ver = eval { local $@; $self->_get_dbh->get_info(18) };
942
943   $info{dbms_ver} = $dbms_ver if defined $dbms_ver;
944
945   $self->_server_info(\%info);
946
947   return \%info;
948 }
949
950 sub _determine_driver {
951   my ($self) = @_;
952
953   if ((not $self->_driver_determined) && (not $self->{_in_determine_driver})) {
954     my $started_connected = 0;
955     local $self->{_in_determine_driver} = 1;
956
957     if (ref($self) eq __PACKAGE__) {
958       my $driver;
959       if ($self->_dbh) { # we are connected
960         $driver = $self->_dbh->{Driver}{Name};
961         $started_connected = 1;
962       } else {
963         # if connect_info is a CODEREF, we have no choice but to connect
964         if (ref $self->_dbi_connect_info->[0] &&
965             Scalar::Util::reftype($self->_dbi_connect_info->[0]) eq 'CODE') {
966           $self->_populate_dbh;
967           $driver = $self->_dbh->{Driver}{Name};
968         }
969         else {
970           # try to use dsn to not require being connected, the driver may still
971           # force a connection in _rebless to determine version
972           # (dsn may not be supplied at all if all we do is make a mock-schema)
973           my $dsn = $self->_dbi_connect_info->[0] || '';
974           ($driver) = $dsn =~ /dbi:([^:]+):/i;
975         }
976       }
977
978       if ($driver) {
979         my $storage_class = "DBIx::Class::Storage::DBI::${driver}";
980         if ($self->load_optional_class($storage_class)) {
981           mro::set_mro($storage_class, 'c3');
982           bless $self, $storage_class;
983           $self->_rebless();
984         }
985       }
986     }
987
988     $self->_driver_determined(1);
989
990     $self->_init; # run driver-specific initializations
991
992     $self->_run_connection_actions
993         if !$started_connected && defined $self->_dbh;
994   }
995 }
996
997 sub _do_connection_actions {
998   my $self          = shift;
999   my $method_prefix = shift;
1000   my $call          = shift;
1001
1002   if (not ref($call)) {
1003     my $method = $method_prefix . $call;
1004     $self->$method(@_);
1005   } elsif (ref($call) eq 'CODE') {
1006     $self->$call(@_);
1007   } elsif (ref($call) eq 'ARRAY') {
1008     if (ref($call->[0]) ne 'ARRAY') {
1009       $self->_do_connection_actions($method_prefix, $_) for @$call;
1010     } else {
1011       $self->_do_connection_actions($method_prefix, @$_) for @$call;
1012     }
1013   } else {
1014     $self->throw_exception (sprintf ("Don't know how to process conection actions of type '%s'", ref($call)) );
1015   }
1016
1017   return $self;
1018 }
1019
1020 sub connect_call_do_sql {
1021   my $self = shift;
1022   $self->_do_query(@_);
1023 }
1024
1025 sub disconnect_call_do_sql {
1026   my $self = shift;
1027   $self->_do_query(@_);
1028 }
1029
1030 # override in db-specific backend when necessary
1031 sub connect_call_datetime_setup { 1 }
1032
1033 sub _do_query {
1034   my ($self, $action) = @_;
1035
1036   if (ref $action eq 'CODE') {
1037     $action = $action->($self);
1038     $self->_do_query($_) foreach @$action;
1039   }
1040   else {
1041     # Most debuggers expect ($sql, @bind), so we need to exclude
1042     # the attribute hash which is the second argument to $dbh->do
1043     # furthermore the bind values are usually to be presented
1044     # as named arrayref pairs, so wrap those here too
1045     my @do_args = (ref $action eq 'ARRAY') ? (@$action) : ($action);
1046     my $sql = shift @do_args;
1047     my $attrs = shift @do_args;
1048     my @bind = map { [ undef, $_ ] } @do_args;
1049
1050     $self->_query_start($sql, @bind);
1051     $self->_get_dbh->do($sql, $attrs, @do_args);
1052     $self->_query_end($sql, @bind);
1053   }
1054
1055   return $self;
1056 }
1057
1058 sub _connect {
1059   my ($self, @info) = @_;
1060
1061   $self->throw_exception("You failed to provide any connection info")
1062     if !@info;
1063
1064   my ($old_connect_via, $dbh);
1065
1066   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
1067     $old_connect_via = $DBI::connect_via;
1068     $DBI::connect_via = 'connect';
1069   }
1070
1071   eval {
1072     if(ref $info[0] eq 'CODE') {
1073        $dbh = $info[0]->();
1074     }
1075     else {
1076        $dbh = DBI->connect(@info);
1077     }
1078
1079     if($dbh && !$self->unsafe) {
1080       my $weak_self = $self;
1081       Scalar::Util::weaken($weak_self);
1082       $dbh->{HandleError} = sub {
1083           if ($weak_self) {
1084             $weak_self->throw_exception("DBI Exception: $_[0]");
1085           }
1086           else {
1087             # the handler may be invoked by something totally out of
1088             # the scope of DBIC
1089             croak ("DBI Exception: $_[0]");
1090           }
1091       };
1092       $dbh->{ShowErrorStatement} = 1;
1093       $dbh->{RaiseError} = 1;
1094       $dbh->{PrintError} = 0;
1095     }
1096   };
1097
1098   $DBI::connect_via = $old_connect_via if $old_connect_via;
1099
1100   $self->throw_exception("DBI Connection failed: " . ($@||$DBI::errstr))
1101     if !$dbh || $@;
1102
1103   $self->_dbh_autocommit($dbh->{AutoCommit});
1104
1105   $dbh;
1106 }
1107
1108 sub svp_begin {
1109   my ($self, $name) = @_;
1110
1111   $name = $self->_svp_generate_name
1112     unless defined $name;
1113
1114   $self->throw_exception ("You can't use savepoints outside a transaction")
1115     if $self->{transaction_depth} == 0;
1116
1117   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1118     unless $self->can('_svp_begin');
1119
1120   push @{ $self->{savepoints} }, $name;
1121
1122   $self->debugobj->svp_begin($name) if $self->debug;
1123
1124   return $self->_svp_begin($name);
1125 }
1126
1127 sub svp_release {
1128   my ($self, $name) = @_;
1129
1130   $self->throw_exception ("You can't use savepoints outside a transaction")
1131     if $self->{transaction_depth} == 0;
1132
1133   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1134     unless $self->can('_svp_release');
1135
1136   if (defined $name) {
1137     $self->throw_exception ("Savepoint '$name' does not exist")
1138       unless grep { $_ eq $name } @{ $self->{savepoints} };
1139
1140     # Dig through the stack until we find the one we are releasing.  This keeps
1141     # the stack up to date.
1142     my $svp;
1143
1144     do { $svp = pop @{ $self->{savepoints} } } while $svp ne $name;
1145   } else {
1146     $name = pop @{ $self->{savepoints} };
1147   }
1148
1149   $self->debugobj->svp_release($name) if $self->debug;
1150
1151   return $self->_svp_release($name);
1152 }
1153
1154 sub svp_rollback {
1155   my ($self, $name) = @_;
1156
1157   $self->throw_exception ("You can't use savepoints outside a transaction")
1158     if $self->{transaction_depth} == 0;
1159
1160   $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1161     unless $self->can('_svp_rollback');
1162
1163   if (defined $name) {
1164       # If they passed us a name, verify that it exists in the stack
1165       unless(grep({ $_ eq $name } @{ $self->{savepoints} })) {
1166           $self->throw_exception("Savepoint '$name' does not exist!");
1167       }
1168
1169       # Dig through the stack until we find the one we are releasing.  This keeps
1170       # the stack up to date.
1171       while(my $s = pop(@{ $self->{savepoints} })) {
1172           last if($s eq $name);
1173       }
1174       # Add the savepoint back to the stack, as a rollback doesn't remove the
1175       # named savepoint, only everything after it.
1176       push(@{ $self->{savepoints} }, $name);
1177   } else {
1178       # We'll assume they want to rollback to the last savepoint
1179       $name = $self->{savepoints}->[-1];
1180   }
1181
1182   $self->debugobj->svp_rollback($name) if $self->debug;
1183
1184   return $self->_svp_rollback($name);
1185 }
1186
1187 sub _svp_generate_name {
1188     my ($self) = @_;
1189
1190     return 'savepoint_'.scalar(@{ $self->{'savepoints'} });
1191 }
1192
1193 sub txn_begin {
1194   my $self = shift;
1195
1196   # this means we have not yet connected and do not know the AC status
1197   # (e.g. coderef $dbh)
1198   $self->ensure_connected if (! defined $self->_dbh_autocommit);
1199
1200   if($self->{transaction_depth} == 0) {
1201     $self->debugobj->txn_begin()
1202       if $self->debug;
1203     $self->_dbh_begin_work;
1204   }
1205   elsif ($self->auto_savepoint) {
1206     $self->svp_begin;
1207   }
1208   $self->{transaction_depth}++;
1209 }
1210
1211 sub _dbh_begin_work {
1212   my $self = shift;
1213
1214   # if the user is utilizing txn_do - good for him, otherwise we need to
1215   # ensure that the $dbh is healthy on BEGIN.
1216   # We do this via ->dbh_do instead of ->dbh, so that the ->dbh "ping"
1217   # will be replaced by a failure of begin_work itself (which will be
1218   # then retried on reconnect)
1219   if ($self->{_in_dbh_do}) {
1220     $self->_dbh->begin_work;
1221   } else {
1222     $self->dbh_do(sub { $_[1]->begin_work });
1223   }
1224 }
1225
1226 sub txn_commit {
1227   my $self = shift;
1228   if ($self->{transaction_depth} == 1) {
1229     $self->debugobj->txn_commit()
1230       if ($self->debug);
1231     $self->_dbh_commit;
1232     $self->{transaction_depth} = 0
1233       if $self->_dbh_autocommit;
1234   }
1235   elsif($self->{transaction_depth} > 1) {
1236     $self->{transaction_depth}--;
1237     $self->svp_release
1238       if $self->auto_savepoint;
1239   }
1240 }
1241
1242 sub _dbh_commit {
1243   my $self = shift;
1244   my $dbh  = $self->_dbh
1245     or $self->throw_exception('cannot COMMIT on a disconnected handle');
1246   $dbh->commit;
1247 }
1248
1249 sub txn_rollback {
1250   my $self = shift;
1251   my $dbh = $self->_dbh;
1252   eval {
1253     if ($self->{transaction_depth} == 1) {
1254       $self->debugobj->txn_rollback()
1255         if ($self->debug);
1256       $self->{transaction_depth} = 0
1257         if $self->_dbh_autocommit;
1258       $self->_dbh_rollback;
1259     }
1260     elsif($self->{transaction_depth} > 1) {
1261       $self->{transaction_depth}--;
1262       if ($self->auto_savepoint) {
1263         $self->svp_rollback;
1264         $self->svp_release;
1265       }
1266     }
1267     else {
1268       die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
1269     }
1270   };
1271   if ($@) {
1272     my $error = $@;
1273     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
1274     $error =~ /$exception_class/ and $self->throw_exception($error);
1275     # ensure that a failed rollback resets the transaction depth
1276     $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
1277     $self->throw_exception($error);
1278   }
1279 }
1280
1281 sub _dbh_rollback {
1282   my $self = shift;
1283   my $dbh  = $self->_dbh
1284     or $self->throw_exception('cannot ROLLBACK on a disconnected handle');
1285   $dbh->rollback;
1286 }
1287
1288 # This used to be the top-half of _execute.  It was split out to make it
1289 #  easier to override in NoBindVars without duping the rest.  It takes up
1290 #  all of _execute's args, and emits $sql, @bind.
1291 sub _prep_for_execute {
1292   my ($self, $op, $extra_bind, $ident, $args) = @_;
1293
1294   if( Scalar::Util::blessed($ident) && $ident->isa("DBIx::Class::ResultSource") ) {
1295     $ident = $ident->from();
1296   }
1297
1298   my ($sql, @bind) = $self->sql_maker->$op($ident, @$args);
1299
1300   unshift(@bind,
1301     map { ref $_ eq 'ARRAY' ? $_ : [ '!!dummy', $_ ] } @$extra_bind)
1302       if $extra_bind;
1303   return ($sql, \@bind);
1304 }
1305
1306
1307 sub _fix_bind_params {
1308     my ($self, @bind) = @_;
1309
1310     ### Turn @bind from something like this:
1311     ###   ( [ "artist", 1 ], [ "cdid", 1, 3 ] )
1312     ### to this:
1313     ###   ( "'1'", "'1'", "'3'" )
1314     return
1315         map {
1316             if ( defined( $_ && $_->[1] ) ) {
1317                 map { qq{'$_'}; } @{$_}[ 1 .. $#$_ ];
1318             }
1319             else { q{'NULL'}; }
1320         } @bind;
1321 }
1322
1323 sub _query_start {
1324     my ( $self, $sql, @bind ) = @_;
1325
1326     if ( $self->debug ) {
1327         @bind = $self->_fix_bind_params(@bind);
1328
1329         $self->debugobj->query_start( $sql, @bind );
1330     }
1331 }
1332
1333 sub _query_end {
1334     my ( $self, $sql, @bind ) = @_;
1335
1336     if ( $self->debug ) {
1337         @bind = $self->_fix_bind_params(@bind);
1338         $self->debugobj->query_end( $sql, @bind );
1339     }
1340 }
1341
1342 sub _dbh_execute {
1343   my ($self, $dbh, $op, $extra_bind, $ident, $bind_attributes, @args) = @_;
1344
1345   my ($sql, $bind) = $self->_prep_for_execute($op, $extra_bind, $ident, \@args);
1346
1347   $self->_query_start( $sql, @$bind );
1348
1349   my $sth = $self->sth($sql,$op);
1350
1351   my $placeholder_index = 1;
1352
1353   foreach my $bound (@$bind) {
1354     my $attributes = {};
1355     my($column_name, @data) = @$bound;
1356
1357     if ($bind_attributes) {
1358       $attributes = $bind_attributes->{$column_name}
1359       if defined $bind_attributes->{$column_name};
1360     }
1361
1362     foreach my $data (@data) {
1363       my $ref = ref $data;
1364       $data = $ref && $ref ne 'ARRAY' ? ''.$data : $data; # stringify args (except arrayrefs)
1365
1366       $sth->bind_param($placeholder_index, $data, $attributes);
1367       $placeholder_index++;
1368     }
1369   }
1370
1371   # Can this fail without throwing an exception anyways???
1372   my $rv = $sth->execute();
1373   $self->throw_exception($sth->errstr) if !$rv;
1374
1375   $self->_query_end( $sql, @$bind );
1376
1377   return (wantarray ? ($rv, $sth, @$bind) : $rv);
1378 }
1379
1380 sub _execute {
1381     my $self = shift;
1382     $self->dbh_do('_dbh_execute', @_);  # retry over disconnects
1383 }
1384
1385 sub _prefetch_insert_auto_nextvals {
1386   my ($self, $source, $to_insert) = @_;
1387
1388   my $upd = {};
1389
1390   foreach my $col ( $source->columns ) {
1391     if ( !defined $to_insert->{$col} ) {
1392       my $col_info = $source->column_info($col);
1393
1394       if ( $col_info->{auto_nextval} ) {
1395         $upd->{$col} = $to_insert->{$col} = $self->_sequence_fetch(
1396           'nextval',
1397           $col_info->{sequence} ||=
1398             $self->_dbh_get_autoinc_seq($self->_get_dbh, $source, $col)
1399         );
1400       }
1401     }
1402   }
1403
1404   return $upd;
1405 }
1406
1407 sub insert {
1408   my $self = shift;
1409   my ($source, $to_insert, $opts) = @_;
1410
1411   my $updated_cols = $self->_prefetch_insert_auto_nextvals (@_);
1412
1413   my $bind_attributes = $self->source_bind_attributes($source);
1414
1415   my ($rv, $sth) = $self->_execute('insert' => [], $source, $bind_attributes, $to_insert, $opts);
1416
1417   if ($opts->{returning}) {
1418     my @ret_cols = @{$opts->{returning}};
1419
1420     my @ret_vals = eval {
1421       local $SIG{__WARN__} = sub {};
1422       my @r = $sth->fetchrow_array;
1423       $sth->finish;
1424       @r;
1425     };
1426
1427     my %ret;
1428     @ret{@ret_cols} = @ret_vals if (@ret_vals);
1429
1430     $updated_cols = {
1431       %$updated_cols,
1432       %ret,
1433     };
1434   }
1435
1436   return $updated_cols;
1437 }
1438
1439 ## Currently it is assumed that all values passed will be "normal", i.e. not
1440 ## scalar refs, or at least, all the same type as the first set, the statement is
1441 ## only prepped once.
1442 sub insert_bulk {
1443   my ($self, $source, $cols, $data) = @_;
1444
1445   my %colvalues;
1446   @colvalues{@$cols} = (0..$#$cols);
1447
1448   for my $i (0..$#$cols) {
1449     my $first_val = $data->[0][$i];
1450     next unless ref $first_val eq 'SCALAR';
1451
1452     $colvalues{ $cols->[$i] } = $first_val;
1453   }
1454
1455   # check for bad data and stringify stringifiable objects
1456   my $bad_slice = sub {
1457     my ($msg, $col_idx, $slice_idx) = @_;
1458     $self->throw_exception(sprintf "%s for column '%s' in populate slice:\n%s",
1459       $msg,
1460       $cols->[$col_idx],
1461       do {
1462         local $Data::Dumper::Maxdepth = 1; # don't dump objects, if any
1463         Data::Dumper::Concise::Dumper({
1464           map { $cols->[$_] => $data->[$slice_idx][$_] } (0 .. $#$cols)
1465         }),
1466       }
1467     );
1468   };
1469
1470   for my $datum_idx (0..$#$data) {
1471     my $datum = $data->[$datum_idx];
1472
1473     for my $col_idx (0..$#$cols) {
1474       my $val            = $datum->[$col_idx];
1475       my $sqla_bind      = $colvalues{ $cols->[$col_idx] };
1476       my $is_literal_sql = (ref $sqla_bind) eq 'SCALAR';
1477
1478       if ($is_literal_sql) {
1479         if (not ref $val) {
1480           $bad_slice->('bind found where literal SQL expected', $col_idx, $datum_idx);
1481         }
1482         elsif ((my $reftype = ref $val) ne 'SCALAR') {
1483           $bad_slice->("$reftype reference found where literal SQL expected",
1484             $col_idx, $datum_idx);
1485         }
1486         elsif ($$val ne $$sqla_bind){
1487           $bad_slice->("inconsistent literal SQL value, expecting: '$$sqla_bind'",
1488             $col_idx, $datum_idx);
1489         }
1490       }
1491       elsif (my $reftype = ref $val) {
1492         require overload;
1493         if (overload::Method($val, '""')) {
1494           $datum->[$col_idx] = "".$val;
1495         }
1496         else {
1497           $bad_slice->("$reftype reference found where bind expected",
1498             $col_idx, $datum_idx);
1499         }
1500       }
1501     }
1502   }
1503
1504   my ($sql, $bind) = $self->_prep_for_execute (
1505     'insert', undef, $source, [\%colvalues]
1506   );
1507   my @bind = @$bind;
1508
1509   my $empty_bind = 1 if (not @bind) &&
1510     (grep { ref $_ eq 'SCALAR' } values %colvalues) == @$cols;
1511
1512   if ((not @bind) && (not $empty_bind)) {
1513     $self->throw_exception(
1514       'Cannot insert_bulk without support for placeholders'
1515     );
1516   }
1517
1518   # neither _execute_array, nor _execute_inserts_with_no_binds are
1519   # atomic (even if _execute _array is a single call). Thus a safety
1520   # scope guard
1521   my $guard = $self->txn_scope_guard;
1522
1523   $self->_query_start( $sql, ['__BULK__'] );
1524   my $sth = $self->sth($sql);
1525   my $rv = do {
1526     if ($empty_bind) {
1527       # bind_param_array doesn't work if there are no binds
1528       $self->_dbh_execute_inserts_with_no_binds( $sth, scalar @$data );
1529     }
1530     else {
1531 #      @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
1532       $self->_execute_array( $source, $sth, \@bind, $cols, $data );
1533     }
1534   };
1535
1536   $self->_query_end( $sql, ['__BULK__'] );
1537
1538   $guard->commit;
1539
1540   return (wantarray ? ($rv, $sth, @bind) : $rv);
1541 }
1542
1543 sub _execute_array {
1544   my ($self, $source, $sth, $bind, $cols, $data, @extra) = @_;
1545
1546   ## This must be an arrayref, else nothing works!
1547   my $tuple_status = [];
1548
1549   ## Get the bind_attributes, if any exist
1550   my $bind_attributes = $self->source_bind_attributes($source);
1551
1552   ## Bind the values and execute
1553   my $placeholder_index = 1;
1554
1555   foreach my $bound (@$bind) {
1556
1557     my $attributes = {};
1558     my ($column_name, $data_index) = @$bound;
1559
1560     if( $bind_attributes ) {
1561       $attributes = $bind_attributes->{$column_name}
1562       if defined $bind_attributes->{$column_name};
1563     }
1564
1565     my @data = map { $_->[$data_index] } @$data;
1566
1567     $sth->bind_param_array(
1568       $placeholder_index,
1569       [@data],
1570       (%$attributes ?  $attributes : ()),
1571     );
1572     $placeholder_index++;
1573   }
1574
1575   my $rv = eval {
1576     $self->_dbh_execute_array($sth, $tuple_status, @extra);
1577   };
1578   my $err = $@ || $sth->errstr;
1579
1580 # Statement must finish even if there was an exception.
1581   eval { $sth->finish };
1582   $err = $@ unless $err;
1583
1584   if ($err) {
1585     my $i = 0;
1586     ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i];
1587
1588     $self->throw_exception("Unexpected populate error: $err")
1589       if ($i > $#$tuple_status);
1590
1591     $self->throw_exception(sprintf "%s for populate slice:\n%s",
1592       ($tuple_status->[$i][1] || $err),
1593       Data::Dumper::Concise::Dumper({
1594         map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols)
1595       }),
1596     );
1597   }
1598   return $rv;
1599 }
1600
1601 sub _dbh_execute_array {
1602     my ($self, $sth, $tuple_status, @extra) = @_;
1603
1604     return $sth->execute_array({ArrayTupleStatus => $tuple_status});
1605 }
1606
1607 sub _dbh_execute_inserts_with_no_binds {
1608   my ($self, $sth, $count) = @_;
1609
1610   eval {
1611     my $dbh = $self->_get_dbh;
1612     local $dbh->{RaiseError} = 1;
1613     local $dbh->{PrintError} = 0;
1614
1615     $sth->execute foreach 1..$count;
1616   };
1617   my $exception = $@;
1618
1619 # Make sure statement is finished even if there was an exception.
1620   eval { $sth->finish };
1621   $exception = $@ unless $exception;
1622
1623   $self->throw_exception($exception) if $exception;
1624
1625   return $count;
1626 }
1627
1628 sub update {
1629   my ($self, $source, @args) = @_;
1630
1631   my $bind_attrs = $self->source_bind_attributes($source);
1632
1633   return $self->_execute('update' => [], $source, $bind_attrs, @args);
1634 }
1635
1636
1637 sub delete {
1638   my ($self, $source, @args) = @_;
1639
1640   my $bind_attrs = $self->source_bind_attributes($source);
1641
1642   return $self->_execute('delete' => [], $source, $bind_attrs, @args);
1643 }
1644
1645 # We were sent here because the $rs contains a complex search
1646 # which will require a subquery to select the correct rows
1647 # (i.e. joined or limited resultsets, or non-introspectable conditions)
1648 #
1649 # Generating a single PK column subquery is trivial and supported
1650 # by all RDBMS. However if we have a multicolumn PK, things get ugly.
1651 # Look at _multipk_update_delete()
1652 sub _subq_update_delete {
1653   my $self = shift;
1654   my ($rs, $op, $values) = @_;
1655
1656   my $rsrc = $rs->result_source;
1657
1658   # quick check if we got a sane rs on our hands
1659   my @pcols = $rsrc->_pri_cols;
1660
1661   my $sel = $rs->_resolved_attrs->{select};
1662   $sel = [ $sel ] unless ref $sel eq 'ARRAY';
1663
1664   if (
1665       join ("\x00", map { join '.', $rs->{attrs}{alias}, $_ } sort @pcols)
1666         ne
1667       join ("\x00", sort @$sel )
1668   ) {
1669     $self->throw_exception (
1670       '_subq_update_delete can not be called on resultsets selecting columns other than the primary keys'
1671     );
1672   }
1673
1674   if (@pcols == 1) {
1675     return $self->$op (
1676       $rsrc,
1677       $op eq 'update' ? $values : (),
1678       { $pcols[0] => { -in => $rs->as_query } },
1679     );
1680   }
1681
1682   else {
1683     return $self->_multipk_update_delete (@_);
1684   }
1685 }
1686
1687 # ANSI SQL does not provide a reliable way to perform a multicol-PK
1688 # resultset update/delete involving subqueries. So by default resort
1689 # to simple (and inefficient) delete_all style per-row opearations,
1690 # while allowing specific storages to override this with a faster
1691 # implementation.
1692 #
1693 sub _multipk_update_delete {
1694   return shift->_per_row_update_delete (@_);
1695 }
1696
1697 # This is the default loop used to delete/update rows for multi PK
1698 # resultsets, and used by mysql exclusively (because it can't do anything
1699 # else).
1700 #
1701 # We do not use $row->$op style queries, because resultset update/delete
1702 # is not expected to cascade (this is what delete_all/update_all is for).
1703 #
1704 # There should be no race conditions as the entire operation is rolled
1705 # in a transaction.
1706 #
1707 sub _per_row_update_delete {
1708   my $self = shift;
1709   my ($rs, $op, $values) = @_;
1710
1711   my $rsrc = $rs->result_source;
1712   my @pcols = $rsrc->_pri_cols;
1713
1714   my $guard = $self->txn_scope_guard;
1715
1716   # emulate the return value of $sth->execute for non-selects
1717   my $row_cnt = '0E0';
1718
1719   my $subrs_cur = $rs->cursor;
1720   my @all_pk = $subrs_cur->all;
1721   for my $pks ( @all_pk) {
1722
1723     my $cond;
1724     for my $i (0.. $#pcols) {
1725       $cond->{$pcols[$i]} = $pks->[$i];
1726     }
1727
1728     $self->$op (
1729       $rsrc,
1730       $op eq 'update' ? $values : (),
1731       $cond,
1732     );
1733
1734     $row_cnt++;
1735   }
1736
1737   $guard->commit;
1738
1739   return $row_cnt;
1740 }
1741
1742 sub _select {
1743   my $self = shift;
1744
1745   # localization is neccessary as
1746   # 1) there is no infrastructure to pass this around before SQLA2
1747   # 2) _select_args sets it and _prep_for_execute consumes it
1748   my $sql_maker = $self->sql_maker;
1749   local $sql_maker->{_dbic_rs_attrs};
1750
1751   return $self->_execute($self->_select_args(@_));
1752 }
1753
1754 sub _select_args_to_query {
1755   my $self = shift;
1756
1757   # localization is neccessary as
1758   # 1) there is no infrastructure to pass this around before SQLA2
1759   # 2) _select_args sets it and _prep_for_execute consumes it
1760   my $sql_maker = $self->sql_maker;
1761   local $sql_maker->{_dbic_rs_attrs};
1762
1763   # my ($op, $bind, $ident, $bind_attrs, $select, $cond, $order, $rows, $offset)
1764   #  = $self->_select_args($ident, $select, $cond, $attrs);
1765   my ($op, $bind, $ident, $bind_attrs, @args) =
1766     $self->_select_args(@_);
1767
1768   # my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, [ $select, $cond, $order, $rows, $offset ]);
1769   my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, \@args);
1770   $prepared_bind ||= [];
1771
1772   return wantarray
1773     ? ($sql, $prepared_bind, $bind_attrs)
1774     : \[ "($sql)", @$prepared_bind ]
1775   ;
1776 }
1777
1778 sub _select_args {
1779   my ($self, $ident, $select, $where, $attrs) = @_;
1780
1781   my ($alias2source, $rs_alias) = $self->_resolve_ident_sources ($ident);
1782
1783   my $sql_maker = $self->sql_maker;
1784   $sql_maker->{_dbic_rs_attrs} = {
1785     %$attrs,
1786     select => $select,
1787     from => $ident,
1788     where => $where,
1789     $rs_alias && $alias2source->{$rs_alias}
1790       ? ( _source_handle => $alias2source->{$rs_alias}->handle )
1791       : ()
1792     ,
1793   };
1794
1795   # calculate bind_attrs before possible $ident mangling
1796   my $bind_attrs = {};
1797   for my $alias (keys %$alias2source) {
1798     my $bindtypes = $self->source_bind_attributes ($alias2source->{$alias}) || {};
1799     for my $col (keys %$bindtypes) {
1800
1801       my $fqcn = join ('.', $alias, $col);
1802       $bind_attrs->{$fqcn} = $bindtypes->{$col} if $bindtypes->{$col};
1803
1804       # Unqialified column names are nice, but at the same time can be
1805       # rather ambiguous. What we do here is basically go along with
1806       # the loop, adding an unqualified column slot to $bind_attrs,
1807       # alongside the fully qualified name. As soon as we encounter
1808       # another column by that name (which would imply another table)
1809       # we unset the unqualified slot and never add any info to it
1810       # to avoid erroneous type binding. If this happens the users
1811       # only choice will be to fully qualify his column name
1812
1813       if (exists $bind_attrs->{$col}) {
1814         $bind_attrs->{$col} = {};
1815       }
1816       else {
1817         $bind_attrs->{$col} = $bind_attrs->{$fqcn};
1818       }
1819     }
1820   }
1821
1822   # adjust limits
1823   if (
1824     $attrs->{software_limit}
1825       ||
1826     $sql_maker->_default_limit_syntax eq "GenericSubQ"
1827   ) {
1828     $attrs->{software_limit} = 1;
1829   }
1830   else {
1831     $self->throw_exception("rows attribute must be positive if present")
1832       if (defined($attrs->{rows}) && !($attrs->{rows} > 0));
1833
1834     # MySQL actually recommends this approach.  I cringe.
1835     $attrs->{rows} = 2**48 if not defined $attrs->{rows} and defined $attrs->{offset};
1836   }
1837
1838   my @limit;
1839
1840   # see if we need to tear the prefetch apart otherwise delegate the limiting to the
1841   # storage, unless software limit was requested
1842   if (
1843     #limited has_many
1844     ( $attrs->{rows} && keys %{$attrs->{collapse}} )
1845        ||
1846     # limited prefetch with RNO subqueries
1847     (
1848       $attrs->{rows}
1849         &&
1850       $sql_maker->limit_dialect eq 'RowNumberOver'
1851         &&
1852       $attrs->{_prefetch_select}
1853         &&
1854       @{$attrs->{_prefetch_select}}
1855     )
1856       ||
1857     # grouped prefetch
1858     ( $attrs->{group_by}
1859         &&
1860       @{$attrs->{group_by}}
1861         &&
1862       $attrs->{_prefetch_select}
1863         &&
1864       @{$attrs->{_prefetch_select}}
1865     )
1866   ) {
1867     ($ident, $select, $where, $attrs)
1868       = $self->_adjust_select_args_for_complex_prefetch ($ident, $select, $where, $attrs);
1869   }
1870
1871   elsif (
1872     ($attrs->{rows} || $attrs->{offset})
1873       &&
1874     $sql_maker->limit_dialect eq 'RowNumberOver'
1875       &&
1876     (ref $ident eq 'ARRAY' && @$ident > 1)  # indicates a join
1877       &&
1878     scalar $self->_parse_order_by ($attrs->{order_by})
1879   ) {
1880     # the RNO limit dialect above mangles the SQL such that the join gets lost
1881     # wrap a subquery here
1882
1883     push @limit, delete @{$attrs}{qw/rows offset/};
1884
1885     my $subq = $self->_select_args_to_query (
1886       $ident,
1887       $select,
1888       $where,
1889       $attrs,
1890     );
1891
1892     $ident = {
1893       -alias => $attrs->{alias},
1894       -source_handle => $ident->[0]{-source_handle},
1895       $attrs->{alias} => $subq,
1896     };
1897
1898     # all part of the subquery now
1899     delete @{$attrs}{qw/order_by group_by having/};
1900     $where = undef;
1901   }
1902
1903   elsif (! $attrs->{software_limit} ) {
1904     push @limit, $attrs->{rows}, $attrs->{offset};
1905   }
1906
1907   # try to simplify the joinmap further (prune unreferenced type-single joins)
1908   $ident = $self->_prune_unused_joins ($ident, $select, $where, $attrs);
1909
1910 ###
1911   # This would be the point to deflate anything found in $where
1912   # (and leave $attrs->{bind} intact). Problem is - inflators historically
1913   # expect a row object. And all we have is a resultsource (it is trivial
1914   # to extract deflator coderefs via $alias2source above).
1915   #
1916   # I don't see a way forward other than changing the way deflators are
1917   # invoked, and that's just bad...
1918 ###
1919
1920   my $order = { map
1921     { $attrs->{$_} ? ( $_ => $attrs->{$_} ) : ()  }
1922     (qw/order_by group_by having/ )
1923   };
1924
1925   return ('select', $attrs->{bind}, $ident, $bind_attrs, $select, $where, $order, @limit);
1926 }
1927
1928 # Returns a counting SELECT for a simple count
1929 # query. Abstracted so that a storage could override
1930 # this to { count => 'firstcol' } or whatever makes
1931 # sense as a performance optimization
1932 sub _count_select {
1933   #my ($self, $source, $rs_attrs) = @_;
1934   return { count => '*' };
1935 }
1936
1937 # Returns a SELECT which will end up in the subselect
1938 # There may or may not be a group_by, as the subquery
1939 # might have been called to accomodate a limit
1940 #
1941 # Most databases would be happy with whatever ends up
1942 # here, but some choke in various ways.
1943 #
1944 sub _subq_count_select {
1945   my ($self, $source, $rs_attrs) = @_;
1946
1947   if (my $groupby = $rs_attrs->{group_by}) {
1948
1949     my $avail_columns = $self->_resolve_column_info ($rs_attrs->{from});
1950
1951     my $sel_index;
1952     for my $sel (@{$rs_attrs->{select}}) {
1953       if (ref $sel eq 'HASH' and $sel->{-as}) {
1954         $sel_index->{$sel->{-as}} = $sel;
1955       }
1956     }
1957
1958     my @selection;
1959     for my $g_part (@$groupby) {
1960       if (ref $g_part or $avail_columns->{$g_part}) {
1961         push @selection, $g_part;
1962       }
1963       elsif ($sel_index->{$g_part}) {
1964         push @selection, $sel_index->{$g_part};
1965       }
1966       else {
1967         $self->throw_exception ("group_by criteria '$g_part' not contained within current resultset source(s)");
1968       }
1969     }
1970
1971     return \@selection;
1972   }
1973
1974   my @pcols = map { join '.', $rs_attrs->{alias}, $_ } ($source->primary_columns);
1975   return @pcols ? \@pcols : [ 1 ];
1976 }
1977
1978 sub source_bind_attributes {
1979   my ($self, $source) = @_;
1980
1981   my $bind_attributes;
1982   foreach my $column ($source->columns) {
1983
1984     my $data_type = $source->column_info($column)->{data_type} || '';
1985     $bind_attributes->{$column} = $self->bind_attribute_by_data_type($data_type)
1986      if $data_type;
1987   }
1988
1989   return $bind_attributes;
1990 }
1991
1992 =head2 select
1993
1994 =over 4
1995
1996 =item Arguments: $ident, $select, $condition, $attrs
1997
1998 =back
1999
2000 Handle a SQL select statement.
2001
2002 =cut
2003
2004 sub select {
2005   my $self = shift;
2006   my ($ident, $select, $condition, $attrs) = @_;
2007   return $self->cursor_class->new($self, \@_, $attrs);
2008 }
2009
2010 sub select_single {
2011   my $self = shift;
2012   my ($rv, $sth, @bind) = $self->_select(@_);
2013   my @row = $sth->fetchrow_array;
2014   my @nextrow = $sth->fetchrow_array if @row;
2015   if(@row && @nextrow) {
2016     carp "Query returned more than one row.  SQL that returns multiple rows is DEPRECATED for ->find and ->single";
2017   }
2018   # Need to call finish() to work round broken DBDs
2019   $sth->finish();
2020   return @row;
2021 }
2022
2023 =head2 sth
2024
2025 =over 4
2026
2027 =item Arguments: $sql
2028
2029 =back
2030
2031 Returns a L<DBI> sth (statement handle) for the supplied SQL.
2032
2033 =cut
2034
2035 sub _dbh_sth {
2036   my ($self, $dbh, $sql) = @_;
2037
2038   # 3 is the if_active parameter which avoids active sth re-use
2039   my $sth = $self->disable_sth_caching
2040     ? $dbh->prepare($sql)
2041     : $dbh->prepare_cached($sql, {}, 3);
2042
2043   # XXX You would think RaiseError would make this impossible,
2044   #  but apparently that's not true :(
2045   $self->throw_exception($dbh->errstr) if !$sth;
2046
2047   $sth;
2048 }
2049
2050 sub sth {
2051   my ($self, $sql) = @_;
2052   $self->dbh_do('_dbh_sth', $sql);  # retry over disconnects
2053 }
2054
2055 sub _dbh_columns_info_for {
2056   my ($self, $dbh, $table) = @_;
2057
2058   if ($dbh->can('column_info')) {
2059     my %result;
2060     eval {
2061       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
2062       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
2063       $sth->execute();
2064       while ( my $info = $sth->fetchrow_hashref() ){
2065         my %column_info;
2066         $column_info{data_type}   = $info->{TYPE_NAME};
2067         $column_info{size}      = $info->{COLUMN_SIZE};
2068         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
2069         $column_info{default_value} = $info->{COLUMN_DEF};
2070         my $col_name = $info->{COLUMN_NAME};
2071         $col_name =~ s/^\"(.*)\"$/$1/;
2072
2073         $result{$col_name} = \%column_info;
2074       }
2075     };
2076     return \%result if !$@ && scalar keys %result;
2077   }
2078
2079   my %result;
2080   my $sth = $dbh->prepare($self->sql_maker->select($table, undef, \'1 = 0'));
2081   $sth->execute;
2082   my @columns = @{$sth->{NAME_lc}};
2083   for my $i ( 0 .. $#columns ){
2084     my %column_info;
2085     $column_info{data_type} = $sth->{TYPE}->[$i];
2086     $column_info{size} = $sth->{PRECISION}->[$i];
2087     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
2088
2089     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
2090       $column_info{data_type} = $1;
2091       $column_info{size}    = $2;
2092     }
2093
2094     $result{$columns[$i]} = \%column_info;
2095   }
2096   $sth->finish;
2097
2098   foreach my $col (keys %result) {
2099     my $colinfo = $result{$col};
2100     my $type_num = $colinfo->{data_type};
2101     my $type_name;
2102     if(defined $type_num && $dbh->can('type_info')) {
2103       my $type_info = $dbh->type_info($type_num);
2104       $type_name = $type_info->{TYPE_NAME} if $type_info;
2105       $colinfo->{data_type} = $type_name if $type_name;
2106     }
2107   }
2108
2109   return \%result;
2110 }
2111
2112 sub columns_info_for {
2113   my ($self, $table) = @_;
2114   $self->_dbh_columns_info_for ($self->_get_dbh, $table);
2115 }
2116
2117 =head2 last_insert_id
2118
2119 Return the row id of the last insert.
2120
2121 =cut
2122
2123 sub _dbh_last_insert_id {
2124     my ($self, $dbh, $source, $col) = @_;
2125
2126     my $id = eval { $dbh->last_insert_id (undef, undef, $source->name, $col) };
2127
2128     return $id if defined $id;
2129
2130     my $class = ref $self;
2131     $self->throw_exception ("No storage specific _dbh_last_insert_id() method implemented in $class, and the generic DBI::last_insert_id() failed");
2132 }
2133
2134 sub last_insert_id {
2135   my $self = shift;
2136   $self->_dbh_last_insert_id ($self->_dbh, @_);
2137 }
2138
2139 =head2 _native_data_type
2140
2141 =over 4
2142
2143 =item Arguments: $type_name
2144
2145 =back
2146
2147 This API is B<EXPERIMENTAL>, will almost definitely change in the future, and
2148 currently only used by L<::AutoCast|DBIx::Class::Storage::DBI::AutoCast> and
2149 L<::Sybase::ASE|DBIx::Class::Storage::DBI::Sybase::ASE>.
2150
2151 The default implementation returns C<undef>, implement in your Storage driver if
2152 you need this functionality.
2153
2154 Should map types from other databases to the native RDBMS type, for example
2155 C<VARCHAR2> to C<VARCHAR>.
2156
2157 Types with modifiers should map to the underlying data type. For example,
2158 C<INTEGER AUTO_INCREMENT> should become C<INTEGER>.
2159
2160 Composite types should map to the container type, for example
2161 C<ENUM(foo,bar,baz)> becomes C<ENUM>.
2162
2163 =cut
2164
2165 sub _native_data_type {
2166   #my ($self, $data_type) = @_;
2167   return undef
2168 }
2169
2170 # Check if placeholders are supported at all
2171 sub _placeholders_supported {
2172   my $self = shift;
2173   my $dbh  = $self->_get_dbh;
2174
2175   # some drivers provide a $dbh attribute (e.g. Sybase and $dbh->{syb_dynamic_supported})
2176   # but it is inaccurate more often than not
2177   eval {
2178     local $dbh->{PrintError} = 0;
2179     local $dbh->{RaiseError} = 1;
2180     $dbh->do('select ?', {}, 1);
2181   };
2182   return $@ ? 0 : 1;
2183 }
2184
2185 # Check if placeholders bound to non-string types throw exceptions
2186 #
2187 sub _typeless_placeholders_supported {
2188   my $self = shift;
2189   my $dbh  = $self->_get_dbh;
2190
2191   eval {
2192     local $dbh->{PrintError} = 0;
2193     local $dbh->{RaiseError} = 1;
2194     # this specifically tests a bind that is NOT a string
2195     $dbh->do('select 1 where 1 = ?', {}, 1);
2196   };
2197   return $@ ? 0 : 1;
2198 }
2199
2200 =head2 sqlt_type
2201
2202 Returns the database driver name.
2203
2204 =cut
2205
2206 sub sqlt_type {
2207   shift->_get_dbh->{Driver}->{Name};
2208 }
2209
2210 =head2 bind_attribute_by_data_type
2211
2212 Given a datatype from column info, returns a database specific bind
2213 attribute for C<< $dbh->bind_param($val,$attribute) >> or nothing if we will
2214 let the database planner just handle it.
2215
2216 Generally only needed for special case column types, like bytea in postgres.
2217
2218 =cut
2219
2220 sub bind_attribute_by_data_type {
2221     return;
2222 }
2223
2224 =head2 is_datatype_numeric
2225
2226 Given a datatype from column_info, returns a boolean value indicating if
2227 the current RDBMS considers it a numeric value. This controls how
2228 L<DBIx::Class::Row/set_column> decides whether to mark the column as
2229 dirty - when the datatype is deemed numeric a C<< != >> comparison will
2230 be performed instead of the usual C<eq>.
2231
2232 =cut
2233
2234 sub is_datatype_numeric {
2235   my ($self, $dt) = @_;
2236
2237   return 0 unless $dt;
2238
2239   return $dt =~ /^ (?:
2240     numeric | int(?:eger)? | (?:tiny|small|medium|big)int | dec(?:imal)? | real | float | double (?: \s+ precision)? | (?:big)?serial
2241   ) $/ix;
2242 }
2243
2244
2245 =head2 create_ddl_dir
2246
2247 =over 4
2248
2249 =item Arguments: $schema \@databases, $version, $directory, $preversion, \%sqlt_args
2250
2251 =back
2252
2253 Creates a SQL file based on the Schema, for each of the specified
2254 database engines in C<\@databases> in the given directory.
2255 (note: specify L<SQL::Translator> names, not L<DBI> driver names).
2256
2257 Given a previous version number, this will also create a file containing
2258 the ALTER TABLE statements to transform the previous schema into the
2259 current one. Note that these statements may contain C<DROP TABLE> or
2260 C<DROP COLUMN> statements that can potentially destroy data.
2261
2262 The file names are created using the C<ddl_filename> method below, please
2263 override this method in your schema if you would like a different file
2264 name format. For the ALTER file, the same format is used, replacing
2265 $version in the name with "$preversion-$version".
2266
2267 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
2268 The most common value for this would be C<< { add_drop_table => 1 } >>
2269 to have the SQL produced include a C<DROP TABLE> statement for each table
2270 created. For quoting purposes supply C<quote_table_names> and
2271 C<quote_field_names>.
2272
2273 If no arguments are passed, then the following default values are assumed:
2274
2275 =over 4
2276
2277 =item databases  - ['MySQL', 'SQLite', 'PostgreSQL']
2278
2279 =item version    - $schema->schema_version
2280
2281 =item directory  - './'
2282
2283 =item preversion - <none>
2284
2285 =back
2286
2287 By default, C<\%sqlt_args> will have
2288
2289  { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
2290
2291 merged with the hash passed in. To disable any of those features, pass in a
2292 hashref like the following
2293
2294  { ignore_constraint_names => 0, # ... other options }
2295
2296
2297 WARNING: You are strongly advised to check all SQL files created, before applying
2298 them.
2299
2300 =cut
2301
2302 sub create_ddl_dir {
2303   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
2304
2305   unless ($dir) {
2306     carp "No directory given, using ./\n";
2307     $dir = './';
2308   }
2309
2310   $self->throw_exception ("Directory '$dir' does not exist\n") unless(-d $dir);
2311
2312   $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
2313   $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
2314
2315   my $schema_version = $schema->schema_version || '1.x';
2316   $version ||= $schema_version;
2317
2318   $sqltargs = {
2319     add_drop_table => 1,
2320     ignore_constraint_names => 1,
2321     ignore_index_names => 1,
2322     %{$sqltargs || {}}
2323   };
2324
2325   unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy')) {
2326     $self->throw_exception("Can't create a ddl file without " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2327   }
2328
2329   my $sqlt = SQL::Translator->new( $sqltargs );
2330
2331   $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
2332   my $sqlt_schema = $sqlt->translate({ data => $schema })
2333     or $self->throw_exception ($sqlt->error);
2334
2335   foreach my $db (@$databases) {
2336     $sqlt->reset();
2337     $sqlt->{schema} = $sqlt_schema;
2338     $sqlt->producer($db);
2339
2340     my $file;
2341     my $filename = $schema->ddl_filename($db, $version, $dir);
2342     if (-e $filename && ($version eq $schema_version )) {
2343       # if we are dumping the current version, overwrite the DDL
2344       carp "Overwriting existing DDL file - $filename";
2345       unlink($filename);
2346     }
2347
2348     my $output = $sqlt->translate;
2349     if(!$output) {
2350       carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
2351       next;
2352     }
2353     if(!open($file, ">$filename")) {
2354       $self->throw_exception("Can't open $filename for writing ($!)");
2355       next;
2356     }
2357     print $file $output;
2358     close($file);
2359
2360     next unless ($preversion);
2361
2362     require SQL::Translator::Diff;
2363
2364     my $prefilename = $schema->ddl_filename($db, $preversion, $dir);
2365     if(!-e $prefilename) {
2366       carp("No previous schema file found ($prefilename)");
2367       next;
2368     }
2369
2370     my $difffile = $schema->ddl_filename($db, $version, $dir, $preversion);
2371     if(-e $difffile) {
2372       carp("Overwriting existing diff file - $difffile");
2373       unlink($difffile);
2374     }
2375
2376     my $source_schema;
2377     {
2378       my $t = SQL::Translator->new($sqltargs);
2379       $t->debug( 0 );
2380       $t->trace( 0 );
2381
2382       $t->parser( $db )
2383         or $self->throw_exception ($t->error);
2384
2385       my $out = $t->translate( $prefilename )
2386         or $self->throw_exception ($t->error);
2387
2388       $source_schema = $t->schema;
2389
2390       $source_schema->name( $prefilename )
2391         unless ( $source_schema->name );
2392     }
2393
2394     # The "new" style of producers have sane normalization and can support
2395     # diffing a SQL file against a DBIC->SQLT schema. Old style ones don't
2396     # And we have to diff parsed SQL against parsed SQL.
2397     my $dest_schema = $sqlt_schema;
2398
2399     unless ( "SQL::Translator::Producer::$db"->can('preprocess_schema') ) {
2400       my $t = SQL::Translator->new($sqltargs);
2401       $t->debug( 0 );
2402       $t->trace( 0 );
2403
2404       $t->parser( $db )
2405         or $self->throw_exception ($t->error);
2406
2407       my $out = $t->translate( $filename )
2408         or $self->throw_exception ($t->error);
2409
2410       $dest_schema = $t->schema;
2411
2412       $dest_schema->name( $filename )
2413         unless $dest_schema->name;
2414     }
2415
2416     my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
2417                                                   $dest_schema,   $db,
2418                                                   $sqltargs
2419                                                  );
2420     if(!open $file, ">$difffile") {
2421       $self->throw_exception("Can't write to $difffile ($!)");
2422       next;
2423     }
2424     print $file $diff;
2425     close($file);
2426   }
2427 }
2428
2429 =head2 deployment_statements
2430
2431 =over 4
2432
2433 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
2434
2435 =back
2436
2437 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
2438
2439 The L<SQL::Translator> (not L<DBI>) database driver name can be explicitly
2440 provided in C<$type>, otherwise the result of L</sqlt_type> is used as default.
2441
2442 C<$directory> is used to return statements from files in a previously created
2443 L</create_ddl_dir> directory and is optional. The filenames are constructed
2444 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
2445
2446 If no C<$directory> is specified then the statements are constructed on the
2447 fly using L<SQL::Translator> and C<$version> is ignored.
2448
2449 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
2450
2451 =cut
2452
2453 sub deployment_statements {
2454   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
2455   $type ||= $self->sqlt_type;
2456   $version ||= $schema->schema_version || '1.x';
2457   $dir ||= './';
2458   my $filename = $schema->ddl_filename($type, $version, $dir);
2459   if(-f $filename)
2460   {
2461       my $file;
2462       open($file, "<$filename")
2463         or $self->throw_exception("Can't open $filename ($!)");
2464       my @rows = <$file>;
2465       close($file);
2466       return join('', @rows);
2467   }
2468
2469   unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy') ) {
2470     $self->throw_exception("Can't deploy without a ddl_dir or " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2471   }
2472
2473   # sources needs to be a parser arg, but for simplicty allow at top level
2474   # coming in
2475   $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
2476       if exists $sqltargs->{sources};
2477
2478   my $tr = SQL::Translator->new(
2479     producer => "SQL::Translator::Producer::${type}",
2480     %$sqltargs,
2481     parser => 'SQL::Translator::Parser::DBIx::Class',
2482     data => $schema,
2483   );
2484
2485   my @ret;
2486   my $wa = wantarray;
2487   if ($wa) {
2488     @ret = $tr->translate;
2489   }
2490   else {
2491     $ret[0] = $tr->translate;
2492   }
2493
2494   $self->throw_exception( 'Unable to produce deployment statements: ' . $tr->error)
2495     unless (@ret && defined $ret[0]);
2496
2497   return $wa ? @ret : $ret[0];
2498 }
2499
2500 sub deploy {
2501   my ($self, $schema, $type, $sqltargs, $dir) = @_;
2502   my $deploy = sub {
2503     my $line = shift;
2504     return if($line =~ /^--/);
2505     return if(!$line);
2506     # next if($line =~ /^DROP/m);
2507     return if($line =~ /^BEGIN TRANSACTION/m);
2508     return if($line =~ /^COMMIT/m);
2509     return if $line =~ /^\s+$/; # skip whitespace only
2510     $self->_query_start($line);
2511     eval {
2512       # do a dbh_do cycle here, as we need some error checking in
2513       # place (even though we will ignore errors)
2514       $self->dbh_do (sub { $_[1]->do($line) });
2515     };
2516     if ($@) {
2517       carp qq{$@ (running "${line}")};
2518     }
2519     $self->_query_end($line);
2520   };
2521   my @statements = $schema->deployment_statements($type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );
2522   if (@statements > 1) {
2523     foreach my $statement (@statements) {
2524       $deploy->( $statement );
2525     }
2526   }
2527   elsif (@statements == 1) {
2528     foreach my $line ( split(";\n", $statements[0])) {
2529       $deploy->( $line );
2530     }
2531   }
2532 }
2533
2534 =head2 datetime_parser
2535
2536 Returns the datetime parser class
2537
2538 =cut
2539
2540 sub datetime_parser {
2541   my $self = shift;
2542   return $self->{datetime_parser} ||= do {
2543     $self->build_datetime_parser(@_);
2544   };
2545 }
2546
2547 =head2 datetime_parser_type
2548
2549 Defines (returns) the datetime parser class - currently hardwired to
2550 L<DateTime::Format::MySQL>
2551
2552 =cut
2553
2554 sub datetime_parser_type { "DateTime::Format::MySQL"; }
2555
2556 =head2 build_datetime_parser
2557
2558 See L</datetime_parser>
2559
2560 =cut
2561
2562 sub build_datetime_parser {
2563   my $self = shift;
2564   my $type = $self->datetime_parser_type(@_);
2565   $self->ensure_class_loaded ($type);
2566   return $type;
2567 }
2568
2569
2570 =head2 is_replicating
2571
2572 A boolean that reports if a particular L<DBIx::Class::Storage::DBI> is set to
2573 replicate from a master database.  Default is undef, which is the result
2574 returned by databases that don't support replication.
2575
2576 =cut
2577
2578 sub is_replicating {
2579     return;
2580
2581 }
2582
2583 =head2 lag_behind_master
2584
2585 Returns a number that represents a certain amount of lag behind a master db
2586 when a given storage is replicating.  The number is database dependent, but
2587 starts at zero and increases with the amount of lag. Default in undef
2588
2589 =cut
2590
2591 sub lag_behind_master {
2592     return;
2593 }
2594
2595 =head2 relname_to_table_alias
2596
2597 =over 4
2598
2599 =item Arguments: $relname, $join_count
2600
2601 =back
2602
2603 L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
2604 queries.
2605
2606 This hook is to allow specific L<DBIx::Class::Storage> drivers to change the
2607 way these aliases are named.
2608
2609 The default behavior is C<< "$relname_$join_count" if $join_count > 1 >>,
2610 otherwise C<"$relname">.
2611
2612 =cut
2613
2614 sub relname_to_table_alias {
2615   my ($self, $relname, $join_count) = @_;
2616
2617   my $alias = ($join_count && $join_count > 1 ?
2618     join('_', $relname, $join_count) : $relname);
2619
2620   return $alias;
2621 }
2622
2623 sub DESTROY {
2624   my $self = shift;
2625
2626   $self->_verify_pid if $self->_dbh;
2627
2628   # some databases need this to stop spewing warnings
2629   if (my $dbh = $self->_dbh) {
2630     local $@;
2631     eval {
2632       %{ $dbh->{CachedKids} } = ();
2633       $dbh->disconnect;
2634     };
2635   }
2636
2637   $self->_dbh(undef);
2638 }
2639
2640 1;
2641
2642 =head1 USAGE NOTES
2643
2644 =head2 DBIx::Class and AutoCommit
2645
2646 DBIx::Class can do some wonderful magic with handling exceptions,
2647 disconnections, and transactions when you use C<< AutoCommit => 1 >>
2648 (the default) combined with C<txn_do> for transaction support.
2649
2650 If you set C<< AutoCommit => 0 >> in your connect info, then you are always
2651 in an assumed transaction between commits, and you're telling us you'd
2652 like to manage that manually.  A lot of the magic protections offered by
2653 this module will go away.  We can't protect you from exceptions due to database
2654 disconnects because we don't know anything about how to restart your
2655 transactions.  You're on your own for handling all sorts of exceptional
2656 cases if you choose the C<< AutoCommit => 0 >> path, just as you would
2657 be with raw DBI.
2658
2659
2660 =head1 AUTHORS
2661
2662 Matt S. Trout <mst@shadowcatsystems.co.uk>
2663
2664 Andy Grundman <andy@hybridized.org>
2665
2666 =head1 LICENSE
2667
2668 You may distribute this code under the same terms as Perl itself.
2669
2670 =cut