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