fe503b4bdb2fb0e3dad8680a598f9794217621e0
[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 DBIx::Class::Carp;
11 use Scalar::Util qw/refaddr weaken reftype blessed/;
12 use List::Util qw/first/;
13 use Context::Preserve 'preserve_context';
14 use Try::Tiny;
15 use Data::Compare (); # no imports!!! guard against insane architecture
16 use SQL::Abstract qw(is_plain_value is_literal_value);
17 use DBIx::Class::_Util qw(quote_sub perlstring);
18 use namespace::clean;
19
20 # default cursor class, overridable in connect_info attributes
21 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
22
23 __PACKAGE__->mk_group_accessors('inherited' => qw/
24   sql_limit_dialect sql_quote_char sql_name_sep
25 /);
26
27 __PACKAGE__->mk_group_accessors('component_class' => qw/sql_maker_class datetime_parser_type/);
28
29 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker');
30 __PACKAGE__->datetime_parser_type('DateTime::Format::MySQL'); # historic default
31
32 __PACKAGE__->sql_name_sep('.');
33
34 __PACKAGE__->mk_group_accessors('simple' => qw/
35   _connect_info _dbic_connect_attributes _driver_determined
36   _dbh _dbh_details _conn_pid _sql_maker _sql_maker_opts _dbh_autocommit
37   _perform_autoinc_retrieval _autoinc_supplied_for_op
38 /);
39
40 # the values for these accessors are picked out (and deleted) from
41 # the attribute hashref passed to connect_info
42 my @storage_options = qw/
43   on_connect_call on_disconnect_call on_connect_do on_disconnect_do
44   disable_sth_caching unsafe auto_savepoint
45 /;
46 __PACKAGE__->mk_group_accessors('simple' => @storage_options);
47
48
49 # capability definitions, using a 2-tiered accessor system
50 # The rationale is:
51 #
52 # A driver/user may define _use_X, which blindly without any checks says:
53 # "(do not) use this capability", (use_dbms_capability is an "inherited"
54 # type accessor)
55 #
56 # If _use_X is undef, _supports_X is then queried. This is a "simple" style
57 # accessor, which in turn calls _determine_supports_X, and stores the return
58 # in a special slot on the storage object, which is wiped every time a $dbh
59 # reconnection takes place (it is not guaranteed that upon reconnection we
60 # will get the same rdbms version). _determine_supports_X does not need to
61 # exist on a driver, as we ->can for it before calling.
62
63 my @capabilities = (qw/
64   insert_returning
65   insert_returning_bound
66
67   multicolumn_in
68
69   placeholders
70   typeless_placeholders
71
72   join_optimizer
73 /);
74 __PACKAGE__->mk_group_accessors( dbms_capability => map { "_supports_$_" } @capabilities );
75 __PACKAGE__->mk_group_accessors( use_dbms_capability => map { "_use_$_" } (@capabilities ) );
76
77 # on by default, not strictly a capability (pending rewrite)
78 __PACKAGE__->_use_join_optimizer (1);
79 sub _determine_supports_join_optimizer { 1 };
80
81 # Each of these methods need _determine_driver called before itself
82 # in order to function reliably. We also need to separate accessors
83 # from plain old method calls, since an accessor called as a setter
84 # does *not* need the driver determination loop fired (and in fact
85 # can produce hard to find bugs, like e.g. losing on_connect_*
86 # semantics on fresh connections)
87 #
88 # The construct below is simply a parameterized around()
89 my $storage_accessor_idx = { map { $_ => 1 } qw(
90   sqlt_type
91   datetime_parser_type
92
93   sql_maker
94   cursor_class
95 )};
96 for my $meth (keys %$storage_accessor_idx, qw(
97   deployment_statements
98
99   build_datetime_parser
100
101   txn_begin
102
103   insert
104   insert_bulk
105   update
106   delete
107   select
108   select_single
109
110   with_deferred_fk_checks
111
112   get_use_dbms_capability
113   get_dbms_capability
114
115   _server_info
116   _get_server_version
117 )) {
118
119   my $orig = __PACKAGE__->can ($meth)
120     or die "$meth is not a ::Storage::DBI method!";
121
122   my $is_getter = $storage_accessor_idx->{$meth} ? 0 : 1;
123
124   quote_sub
125     __PACKAGE__ ."::$meth", sprintf( <<'EOC', $is_getter, perlstring $meth ), { '$orig' => \$orig };
126
127     if (
128       # only fire when invoked on an instance, a valid class-based invocation
129       # would e.g. be setting a default for an inherited accessor
130       ref $_[0]
131         and
132       ! $_[0]->{_driver_determined}
133         and
134       ! $_[0]->{_in_determine_driver}
135         and
136       # if this is a known *setter* - just set it, no need to connect
137       # and determine the driver
138       ( %1$s or @_ <= 1 )
139         and
140       # Only try to determine stuff if we have *something* that either is or can
141       # provide a DSN. Allows for bare $schema's generated with a plain ->connect()
142       # to still be marginally useful
143       $_[0]->_dbi_connect_info->[0]
144     ) {
145       $_[0]->_determine_driver;
146
147       # work around http://rt.perl.org/rt3/Public/Bug/Display.html?id=35878
148       goto $_[0]->can(%2$s) unless DBIx::Class::_ENV_::BROKEN_GOTO;
149
150       my $cref = $_[0]->can(%2$s);
151       goto $cref;
152     }
153
154     goto $orig;
155 EOC
156 }
157
158 =head1 NAME
159
160 DBIx::Class::Storage::DBI - DBI storage handler
161
162 =head1 SYNOPSIS
163
164   my $schema = MySchema->connect('dbi:SQLite:my.db');
165
166   $schema->storage->debug(1);
167
168   my @stuff = $schema->storage->dbh_do(
169     sub {
170       my ($storage, $dbh, @args) = @_;
171       $dbh->do("DROP TABLE authors");
172     },
173     @column_list
174   );
175
176   $schema->resultset('Book')->search({
177      written_on => $schema->storage->datetime_parser->format_datetime(DateTime->now)
178   });
179
180 =head1 DESCRIPTION
181
182 This class represents the connection to an RDBMS via L<DBI>.  See
183 L<DBIx::Class::Storage> for general information.  This pod only
184 documents DBI-specific methods and behaviors.
185
186 =head1 METHODS
187
188 =cut
189
190 sub new {
191   my $new = shift->next::method(@_);
192
193   $new->_sql_maker_opts({});
194   $new->_dbh_details({});
195   $new->{_in_do_block} = 0;
196
197   # read below to see what this does
198   $new->_arm_global_destructor;
199
200   $new;
201 }
202
203 # This is hack to work around perl shooting stuff in random
204 # order on exit(). If we do not walk the remaining storage
205 # objects in an END block, there is a *small but real* chance
206 # of a fork()ed child to kill the parent's shared DBI handle,
207 # *before perl reaches the DESTROY in this package*
208 # Yes, it is ugly and effective.
209 # Additionally this registry is used by the CLONE method to
210 # make sure no handles are shared between threads
211 {
212   my %seek_and_destroy;
213
214   sub _arm_global_destructor {
215
216     # quick "garbage collection" pass - prevents the registry
217     # from slowly growing with a bunch of undef-valued keys
218     defined $seek_and_destroy{$_} or delete $seek_and_destroy{$_}
219       for keys %seek_and_destroy;
220
221     weaken (
222       $seek_and_destroy{ refaddr($_[0]) } = $_[0]
223     );
224   }
225
226   END {
227     local $?; # just in case the DBI destructor changes it somehow
228
229     # destroy just the object if not native to this process
230     $_->_verify_pid for (grep
231       { defined $_ }
232       values %seek_and_destroy
233     );
234   }
235
236   sub CLONE {
237     # As per DBI's recommendation, DBIC disconnects all handles as
238     # soon as possible (DBIC will reconnect only on demand from within
239     # the thread)
240     my @instances = grep { defined $_ } values %seek_and_destroy;
241     %seek_and_destroy = ();
242
243     for (@instances) {
244       $_->_dbh(undef);
245
246       $_->transaction_depth(0);
247       $_->savepoints([]);
248
249       # properly renumber existing refs
250       $_->_arm_global_destructor
251     }
252   }
253 }
254
255 sub DESTROY {
256   my $self = shift;
257
258   # some databases spew warnings on implicit disconnect
259   $self->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
260   local $SIG{__WARN__} = sub {};
261   $self->_dbh(undef);
262
263   # this op is necessary, since the very last perl runtime statement
264   # triggers a global destruction shootout, and the $SIG localization
265   # may very well be destroyed before perl actually gets to do the
266   # $dbh undef
267   1;
268 }
269
270 # handle pid changes correctly - do not destroy parent's connection
271 sub _verify_pid {
272   my $self = shift;
273
274   my $pid = $self->_conn_pid;
275   if( defined $pid and $pid != $$ and my $dbh = $self->_dbh ) {
276     $dbh->{InactiveDestroy} = 1;
277     $self->_dbh(undef);
278     $self->transaction_depth(0);
279     $self->savepoints([]);
280   }
281
282   return;
283 }
284
285 =head2 connect_info
286
287 This method is normally called by L<DBIx::Class::Schema/connection>, which
288 encapsulates its argument list in an arrayref before passing them here.
289
290 The argument list may contain:
291
292 =over
293
294 =item *
295
296 The same 4-element argument set one would normally pass to
297 L<DBI/connect>, optionally followed by
298 L<extra attributes|/DBIx::Class specific connection attributes>
299 recognized by DBIx::Class:
300
301   $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
302
303 =item *
304
305 A single code reference which returns a connected
306 L<DBI database handle|DBI/connect> optionally followed by
307 L<extra attributes|/DBIx::Class specific connection attributes> recognized
308 by DBIx::Class:
309
310   $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
311
312 =item *
313
314 A single hashref with all the attributes and the dsn/user/password
315 mixed together:
316
317   $connect_info_args = [{
318     dsn => $dsn,
319     user => $user,
320     password => $pass,
321     %dbi_attributes,
322     %extra_attributes,
323   }];
324
325   $connect_info_args = [{
326     dbh_maker => sub { DBI->connect (...) },
327     %dbi_attributes,
328     %extra_attributes,
329   }];
330
331 This is particularly useful for L<Catalyst> based applications, allowing the
332 following config (L<Config::General> style):
333
334   <Model::DB>
335     schema_class   App::DB
336     <connect_info>
337       dsn          dbi:mysql:database=test
338       user         testuser
339       password     TestPass
340       AutoCommit   1
341     </connect_info>
342   </Model::DB>
343
344 The C<dsn>/C<user>/C<password> combination can be substituted by the
345 C<dbh_maker> key whose value is a coderef that returns a connected
346 L<DBI database handle|DBI/connect>
347
348 =back
349
350 Please note that the L<DBI> docs recommend that you always explicitly
351 set C<AutoCommit> to either I<0> or I<1>.  L<DBIx::Class> further
352 recommends that it be set to I<1>, and that you perform transactions
353 via our L<DBIx::Class::Schema/txn_do> method.  L<DBIx::Class> will set it
354 to I<1> if you do not do explicitly set it to zero.  This is the default
355 for most DBDs. See L</DBIx::Class and AutoCommit> for details.
356
357 =head3 DBIx::Class specific connection attributes
358
359 In addition to the standard L<DBI|DBI/ATTRIBUTES COMMON TO ALL HANDLES>
360 L<connection|DBI/Database Handle Attributes> attributes, DBIx::Class recognizes
361 the following connection options. These options can be mixed in with your other
362 L<DBI> connection attributes, or placed in a separate hashref
363 (C<\%extra_attributes>) as shown above.
364
365 Every time C<connect_info> is invoked, any previous settings for
366 these options will be cleared before setting the new ones, regardless of
367 whether any options are specified in the new C<connect_info>.
368
369
370 =over
371
372 =item on_connect_do
373
374 Specifies things to do immediately after connecting or re-connecting to
375 the database.  Its value may contain:
376
377 =over
378
379 =item a scalar
380
381 This contains one SQL statement to execute.
382
383 =item an array reference
384
385 This contains SQL statements to execute in order.  Each element contains
386 a string or a code reference that returns a string.
387
388 =item a code reference
389
390 This contains some code to execute.  Unlike code references within an
391 array reference, its return value is ignored.
392
393 =back
394
395 =item on_disconnect_do
396
397 Takes arguments in the same form as L</on_connect_do> and executes them
398 immediately before disconnecting from the database.
399
400 Note, this only runs if you explicitly call L</disconnect> on the
401 storage object.
402
403 =item on_connect_call
404
405 A more generalized form of L</on_connect_do> that calls the specified
406 C<connect_call_METHOD> methods in your storage driver.
407
408   on_connect_do => 'select 1'
409
410 is equivalent to:
411
412   on_connect_call => [ [ do_sql => 'select 1' ] ]
413
414 Its values may contain:
415
416 =over
417
418 =item a scalar
419
420 Will call the C<connect_call_METHOD> method.
421
422 =item a code reference
423
424 Will execute C<< $code->($storage) >>
425
426 =item an array reference
427
428 Each value can be a method name or code reference.
429
430 =item an array of arrays
431
432 For each array, the first item is taken to be the C<connect_call_> method name
433 or code reference, and the rest are parameters to it.
434
435 =back
436
437 Some predefined storage methods you may use:
438
439 =over
440
441 =item do_sql
442
443 Executes a SQL string or a code reference that returns a SQL string. This is
444 what L</on_connect_do> and L</on_disconnect_do> use.
445
446 It can take:
447
448 =over
449
450 =item a scalar
451
452 Will execute the scalar as SQL.
453
454 =item an arrayref
455
456 Taken to be arguments to L<DBI/do>, the SQL string optionally followed by the
457 attributes hashref and bind values.
458
459 =item a code reference
460
461 Will execute C<< $code->($storage) >> and execute the return array refs as
462 above.
463
464 =back
465
466 =item datetime_setup
467
468 Execute any statements necessary to initialize the database session to return
469 and accept datetime/timestamp values used with
470 L<DBIx::Class::InflateColumn::DateTime>.
471
472 Only necessary for some databases, see your specific storage driver for
473 implementation details.
474
475 =back
476
477 =item on_disconnect_call
478
479 Takes arguments in the same form as L</on_connect_call> and executes them
480 immediately before disconnecting from the database.
481
482 Calls the C<disconnect_call_METHOD> methods as opposed to the
483 C<connect_call_METHOD> methods called by L</on_connect_call>.
484
485 Note, this only runs if you explicitly call L</disconnect> on the
486 storage object.
487
488 =item disable_sth_caching
489
490 If set to a true value, this option will disable the caching of
491 statement handles via L<DBI/prepare_cached>.
492
493 =item limit_dialect
494
495 Sets a specific SQL::Abstract::Limit-style limit dialect, overriding the
496 default L</sql_limit_dialect> setting of the storage (if any). For a list
497 of available limit dialects see L<DBIx::Class::SQLMaker::LimitDialects>.
498
499 =item quote_names
500
501 When true automatically sets L</quote_char> and L</name_sep> to the characters
502 appropriate for your particular RDBMS. This option is preferred over specifying
503 L</quote_char> directly.
504
505 =item quote_char
506
507 Specifies what characters to use to quote table and column names.
508
509 C<quote_char> expects either a single character, in which case is it
510 is placed on either side of the table/column name, or an arrayref of length
511 2 in which case the table/column name is placed between the elements.
512
513 For example under MySQL you should use C<< quote_char => '`' >>, and for
514 SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
515
516 =item name_sep
517
518 This parameter is only useful in conjunction with C<quote_char>, and is used to
519 specify the character that separates elements (schemas, tables, columns) from
520 each other. If unspecified it defaults to the most commonly used C<.>.
521
522 =item unsafe
523
524 This Storage driver normally installs its own C<HandleError>, sets
525 C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
526 all database handles, including those supplied by a coderef.  It does this
527 so that it can have consistent and useful error behavior.
528
529 If you set this option to a true value, Storage will not do its usual
530 modifications to the database handle's attributes, and instead relies on
531 the settings in your connect_info DBI options (or the values you set in
532 your connection coderef, in the case that you are connecting via coderef).
533
534 Note that your custom settings can cause Storage to malfunction,
535 especially if you set a C<HandleError> handler that suppresses exceptions
536 and/or disable C<RaiseError>.
537
538 =item auto_savepoint
539
540 If this option is true, L<DBIx::Class> will use savepoints when nesting
541 transactions, making it possible to recover from failure in the inner
542 transaction without having to abort all outer transactions.
543
544 =item cursor_class
545
546 Use this argument to supply a cursor class other than the default
547 L<DBIx::Class::Storage::DBI::Cursor>.
548
549 =back
550
551 Some real-life examples of arguments to L</connect_info> and
552 L<DBIx::Class::Schema/connect>
553
554   # Simple SQLite connection
555   ->connect_info([ 'dbi:SQLite:./foo.db' ]);
556
557   # Connect via subref
558   ->connect_info([ sub { DBI->connect(...) } ]);
559
560   # Connect via subref in hashref
561   ->connect_info([{
562     dbh_maker => sub { DBI->connect(...) },
563     on_connect_do => 'alter session ...',
564   }]);
565
566   # A bit more complicated
567   ->connect_info(
568     [
569       'dbi:Pg:dbname=foo',
570       'postgres',
571       'my_pg_password',
572       { AutoCommit => 1 },
573       { quote_char => q{"} },
574     ]
575   );
576
577   # Equivalent to the previous example
578   ->connect_info(
579     [
580       'dbi:Pg:dbname=foo',
581       'postgres',
582       'my_pg_password',
583       { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
584     ]
585   );
586
587   # Same, but with hashref as argument
588   # See parse_connect_info for explanation
589   ->connect_info(
590     [{
591       dsn         => 'dbi:Pg:dbname=foo',
592       user        => 'postgres',
593       password    => 'my_pg_password',
594       AutoCommit  => 1,
595       quote_char  => q{"},
596       name_sep    => q{.},
597     }]
598   );
599
600   # Subref + DBIx::Class-specific connection options
601   ->connect_info(
602     [
603       sub { DBI->connect(...) },
604       {
605           quote_char => q{`},
606           name_sep => q{@},
607           on_connect_do => ['SET search_path TO myschema,otherschema,public'],
608           disable_sth_caching => 1,
609       },
610     ]
611   );
612
613
614
615 =cut
616
617 sub connect_info {
618   my ($self, $info) = @_;
619
620   return $self->_connect_info if !$info;
621
622   $self->_connect_info($info); # copy for _connect_info
623
624   $info = $self->_normalize_connect_info($info)
625     if ref $info eq 'ARRAY';
626
627   my %attrs = (
628     %{ $self->_default_dbi_connect_attributes || {} },
629     %{ $info->{attributes} || {} },
630   );
631
632   my @args = @{ $info->{arguments} };
633
634   if (keys %attrs and ref $args[0] ne 'CODE') {
635     carp_unique (
636         'You provided explicit AutoCommit => 0 in your connection_info. '
637       . 'This is almost universally a bad idea (see the footnotes of '
638       . 'DBIx::Class::Storage::DBI for more info). If you still want to '
639       . 'do this you can set $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK} to disable '
640       . 'this warning.'
641     ) if ! $attrs{AutoCommit} and ! $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK};
642
643     push @args, \%attrs if keys %attrs;
644   }
645
646   # this is the authoritative "always an arrayref" thing fed to DBI->connect
647   # OR a single-element coderef-based $dbh factory
648   $self->_dbi_connect_info(\@args);
649
650   # extract the individual storage options
651   for my $storage_opt (keys %{ $info->{storage_options} }) {
652     my $value = $info->{storage_options}{$storage_opt};
653
654     $self->$storage_opt($value);
655   }
656
657   # Extract the individual sqlmaker options
658   #
659   # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
660   #  the new set of options
661   $self->_sql_maker(undef);
662   $self->_sql_maker_opts({});
663
664   for my $sql_maker_opt (keys %{ $info->{sql_maker_options} }) {
665     my $value = $info->{sql_maker_options}{$sql_maker_opt};
666
667     $self->_sql_maker_opts->{$sql_maker_opt} = $value;
668   }
669
670   # FIXME - dirty:
671   # save attributes in a separate accessor so they are always
672   # introspectable, even in case of a CODE $dbhmaker
673   $self->_dbic_connect_attributes (\%attrs);
674
675   return $self->_connect_info;
676 }
677
678 sub _dbi_connect_info {
679   my $self = shift;
680
681   return $self->{_dbi_connect_info} = $_[0]
682     if @_;
683
684   my $conninfo = $self->{_dbi_connect_info} || [];
685
686   # last ditch effort to grab a DSN
687   if ( ! defined $conninfo->[0] and $ENV{DBI_DSN} ) {
688     my @new_conninfo = @$conninfo;
689     $new_conninfo[0] = $ENV{DBI_DSN};
690     $conninfo = \@new_conninfo;
691   }
692
693   return $conninfo;
694 }
695
696
697 sub _normalize_connect_info {
698   my ($self, $info_arg) = @_;
699   my %info;
700
701   my @args = @$info_arg;  # take a shallow copy for further mutilation
702
703   # combine/pre-parse arguments depending on invocation style
704
705   my %attrs;
706   if (ref $args[0] eq 'CODE') {     # coderef with optional \%extra_attributes
707     %attrs = %{ $args[1] || {} };
708     @args = $args[0];
709   }
710   elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
711     %attrs = %{$args[0]};
712     @args = ();
713     if (my $code = delete $attrs{dbh_maker}) {
714       @args = $code;
715
716       my @ignored = grep { delete $attrs{$_} } (qw/dsn user password/);
717       if (@ignored) {
718         carp sprintf (
719             'Attribute(s) %s in connect_info were ignored, as they can not be applied '
720           . "to the result of 'dbh_maker'",
721
722           join (', ', map { "'$_'" } (@ignored) ),
723         );
724       }
725     }
726     else {
727       @args = delete @attrs{qw/dsn user password/};
728     }
729   }
730   else {                # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
731     %attrs = (
732       % { $args[3] || {} },
733       % { $args[4] || {} },
734     );
735     @args = @args[0,1,2];
736   }
737
738   $info{arguments} = \@args;
739
740   my @storage_opts = grep exists $attrs{$_},
741     @storage_options, 'cursor_class';
742
743   @{ $info{storage_options} }{@storage_opts} =
744     delete @attrs{@storage_opts} if @storage_opts;
745
746   my @sql_maker_opts = grep exists $attrs{$_},
747     qw/limit_dialect quote_char name_sep quote_names/;
748
749   @{ $info{sql_maker_options} }{@sql_maker_opts} =
750     delete @attrs{@sql_maker_opts} if @sql_maker_opts;
751
752   $info{attributes} = \%attrs if %attrs;
753
754   return \%info;
755 }
756
757 sub _default_dbi_connect_attributes () {
758   +{
759     AutoCommit => 1,
760     PrintError => 0,
761     RaiseError => 1,
762     ShowErrorStatement => 1,
763   };
764 }
765
766 =head2 on_connect_do
767
768 This method is deprecated in favour of setting via L</connect_info>.
769
770 =cut
771
772 =head2 on_disconnect_do
773
774 This method is deprecated in favour of setting via L</connect_info>.
775
776 =cut
777
778 sub _parse_connect_do {
779   my ($self, $type) = @_;
780
781   my $val = $self->$type;
782   return () if not defined $val;
783
784   my @res;
785
786   if (not ref($val)) {
787     push @res, [ 'do_sql', $val ];
788   } elsif (ref($val) eq 'CODE') {
789     push @res, $val;
790   } elsif (ref($val) eq 'ARRAY') {
791     push @res, map { [ 'do_sql', $_ ] } @$val;
792   } else {
793     $self->throw_exception("Invalid type for $type: ".ref($val));
794   }
795
796   return \@res;
797 }
798
799 =head2 dbh_do
800
801 Arguments: ($subref | $method_name), @extra_coderef_args?
802
803 Execute the given $subref or $method_name using the new exception-based
804 connection management.
805
806 The first two arguments will be the storage object that C<dbh_do> was called
807 on and a database handle to use.  Any additional arguments will be passed
808 verbatim to the called subref as arguments 2 and onwards.
809
810 Using this (instead of $self->_dbh or $self->dbh) ensures correct
811 exception handling and reconnection (or failover in future subclasses).
812
813 Your subref should have no side-effects outside of the database, as
814 there is the potential for your subref to be partially double-executed
815 if the database connection was stale/dysfunctional.
816
817 Example:
818
819   my @stuff = $schema->storage->dbh_do(
820     sub {
821       my ($storage, $dbh, @cols) = @_;
822       my $cols = join(q{, }, @cols);
823       $dbh->selectrow_array("SELECT $cols FROM foo");
824     },
825     @column_list
826   );
827
828 =cut
829
830 sub dbh_do {
831   my $self = shift;
832   my $run_target = shift; # either a coderef or a method name
833
834   # short circuit when we know there is no need for a runner
835   #
836   # FIXME - assumption may be wrong
837   # the rationale for the txn_depth check is that if this block is a part
838   # of a larger transaction, everything up to that point is screwed anyway
839   return $self->$run_target($self->_get_dbh, @_)
840     if $self->{_in_do_block} or $self->transaction_depth;
841
842   # take a ref instead of a copy, to preserve @_ aliasing
843   # semantics within the coderef, but only if needed
844   # (pseudoforking doesn't like this trick much)
845   my $args = @_ ? \@_ : [];
846
847   DBIx::Class::Storage::BlockRunner->new(
848     storage => $self,
849     wrap_txn => 0,
850     retry_handler => sub {
851       $_[0]->failed_attempt_count == 1
852         and
853       ! $_[0]->storage->connected
854     },
855   )->run(sub {
856     $self->$run_target ($self->_get_dbh, @$args )
857   });
858 }
859
860 sub txn_do {
861   $_[0]->_get_dbh; # connects or reconnects on pid change, necessary to grab correct txn_depth
862   shift->next::method(@_);
863 }
864
865 =head2 disconnect
866
867 Our C<disconnect> method also performs a rollback first if the
868 database is not in C<AutoCommit> mode.
869
870 =cut
871
872 sub disconnect {
873   my ($self) = @_;
874
875   if( $self->_dbh ) {
876     my @actions;
877
878     push @actions, ( $self->on_disconnect_call || () );
879     push @actions, $self->_parse_connect_do ('on_disconnect_do');
880
881     $self->_do_connection_actions(disconnect_call_ => $_) for @actions;
882
883     # stops the "implicit rollback on disconnect" warning
884     $self->_exec_txn_rollback unless $self->_dbh_autocommit;
885
886     %{ $self->_dbh->{CachedKids} } = ();
887     $self->_dbh->disconnect;
888     $self->_dbh(undef);
889   }
890 }
891
892 =head2 with_deferred_fk_checks
893
894 =over 4
895
896 =item Arguments: C<$coderef>
897
898 =item Return Value: The return value of $coderef
899
900 =back
901
902 Storage specific method to run the code ref with FK checks deferred or
903 in MySQL's case disabled entirely.
904
905 =cut
906
907 # Storage subclasses should override this
908 sub with_deferred_fk_checks {
909   my ($self, $sub) = @_;
910   $sub->();
911 }
912
913 =head2 connected
914
915 =over
916
917 =item Arguments: none
918
919 =item Return Value: 1|0
920
921 =back
922
923 Verifies that the current database handle is active and ready to execute
924 an SQL statement (e.g. the connection did not get stale, server is still
925 answering, etc.) This method is used internally by L</dbh>.
926
927 =cut
928
929 sub connected {
930   my $self = shift;
931   return 0 unless $self->_seems_connected;
932
933   #be on the safe side
934   local $self->_dbh->{RaiseError} = 1;
935
936   return $self->_ping;
937 }
938
939 sub _seems_connected {
940   my $self = shift;
941
942   $self->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
943
944   my $dbh = $self->_dbh
945     or return 0;
946
947   return $dbh->FETCH('Active');
948 }
949
950 sub _ping {
951   my $self = shift;
952
953   my $dbh = $self->_dbh or return 0;
954
955   return $dbh->ping;
956 }
957
958 sub ensure_connected {
959   my ($self) = @_;
960
961   unless ($self->connected) {
962     $self->_populate_dbh;
963   }
964 }
965
966 =head2 dbh
967
968 Returns a C<$dbh> - a data base handle of class L<DBI>. The returned handle
969 is guaranteed to be healthy by implicitly calling L</connected>, and if
970 necessary performing a reconnection before returning. Keep in mind that this
971 is very B<expensive> on some database engines. Consider using L</dbh_do>
972 instead.
973
974 =cut
975
976 sub dbh {
977   my ($self) = @_;
978
979   if (not $self->_dbh) {
980     $self->_populate_dbh;
981   } else {
982     $self->ensure_connected;
983   }
984   return $self->_dbh;
985 }
986
987 # this is the internal "get dbh or connect (don't check)" method
988 sub _get_dbh {
989   my $self = shift;
990   $self->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
991   $self->_populate_dbh unless $self->_dbh;
992   return $self->_dbh;
993 }
994
995 # *DELIBERATELY* not a setter (for the time being)
996 # Too intertwined with everything else for any kind of sanity
997 sub sql_maker {
998   my $self = shift;
999
1000   $self->throw_exception('sql_maker() is not a setter method') if @_;
1001
1002   unless ($self->_sql_maker) {
1003     my $sql_maker_class = $self->sql_maker_class;
1004
1005     my %opts = %{$self->_sql_maker_opts||{}};
1006     my $dialect =
1007       $opts{limit_dialect}
1008         ||
1009       $self->sql_limit_dialect
1010         ||
1011       do {
1012         my $s_class = (ref $self) || $self;
1013         carp_unique (
1014           "Your storage class ($s_class) does not set sql_limit_dialect and you "
1015         . 'have not supplied an explicit limit_dialect in your connection_info. '
1016         . 'DBIC will attempt to use the GenericSubQ dialect, which works on most '
1017         . 'databases but can be (and often is) painfully slow. '
1018         . "Please file an RT ticket against '$s_class'"
1019         ) if $self->_dbi_connect_info->[0];
1020
1021         'GenericSubQ';
1022       }
1023     ;
1024
1025     my ($quote_char, $name_sep);
1026
1027     if ($opts{quote_names}) {
1028       $quote_char = (delete $opts{quote_char}) || $self->sql_quote_char || do {
1029         my $s_class = (ref $self) || $self;
1030         carp_unique (
1031           "You requested 'quote_names' but your storage class ($s_class) does "
1032         . 'not explicitly define a default sql_quote_char and you have not '
1033         . 'supplied a quote_char as part of your connection_info. DBIC will '
1034         .q{default to the ANSI SQL standard quote '"', which works most of }
1035         . "the time. Please file an RT ticket against '$s_class'."
1036         );
1037
1038         '"'; # RV
1039       };
1040
1041       $name_sep = (delete $opts{name_sep}) || $self->sql_name_sep;
1042     }
1043
1044     $self->_sql_maker($sql_maker_class->new(
1045       bindtype=>'columns',
1046       array_datatypes => 1,
1047       limit_dialect => $dialect,
1048       ($quote_char ? (quote_char => $quote_char) : ()),
1049       name_sep => ($name_sep || '.'),
1050       %opts,
1051     ));
1052   }
1053   return $self->_sql_maker;
1054 }
1055
1056 # nothing to do by default
1057 sub _rebless {}
1058 sub _init {}
1059
1060 sub _populate_dbh {
1061   my ($self) = @_;
1062
1063   $self->_dbh(undef); # in case ->connected failed we might get sent here
1064   $self->_dbh_details({}); # reset everything we know
1065   $self->_sql_maker(undef); # this may also end up being different
1066
1067   $self->_dbh($self->_connect);
1068
1069   $self->_conn_pid($$) unless DBIx::Class::_ENV_::BROKEN_FORK; # on win32 these are in fact threads
1070
1071   $self->_determine_driver;
1072
1073   # Always set the transaction depth on connect, since
1074   #  there is no transaction in progress by definition
1075   $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
1076
1077   $self->_run_connection_actions unless $self->{_in_determine_driver};
1078 }
1079
1080 sub _run_connection_actions {
1081   my $self = shift;
1082   my @actions;
1083
1084   push @actions, ( $self->on_connect_call || () );
1085   push @actions, $self->_parse_connect_do ('on_connect_do');
1086
1087   $self->_do_connection_actions(connect_call_ => $_) for @actions;
1088 }
1089
1090
1091
1092 sub set_use_dbms_capability {
1093   $_[0]->set_inherited ($_[1], $_[2]);
1094 }
1095
1096 sub get_use_dbms_capability {
1097   my ($self, $capname) = @_;
1098
1099   my $use = $self->get_inherited ($capname);
1100   return defined $use
1101     ? $use
1102     : do { $capname =~ s/^_use_/_supports_/; $self->get_dbms_capability ($capname) }
1103   ;
1104 }
1105
1106 sub set_dbms_capability {
1107   $_[0]->_dbh_details->{capability}{$_[1]} = $_[2];
1108 }
1109
1110 sub get_dbms_capability {
1111   my ($self, $capname) = @_;
1112
1113   my $cap = $self->_dbh_details->{capability}{$capname};
1114
1115   unless (defined $cap) {
1116     if (my $meth = $self->can ("_determine$capname")) {
1117       $cap = $self->$meth ? 1 : 0;
1118     }
1119     else {
1120       $cap = 0;
1121     }
1122
1123     $self->set_dbms_capability ($capname, $cap);
1124   }
1125
1126   return $cap;
1127 }
1128
1129 sub _server_info {
1130   my $self = shift;
1131
1132   my $info;
1133   unless ($info = $self->_dbh_details->{info}) {
1134
1135     $info = {};
1136
1137     my $server_version = try {
1138       $self->_get_server_version
1139     } catch {
1140       # driver determination *may* use this codepath
1141       # in which case we must rethrow
1142       $self->throw_exception($_) if $self->{_in_determine_driver};
1143
1144       # $server_version on failure
1145       undef;
1146     };
1147
1148     if (defined $server_version) {
1149       $info->{dbms_version} = $server_version;
1150
1151       my ($numeric_version) = $server_version =~ /^([\d\.]+)/;
1152       my @verparts = split (/\./, $numeric_version);
1153       if (
1154         @verparts
1155           &&
1156         $verparts[0] <= 999
1157       ) {
1158         # consider only up to 3 version parts, iff not more than 3 digits
1159         my @use_parts;
1160         while (@verparts && @use_parts < 3) {
1161           my $p = shift @verparts;
1162           last if $p > 999;
1163           push @use_parts, $p;
1164         }
1165         push @use_parts, 0 while @use_parts < 3;
1166
1167         $info->{normalized_dbms_version} = sprintf "%d.%03d%03d", @use_parts;
1168       }
1169     }
1170
1171     $self->_dbh_details->{info} = $info;
1172   }
1173
1174   return $info;
1175 }
1176
1177 sub _get_server_version {
1178   shift->_dbh_get_info('SQL_DBMS_VER');
1179 }
1180
1181 sub _dbh_get_info {
1182   my ($self, $info) = @_;
1183
1184   if ($info =~ /[^0-9]/) {
1185     require DBI::Const::GetInfoType;
1186     $info = $DBI::Const::GetInfoType::GetInfoType{$info};
1187     $self->throw_exception("Info type '$_[1]' not provided by DBI::Const::GetInfoType")
1188       unless defined $info;
1189   }
1190
1191   $self->_get_dbh->get_info($info);
1192 }
1193
1194 sub _describe_connection {
1195   require DBI::Const::GetInfoReturn;
1196
1197   my $self = shift;
1198
1199   my $drv;
1200   try {
1201     $drv = $self->_extract_driver_from_connect_info;
1202     $self->ensure_connected;
1203   };
1204
1205   $drv = "DBD::$drv" if $drv;
1206
1207   my $res = {
1208     DBIC_DSN => $self->_dbi_connect_info->[0],
1209     DBI_VER => DBI->VERSION,
1210     DBIC_VER => DBIx::Class->VERSION,
1211     DBIC_DRIVER => ref $self,
1212     $drv ? (
1213       DBD => $drv,
1214       DBD_VER => try { $drv->VERSION },
1215     ) : (),
1216   };
1217
1218   # try to grab data even if we never managed to connect
1219   # will cover us in cases of an oddly broken half-connect
1220   for my $inf (
1221     #keys %DBI::Const::GetInfoType::GetInfoType,
1222     qw/
1223       SQL_CURSOR_COMMIT_BEHAVIOR
1224       SQL_CURSOR_ROLLBACK_BEHAVIOR
1225       SQL_CURSOR_SENSITIVITY
1226       SQL_DATA_SOURCE_NAME
1227       SQL_DBMS_NAME
1228       SQL_DBMS_VER
1229       SQL_DEFAULT_TXN_ISOLATION
1230       SQL_DM_VER
1231       SQL_DRIVER_NAME
1232       SQL_DRIVER_ODBC_VER
1233       SQL_DRIVER_VER
1234       SQL_EXPRESSIONS_IN_ORDERBY
1235       SQL_GROUP_BY
1236       SQL_IDENTIFIER_CASE
1237       SQL_IDENTIFIER_QUOTE_CHAR
1238       SQL_MAX_CATALOG_NAME_LEN
1239       SQL_MAX_COLUMN_NAME_LEN
1240       SQL_MAX_IDENTIFIER_LEN
1241       SQL_MAX_TABLE_NAME_LEN
1242       SQL_MULTIPLE_ACTIVE_TXN
1243       SQL_MULT_RESULT_SETS
1244       SQL_NEED_LONG_DATA_LEN
1245       SQL_NON_NULLABLE_COLUMNS
1246       SQL_ODBC_VER
1247       SQL_QUALIFIER_NAME_SEPARATOR
1248       SQL_QUOTED_IDENTIFIER_CASE
1249       SQL_TXN_CAPABLE
1250       SQL_TXN_ISOLATION_OPTION
1251     /
1252   ) {
1253     # some drivers barf on things they do not know about instead
1254     # of returning undef
1255     my $v = try { $self->_dbh_get_info($inf) };
1256     next unless defined $v;
1257
1258     #my $key = sprintf( '%s(%s)', $inf, $DBI::Const::GetInfoType::GetInfoType{$inf} );
1259     my $expl = DBI::Const::GetInfoReturn::Explain($inf, $v);
1260     $res->{$inf} = DBI::Const::GetInfoReturn::Format($inf, $v) . ( $expl ? " ($expl)" : '' );
1261   }
1262
1263   $res;
1264 }
1265
1266 sub _determine_driver {
1267   my ($self) = @_;
1268
1269   if ((not $self->_driver_determined) && (not $self->{_in_determine_driver})) {
1270     my $started_connected = 0;
1271     local $self->{_in_determine_driver} = 1;
1272
1273     if (ref($self) eq __PACKAGE__) {
1274       my $driver;
1275       if ($self->_dbh) { # we are connected
1276         $driver = $self->_dbh->{Driver}{Name};
1277         $started_connected = 1;
1278       }
1279       else {
1280         $driver = $self->_extract_driver_from_connect_info;
1281       }
1282
1283       if ($driver) {
1284         my $storage_class = "DBIx::Class::Storage::DBI::${driver}";
1285         if ($self->load_optional_class($storage_class)) {
1286           mro::set_mro($storage_class, 'c3');
1287           bless $self, $storage_class;
1288           $self->_rebless();
1289         }
1290         else {
1291           $self->_warn_undetermined_driver(
1292             'This version of DBIC does not yet seem to supply a driver for '
1293           . "your particular RDBMS and/or connection method ('$driver')."
1294           );
1295         }
1296       }
1297       else {
1298         $self->_warn_undetermined_driver(
1299           'Unable to extract a driver name from connect info - this '
1300         . 'should not have happened.'
1301         );
1302       }
1303     }
1304
1305     $self->_driver_determined(1);
1306
1307     Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
1308
1309     if ($self->can('source_bind_attributes')) {
1310       $self->throw_exception(
1311         "Your storage subclass @{[ ref $self ]} provides (or inherits) the method "
1312       . 'source_bind_attributes() for which support has been removed as of Jan 2013. '
1313       . 'If you are not sure how to proceed please contact the development team via '
1314       . DBIx::Class::_ENV_::HELP_URL
1315       );
1316     }
1317
1318     $self->_init; # run driver-specific initializations
1319
1320     $self->_run_connection_actions
1321         if !$started_connected && defined $self->_dbh;
1322   }
1323 }
1324
1325 sub _extract_driver_from_connect_info {
1326   my $self = shift;
1327
1328   my $drv;
1329
1330   # if connect_info is a CODEREF, we have no choice but to connect
1331   if (
1332     ref $self->_dbi_connect_info->[0]
1333       and
1334     reftype $self->_dbi_connect_info->[0] eq 'CODE'
1335   ) {
1336     $self->_populate_dbh;
1337     $drv = $self->_dbh->{Driver}{Name};
1338   }
1339   else {
1340     # try to use dsn to not require being connected, the driver may still
1341     # force a connection later in _rebless to determine version
1342     # (dsn may not be supplied at all if all we do is make a mock-schema)
1343     ($drv) = ($self->_dbi_connect_info->[0] || '') =~ /^dbi:([^:]+):/i;
1344     $drv ||= $ENV{DBI_DRIVER};
1345   }
1346
1347   return $drv;
1348 }
1349
1350 sub _determine_connector_driver {
1351   my ($self, $conn) = @_;
1352
1353   my $dbtype = $self->_dbh_get_info('SQL_DBMS_NAME');
1354
1355   if (not $dbtype) {
1356     $self->_warn_undetermined_driver(
1357       'Unable to retrieve RDBMS type (SQL_DBMS_NAME) of the engine behind your '
1358     . "$conn connector - this should not have happened."
1359     );
1360     return;
1361   }
1362
1363   $dbtype =~ s/\W/_/gi;
1364
1365   my $subclass = "DBIx::Class::Storage::DBI::${conn}::${dbtype}";
1366   return if $self->isa($subclass);
1367
1368   if ($self->load_optional_class($subclass)) {
1369     bless $self, $subclass;
1370     $self->_rebless;
1371   }
1372   else {
1373     $self->_warn_undetermined_driver(
1374       'This version of DBIC does not yet seem to supply a driver for '
1375     . "your particular RDBMS and/or connection method ('$conn/$dbtype')."
1376     );
1377   }
1378 }
1379
1380 sub _warn_undetermined_driver {
1381   my ($self, $msg) = @_;
1382
1383   require Data::Dumper::Concise;
1384
1385   carp_once ($msg . ' While we will attempt to continue anyway, the results '
1386   . 'are likely to be underwhelming. Please upgrade DBIC, and if this message '
1387   . "does not go away, file a bugreport including the following info:\n"
1388   . Data::Dumper::Concise::Dumper($self->_describe_connection)
1389   );
1390 }
1391
1392 sub _do_connection_actions {
1393   my $self          = shift;
1394   my $method_prefix = shift;
1395   my $call          = shift;
1396
1397   if (not ref($call)) {
1398     my $method = $method_prefix . $call;
1399     $self->$method(@_);
1400   } elsif (ref($call) eq 'CODE') {
1401     $self->$call(@_);
1402   } elsif (ref($call) eq 'ARRAY') {
1403     if (ref($call->[0]) ne 'ARRAY') {
1404       $self->_do_connection_actions($method_prefix, $_) for @$call;
1405     } else {
1406       $self->_do_connection_actions($method_prefix, @$_) for @$call;
1407     }
1408   } else {
1409     $self->throw_exception (sprintf ("Don't know how to process conection actions of type '%s'", ref($call)) );
1410   }
1411
1412   return $self;
1413 }
1414
1415 sub connect_call_do_sql {
1416   my $self = shift;
1417   $self->_do_query(@_);
1418 }
1419
1420 sub disconnect_call_do_sql {
1421   my $self = shift;
1422   $self->_do_query(@_);
1423 }
1424
1425 # override in db-specific backend when necessary
1426 sub connect_call_datetime_setup { 1 }
1427
1428 sub _do_query {
1429   my ($self, $action) = @_;
1430
1431   if (ref $action eq 'CODE') {
1432     $action = $action->($self);
1433     $self->_do_query($_) foreach @$action;
1434   }
1435   else {
1436     # Most debuggers expect ($sql, @bind), so we need to exclude
1437     # the attribute hash which is the second argument to $dbh->do
1438     # furthermore the bind values are usually to be presented
1439     # as named arrayref pairs, so wrap those here too
1440     my @do_args = (ref $action eq 'ARRAY') ? (@$action) : ($action);
1441     my $sql = shift @do_args;
1442     my $attrs = shift @do_args;
1443     my @bind = map { [ undef, $_ ] } @do_args;
1444
1445     $self->dbh_do(sub {
1446       $_[0]->_query_start($sql, \@bind);
1447       $_[1]->do($sql, $attrs, @do_args);
1448       $_[0]->_query_end($sql, \@bind);
1449     });
1450   }
1451
1452   return $self;
1453 }
1454
1455 sub _connect {
1456   my $self = shift;
1457
1458   my $info = $self->_dbi_connect_info;
1459
1460   $self->throw_exception("You did not provide any connection_info")
1461     unless defined $info->[0];
1462
1463   my ($old_connect_via, $dbh);
1464
1465   local $DBI::connect_via = 'connect' if $INC{'Apache/DBI.pm'} && $ENV{MOD_PERL};
1466
1467   # this odd anonymous coderef dereference is in fact really
1468   # necessary to avoid the unwanted effect described in perl5
1469   # RT#75792
1470   #
1471   # in addition the coderef itself can't reside inside the try{} block below
1472   # as it somehow triggers a leak under perl -d
1473   my $dbh_error_handler_installer = sub {
1474     weaken (my $weak_self = $_[0]);
1475
1476     # the coderef is blessed so we can distinguish it from externally
1477     # supplied handles (which must be preserved)
1478     $_[1]->{HandleError} = bless sub {
1479       if ($weak_self) {
1480         $weak_self->throw_exception("DBI Exception: $_[0]");
1481       }
1482       else {
1483         # the handler may be invoked by something totally out of
1484         # the scope of DBIC
1485         DBIx::Class::Exception->throw("DBI Exception (unhandled by DBIC, ::Schema GCed): $_[0]");
1486       }
1487     }, '__DBIC__DBH__ERROR__HANDLER__';
1488   };
1489
1490   try {
1491     if(ref $info->[0] eq 'CODE') {
1492       $dbh = $info->[0]->();
1493     }
1494     else {
1495       require DBI;
1496       $dbh = DBI->connect(@$info);
1497     }
1498
1499     die $DBI::errstr unless $dbh;
1500
1501     die sprintf ("%s fresh DBI handle with a *false* 'Active' attribute. "
1502       . 'This handle is disconnected as far as DBIC is concerned, and we can '
1503       . 'not continue',
1504       ref $info->[0] eq 'CODE'
1505         ? "Connection coderef $info->[0] returned a"
1506         : 'DBI->connect($schema->storage->connect_info) resulted in a'
1507     ) unless $dbh->FETCH('Active');
1508
1509     # sanity checks unless asked otherwise
1510     unless ($self->unsafe) {
1511
1512       $self->throw_exception(
1513         'Refusing clobbering of {HandleError} installed on externally supplied '
1514        ."DBI handle $dbh. Either remove the handler or use the 'unsafe' attribute."
1515       ) if $dbh->{HandleError} and ref $dbh->{HandleError} ne '__DBIC__DBH__ERROR__HANDLER__';
1516
1517       # Default via _default_dbi_connect_attributes is 1, hence it was an explicit
1518       # request, or an external handle. Complain and set anyway
1519       unless ($dbh->{RaiseError}) {
1520         carp( ref $info->[0] eq 'CODE'
1521
1522           ? "The 'RaiseError' of the externally supplied DBI handle is set to false. "
1523            ."DBIx::Class will toggle it back to true, unless the 'unsafe' connect "
1524            .'attribute has been supplied'
1525
1526           : 'RaiseError => 0 supplied in your connection_info, without an explicit '
1527            .'unsafe => 1. Toggling RaiseError back to true'
1528         );
1529
1530         $dbh->{RaiseError} = 1;
1531       }
1532
1533       $dbh_error_handler_installer->($self, $dbh);
1534     }
1535   }
1536   catch {
1537     $self->throw_exception("DBI Connection failed: $_")
1538   };
1539
1540   $self->_dbh_autocommit($dbh->{AutoCommit});
1541   return $dbh;
1542 }
1543
1544 sub txn_begin {
1545   my $self = shift;
1546
1547   # this means we have not yet connected and do not know the AC status
1548   # (e.g. coderef $dbh), need a full-fledged connection check
1549   if (! defined $self->_dbh_autocommit) {
1550     $self->ensure_connected;
1551   }
1552   # Otherwise simply connect or re-connect on pid changes
1553   else {
1554     $self->_get_dbh;
1555   }
1556
1557   $self->next::method(@_);
1558 }
1559
1560 sub _exec_txn_begin {
1561   my $self = shift;
1562
1563   # if the user is utilizing txn_do - good for him, otherwise we need to
1564   # ensure that the $dbh is healthy on BEGIN.
1565   # We do this via ->dbh_do instead of ->dbh, so that the ->dbh "ping"
1566   # will be replaced by a failure of begin_work itself (which will be
1567   # then retried on reconnect)
1568   if ($self->{_in_do_block}) {
1569     $self->_dbh->begin_work;
1570   } else {
1571     $self->dbh_do(sub { $_[1]->begin_work });
1572   }
1573 }
1574
1575 sub txn_commit {
1576   my $self = shift;
1577
1578   $self->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
1579   $self->throw_exception("Unable to txn_commit() on a disconnected storage")
1580     unless $self->_dbh;
1581
1582   # esoteric case for folks using external $dbh handles
1583   if (! $self->transaction_depth and ! $self->_dbh->FETCH('AutoCommit') ) {
1584     carp "Storage transaction_depth 0 does not match "
1585         ."false AutoCommit of $self->{_dbh}, attempting COMMIT anyway";
1586     $self->transaction_depth(1);
1587   }
1588
1589   $self->next::method(@_);
1590
1591   # if AutoCommit is disabled txn_depth never goes to 0
1592   # as a new txn is started immediately on commit
1593   $self->transaction_depth(1) if (
1594     !$self->transaction_depth
1595       and
1596     defined $self->_dbh_autocommit
1597       and
1598     ! $self->_dbh_autocommit
1599   );
1600 }
1601
1602 sub _exec_txn_commit {
1603   shift->_dbh->commit;
1604 }
1605
1606 sub txn_rollback {
1607   my $self = shift;
1608
1609   $self->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
1610   $self->throw_exception("Unable to txn_rollback() on a disconnected storage")
1611     unless $self->_dbh;
1612
1613   # esoteric case for folks using external $dbh handles
1614   if (! $self->transaction_depth and ! $self->_dbh->FETCH('AutoCommit') ) {
1615     carp "Storage transaction_depth 0 does not match "
1616         ."false AutoCommit of $self->{_dbh}, attempting ROLLBACK anyway";
1617     $self->transaction_depth(1);
1618   }
1619
1620   $self->next::method(@_);
1621
1622   # if AutoCommit is disabled txn_depth never goes to 0
1623   # as a new txn is started immediately on commit
1624   $self->transaction_depth(1) if (
1625     !$self->transaction_depth
1626       and
1627     defined $self->_dbh_autocommit
1628       and
1629     ! $self->_dbh_autocommit
1630   );
1631 }
1632
1633 sub _exec_txn_rollback {
1634   shift->_dbh->rollback;
1635 }
1636
1637 # generate the DBI-specific stubs, which then fallback to ::Storage proper
1638 quote_sub __PACKAGE__ . "::$_" => sprintf (<<'EOS', $_) for qw(svp_begin svp_release svp_rollback);
1639   $_[0]->_verify_pid unless DBIx::Class::_ENV_::BROKEN_FORK;
1640   $_[0]->throw_exception('Unable to %s() on a disconnected storage')
1641     unless $_[0]->_dbh;
1642   shift->next::method(@_);
1643 EOS
1644
1645 # This used to be the top-half of _execute.  It was split out to make it
1646 #  easier to override in NoBindVars without duping the rest.  It takes up
1647 #  all of _execute's args, and emits $sql, @bind.
1648 sub _prep_for_execute {
1649   #my ($self, $op, $ident, $args) = @_;
1650   return shift->_gen_sql_bind(@_)
1651 }
1652
1653 sub _gen_sql_bind {
1654   my ($self, $op, $ident, $args) = @_;
1655
1656   my ($colinfos, $from);
1657   if ( blessed($ident) ) {
1658     $from = $ident->from;
1659     $colinfos = $ident->columns_info;
1660   }
1661
1662   my ($sql, $bind);
1663   ($sql, @$bind) = $self->sql_maker->$op( ($from || $ident), @$args );
1664
1665   $bind = $self->_resolve_bindattrs(
1666     $ident, [ @{$args->[2]{bind}||[]}, @$bind ], $colinfos
1667   );
1668
1669   if (
1670     ! $ENV{DBIC_DT_SEARCH_OK}
1671       and
1672     $op eq 'select'
1673       and
1674     first {
1675       length ref $_->[1]
1676         and
1677       blessed($_->[1])
1678         and
1679       $_->[1]->isa('DateTime')
1680     } @$bind
1681   ) {
1682     carp_unique 'DateTime objects passed to search() are not supported '
1683       . 'properly (InflateColumn::DateTime formats and settings are not '
1684       . 'respected.) See "Formatting DateTime objects in queries" in '
1685       . 'DBIx::Class::Manual::Cookbook. To disable this warning for good '
1686       . 'set $ENV{DBIC_DT_SEARCH_OK} to true'
1687   }
1688
1689   return( $sql, $bind );
1690 }
1691
1692 sub _resolve_bindattrs {
1693   my ($self, $ident, $bind, $colinfos) = @_;
1694
1695   my $resolve_bindinfo = sub {
1696     #my $infohash = shift;
1697
1698     $colinfos ||= { %{ $self->_resolve_column_info($ident) } };
1699
1700     my $ret;
1701     if (my $col = $_[0]->{dbic_colname}) {
1702       $ret = { %{$_[0]} };
1703
1704       $ret->{sqlt_datatype} ||= $colinfos->{$col}{data_type}
1705         if $colinfos->{$col}{data_type};
1706
1707       $ret->{sqlt_size} ||= $colinfos->{$col}{size}
1708         if $colinfos->{$col}{size};
1709     }
1710
1711     $ret || $_[0];
1712   };
1713
1714   return [ map {
1715     my $resolved =
1716       ( ref $_ ne 'ARRAY' or @$_ != 2 ) ? [ {}, $_ ]
1717     : ( ! defined $_->[0] )             ? [ {}, $_->[1] ]
1718     : (ref $_->[0] eq 'HASH')           ? [(
1719                                             ! keys %{$_->[0]}
1720                                               or
1721                                             exists $_->[0]{dbd_attrs}
1722                                               or
1723                                             $_->[0]{sqlt_datatype}
1724                                            ) ? $_->[0]
1725                                              : $resolve_bindinfo->($_->[0])
1726                                            , $_->[1]
1727                                           ]
1728     : (ref $_->[0] eq 'SCALAR')         ? [ { sqlt_datatype => ${$_->[0]} }, $_->[1] ]
1729     :                                     [ $resolve_bindinfo->(
1730                                               { dbic_colname => $_->[0] }
1731                                             ), $_->[1] ]
1732     ;
1733
1734     if (
1735       ! exists $resolved->[0]{dbd_attrs}
1736         and
1737       ! $resolved->[0]{sqlt_datatype}
1738         and
1739       length ref $resolved->[1]
1740         and
1741       ! is_plain_value $resolved->[1]
1742     ) {
1743       require Data::Dumper;
1744       local $Data::Dumper::Maxdepth = 1;
1745       local $Data::Dumper::Terse = 1;
1746       local $Data::Dumper::Useqq = 1;
1747       local $Data::Dumper::Indent = 0;
1748       local $Data::Dumper::Pad = ' ';
1749       $self->throw_exception(
1750         'You must supply a datatype/bindtype (see DBIx::Class::ResultSet/DBIC BIND VALUES) '
1751       . 'for non-scalar value '. Data::Dumper::Dumper ($resolved->[1])
1752       );
1753     }
1754
1755     $resolved;
1756
1757   } @$bind ];
1758 }
1759
1760 sub _format_for_trace {
1761   #my ($self, $bind) = @_;
1762
1763   ### Turn @bind from something like this:
1764   ###   ( [ "artist", 1 ], [ \%attrs, 3 ] )
1765   ### to this:
1766   ###   ( "'1'", "'3'" )
1767
1768   map {
1769     defined( $_ && $_->[1] )
1770       ? qq{'$_->[1]'}
1771       : q{NULL}
1772   } @{$_[1] || []};
1773 }
1774
1775 sub _query_start {
1776   my ( $self, $sql, $bind ) = @_;
1777
1778   $self->debugobj->query_start( $sql, $self->_format_for_trace($bind) )
1779     if $self->debug;
1780 }
1781
1782 sub _query_end {
1783   my ( $self, $sql, $bind ) = @_;
1784
1785   $self->debugobj->query_end( $sql, $self->_format_for_trace($bind) )
1786     if $self->debug;
1787 }
1788
1789 sub _dbi_attrs_for_bind {
1790   my ($self, $ident, $bind) = @_;
1791
1792   my @attrs;
1793
1794   for (map { $_->[0] } @$bind) {
1795     push @attrs, do {
1796       if (exists $_->{dbd_attrs}) {
1797         $_->{dbd_attrs}
1798       }
1799       elsif($_->{sqlt_datatype}) {
1800         # cache the result in the dbh_details hash, as it can not change unless
1801         # we connect to something else
1802         my $cache = $self->_dbh_details->{_datatype_map_cache} ||= {};
1803         if (not exists $cache->{$_->{sqlt_datatype}}) {
1804           $cache->{$_->{sqlt_datatype}} = $self->bind_attribute_by_data_type($_->{sqlt_datatype}) || undef;
1805         }
1806         $cache->{$_->{sqlt_datatype}};
1807       }
1808       else {
1809         undef;  # always push something at this position
1810       }
1811     }
1812   }
1813
1814   return \@attrs;
1815 }
1816
1817 sub _execute {
1818   my ($self, $op, $ident, @args) = @_;
1819
1820   my ($sql, $bind) = $self->_prep_for_execute($op, $ident, \@args);
1821
1822   # not even a PID check - we do not care about the state of the _dbh.
1823   # All we need is to get the appropriate drivers loaded if they aren't
1824   # already so that the assumption in ad7c50fc26e holds
1825   $self->_populate_dbh unless $self->_dbh;
1826
1827   $self->dbh_do( _dbh_execute =>     # retry over disconnects
1828     $sql,
1829     $bind,
1830     $self->_dbi_attrs_for_bind($ident, $bind),
1831   );
1832 }
1833
1834 sub _dbh_execute {
1835   my ($self, $dbh, $sql, $bind, $bind_attrs) = @_;
1836
1837   $self->_query_start( $sql, $bind );
1838
1839   my $sth = $self->_bind_sth_params(
1840     $self->_prepare_sth($dbh, $sql),
1841     $bind,
1842     $bind_attrs,
1843   );
1844
1845   # Can this fail without throwing an exception anyways???
1846   my $rv = $sth->execute();
1847   $self->throw_exception(
1848     $sth->errstr || $sth->err || 'Unknown error: execute() returned false, but error flags were not set...'
1849   ) if !$rv;
1850
1851   $self->_query_end( $sql, $bind );
1852
1853   return (wantarray ? ($rv, $sth, @$bind) : $rv);
1854 }
1855
1856 sub _prepare_sth {
1857   my ($self, $dbh, $sql) = @_;
1858
1859   # 3 is the if_active parameter which avoids active sth re-use
1860   my $sth = $self->disable_sth_caching
1861     ? $dbh->prepare($sql)
1862     : $dbh->prepare_cached($sql, {}, 3);
1863
1864   # XXX You would think RaiseError would make this impossible,
1865   #  but apparently that's not true :(
1866   $self->throw_exception(
1867     $dbh->errstr
1868       ||
1869     sprintf( "\$dbh->prepare() of '%s' through %s failed *silently* without "
1870             .'an exception and/or setting $dbh->errstr',
1871       length ($sql) > 20
1872         ? substr($sql, 0, 20) . '...'
1873         : $sql
1874       ,
1875       'DBD::' . $dbh->{Driver}{Name},
1876     )
1877   ) if !$sth;
1878
1879   $sth;
1880 }
1881
1882 sub _bind_sth_params {
1883   my ($self, $sth, $bind, $bind_attrs) = @_;
1884
1885   for my $i (0 .. $#$bind) {
1886     if (ref $bind->[$i][1] eq 'SCALAR') {  # any scalarrefs are assumed to be bind_inouts
1887       $sth->bind_param_inout(
1888         $i + 1, # bind params counts are 1-based
1889         $bind->[$i][1],
1890         $bind->[$i][0]{dbd_size} || $self->_max_column_bytesize($bind->[$i][0]), # size
1891         $bind_attrs->[$i],
1892       );
1893     }
1894     else {
1895       # FIXME SUBOPTIMAL - DBI needs fixing to always stringify regardless of DBD
1896       my $v = ( length ref $bind->[$i][1] and is_plain_value $bind->[$i][1] )
1897         ? "$bind->[$i][1]"
1898         : $bind->[$i][1]
1899       ;
1900
1901       $sth->bind_param(
1902         $i + 1,
1903         # The temp-var is CRUCIAL - DO NOT REMOVE IT, breaks older DBD::SQLite RT#79576
1904         $v,
1905         $bind_attrs->[$i],
1906       );
1907     }
1908   }
1909
1910   $sth;
1911 }
1912
1913 sub _prefetch_autovalues {
1914   my ($self, $source, $colinfo, $to_insert) = @_;
1915
1916   my %values;
1917   for my $col (keys %$colinfo) {
1918     if (
1919       $colinfo->{$col}{auto_nextval}
1920         and
1921       (
1922         ! exists $to_insert->{$col}
1923           or
1924         is_literal_value($to_insert->{$col})
1925       )
1926     ) {
1927       $values{$col} = $self->_sequence_fetch(
1928         'NEXTVAL',
1929         ( $colinfo->{$col}{sequence} ||=
1930             $self->_dbh_get_autoinc_seq($self->_get_dbh, $source, $col)
1931         ),
1932       );
1933     }
1934   }
1935
1936   \%values;
1937 }
1938
1939 sub insert {
1940   my ($self, $source, $to_insert) = @_;
1941
1942   my $col_infos = $source->columns_info;
1943
1944   my $prefetched_values = $self->_prefetch_autovalues($source, $col_infos, $to_insert);
1945
1946   # fuse the values, but keep a separate list of prefetched_values so that
1947   # they can be fused once again with the final return
1948   $to_insert = { %$to_insert, %$prefetched_values };
1949
1950   # FIXME - we seem to assume undef values as non-supplied. This is wrong.
1951   # Investigate what does it take to s/defined/exists/
1952   my %pcols = map { $_ => 1 } $source->primary_columns;
1953   my (%retrieve_cols, $autoinc_supplied, $retrieve_autoinc_col);
1954   for my $col ($source->columns) {
1955     if ($col_infos->{$col}{is_auto_increment}) {
1956       $autoinc_supplied ||= 1 if defined $to_insert->{$col};
1957       $retrieve_autoinc_col ||= $col unless $autoinc_supplied;
1958     }
1959
1960     # nothing to retrieve when explicit values are supplied
1961     next if (
1962       defined $to_insert->{$col} and ! is_literal_value($to_insert->{$col})
1963     );
1964
1965     # the 'scalar keys' is a trick to preserve the ->columns declaration order
1966     $retrieve_cols{$col} = scalar keys %retrieve_cols if (
1967       $pcols{$col}
1968         or
1969       $col_infos->{$col}{retrieve_on_insert}
1970     );
1971   };
1972
1973   local $self->{_autoinc_supplied_for_op} = $autoinc_supplied;
1974   local $self->{_perform_autoinc_retrieval} = $retrieve_autoinc_col;
1975
1976   my ($sqla_opts, @ir_container);
1977   if (%retrieve_cols and $self->_use_insert_returning) {
1978     $sqla_opts->{returning_container} = \@ir_container
1979       if $self->_use_insert_returning_bound;
1980
1981     $sqla_opts->{returning} = [
1982       sort { $retrieve_cols{$a} <=> $retrieve_cols{$b} } keys %retrieve_cols
1983     ];
1984   }
1985
1986   my ($rv, $sth) = $self->_execute('insert', $source, $to_insert, $sqla_opts);
1987
1988   my %returned_cols = %$to_insert;
1989   if (my $retlist = $sqla_opts->{returning}) {  # if IR is supported - we will get everything in one set
1990     @ir_container = try {
1991       local $SIG{__WARN__} = sub {};
1992       my @r = $sth->fetchrow_array;
1993       $sth->finish;
1994       @r;
1995     } unless @ir_container;
1996
1997     @returned_cols{@$retlist} = @ir_container if @ir_container;
1998   }
1999   else {
2000     # pull in PK if needed and then everything else
2001     if (my @missing_pri = grep { $pcols{$_} } keys %retrieve_cols) {
2002
2003       $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" )
2004         unless $self->can('last_insert_id');
2005
2006       my @pri_values = $self->last_insert_id($source, @missing_pri);
2007
2008       $self->throw_exception( "Can't get last insert id" )
2009         unless (@pri_values == @missing_pri);
2010
2011       @returned_cols{@missing_pri} = @pri_values;
2012       delete @retrieve_cols{@missing_pri};
2013     }
2014
2015     # if there is more left to pull
2016     if (%retrieve_cols) {
2017       $self->throw_exception(
2018         'Unable to retrieve additional columns without a Primary Key on ' . $source->source_name
2019       ) unless %pcols;
2020
2021       my @left_to_fetch = sort { $retrieve_cols{$a} <=> $retrieve_cols{$b} } keys %retrieve_cols;
2022
2023       my $cur = DBIx::Class::ResultSet->new($source, {
2024         where => { map { $_ => $returned_cols{$_} } (keys %pcols) },
2025         select => \@left_to_fetch,
2026       })->cursor;
2027
2028       @returned_cols{@left_to_fetch} = $cur->next;
2029
2030       $self->throw_exception('Duplicate row returned for PK-search after fresh insert')
2031         if scalar $cur->next;
2032     }
2033   }
2034
2035   return { %$prefetched_values, %returned_cols };
2036 }
2037
2038 sub insert_bulk {
2039   my ($self, $source, $cols, $data) = @_;
2040
2041   my $colinfos = $source->columns_info($cols);
2042
2043   local $self->{_autoinc_supplied_for_op} =
2044     (grep { $_->{is_auto_increment} } values %$colinfos)
2045       ? 1
2046       : 0
2047   ;
2048
2049   # get a slice type index based on first row of data
2050   # a "column" in this context may refer to more than one bind value
2051   # e.g. \[ '?, ?', [...], [...] ]
2052   #
2053   # construct the value type index - a description of values types for every
2054   # per-column slice of $data:
2055   #
2056   # nonexistent - nonbind literal
2057   # 0 - regular value
2058   # [] of bindattrs - resolved attribute(s) of bind(s) passed via literal+bind \[] combo
2059   #
2060   # also construct the column hash to pass to the SQL generator. For plain
2061   # (non literal) values - convert the members of the first row into a
2062   # literal+bind combo, with extra positional info in the bind attr hashref.
2063   # This will allow us to match the order properly, and is so contrived
2064   # because a user-supplied literal/bind (or something else specific to a
2065   # resultsource and/or storage driver) can inject extra binds along the
2066   # way, so one can't rely on "shift positions" ordering at all. Also we
2067   # can't just hand SQLA a set of some known "values" (e.g. hashrefs that
2068   # can be later matched up by address), because we want to supply a real
2069   # value on which perhaps e.g. datatype checks will be performed
2070   my ($proto_data, $value_type_by_col_idx);
2071   for my $col_idx (0..$#$cols) {
2072     my $colname = $cols->[$col_idx];
2073     if (ref $data->[0][$col_idx] eq 'SCALAR') {
2074       # no bind value at all - no type
2075
2076       $proto_data->{$colname} = $data->[0][$col_idx];
2077     }
2078     elsif (ref $data->[0][$col_idx] eq 'REF' and ref ${$data->[0][$col_idx]} eq 'ARRAY' ) {
2079       # repack, so we don't end up mangling the original \[]
2080       my ($sql, @bind) = @${$data->[0][$col_idx]};
2081
2082       # normalization of user supplied stuff
2083       my $resolved_bind = $self->_resolve_bindattrs(
2084         $source, \@bind, $colinfos,
2085       );
2086
2087       # store value-less (attrs only) bind info - we will be comparing all
2088       # supplied binds against this for sanity
2089       $value_type_by_col_idx->{$col_idx} = [ map { $_->[0] } @$resolved_bind ];
2090
2091       $proto_data->{$colname} = \[ $sql, map { [
2092         # inject slice order to use for $proto_bind construction
2093           { %{$resolved_bind->[$_][0]}, _bind_data_slice_idx => $col_idx, _literal_bind_subindex => $_+1 }
2094             =>
2095           $resolved_bind->[$_][1]
2096         ] } (0 .. $#bind)
2097       ];
2098     }
2099     else {
2100       $value_type_by_col_idx->{$col_idx} = undef;
2101
2102       $proto_data->{$colname} = \[ '?', [
2103         { dbic_colname => $colname, _bind_data_slice_idx => $col_idx }
2104           =>
2105         $data->[0][$col_idx]
2106       ] ];
2107     }
2108   }
2109
2110   my ($sql, $proto_bind) = $self->_prep_for_execute (
2111     'insert',
2112     $source,
2113     [ $proto_data ],
2114   );
2115
2116   if (! @$proto_bind and keys %$value_type_by_col_idx) {
2117     # if the bindlist is empty and we had some dynamic binds, this means the
2118     # storage ate them away (e.g. the NoBindVars component) and interpolated
2119     # them directly into the SQL. This obviously can't be good for multi-inserts
2120     $self->throw_exception('Cannot insert_bulk without support for placeholders');
2121   }
2122
2123   # sanity checks
2124   # FIXME - devise a flag "no babysitting" or somesuch to shut this off
2125   #
2126   # use an error reporting closure for convenience (less to pass)
2127   my $bad_slice_report_cref = sub {
2128     my ($msg, $r_idx, $c_idx) = @_;
2129     $self->throw_exception(sprintf "%s for column '%s' in populate slice:\n%s",
2130       $msg,
2131       $cols->[$c_idx],
2132       do {
2133         require Data::Dumper::Concise;
2134         local $Data::Dumper::Maxdepth = 5;
2135         Data::Dumper::Concise::Dumper ({
2136           map { $cols->[$_] =>
2137             $data->[$r_idx][$_]
2138           } 0..$#$cols
2139         }),
2140       }
2141     );
2142   };
2143
2144   for my $col_idx (0..$#$cols) {
2145     my $reference_val = $data->[0][$col_idx];
2146
2147     for my $row_idx (1..$#$data) {  # we are comparing against what we got from [0] above, hence start from 1
2148       my $val = $data->[$row_idx][$col_idx];
2149
2150       if (! exists $value_type_by_col_idx->{$col_idx}) { # literal no binds
2151         if (ref $val ne 'SCALAR') {
2152           $bad_slice_report_cref->(
2153             "Incorrect value (expecting SCALAR-ref \\'$$reference_val')",
2154             $row_idx,
2155             $col_idx,
2156           );
2157         }
2158         elsif ($$val ne $$reference_val) {
2159           $bad_slice_report_cref->(
2160             "Inconsistent literal SQL value (expecting \\'$$reference_val')",
2161             $row_idx,
2162             $col_idx,
2163           );
2164         }
2165       }
2166       elsif (! defined $value_type_by_col_idx->{$col_idx} ) {  # regular non-literal value
2167         if (is_literal_value($val)) {
2168           $bad_slice_report_cref->("Literal SQL found where a plain bind value is expected", $row_idx, $col_idx);
2169         }
2170       }
2171       else {  # binds from a \[], compare type and attrs
2172         if (ref $val ne 'REF' or ref $$val ne 'ARRAY') {
2173           $bad_slice_report_cref->(
2174             "Incorrect value (expecting ARRAYREF-ref \\['${$reference_val}->[0]', ... ])",
2175             $row_idx,
2176             $col_idx,
2177           );
2178         }
2179         # start drilling down and bail out early on identical refs
2180         elsif (
2181           $reference_val != $val
2182             or
2183           $$reference_val != $$val
2184         ) {
2185           if (${$val}->[0] ne ${$reference_val}->[0]) {
2186             $bad_slice_report_cref->(
2187               "Inconsistent literal/bind SQL (expecting \\['${$reference_val}->[0]', ... ])",
2188               $row_idx,
2189               $col_idx,
2190             );
2191           }
2192           # need to check the bind attrs - a bind will happen only once for
2193           # the entire dataset, so any changes further down will be ignored.
2194           elsif (! Data::Compare::Compare(
2195             $value_type_by_col_idx->{$col_idx},
2196             [
2197               map
2198               { $_->[0] }
2199               @{$self->_resolve_bindattrs(
2200                 $source, [ @{$$val}[1 .. $#$$val] ], $colinfos,
2201               )}
2202             ],
2203           )) {
2204             $bad_slice_report_cref->(
2205               'Differing bind attributes on literal/bind values not supported',
2206               $row_idx,
2207               $col_idx,
2208             );
2209           }
2210         }
2211       }
2212     }
2213   }
2214
2215   # neither _dbh_execute_for_fetch, nor _dbh_execute_inserts_with_no_binds
2216   # are atomic (even if execute_for_fetch is a single call). Thus a safety
2217   # scope guard
2218   my $guard = $self->txn_scope_guard;
2219
2220   $self->_query_start( $sql, @$proto_bind ? [[undef => '__BULK_INSERT__' ]] : () );
2221   my $sth = $self->_prepare_sth($self->_dbh, $sql);
2222   my $rv = do {
2223     if (@$proto_bind) {
2224       # proto bind contains the information on which pieces of $data to pull
2225       # $cols is passed in only for prettier error-reporting
2226       $self->_dbh_execute_for_fetch( $source, $sth, $proto_bind, $cols, $data );
2227     }
2228     else {
2229       # bind_param_array doesn't work if there are no binds
2230       $self->_dbh_execute_inserts_with_no_binds( $sth, scalar @$data );
2231     }
2232   };
2233
2234   $self->_query_end( $sql, @$proto_bind ? [[ undef => '__BULK_INSERT__' ]] : () );
2235
2236   $guard->commit;
2237
2238   return wantarray ? ($rv, $sth, @$proto_bind) : $rv;
2239 }
2240
2241 # execute_for_fetch is capable of returning data just fine (it means it
2242 # can be used for INSERT...RETURNING and UPDATE...RETURNING. Since this
2243 # is the void-populate fast-path we will just ignore this altogether
2244 # for the time being.
2245 sub _dbh_execute_for_fetch {
2246   my ($self, $source, $sth, $proto_bind, $cols, $data) = @_;
2247
2248   # If we have any bind attributes to take care of, we will bind the
2249   # proto-bind data (which will never be used by execute_for_fetch)
2250   # However since column bindtypes are "sticky", this is sufficient
2251   # to get the DBD to apply the bindtype to all values later on
2252   my $bind_attrs = $self->_dbi_attrs_for_bind($source, $proto_bind);
2253
2254   for my $i (0 .. $#$proto_bind) {
2255     $sth->bind_param (
2256       $i+1, # DBI bind indexes are 1-based
2257       $proto_bind->[$i][1],
2258       $bind_attrs->[$i],
2259     ) if defined $bind_attrs->[$i];
2260   }
2261
2262   # At this point $data slots named in the _bind_data_slice_idx of
2263   # each piece of $proto_bind are either \[]s or plain values to be
2264   # passed in. Construct the dispensing coderef. *NOTE* the order
2265   # of $data will differ from this of the ?s in the SQL (due to
2266   # alphabetical ordering by colname). We actually do want to
2267   # preserve this behavior so that prepare_cached has a better
2268   # chance of matching on unrelated calls
2269
2270   my $fetch_row_idx = -1; # saner loop this way
2271   my $fetch_tuple = sub {
2272     return undef if ++$fetch_row_idx > $#$data;
2273
2274     return [ map {
2275       my $v = ! defined $_->{_literal_bind_subindex}
2276
2277         ? $data->[ $fetch_row_idx ]->[ $_->{_bind_data_slice_idx} ]
2278
2279         # There are no attributes to resolve here - we already did everything
2280         # when we constructed proto_bind. However we still want to sanity-check
2281         # what the user supplied, so pass stuff through to the resolver *anyway*
2282         : $self->_resolve_bindattrs (
2283             undef,  # a fake rsrc
2284             [ ${ $data->[ $fetch_row_idx ]->[ $_->{_bind_data_slice_idx} ]}->[ $_->{_literal_bind_subindex} ] ],
2285             {},     # a fake column_info bag
2286           )->[0][1]
2287       ;
2288
2289       # FIXME SUBOPTIMAL - DBI needs fixing to always stringify regardless of DBD
2290       # For the time being forcibly stringify whatever is stringifiable
2291       (length ref $v and is_plain_value $v)
2292         ? "$v"
2293         : $v
2294       ;
2295     } map { $_->[0] } @$proto_bind ];
2296   };
2297
2298   my $tuple_status = [];
2299   my ($rv, $err);
2300   try {
2301     $rv = $sth->execute_for_fetch(
2302       $fetch_tuple,
2303       $tuple_status,
2304     );
2305   }
2306   catch {
2307     $err = shift;
2308   };
2309
2310   # Not all DBDs are create equal. Some throw on error, some return
2311   # an undef $rv, and some set $sth->err - try whatever we can
2312   $err = ($sth->errstr || 'UNKNOWN ERROR ($sth->errstr is unset)') if (
2313     ! defined $err
2314       and
2315     ( !defined $rv or $sth->err )
2316   );
2317
2318   # Statement must finish even if there was an exception.
2319   try {
2320     $sth->finish
2321   }
2322   catch {
2323     $err = shift unless defined $err
2324   };
2325
2326   if (defined $err) {
2327     my $i = 0;
2328     ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i];
2329
2330     $self->throw_exception("Unexpected populate error: $err")
2331       if ($i > $#$tuple_status);
2332
2333     require Data::Dumper::Concise;
2334     $self->throw_exception(sprintf "execute_for_fetch() aborted with '%s' at populate slice:\n%s",
2335       ($tuple_status->[$i][1] || $err),
2336       Data::Dumper::Concise::Dumper( { map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) } ),
2337     );
2338   }
2339
2340   return $rv;
2341 }
2342
2343 sub _dbh_execute_inserts_with_no_binds {
2344   my ($self, $sth, $count) = @_;
2345
2346   my $err;
2347   try {
2348     my $dbh = $self->_get_dbh;
2349     local $dbh->{RaiseError} = 1;
2350     local $dbh->{PrintError} = 0;
2351
2352     $sth->execute foreach 1..$count;
2353   }
2354   catch {
2355     $err = shift;
2356   };
2357
2358   # Make sure statement is finished even if there was an exception.
2359   try {
2360     $sth->finish
2361   }
2362   catch {
2363     $err = shift unless defined $err;
2364   };
2365
2366   $self->throw_exception($err) if defined $err;
2367
2368   return $count;
2369 }
2370
2371 sub update {
2372   #my ($self, $source, @args) = @_;
2373   shift->_execute('update', @_);
2374 }
2375
2376
2377 sub delete {
2378   #my ($self, $source, @args) = @_;
2379   shift->_execute('delete', @_);
2380 }
2381
2382 sub _select {
2383   my $self = shift;
2384   $self->_execute($self->_select_args(@_));
2385 }
2386
2387 sub _select_args_to_query {
2388   my $self = shift;
2389
2390   $self->throw_exception(
2391     "Unable to generate limited query representation with 'software_limit' enabled"
2392   ) if ($_[3]->{software_limit} and ($_[3]->{offset} or $_[3]->{rows}) );
2393
2394   # my ($op, $ident, $select, $cond, $rs_attrs, $rows, $offset)
2395   #  = $self->_select_args($ident, $select, $cond, $attrs);
2396   my ($op, $ident, @args) =
2397     $self->_select_args(@_);
2398
2399   # my ($sql, $prepared_bind) = $self->_gen_sql_bind($op, $ident, [ $select, $cond, $rs_attrs, $rows, $offset ]);
2400   my ($sql, $bind) = $self->_gen_sql_bind($op, $ident, \@args);
2401
2402   # reuse the bind arrayref
2403   unshift @{$bind}, "($sql)";
2404   \$bind;
2405 }
2406
2407 sub _select_args {
2408   my ($self, $ident, $select, $where, $orig_attrs) = @_;
2409
2410   # FIXME - that kind of caching would be nice to have
2411   # however currently we *may* pass the same $orig_attrs
2412   # with different ident/select/where
2413   # the whole interface needs to be rethought, since it
2414   # was centered around the flawed SQLA API. We can do
2415   # soooooo much better now. But that is also another
2416   # battle...
2417   #return (
2418   #  'select', $orig_attrs->{!args_as_stored_at_the_end_of_this_method!}
2419   #) if $orig_attrs->{!args_as_stored_at_the_end_of_this_method!};
2420
2421   my $sql_maker = $self->sql_maker;
2422
2423   my $attrs = {
2424     %$orig_attrs,
2425     select => $select,
2426     from => $ident,
2427     where => $where,
2428   };
2429
2430   # Sanity check the attributes (SQLMaker does it too, but
2431   # in case of a software_limit we'll never reach there)
2432   if (defined $attrs->{offset}) {
2433     $self->throw_exception('A supplied offset attribute must be a non-negative integer')
2434       if ( $attrs->{offset} =~ /\D/ or $attrs->{offset} < 0 );
2435   }
2436
2437   if (defined $attrs->{rows}) {
2438     $self->throw_exception("The rows attribute must be a positive integer if present")
2439       if ( $attrs->{rows} =~ /\D/ or $attrs->{rows} <= 0 );
2440   }
2441   elsif ($attrs->{offset}) {
2442     # MySQL actually recommends this approach.  I cringe.
2443     $attrs->{rows} = $sql_maker->__max_int;
2444   }
2445
2446   # see if we will need to tear the prefetch apart to satisfy group_by == select
2447   # this is *extremely tricky* to get right, I am still not sure I did
2448   #
2449   my ($prefetch_needs_subquery, @limit_args);
2450
2451   if ( $attrs->{_grouped_by_distinct} and $attrs->{collapse} ) {
2452     # we already know there is a valid group_by (we made it) and we know it is
2453     # intended to be based *only* on non-multi stuff
2454     # short circuit the group_by parsing below
2455     $prefetch_needs_subquery = 1;
2456   }
2457   elsif (
2458     # The rationale is that even if we do *not* have collapse, we still
2459     # need to wrap the core grouped select/group_by in a subquery
2460     # so that databases that care about group_by/select equivalence
2461     # are happy (this includes MySQL in strict_mode)
2462     # If any of the other joined tables are referenced in the group_by
2463     # however - the user is on their own
2464     ( $prefetch_needs_subquery or ! $attrs->{_simple_passthrough_construction} )
2465       and
2466     $attrs->{group_by}
2467       and
2468     @{$attrs->{group_by}}
2469       and
2470     my $grp_aliases = try { # try{} because $attrs->{from} may be unreadable
2471       $self->_resolve_aliastypes_from_select_args({ from => $attrs->{from}, group_by => $attrs->{group_by} })
2472     }
2473   ) {
2474     # no aliases other than our own in group_by
2475     # if there are - do not allow subquery even if limit is present
2476     $prefetch_needs_subquery = ! scalar grep { $_ ne $attrs->{alias} } keys %{ $grp_aliases->{grouping} || {} };
2477   }
2478   elsif ( $attrs->{rows} && $attrs->{collapse} ) {
2479     # active collapse with a limit - that one is a no-brainer unless
2480     # overruled by a group_by above
2481     $prefetch_needs_subquery = 1;
2482   }
2483
2484   if ($prefetch_needs_subquery) {
2485     $attrs = $self->_adjust_select_args_for_complex_prefetch ($attrs);
2486   }
2487   elsif (! $attrs->{software_limit} ) {
2488     push @limit_args, (
2489       $attrs->{rows} || (),
2490       $attrs->{offset} || (),
2491     );
2492   }
2493
2494   # try to simplify the joinmap further (prune unreferenced type-single joins)
2495   if (
2496     ! $prefetch_needs_subquery  # already pruned
2497       and
2498     ref $attrs->{from}
2499       and
2500     reftype $attrs->{from} eq 'ARRAY'
2501       and
2502     @{$attrs->{from}} != 1
2503   ) {
2504     ($attrs->{from}, $attrs->{_aliastypes}) = $self->_prune_unused_joins ($attrs);
2505   }
2506
2507   # FIXME this is a gross, inefficient, largely incorrect and fragile hack
2508   # during the result inflation stage we *need* to know what was the aliastype
2509   # map as sqla saw it when the final pieces of SQL were being assembled
2510   # Originally we simply carried around the entirety of $attrs, but this
2511   # resulted in resultsets that are being reused growing continuously, as
2512   # the hash in question grew deeper and deeper.
2513   # Instead hand-pick what to take with us here (we actually don't need much
2514   # at this point just the map itself)
2515   $orig_attrs->{_last_sqlmaker_alias_map} = $attrs->{_aliastypes};
2516
2517 ###
2518   #   my $alias2source = $self->_resolve_ident_sources ($ident);
2519   #
2520   # This would be the point to deflate anything found in $attrs->{where}
2521   # (and leave $attrs->{bind} intact). Problem is - inflators historically
2522   # expect a result object. And all we have is a resultsource (it is trivial
2523   # to extract deflator coderefs via $alias2source above).
2524   #
2525   # I don't see a way forward other than changing the way deflators are
2526   # invoked, and that's just bad...
2527 ###
2528
2529   return ( 'select', @{$attrs}{qw(from select where)}, $attrs, @limit_args );
2530 }
2531
2532 # Returns a counting SELECT for a simple count
2533 # query. Abstracted so that a storage could override
2534 # this to { count => 'firstcol' } or whatever makes
2535 # sense as a performance optimization
2536 sub _count_select {
2537   #my ($self, $source, $rs_attrs) = @_;
2538   return { count => '*' };
2539 }
2540
2541 =head2 select
2542
2543 =over 4
2544
2545 =item Arguments: $ident, $select, $condition, $attrs
2546
2547 =back
2548
2549 Handle a SQL select statement.
2550
2551 =cut
2552
2553 sub select {
2554   my $self = shift;
2555   my ($ident, $select, $condition, $attrs) = @_;
2556   return $self->cursor_class->new($self, \@_, $attrs);
2557 }
2558
2559 sub select_single {
2560   my $self = shift;
2561   my ($rv, $sth, @bind) = $self->_select(@_);
2562   my @row = $sth->fetchrow_array;
2563   my @nextrow = $sth->fetchrow_array if @row;
2564   if(@row && @nextrow) {
2565     carp "Query returned more than one row.  SQL that returns multiple rows is DEPRECATED for ->find and ->single";
2566   }
2567   # Need to call finish() to work round broken DBDs
2568   $sth->finish();
2569   return @row;
2570 }
2571
2572 =head2 sql_limit_dialect
2573
2574 This is an accessor for the default SQL limit dialect used by a particular
2575 storage driver. Can be overridden by supplying an explicit L</limit_dialect>
2576 to L<DBIx::Class::Schema/connect>. For a list of available limit dialects
2577 see L<DBIx::Class::SQLMaker::LimitDialects>.
2578
2579 =cut
2580
2581 sub _dbh_columns_info_for {
2582   my ($self, $dbh, $table) = @_;
2583
2584   if ($dbh->can('column_info')) {
2585     my %result;
2586     my $caught;
2587     try {
2588       my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
2589       my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
2590       $sth->execute();
2591       while ( my $info = $sth->fetchrow_hashref() ){
2592         my %column_info;
2593         $column_info{data_type}   = $info->{TYPE_NAME};
2594         $column_info{size}      = $info->{COLUMN_SIZE};
2595         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
2596         $column_info{default_value} = $info->{COLUMN_DEF};
2597         my $col_name = $info->{COLUMN_NAME};
2598         $col_name =~ s/^\"(.*)\"$/$1/;
2599
2600         $result{$col_name} = \%column_info;
2601       }
2602     } catch {
2603       $caught = 1;
2604     };
2605     return \%result if !$caught && scalar keys %result;
2606   }
2607
2608   my %result;
2609   my $sth = $dbh->prepare($self->sql_maker->select($table, undef, \'1 = 0'));
2610   $sth->execute;
2611   my @columns = @{$sth->{NAME_lc}};
2612   for my $i ( 0 .. $#columns ){
2613     my %column_info;
2614     $column_info{data_type} = $sth->{TYPE}->[$i];
2615     $column_info{size} = $sth->{PRECISION}->[$i];
2616     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
2617
2618     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
2619       $column_info{data_type} = $1;
2620       $column_info{size}    = $2;
2621     }
2622
2623     $result{$columns[$i]} = \%column_info;
2624   }
2625   $sth->finish;
2626
2627   foreach my $col (keys %result) {
2628     my $colinfo = $result{$col};
2629     my $type_num = $colinfo->{data_type};
2630     my $type_name;
2631     if(defined $type_num && $dbh->can('type_info')) {
2632       my $type_info = $dbh->type_info($type_num);
2633       $type_name = $type_info->{TYPE_NAME} if $type_info;
2634       $colinfo->{data_type} = $type_name if $type_name;
2635     }
2636   }
2637
2638   return \%result;
2639 }
2640
2641 sub columns_info_for {
2642   my ($self, $table) = @_;
2643   $self->_dbh_columns_info_for ($self->_get_dbh, $table);
2644 }
2645
2646 =head2 last_insert_id
2647
2648 Return the row id of the last insert.
2649
2650 =cut
2651
2652 sub _dbh_last_insert_id {
2653     my ($self, $dbh, $source, $col) = @_;
2654
2655     my $id = try { $dbh->last_insert_id (undef, undef, $source->name, $col) };
2656
2657     return $id if defined $id;
2658
2659     my $class = ref $self;
2660     $self->throw_exception ("No storage specific _dbh_last_insert_id() method implemented in $class, and the generic DBI::last_insert_id() failed");
2661 }
2662
2663 sub last_insert_id {
2664   my $self = shift;
2665   $self->_dbh_last_insert_id ($self->_dbh, @_);
2666 }
2667
2668 =head2 _native_data_type
2669
2670 =over 4
2671
2672 =item Arguments: $type_name
2673
2674 =back
2675
2676 This API is B<EXPERIMENTAL>, will almost definitely change in the future, and
2677 currently only used by L<::AutoCast|DBIx::Class::Storage::DBI::AutoCast> and
2678 L<::Sybase::ASE|DBIx::Class::Storage::DBI::Sybase::ASE>.
2679
2680 The default implementation returns C<undef>, implement in your Storage driver if
2681 you need this functionality.
2682
2683 Should map types from other databases to the native RDBMS type, for example
2684 C<VARCHAR2> to C<VARCHAR>.
2685
2686 Types with modifiers should map to the underlying data type. For example,
2687 C<INTEGER AUTO_INCREMENT> should become C<INTEGER>.
2688
2689 Composite types should map to the container type, for example
2690 C<ENUM(foo,bar,baz)> becomes C<ENUM>.
2691
2692 =cut
2693
2694 sub _native_data_type {
2695   #my ($self, $data_type) = @_;
2696   return undef
2697 }
2698
2699 # Check if placeholders are supported at all
2700 sub _determine_supports_placeholders {
2701   my $self = shift;
2702   my $dbh  = $self->_get_dbh;
2703
2704   # some drivers provide a $dbh attribute (e.g. Sybase and $dbh->{syb_dynamic_supported})
2705   # but it is inaccurate more often than not
2706   return try {
2707     local $dbh->{PrintError} = 0;
2708     local $dbh->{RaiseError} = 1;
2709     $dbh->do('select ?', {}, 1);
2710     1;
2711   }
2712   catch {
2713     0;
2714   };
2715 }
2716
2717 # Check if placeholders bound to non-string types throw exceptions
2718 #
2719 sub _determine_supports_typeless_placeholders {
2720   my $self = shift;
2721   my $dbh  = $self->_get_dbh;
2722
2723   return try {
2724     local $dbh->{PrintError} = 0;
2725     local $dbh->{RaiseError} = 1;
2726     # this specifically tests a bind that is NOT a string
2727     $dbh->do('select 1 where 1 = ?', {}, 1);
2728     1;
2729   }
2730   catch {
2731     0;
2732   };
2733 }
2734
2735 =head2 sqlt_type
2736
2737 Returns the database driver name.
2738
2739 =cut
2740
2741 sub sqlt_type {
2742   shift->_get_dbh->{Driver}->{Name};
2743 }
2744
2745 =head2 bind_attribute_by_data_type
2746
2747 Given a datatype from column info, returns a database specific bind
2748 attribute for C<< $dbh->bind_param($val,$attribute) >> or nothing if we will
2749 let the database planner just handle it.
2750
2751 This method is always called after the driver has been determined and a DBI
2752 connection has been established. Therefore you can refer to C<DBI::$constant>
2753 and/or C<DBD::$driver::$constant> directly, without worrying about loading
2754 the correct modules.
2755
2756 =cut
2757
2758 sub bind_attribute_by_data_type {
2759     return;
2760 }
2761
2762 =head2 is_datatype_numeric
2763
2764 Given a datatype from column_info, returns a boolean value indicating if
2765 the current RDBMS considers it a numeric value. This controls how
2766 L<DBIx::Class::Row/set_column> decides whether to mark the column as
2767 dirty - when the datatype is deemed numeric a C<< != >> comparison will
2768 be performed instead of the usual C<eq>.
2769
2770 =cut
2771
2772 sub is_datatype_numeric {
2773   #my ($self, $dt) = @_;
2774
2775   return 0 unless $_[1];
2776
2777   $_[1] =~ /^ (?:
2778     numeric | int(?:eger)? | (?:tiny|small|medium|big)int | dec(?:imal)? | real | float | double (?: \s+ precision)? | (?:big)?serial
2779   ) $/ix;
2780 }
2781
2782
2783 =head2 create_ddl_dir
2784
2785 =over 4
2786
2787 =item Arguments: $schema, \@databases, $version, $directory, $preversion, \%sqlt_args
2788
2789 =back
2790
2791 Creates a SQL file based on the Schema, for each of the specified
2792 database engines in C<\@databases> in the given directory.
2793 (note: specify L<SQL::Translator> names, not L<DBI> driver names).
2794
2795 Given a previous version number, this will also create a file containing
2796 the ALTER TABLE statements to transform the previous schema into the
2797 current one. Note that these statements may contain C<DROP TABLE> or
2798 C<DROP COLUMN> statements that can potentially destroy data.
2799
2800 The file names are created using the C<ddl_filename> method below, please
2801 override this method in your schema if you would like a different file
2802 name format. For the ALTER file, the same format is used, replacing
2803 $version in the name with "$preversion-$version".
2804
2805 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
2806 The most common value for this would be C<< { add_drop_table => 1 } >>
2807 to have the SQL produced include a C<DROP TABLE> statement for each table
2808 created. For quoting purposes supply C<quote_identifiers>.
2809
2810 If no arguments are passed, then the following default values are assumed:
2811
2812 =over 4
2813
2814 =item databases  - ['MySQL', 'SQLite', 'PostgreSQL']
2815
2816 =item version    - $schema->schema_version
2817
2818 =item directory  - './'
2819
2820 =item preversion - <none>
2821
2822 =back
2823
2824 By default, C<\%sqlt_args> will have
2825
2826  { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
2827
2828 merged with the hash passed in. To disable any of those features, pass in a
2829 hashref like the following
2830
2831  { ignore_constraint_names => 0, # ... other options }
2832
2833
2834 WARNING: You are strongly advised to check all SQL files created, before applying
2835 them.
2836
2837 =cut
2838
2839 sub create_ddl_dir {
2840   my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
2841
2842   unless ($dir) {
2843     carp "No directory given, using ./\n";
2844     $dir = './';
2845   } else {
2846       -d $dir
2847         or
2848       (require File::Path and File::Path::mkpath (["$dir"]))  # mkpath does not like objects (i.e. Path::Class::Dir)
2849         or
2850       $self->throw_exception(
2851         "Failed to create '$dir': " . ($! || $@ || 'error unknown')
2852       );
2853   }
2854
2855   $self->throw_exception ("Directory '$dir' does not exist\n") unless(-d $dir);
2856
2857   $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
2858   $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
2859
2860   my $schema_version = $schema->schema_version || '1.x';
2861   $version ||= $schema_version;
2862
2863   $sqltargs = {
2864     add_drop_table => 1,
2865     ignore_constraint_names => 1,
2866     ignore_index_names => 1,
2867     quote_identifiers => $self->sql_maker->_quoting_enabled,
2868     %{$sqltargs || {}}
2869   };
2870
2871   unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy')) {
2872     $self->throw_exception("Can't create a ddl file without " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2873   }
2874
2875   my $sqlt = SQL::Translator->new( $sqltargs );
2876
2877   $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
2878   my $sqlt_schema = $sqlt->translate({ data => $schema })
2879     or $self->throw_exception ($sqlt->error);
2880
2881   foreach my $db (@$databases) {
2882     $sqlt->reset();
2883     $sqlt->{schema} = $sqlt_schema;
2884     $sqlt->producer($db);
2885
2886     my $file;
2887     my $filename = $schema->ddl_filename($db, $version, $dir);
2888     if (-e $filename && ($version eq $schema_version )) {
2889       # if we are dumping the current version, overwrite the DDL
2890       carp "Overwriting existing DDL file - $filename";
2891       unlink($filename);
2892     }
2893
2894     my $output = $sqlt->translate;
2895     if(!$output) {
2896       carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
2897       next;
2898     }
2899     if(!open($file, ">$filename")) {
2900       $self->throw_exception("Can't open $filename for writing ($!)");
2901       next;
2902     }
2903     print $file $output;
2904     close($file);
2905
2906     next unless ($preversion);
2907
2908     require SQL::Translator::Diff;
2909
2910     my $prefilename = $schema->ddl_filename($db, $preversion, $dir);
2911     if(!-e $prefilename) {
2912       carp("No previous schema file found ($prefilename)");
2913       next;
2914     }
2915
2916     my $difffile = $schema->ddl_filename($db, $version, $dir, $preversion);
2917     if(-e $difffile) {
2918       carp("Overwriting existing diff file - $difffile");
2919       unlink($difffile);
2920     }
2921
2922     my $source_schema;
2923     {
2924       my $t = SQL::Translator->new($sqltargs);
2925       $t->debug( 0 );
2926       $t->trace( 0 );
2927
2928       $t->parser( $db )
2929         or $self->throw_exception ($t->error);
2930
2931       my $out = $t->translate( $prefilename )
2932         or $self->throw_exception ($t->error);
2933
2934       $source_schema = $t->schema;
2935
2936       $source_schema->name( $prefilename )
2937         unless ( $source_schema->name );
2938     }
2939
2940     # The "new" style of producers have sane normalization and can support
2941     # diffing a SQL file against a DBIC->SQLT schema. Old style ones don't
2942     # And we have to diff parsed SQL against parsed SQL.
2943     my $dest_schema = $sqlt_schema;
2944
2945     unless ( "SQL::Translator::Producer::$db"->can('preprocess_schema') ) {
2946       my $t = SQL::Translator->new($sqltargs);
2947       $t->debug( 0 );
2948       $t->trace( 0 );
2949
2950       $t->parser( $db )
2951         or $self->throw_exception ($t->error);
2952
2953       my $out = $t->translate( $filename )
2954         or $self->throw_exception ($t->error);
2955
2956       $dest_schema = $t->schema;
2957
2958       $dest_schema->name( $filename )
2959         unless $dest_schema->name;
2960     }
2961
2962     my $diff = do {
2963       # FIXME - this is a terrible workaround for
2964       # https://github.com/dbsrgits/sql-translator/commit/2d23c1e
2965       # Fixing it in this sloppy manner so that we don't hve to
2966       # lockstep an SQLT release as well. Needs to be removed at
2967       # some point, and SQLT dep bumped
2968       local $SQL::Translator::Producer::SQLite::NO_QUOTES
2969         if $SQL::Translator::Producer::SQLite::NO_QUOTES;
2970
2971       SQL::Translator::Diff::schema_diff($source_schema, $db,
2972                                          $dest_schema,   $db,
2973                                          $sqltargs
2974                                        );
2975     };
2976
2977     if(!open $file, ">$difffile") {
2978       $self->throw_exception("Can't write to $difffile ($!)");
2979       next;
2980     }
2981     print $file $diff;
2982     close($file);
2983   }
2984 }
2985
2986 =head2 deployment_statements
2987
2988 =over 4
2989
2990 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
2991
2992 =back
2993
2994 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
2995
2996 The L<SQL::Translator> (not L<DBI>) database driver name can be explicitly
2997 provided in C<$type>, otherwise the result of L</sqlt_type> is used as default.
2998
2999 C<$directory> is used to return statements from files in a previously created
3000 L</create_ddl_dir> directory and is optional. The filenames are constructed
3001 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
3002
3003 If no C<$directory> is specified then the statements are constructed on the
3004 fly using L<SQL::Translator> and C<$version> is ignored.
3005
3006 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
3007
3008 =cut
3009
3010 sub deployment_statements {
3011   my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
3012   $type ||= $self->sqlt_type;
3013   $version ||= $schema->schema_version || '1.x';
3014   $dir ||= './';
3015   my $filename = $schema->ddl_filename($type, $version, $dir);
3016   if(-f $filename)
3017   {
3018       # FIXME replace this block when a proper sane sql parser is available
3019       my $file;
3020       open($file, "<$filename")
3021         or $self->throw_exception("Can't open $filename ($!)");
3022       my @rows = <$file>;
3023       close($file);
3024       return join('', @rows);
3025   }
3026
3027   unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy') ) {
3028     $self->throw_exception("Can't deploy without a ddl_dir or " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
3029   }
3030
3031   # sources needs to be a parser arg, but for simplicity allow at top level
3032   # coming in
3033   $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
3034       if exists $sqltargs->{sources};
3035
3036   $sqltargs->{quote_identifiers} = $self->sql_maker->_quoting_enabled
3037     unless exists $sqltargs->{quote_identifiers};
3038
3039   my $tr = SQL::Translator->new(
3040     producer => "SQL::Translator::Producer::${type}",
3041     %$sqltargs,
3042     parser => 'SQL::Translator::Parser::DBIx::Class',
3043     data => $schema,
3044   );
3045
3046   return preserve_context {
3047     $tr->translate
3048   } after => sub {
3049     $self->throw_exception( 'Unable to produce deployment statements: ' . $tr->error)
3050       unless defined $_[0];
3051   };
3052 }
3053
3054 # FIXME deploy() currently does not accurately report sql errors
3055 # Will always return true while errors are warned
3056 sub deploy {
3057   my ($self, $schema, $type, $sqltargs, $dir) = @_;
3058   my $deploy = sub {
3059     my $line = shift;
3060     return if(!$line);
3061     return if($line =~ /^--/);
3062     # next if($line =~ /^DROP/m);
3063     return if($line =~ /^BEGIN TRANSACTION/m);
3064     return if($line =~ /^COMMIT/m);
3065     return if $line =~ /^\s+$/; # skip whitespace only
3066     $self->_query_start($line);
3067     try {
3068       # do a dbh_do cycle here, as we need some error checking in
3069       # place (even though we will ignore errors)
3070       $self->dbh_do (sub { $_[1]->do($line) });
3071     } catch {
3072       carp qq{$_ (running "${line}")};
3073     };
3074     $self->_query_end($line);
3075   };
3076   my @statements = $schema->deployment_statements($type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );
3077   if (@statements > 1) {
3078     foreach my $statement (@statements) {
3079       $deploy->( $statement );
3080     }
3081   }
3082   elsif (@statements == 1) {
3083     # split on single line comments and end of statements
3084     foreach my $line ( split(/\s*--.*\n|;\n/, $statements[0])) {
3085       $deploy->( $line );
3086     }
3087   }
3088 }
3089
3090 =head2 datetime_parser
3091
3092 Returns the datetime parser class
3093
3094 =cut
3095
3096 sub datetime_parser {
3097   my $self = shift;
3098   return $self->{datetime_parser} ||= do {
3099     $self->build_datetime_parser(@_);
3100   };
3101 }
3102
3103 =head2 datetime_parser_type
3104
3105 Defines the datetime parser class - currently defaults to L<DateTime::Format::MySQL>
3106
3107 =head2 build_datetime_parser
3108
3109 See L</datetime_parser>
3110
3111 =cut
3112
3113 sub build_datetime_parser {
3114   my $self = shift;
3115   my $type = $self->datetime_parser_type(@_);
3116   return $type;
3117 }
3118
3119
3120 =head2 is_replicating
3121
3122 A boolean that reports if a particular L<DBIx::Class::Storage::DBI> is set to
3123 replicate from a master database.  Default is undef, which is the result
3124 returned by databases that don't support replication.
3125
3126 =cut
3127
3128 sub is_replicating {
3129     return;
3130
3131 }
3132
3133 =head2 lag_behind_master
3134
3135 Returns a number that represents a certain amount of lag behind a master db
3136 when a given storage is replicating.  The number is database dependent, but
3137 starts at zero and increases with the amount of lag. Default in undef
3138
3139 =cut
3140
3141 sub lag_behind_master {
3142     return;
3143 }
3144
3145 =head2 relname_to_table_alias
3146
3147 =over 4
3148
3149 =item Arguments: $relname, $join_count
3150
3151 =item Return Value: $alias
3152
3153 =back
3154
3155 L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
3156 queries.
3157
3158 This hook is to allow specific L<DBIx::Class::Storage> drivers to change the
3159 way these aliases are named.
3160
3161 The default behavior is C<< "$relname_$join_count" if $join_count > 1 >>,
3162 otherwise C<"$relname">.
3163
3164 =cut
3165
3166 sub relname_to_table_alias {
3167   my ($self, $relname, $join_count) = @_;
3168
3169   my $alias = ($join_count && $join_count > 1 ?
3170     join('_', $relname, $join_count) : $relname);
3171
3172   return $alias;
3173 }
3174
3175 # The size in bytes to use for DBI's ->bind_param_inout, this is the generic
3176 # version and it may be necessary to amend or override it for a specific storage
3177 # if such binds are necessary.
3178 sub _max_column_bytesize {
3179   my ($self, $attr) = @_;
3180
3181   my $max_size;
3182
3183   if ($attr->{sqlt_datatype}) {
3184     my $data_type = lc($attr->{sqlt_datatype});
3185
3186     if ($attr->{sqlt_size}) {
3187
3188       # String/sized-binary types
3189       if ($data_type =~ /^(?:
3190           l? (?:var)? char(?:acter)? (?:\s*varying)?
3191             |
3192           (?:var)? binary (?:\s*varying)?
3193             |
3194           raw
3195         )\b/x
3196       ) {
3197         $max_size = $attr->{sqlt_size};
3198       }
3199       # Other charset/unicode types, assume scale of 4
3200       elsif ($data_type =~ /^(?:
3201           national \s* character (?:\s*varying)?
3202             |
3203           nchar
3204             |
3205           univarchar
3206             |
3207           nvarchar
3208         )\b/x
3209       ) {
3210         $max_size = $attr->{sqlt_size} * 4;
3211       }
3212     }
3213
3214     if (!$max_size and !$self->_is_lob_type($data_type)) {
3215       $max_size = 100 # for all other (numeric?) datatypes
3216     }
3217   }
3218
3219   $max_size || $self->_dbic_connect_attributes->{LongReadLen} || $self->_get_dbh->{LongReadLen} || 8000;
3220 }
3221
3222 # Determine if a data_type is some type of BLOB
3223 sub _is_lob_type {
3224   my ($self, $data_type) = @_;
3225   $data_type && ($data_type =~ /lob|bfile|text|image|bytea|memo/i
3226     || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary
3227                                   |varchar|character\s*varying|nvarchar
3228                                   |national\s*character\s*varying))?\z/xi);
3229 }
3230
3231 sub _is_binary_lob_type {
3232   my ($self, $data_type) = @_;
3233   $data_type && ($data_type =~ /blob|bfile|image|bytea/i
3234     || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary))?\z/xi);
3235 }
3236
3237 sub _is_text_lob_type {
3238   my ($self, $data_type) = @_;
3239   $data_type && ($data_type =~ /^(?:clob|memo)\z/i
3240     || $data_type =~ /^long(?:\s+(?:varchar|character\s*varying|nvarchar
3241                         |national\s*character\s*varying))\z/xi);
3242 }
3243
3244 # Determine if a data_type is some type of a binary type
3245 sub _is_binary_type {
3246   my ($self, $data_type) = @_;
3247   $data_type && ($self->_is_binary_lob_type($data_type)
3248     || $data_type =~ /(?:var)?(?:binary|bit|graphic)(?:\s*varying)?/i);
3249 }
3250
3251 1;
3252
3253 =head1 USAGE NOTES
3254
3255 =head2 DBIx::Class and AutoCommit
3256
3257 DBIx::Class can do some wonderful magic with handling exceptions,
3258 disconnections, and transactions when you use C<< AutoCommit => 1 >>
3259 (the default) combined with L<txn_do|DBIx::Class::Storage/txn_do> for
3260 transaction support.
3261
3262 If you set C<< AutoCommit => 0 >> in your connect info, then you are always
3263 in an assumed transaction between commits, and you're telling us you'd
3264 like to manage that manually.  A lot of the magic protections offered by
3265 this module will go away.  We can't protect you from exceptions due to database
3266 disconnects because we don't know anything about how to restart your
3267 transactions.  You're on your own for handling all sorts of exceptional
3268 cases if you choose the C<< AutoCommit => 0 >> path, just as you would
3269 be with raw DBI.
3270
3271
3272 =head1 AUTHOR AND CONTRIBUTORS
3273
3274 See L<AUTHOR|DBIx::Class/AUTHOR> and L<CONTRIBUTORS|DBIx::Class/CONTRIBUTORS> in DBIx::Class
3275
3276 =head1 LICENSE
3277
3278 You may distribute this code under the same terms as Perl itself.
3279
3280 =cut