1 package DBIx::Class::Storage::DBI;
2 # -*- mode: cperl; cperl-indent-level: 2 -*-
7 use base qw/DBIx::Class::Storage::DBIHacks DBIx::Class::Storage/;
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';
20 # default cursor class, overridable in connect_info attributes
21 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
23 __PACKAGE__->mk_group_accessors('inherited' => qw/
24 sql_limit_dialect sql_quote_char sql_name_sep
27 __PACKAGE__->mk_group_accessors('component_class' => qw/sql_maker_class datetime_parser_type/);
29 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker');
30 __PACKAGE__->datetime_parser_type('DateTime::Format::MySQL'); # historic default
32 __PACKAGE__->sql_name_sep('.');
34 __PACKAGE__->mk_group_accessors('simple' => qw/
35 _connect_info _dbi_connect_info _dbic_connect_attributes _driver_determined
36 _dbh _dbh_details _conn_pid _sql_maker _sql_maker_opts
37 transaction_depth _dbh_autocommit savepoints
40 # the values for these accessors are picked out (and deleted) from
41 # the attribute hashref passed to connect_info
42 my @storage_options = qw/
43 on_connect_call on_disconnect_call on_connect_do on_disconnect_do
44 disable_sth_caching unsafe auto_savepoint
46 __PACKAGE__->mk_group_accessors('simple' => @storage_options);
49 # capability definitions, using a 2-tiered accessor system
52 # A driver/user may define _use_X, which blindly without any checks says:
53 # "(do not) use this capability", (use_dbms_capability is an "inherited"
56 # If _use_X is undef, _supports_X is then queried. This is a "simple" style
57 # accessor, which in turn calls _determine_supports_X, and stores the return
58 # in a special slot on the storage object, which is wiped every time a $dbh
59 # reconnection takes place (it is not guaranteed that upon reconnection we
60 # will get the same rdbms version). _determine_supports_X does not need to
61 # exist on a driver, as we ->can for it before calling.
63 my @capabilities = (qw/
65 insert_returning_bound
70 __PACKAGE__->mk_group_accessors( dbms_capability => map { "_supports_$_" } @capabilities );
71 __PACKAGE__->mk_group_accessors( use_dbms_capability => map { "_use_$_" } (@capabilities ) );
73 # on by default, not strictly a capability (pending rewrite)
74 __PACKAGE__->_use_join_optimizer (1);
75 sub _determine_supports_join_optimizer { 1 };
77 # Each of these methods need _determine_driver called before itself
78 # in order to function reliably. This is a purely DRY optimization
80 # get_(use)_dbms_capability need to be called on the correct Storage
81 # class, as _use_X may be hardcoded class-wide, and _supports_X calls
82 # _determine_supports_X which obv. needs a correct driver as well
83 my @rdbms_specific_methods = qw/
97 get_use_dbms_capability
104 for my $meth (@rdbms_specific_methods) {
106 my $orig = __PACKAGE__->can ($meth)
107 or die "$meth is not a ::Storage::DBI method!";
110 no warnings qw/redefine/;
111 *{__PACKAGE__ ."::$meth"} = subname $meth => sub {
113 # only fire when invoked on an instance, a valid class-based invocation
114 # would e.g. be setting a default for an inherited accessor
117 ! $_[0]->_driver_determined
119 ! $_[0]->{_in_determine_driver}
121 $_[0]->_determine_driver;
123 # This for some reason crashes and burns on perl 5.8.1
124 # IFF the method ends up throwing an exception
125 #goto $_[0]->can ($meth);
127 my $cref = $_[0]->can ($meth);
138 DBIx::Class::Storage::DBI - DBI storage handler
142 my $schema = MySchema->connect('dbi:SQLite:my.db');
144 $schema->storage->debug(1);
146 my @stuff = $schema->storage->dbh_do(
148 my ($storage, $dbh, @args) = @_;
149 $dbh->do("DROP TABLE authors");
154 $schema->resultset('Book')->search({
155 written_on => $schema->storage->datetime_parser->format_datetime(DateTime->now)
160 This class represents the connection to an RDBMS via L<DBI>. See
161 L<DBIx::Class::Storage> for general information. This pod only
162 documents DBI-specific methods and behaviors.
169 my $new = shift->next::method(@_);
171 $new->transaction_depth(0);
172 $new->_sql_maker_opts({});
173 $new->_dbh_details({});
174 $new->{savepoints} = [];
175 $new->{_in_dbh_do} = 0;
176 $new->{_dbh_gen} = 0;
178 # read below to see what this does
179 $new->_arm_global_destructor;
184 # This is hack to work around perl shooting stuff in random
185 # order on exit(). If we do not walk the remaining storage
186 # objects in an END block, there is a *small but real* chance
187 # of a fork()ed child to kill the parent's shared DBI handle,
188 # *before perl reaches the DESTROY in this package*
189 # Yes, it is ugly and effective.
190 # Additionally this registry is used by the CLONE method to
191 # make sure no handles are shared between threads
193 my %seek_and_destroy;
195 sub _arm_global_destructor {
197 my $key = refaddr ($self);
198 $seek_and_destroy{$key} = $self;
199 weaken ($seek_and_destroy{$key});
203 local $?; # just in case the DBI destructor changes it somehow
205 # destroy just the object if not native to this process/thread
206 $_->_verify_pid for (grep
208 values %seek_and_destroy
213 # As per DBI's recommendation, DBIC disconnects all handles as
214 # soon as possible (DBIC will reconnect only on demand from within
216 for (values %seek_and_destroy) {
218 $_->{_dbh_gen}++; # so that existing cursors will drop as well
227 # some databases spew warnings on implicit disconnect
228 local $SIG{__WARN__} = sub {};
231 # this op is necessary, since the very last perl runtime statement
232 # triggers a global destruction shootout, and the $SIG localization
233 # may very well be destroyed before perl actually gets to do the
238 # handle pid changes correctly - do not destroy parent's connection
242 my $pid = $self->_conn_pid;
243 if( defined $pid and $pid != $$ and my $dbh = $self->_dbh ) {
244 $dbh->{InactiveDestroy} = 1;
254 This method is normally called by L<DBIx::Class::Schema/connection>, which
255 encapsulates its argument list in an arrayref before passing them here.
257 The argument list may contain:
263 The same 4-element argument set one would normally pass to
264 L<DBI/connect>, optionally followed by
265 L<extra attributes|/DBIx::Class specific connection attributes>
266 recognized by DBIx::Class:
268 $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
272 A single code reference which returns a connected
273 L<DBI database handle|DBI/connect> optionally followed by
274 L<extra attributes|/DBIx::Class specific connection attributes> recognized
277 $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
281 A single hashref with all the attributes and the dsn/user/password
284 $connect_info_args = [{
292 $connect_info_args = [{
293 dbh_maker => sub { DBI->connect (...) },
298 This is particularly useful for L<Catalyst> based applications, allowing the
299 following config (L<Config::General> style):
304 dsn dbi:mysql:database=test
311 The C<dsn>/C<user>/C<password> combination can be substituted by the
312 C<dbh_maker> key whose value is a coderef that returns a connected
313 L<DBI database handle|DBI/connect>
317 Please note that the L<DBI> docs recommend that you always explicitly
318 set C<AutoCommit> to either I<0> or I<1>. L<DBIx::Class> further
319 recommends that it be set to I<1>, and that you perform transactions
320 via our L<DBIx::Class::Schema/txn_do> method. L<DBIx::Class> will set it
321 to I<1> if you do not do explicitly set it to zero. This is the default
322 for most DBDs. See L</DBIx::Class and AutoCommit> for details.
324 =head3 DBIx::Class specific connection attributes
326 In addition to the standard L<DBI|DBI/ATTRIBUTES_COMMON_TO_ALL_HANDLES>
327 L<connection|DBI/Database_Handle_Attributes> attributes, DBIx::Class recognizes
328 the following connection options. These options can be mixed in with your other
329 L<DBI> connection attributes, or placed in a separate hashref
330 (C<\%extra_attributes>) as shown above.
332 Every time C<connect_info> is invoked, any previous settings for
333 these options will be cleared before setting the new ones, regardless of
334 whether any options are specified in the new C<connect_info>.
341 Specifies things to do immediately after connecting or re-connecting to
342 the database. Its value may contain:
348 This contains one SQL statement to execute.
350 =item an array reference
352 This contains SQL statements to execute in order. Each element contains
353 a string or a code reference that returns a string.
355 =item a code reference
357 This contains some code to execute. Unlike code references within an
358 array reference, its return value is ignored.
362 =item on_disconnect_do
364 Takes arguments in the same form as L</on_connect_do> and executes them
365 immediately before disconnecting from the database.
367 Note, this only runs if you explicitly call L</disconnect> on the
370 =item on_connect_call
372 A more generalized form of L</on_connect_do> that calls the specified
373 C<connect_call_METHOD> methods in your storage driver.
375 on_connect_do => 'select 1'
379 on_connect_call => [ [ do_sql => 'select 1' ] ]
381 Its values may contain:
387 Will call the C<connect_call_METHOD> method.
389 =item a code reference
391 Will execute C<< $code->($storage) >>
393 =item an array reference
395 Each value can be a method name or code reference.
397 =item an array of arrays
399 For each array, the first item is taken to be the C<connect_call_> method name
400 or code reference, and the rest are parameters to it.
404 Some predefined storage methods you may use:
410 Executes a SQL string or a code reference that returns a SQL string. This is
411 what L</on_connect_do> and L</on_disconnect_do> use.
419 Will execute the scalar as SQL.
423 Taken to be arguments to L<DBI/do>, the SQL string optionally followed by the
424 attributes hashref and bind values.
426 =item a code reference
428 Will execute C<< $code->($storage) >> and execute the return array refs as
435 Execute any statements necessary to initialize the database session to return
436 and accept datetime/timestamp values used with
437 L<DBIx::Class::InflateColumn::DateTime>.
439 Only necessary for some databases, see your specific storage driver for
440 implementation details.
444 =item on_disconnect_call
446 Takes arguments in the same form as L</on_connect_call> and executes them
447 immediately before disconnecting from the database.
449 Calls the C<disconnect_call_METHOD> methods as opposed to the
450 C<connect_call_METHOD> methods called by L</on_connect_call>.
452 Note, this only runs if you explicitly call L</disconnect> on the
455 =item disable_sth_caching
457 If set to a true value, this option will disable the caching of
458 statement handles via L<DBI/prepare_cached>.
462 Sets a specific SQL::Abstract::Limit-style limit dialect, overriding the
463 default L</sql_limit_dialect> setting of the storage (if any). For a list
464 of available limit dialects see L<DBIx::Class::SQLMaker::LimitDialects>.
468 When true automatically sets L</quote_char> and L</name_sep> to the characters
469 appropriate for your particular RDBMS. This option is preferred over specifying
470 L</quote_char> directly.
474 Specifies what characters to use to quote table and column names.
476 C<quote_char> expects either a single character, in which case is it
477 is placed on either side of the table/column name, or an arrayref of length
478 2 in which case the table/column name is placed between the elements.
480 For example under MySQL you should use C<< quote_char => '`' >>, and for
481 SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
485 This parameter is only useful in conjunction with C<quote_char>, and is used to
486 specify the character that separates elements (schemas, tables, columns) from
487 each other. If unspecified it defaults to the most commonly used C<.>.
491 This Storage driver normally installs its own C<HandleError>, sets
492 C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
493 all database handles, including those supplied by a coderef. It does this
494 so that it can have consistent and useful error behavior.
496 If you set this option to a true value, Storage will not do its usual
497 modifications to the database handle's attributes, and instead relies on
498 the settings in your connect_info DBI options (or the values you set in
499 your connection coderef, in the case that you are connecting via coderef).
501 Note that your custom settings can cause Storage to malfunction,
502 especially if you set a C<HandleError> handler that suppresses exceptions
503 and/or disable C<RaiseError>.
507 If this option is true, L<DBIx::Class> will use savepoints when nesting
508 transactions, making it possible to recover from failure in the inner
509 transaction without having to abort all outer transactions.
513 Use this argument to supply a cursor class other than the default
514 L<DBIx::Class::Storage::DBI::Cursor>.
518 Some real-life examples of arguments to L</connect_info> and
519 L<DBIx::Class::Schema/connect>
521 # Simple SQLite connection
522 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
525 ->connect_info([ sub { DBI->connect(...) } ]);
527 # Connect via subref in hashref
529 dbh_maker => sub { DBI->connect(...) },
530 on_connect_do => 'alter session ...',
533 # A bit more complicated
540 { quote_char => q{"} },
544 # Equivalent to the previous example
550 { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
554 # Same, but with hashref as argument
555 # See parse_connect_info for explanation
558 dsn => 'dbi:Pg:dbname=foo',
560 password => 'my_pg_password',
567 # Subref + DBIx::Class-specific connection options
570 sub { DBI->connect(...) },
574 on_connect_do => ['SET search_path TO myschema,otherschema,public'],
575 disable_sth_caching => 1,
585 my ($self, $info) = @_;
587 return $self->_connect_info if !$info;
589 $self->_connect_info($info); # copy for _connect_info
591 $info = $self->_normalize_connect_info($info)
592 if ref $info eq 'ARRAY';
594 for my $storage_opt (keys %{ $info->{storage_options} }) {
595 my $value = $info->{storage_options}{$storage_opt};
597 $self->$storage_opt($value);
600 # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
601 # the new set of options
602 $self->_sql_maker(undef);
603 $self->_sql_maker_opts({});
605 for my $sql_maker_opt (keys %{ $info->{sql_maker_options} }) {
606 my $value = $info->{sql_maker_options}{$sql_maker_opt};
608 $self->_sql_maker_opts->{$sql_maker_opt} = $value;
612 %{ $self->_default_dbi_connect_attributes || {} },
613 %{ $info->{attributes} || {} },
616 my @args = @{ $info->{arguments} };
618 if (keys %attrs and ref $args[0] ne 'CODE') {
620 'You provided explicit AutoCommit => 0 in your connection_info. '
621 . 'This is almost universally a bad idea (see the footnotes of '
622 . 'DBIx::Class::Storage::DBI for more info). If you still want to '
623 . 'do this you can set $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK} to disable '
625 if ! $attrs{AutoCommit} and ! $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK};
627 push @args, \%attrs if keys %attrs;
629 $self->_dbi_connect_info(\@args);
632 # save attributes them in a separate accessor so they are always
633 # introspectable, even in case of a CODE $dbhmaker
634 $self->_dbic_connect_attributes (\%attrs);
636 return $self->_connect_info;
639 sub _normalize_connect_info {
640 my ($self, $info_arg) = @_;
643 my @args = @$info_arg; # take a shallow copy for further mutilation
645 # combine/pre-parse arguments depending on invocation style
648 if (ref $args[0] eq 'CODE') { # coderef with optional \%extra_attributes
649 %attrs = %{ $args[1] || {} };
652 elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
653 %attrs = %{$args[0]};
655 if (my $code = delete $attrs{dbh_maker}) {
658 my @ignored = grep { delete $attrs{$_} } (qw/dsn user password/);
661 'Attribute(s) %s in connect_info were ignored, as they can not be applied '
662 . "to the result of 'dbh_maker'",
664 join (', ', map { "'$_'" } (@ignored) ),
669 @args = delete @attrs{qw/dsn user password/};
672 else { # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
674 % { $args[3] || {} },
675 % { $args[4] || {} },
677 @args = @args[0,1,2];
680 $info{arguments} = \@args;
682 my @storage_opts = grep exists $attrs{$_},
683 @storage_options, 'cursor_class';
685 @{ $info{storage_options} }{@storage_opts} =
686 delete @attrs{@storage_opts} if @storage_opts;
688 my @sql_maker_opts = grep exists $attrs{$_},
689 qw/limit_dialect quote_char name_sep quote_names/;
691 @{ $info{sql_maker_options} }{@sql_maker_opts} =
692 delete @attrs{@sql_maker_opts} if @sql_maker_opts;
694 $info{attributes} = \%attrs if %attrs;
699 sub _default_dbi_connect_attributes () {
704 ShowErrorStatement => 1,
710 This method is deprecated in favour of setting via L</connect_info>.
714 =head2 on_disconnect_do
716 This method is deprecated in favour of setting via L</connect_info>.
720 sub _parse_connect_do {
721 my ($self, $type) = @_;
723 my $val = $self->$type;
724 return () if not defined $val;
729 push @res, [ 'do_sql', $val ];
730 } elsif (ref($val) eq 'CODE') {
732 } elsif (ref($val) eq 'ARRAY') {
733 push @res, map { [ 'do_sql', $_ ] } @$val;
735 $self->throw_exception("Invalid type for $type: ".ref($val));
743 Arguments: ($subref | $method_name), @extra_coderef_args?
745 Execute the given $subref or $method_name using the new exception-based
746 connection management.
748 The first two arguments will be the storage object that C<dbh_do> was called
749 on and a database handle to use. Any additional arguments will be passed
750 verbatim to the called subref as arguments 2 and onwards.
752 Using this (instead of $self->_dbh or $self->dbh) ensures correct
753 exception handling and reconnection (or failover in future subclasses).
755 Your subref should have no side-effects outside of the database, as
756 there is the potential for your subref to be partially double-executed
757 if the database connection was stale/dysfunctional.
761 my @stuff = $schema->storage->dbh_do(
763 my ($storage, $dbh, @cols) = @_;
764 my $cols = join(q{, }, @cols);
765 $dbh->selectrow_array("SELECT $cols FROM foo");
776 my $dbh = $self->_get_dbh;
778 return $self->$code($dbh, @_)
779 if ( $self->{_in_dbh_do} || $self->{transaction_depth} );
781 local $self->{_in_dbh_do} = 1;
783 # take a ref instead of a copy, to preserve coderef @_ aliasing semantics
786 $self->$code ($dbh, @$args);
788 $self->throw_exception($_) if $self->connected;
790 # We were not connected - reconnect and retry, but let any
791 # exception fall right through this time
792 carp "Retrying $code after catching disconnected exception: $_"
793 if $ENV{DBIC_DBIRETRY_DEBUG};
795 $self->_populate_dbh;
796 $self->$code($self->_dbh, @$args);
800 # This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do.
801 # It also informs dbh_do to bypass itself while under the direction of txn_do,
802 # via $self->{_in_dbh_do} (this saves some redundant eval and errorcheck, etc)
807 ref $coderef eq 'CODE' or $self->throw_exception
808 ('$coderef must be a CODE reference');
810 local $self->{_in_dbh_do} = 1;
813 my $want = wantarray;
819 # take a ref instead of a copy, to preserve coderef @_ aliasing semantics
824 my $txn_start_depth = $self->transaction_depth;
826 @result = $coderef->(@$args);
828 elsif(defined $want) {
829 $result[0] = $coderef->(@$args);
835 my $delta_txn = $txn_start_depth - $self->transaction_depth;
836 if ($delta_txn == 0) {
839 elsif ($delta_txn != 1) {
840 # an off-by-one would mean we fired a rollback
841 carp "Unexpected reduction of transaction depth by $delta_txn after execution of $coderef";
847 if(! defined $exception) { return wantarray ? @result : $result[0] }
849 if($self->transaction_depth > 1 || $tried++ || $self->connected) {
850 my $rollback_exception;
851 try { $self->txn_rollback } catch { $rollback_exception = shift };
852 if(defined $rollback_exception) {
853 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
854 $self->throw_exception($exception) # propagate nested rollback
855 if $rollback_exception =~ /$exception_class/;
857 $self->throw_exception(
858 "Transaction aborted: ${exception}. "
859 . "Rollback failed: ${rollback_exception}"
862 $self->throw_exception($exception)
865 # We were not connected, and was first try - reconnect and retry
867 carp "Retrying $coderef after catching disconnected exception: $exception"
868 if $ENV{DBIC_TXNRETRY_DEBUG};
869 $self->_populate_dbh;
875 Our C<disconnect> method also performs a rollback first if the
876 database is not in C<AutoCommit> mode.
886 push @actions, ( $self->on_disconnect_call || () );
887 push @actions, $self->_parse_connect_do ('on_disconnect_do');
889 $self->_do_connection_actions(disconnect_call_ => $_) for @actions;
891 $self->_dbh_rollback unless $self->_dbh_autocommit;
893 %{ $self->_dbh->{CachedKids} } = ();
894 $self->_dbh->disconnect;
900 =head2 with_deferred_fk_checks
904 =item Arguments: C<$coderef>
906 =item Return Value: The return value of $coderef
910 Storage specific method to run the code ref with FK checks deferred or
911 in MySQL's case disabled entirely.
915 # Storage subclasses should override this
916 sub with_deferred_fk_checks {
917 my ($self, $sub) = @_;
925 =item Arguments: none
927 =item Return Value: 1|0
931 Verifies that the current database handle is active and ready to execute
932 an SQL statement (e.g. the connection did not get stale, server is still
933 answering, etc.) This method is used internally by L</dbh>.
939 return 0 unless $self->_seems_connected;
942 local $self->_dbh->{RaiseError} = 1;
947 sub _seems_connected {
952 my $dbh = $self->_dbh
955 return $dbh->FETCH('Active');
961 my $dbh = $self->_dbh or return 0;
966 sub ensure_connected {
969 unless ($self->connected) {
970 $self->_populate_dbh;
976 Returns a C<$dbh> - a data base handle of class L<DBI>. The returned handle
977 is guaranteed to be healthy by implicitly calling L</connected>, and if
978 necessary performing a reconnection before returning. Keep in mind that this
979 is very B<expensive> on some database engines. Consider using L</dbh_do>
987 if (not $self->_dbh) {
988 $self->_populate_dbh;
990 $self->ensure_connected;
995 # this is the internal "get dbh or connect (don't check)" method
999 $self->_populate_dbh unless $self->_dbh;
1005 unless ($self->_sql_maker) {
1006 my $sql_maker_class = $self->sql_maker_class;
1008 my %opts = %{$self->_sql_maker_opts||{}};
1010 $opts{limit_dialect}
1012 $self->sql_limit_dialect
1015 my $s_class = (ref $self) || $self;
1017 "Your storage class ($s_class) does not set sql_limit_dialect and you "
1018 . 'have not supplied an explicit limit_dialect in your connection_info. '
1019 . 'DBIC will attempt to use the GenericSubQ dialect, which works on most '
1020 . 'databases but can be (and often is) painfully slow. '
1021 . "Please file an RT ticket against '$s_class' ."
1028 my ($quote_char, $name_sep);
1030 if ($opts{quote_names}) {
1031 $quote_char = (delete $opts{quote_char}) || $self->sql_quote_char || do {
1032 my $s_class = (ref $self) || $self;
1034 "You requested 'quote_names' but your storage class ($s_class) does "
1035 . 'not explicitly define a default sql_quote_char and you have not '
1036 . 'supplied a quote_char as part of your connection_info. DBIC will '
1037 .q{default to the ANSI SQL standard quote '"', which works most of }
1038 . "the time. Please file an RT ticket against '$s_class'."
1044 $name_sep = (delete $opts{name_sep}) || $self->sql_name_sep;
1047 $self->_sql_maker($sql_maker_class->new(
1048 bindtype=>'columns',
1049 array_datatypes => 1,
1050 limit_dialect => $dialect,
1051 ($quote_char ? (quote_char => $quote_char) : ()),
1052 name_sep => ($name_sep || '.'),
1056 return $self->_sql_maker;
1059 # nothing to do by default
1066 my @info = @{$self->_dbi_connect_info || []};
1067 $self->_dbh(undef); # in case ->connected failed we might get sent here
1068 $self->_dbh_details({}); # reset everything we know
1070 $self->_dbh($self->_connect(@info));
1072 $self->_conn_pid($$) if $^O ne 'MSWin32'; # on win32 these are in fact threads
1074 $self->_determine_driver;
1076 # Always set the transaction depth on connect, since
1077 # there is no transaction in progress by definition
1078 $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
1080 $self->_run_connection_actions unless $self->{_in_determine_driver};
1083 sub _run_connection_actions {
1087 push @actions, ( $self->on_connect_call || () );
1088 push @actions, $self->_parse_connect_do ('on_connect_do');
1090 $self->_do_connection_actions(connect_call_ => $_) for @actions;
1095 sub set_use_dbms_capability {
1096 $_[0]->set_inherited ($_[1], $_[2]);
1099 sub get_use_dbms_capability {
1100 my ($self, $capname) = @_;
1102 my $use = $self->get_inherited ($capname);
1105 : do { $capname =~ s/^_use_/_supports_/; $self->get_dbms_capability ($capname) }
1109 sub set_dbms_capability {
1110 $_[0]->_dbh_details->{capability}{$_[1]} = $_[2];
1113 sub get_dbms_capability {
1114 my ($self, $capname) = @_;
1116 my $cap = $self->_dbh_details->{capability}{$capname};
1118 unless (defined $cap) {
1119 if (my $meth = $self->can ("_determine$capname")) {
1120 $cap = $self->$meth ? 1 : 0;
1126 $self->set_dbms_capability ($capname, $cap);
1136 unless ($info = $self->_dbh_details->{info}) {
1140 my $server_version = try { $self->_get_server_version };
1142 if (defined $server_version) {
1143 $info->{dbms_version} = $server_version;
1145 my ($numeric_version) = $server_version =~ /^([\d\.]+)/;
1146 my @verparts = split (/\./, $numeric_version);
1152 # consider only up to 3 version parts, iff not more than 3 digits
1154 while (@verparts && @use_parts < 3) {
1155 my $p = shift @verparts;
1157 push @use_parts, $p;
1159 push @use_parts, 0 while @use_parts < 3;
1161 $info->{normalized_dbms_version} = sprintf "%d.%03d%03d", @use_parts;
1165 $self->_dbh_details->{info} = $info;
1171 sub _get_server_version {
1172 shift->_dbh_get_info(18);
1176 my ($self, $info) = @_;
1178 return try { $self->_get_dbh->get_info($info) } || undef;
1181 sub _determine_driver {
1184 if ((not $self->_driver_determined) && (not $self->{_in_determine_driver})) {
1185 my $started_connected = 0;
1186 local $self->{_in_determine_driver} = 1;
1188 if (ref($self) eq __PACKAGE__) {
1190 if ($self->_dbh) { # we are connected
1191 $driver = $self->_dbh->{Driver}{Name};
1192 $started_connected = 1;
1194 # if connect_info is a CODEREF, we have no choice but to connect
1195 if (ref $self->_dbi_connect_info->[0] &&
1196 reftype $self->_dbi_connect_info->[0] eq 'CODE') {
1197 $self->_populate_dbh;
1198 $driver = $self->_dbh->{Driver}{Name};
1201 # try to use dsn to not require being connected, the driver may still
1202 # force a connection in _rebless to determine version
1203 # (dsn may not be supplied at all if all we do is make a mock-schema)
1204 my $dsn = $self->_dbi_connect_info->[0] || $ENV{DBI_DSN} || '';
1205 ($driver) = $dsn =~ /dbi:([^:]+):/i;
1206 $driver ||= $ENV{DBI_DRIVER};
1211 my $storage_class = "DBIx::Class::Storage::DBI::${driver}";
1212 if ($self->load_optional_class($storage_class)) {
1213 mro::set_mro($storage_class, 'c3');
1214 bless $self, $storage_class;
1220 $self->_driver_determined(1);
1222 Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
1224 $self->_init; # run driver-specific initializations
1226 $self->_run_connection_actions
1227 if !$started_connected && defined $self->_dbh;
1231 sub _do_connection_actions {
1233 my $method_prefix = shift;
1236 if (not ref($call)) {
1237 my $method = $method_prefix . $call;
1239 } elsif (ref($call) eq 'CODE') {
1241 } elsif (ref($call) eq 'ARRAY') {
1242 if (ref($call->[0]) ne 'ARRAY') {
1243 $self->_do_connection_actions($method_prefix, $_) for @$call;
1245 $self->_do_connection_actions($method_prefix, @$_) for @$call;
1248 $self->throw_exception (sprintf ("Don't know how to process conection actions of type '%s'", ref($call)) );
1254 sub connect_call_do_sql {
1256 $self->_do_query(@_);
1259 sub disconnect_call_do_sql {
1261 $self->_do_query(@_);
1264 # override in db-specific backend when necessary
1265 sub connect_call_datetime_setup { 1 }
1268 my ($self, $action) = @_;
1270 if (ref $action eq 'CODE') {
1271 $action = $action->($self);
1272 $self->_do_query($_) foreach @$action;
1275 # Most debuggers expect ($sql, @bind), so we need to exclude
1276 # the attribute hash which is the second argument to $dbh->do
1277 # furthermore the bind values are usually to be presented
1278 # as named arrayref pairs, so wrap those here too
1279 my @do_args = (ref $action eq 'ARRAY') ? (@$action) : ($action);
1280 my $sql = shift @do_args;
1281 my $attrs = shift @do_args;
1282 my @bind = map { [ undef, $_ ] } @do_args;
1284 $self->_query_start($sql, @bind);
1285 $self->_get_dbh->do($sql, $attrs, @do_args);
1286 $self->_query_end($sql, @bind);
1293 my ($self, @info) = @_;
1295 $self->throw_exception("You failed to provide any connection info")
1298 my ($old_connect_via, $dbh);
1300 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
1301 $old_connect_via = $DBI::connect_via;
1302 $DBI::connect_via = 'connect';
1306 if(ref $info[0] eq 'CODE') {
1307 $dbh = $info[0]->();
1311 $dbh = DBI->connect(@info);
1318 unless ($self->unsafe) {
1320 $self->throw_exception(
1321 'Refusing clobbering of {HandleError} installed on externally supplied '
1322 ."DBI handle $dbh. Either remove the handler or use the 'unsafe' attribute."
1323 ) if $dbh->{HandleError} and ref $dbh->{HandleError} ne '__DBIC__DBH__ERROR__HANDLER__';
1325 # Default via _default_dbi_connect_attributes is 1, hence it was an explicit
1326 # request, or an external handle. Complain and set anyway
1327 unless ($dbh->{RaiseError}) {
1328 carp( ref $info[0] eq 'CODE'
1330 ? "The 'RaiseError' of the externally supplied DBI handle is set to false. "
1331 ."DBIx::Class will toggle it back to true, unless the 'unsafe' connect "
1332 .'attribute has been supplied'
1334 : 'RaiseError => 0 supplied in your connection_info, without an explicit '
1335 .'unsafe => 1. Toggling RaiseError back to true'
1338 $dbh->{RaiseError} = 1;
1341 # this odd anonymous coderef dereference is in fact really
1342 # necessary to avoid the unwanted effect described in perl5
1345 my $weak_self = $_[0];
1348 # the coderef is blessed so we can distinguish it from externally
1349 # supplied handles (which must be preserved)
1350 $_[1]->{HandleError} = bless sub {
1352 $weak_self->throw_exception("DBI Exception: $_[0]");
1355 # the handler may be invoked by something totally out of
1357 DBIx::Class::Exception->throw("DBI Exception (unhandled by DBIC, ::Schema GCed): $_[0]");
1359 }, '__DBIC__DBH__ERROR__HANDLER__';
1364 $self->throw_exception("DBI Connection failed: $_")
1367 $DBI::connect_via = $old_connect_via if $old_connect_via;
1370 $self->_dbh_autocommit($dbh->{AutoCommit});
1375 my ($self, $name) = @_;
1377 $name = $self->_svp_generate_name
1378 unless defined $name;
1380 $self->throw_exception ("You can't use savepoints outside a transaction")
1381 if $self->{transaction_depth} == 0;
1383 $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1384 unless $self->can('_svp_begin');
1386 push @{ $self->{savepoints} }, $name;
1388 $self->debugobj->svp_begin($name) if $self->debug;
1390 return $self->_svp_begin($name);
1394 my ($self, $name) = @_;
1396 $self->throw_exception ("You can't use savepoints outside a transaction")
1397 if $self->{transaction_depth} == 0;
1399 $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1400 unless $self->can('_svp_release');
1402 if (defined $name) {
1403 $self->throw_exception ("Savepoint '$name' does not exist")
1404 unless grep { $_ eq $name } @{ $self->{savepoints} };
1406 # Dig through the stack until we find the one we are releasing. This keeps
1407 # the stack up to date.
1410 do { $svp = pop @{ $self->{savepoints} } } while $svp ne $name;
1412 $name = pop @{ $self->{savepoints} };
1415 $self->debugobj->svp_release($name) if $self->debug;
1417 return $self->_svp_release($name);
1421 my ($self, $name) = @_;
1423 $self->throw_exception ("You can't use savepoints outside a transaction")
1424 if $self->{transaction_depth} == 0;
1426 $self->throw_exception ("Your Storage implementation doesn't support savepoints")
1427 unless $self->can('_svp_rollback');
1429 if (defined $name) {
1430 # If they passed us a name, verify that it exists in the stack
1431 unless(grep({ $_ eq $name } @{ $self->{savepoints} })) {
1432 $self->throw_exception("Savepoint '$name' does not exist!");
1435 # Dig through the stack until we find the one we are releasing. This keeps
1436 # the stack up to date.
1437 while(my $s = pop(@{ $self->{savepoints} })) {
1438 last if($s eq $name);
1440 # Add the savepoint back to the stack, as a rollback doesn't remove the
1441 # named savepoint, only everything after it.
1442 push(@{ $self->{savepoints} }, $name);
1444 # We'll assume they want to rollback to the last savepoint
1445 $name = $self->{savepoints}->[-1];
1448 $self->debugobj->svp_rollback($name) if $self->debug;
1450 return $self->_svp_rollback($name);
1453 sub _svp_generate_name {
1455 return 'savepoint_'.scalar(@{ $self->{'savepoints'} });
1461 # this means we have not yet connected and do not know the AC status
1462 # (e.g. coderef $dbh)
1463 if (! defined $self->_dbh_autocommit) {
1464 $self->ensure_connected;
1466 # otherwise re-connect on pid changes, so
1467 # that the txn_depth is adjusted properly
1468 # the lightweight _get_dbh is good enoug here
1469 # (only superficial handle check, no pings)
1474 if($self->transaction_depth == 0) {
1475 $self->debugobj->txn_begin()
1477 $self->_dbh_begin_work;
1479 elsif ($self->auto_savepoint) {
1482 $self->{transaction_depth}++;
1485 sub _dbh_begin_work {
1488 # if the user is utilizing txn_do - good for him, otherwise we need to
1489 # ensure that the $dbh is healthy on BEGIN.
1490 # We do this via ->dbh_do instead of ->dbh, so that the ->dbh "ping"
1491 # will be replaced by a failure of begin_work itself (which will be
1492 # then retried on reconnect)
1493 if ($self->{_in_dbh_do}) {
1494 $self->_dbh->begin_work;
1496 $self->dbh_do(sub { $_[1]->begin_work });
1502 if (! $self->_dbh) {
1503 $self->throw_exception('cannot COMMIT on a disconnected handle');
1505 elsif ($self->{transaction_depth} == 1) {
1506 $self->debugobj->txn_commit()
1509 $self->{transaction_depth} = 0
1510 if $self->_dbh_autocommit;
1512 elsif($self->{transaction_depth} > 1) {
1513 $self->{transaction_depth}--;
1515 if $self->auto_savepoint;
1517 elsif (! $self->_dbh->FETCH('AutoCommit') ) {
1519 carp "Storage transaction_depth $self->{transaction_depth} does not match "
1520 ."false AutoCommit of $self->{_dbh}, attempting COMMIT anyway";
1522 $self->debugobj->txn_commit()
1525 $self->{transaction_depth} = 0
1526 if $self->_dbh_autocommit;
1529 $self->throw_exception( 'Refusing to commit without a started transaction' );
1535 my $dbh = $self->_dbh
1536 or $self->throw_exception('cannot COMMIT on a disconnected handle');
1542 my $dbh = $self->_dbh;
1544 if ($self->{transaction_depth} == 1) {
1545 $self->debugobj->txn_rollback()
1547 $self->{transaction_depth} = 0
1548 if $self->_dbh_autocommit;
1549 $self->_dbh_rollback;
1551 elsif($self->{transaction_depth} > 1) {
1552 $self->{transaction_depth}--;
1553 if ($self->auto_savepoint) {
1554 $self->svp_rollback;
1559 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
1563 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
1565 if ($_ !~ /$exception_class/) {
1566 # ensure that a failed rollback resets the transaction depth
1567 $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
1570 $self->throw_exception($_)
1576 my $dbh = $self->_dbh
1577 or $self->throw_exception('cannot ROLLBACK on a disconnected handle');
1581 # This used to be the top-half of _execute. It was split out to make it
1582 # easier to override in NoBindVars without duping the rest. It takes up
1583 # all of _execute's args, and emits $sql, @bind.
1584 sub _prep_for_execute {
1585 my ($self, $op, $extra_bind, $ident, $args) = @_;
1587 if( blessed $ident && $ident->isa("DBIx::Class::ResultSource") ) {
1588 $ident = $ident->from();
1591 my ($sql, @bind) = $self->sql_maker->$op($ident, @$args);
1594 map { ref $_ eq 'ARRAY' ? $_ : [ '!!dummy', $_ ] } @$extra_bind)
1596 return ($sql, \@bind);
1600 sub _fix_bind_params {
1601 my ($self, @bind) = @_;
1603 ### Turn @bind from something like this:
1604 ### ( [ "artist", 1 ], [ "cdid", 1, 3 ] )
1606 ### ( "'1'", "'1'", "'3'" )
1609 if ( defined( $_ && $_->[1] ) ) {
1610 map { qq{'$_'}; } @{$_}[ 1 .. $#$_ ];
1617 my ( $self, $sql, @bind ) = @_;
1619 if ( $self->debug ) {
1620 @bind = $self->_fix_bind_params(@bind);
1622 $self->debugobj->query_start( $sql, @bind );
1627 my ( $self, $sql, @bind ) = @_;
1629 if ( $self->debug ) {
1630 @bind = $self->_fix_bind_params(@bind);
1631 $self->debugobj->query_end( $sql, @bind );
1636 my ($self, $dbh, $op, $extra_bind, $ident, $bind_attributes, @args) = @_;
1638 my ($sql, $bind) = $self->_prep_for_execute($op, $extra_bind, $ident, \@args);
1640 $self->_query_start( $sql, @$bind );
1642 my $sth = $self->sth($sql,$op);
1644 my $placeholder_index = 1;
1646 foreach my $bound (@$bind) {
1647 my $attributes = {};
1648 my($column_name, @data) = @$bound;
1650 if ($bind_attributes) {
1651 $attributes = $bind_attributes->{$column_name}
1652 if defined $bind_attributes->{$column_name};
1655 foreach my $data (@data) {
1656 my $ref = ref $data;
1658 if ($ref and overload::Method($data, '""') ) {
1661 elsif ($ref eq 'SCALAR') { # any scalarrefs are assumed to be bind_inouts
1662 $sth->bind_param_inout(
1663 $placeholder_index++,
1665 $self->_max_column_bytesize($ident, $column_name),
1671 $sth->bind_param($placeholder_index++, $data, $attributes);
1675 # Can this fail without throwing an exception anyways???
1676 my $rv = $sth->execute();
1677 $self->throw_exception(
1678 $sth->errstr || $sth->err || 'Unknown error: execute() returned false, but error flags were not set...'
1681 $self->_query_end( $sql, @$bind );
1683 return (wantarray ? ($rv, $sth, @$bind) : $rv);
1688 $self->dbh_do('_dbh_execute', @_); # retry over disconnects
1691 sub _prefetch_autovalues {
1692 my ($self, $source, $to_insert) = @_;
1694 my $colinfo = $source->columns_info;
1697 for my $col (keys %$colinfo) {
1699 $colinfo->{$col}{auto_nextval}
1702 ! exists $to_insert->{$col}
1704 ref $to_insert->{$col} eq 'SCALAR'
1707 $values{$col} = $self->_sequence_fetch(
1709 ( $colinfo->{$col}{sequence} ||=
1710 $self->_dbh_get_autoinc_seq($self->_get_dbh, $source, $col)
1720 my ($self, $source, $to_insert) = @_;
1722 my $prefetched_values = $self->_prefetch_autovalues($source, $to_insert);
1725 $to_insert = { %$to_insert, %$prefetched_values };
1727 # list of primary keys we try to fetch from the database
1728 # both not-exsists and scalarrefs are considered
1730 for ($source->primary_columns) {
1731 $fetch_pks{$_} = scalar keys %fetch_pks # so we can preserve order for prettyness
1732 if ! exists $to_insert->{$_} or ref $to_insert->{$_} eq 'SCALAR';
1735 my ($sqla_opts, @ir_container);
1736 if ($self->_use_insert_returning) {
1738 # retain order as declared in the resultsource
1739 for (sort { $fetch_pks{$a} <=> $fetch_pks{$b} } keys %fetch_pks ) {
1740 push @{$sqla_opts->{returning}}, $_;
1741 $sqla_opts->{returning_container} = \@ir_container
1742 if $self->_use_insert_returning_bound;
1746 my $bind_attributes = $self->source_bind_attributes($source);
1748 my ($rv, $sth) = $self->_execute('insert' => [], $source, $bind_attributes, $to_insert, $sqla_opts);
1752 if (my $retlist = $sqla_opts->{returning}) {
1753 @ir_container = try {
1754 local $SIG{__WARN__} = sub {};
1755 my @r = $sth->fetchrow_array;
1758 } unless @ir_container;
1760 @returned_cols{@$retlist} = @ir_container if @ir_container;
1763 return { %$prefetched_values, %returned_cols };
1767 ## Currently it is assumed that all values passed will be "normal", i.e. not
1768 ## scalar refs, or at least, all the same type as the first set, the statement is
1769 ## only prepped once.
1771 my ($self, $source, $cols, $data) = @_;
1774 @colvalues{@$cols} = (0..$#$cols);
1776 for my $i (0..$#$cols) {
1777 my $first_val = $data->[0][$i];
1778 next unless ref $first_val eq 'SCALAR';
1780 $colvalues{ $cols->[$i] } = $first_val;
1783 # check for bad data and stringify stringifiable objects
1784 my $bad_slice = sub {
1785 my ($msg, $col_idx, $slice_idx) = @_;
1786 $self->throw_exception(sprintf "%s for column '%s' in populate slice:\n%s",
1790 require Data::Dumper::Concise;
1791 local $Data::Dumper::Maxdepth = 1; # don't dump objects, if any
1792 Data::Dumper::Concise::Dumper ({
1793 map { $cols->[$_] => $data->[$slice_idx][$_] } (0 .. $#$cols)
1799 for my $datum_idx (0..$#$data) {
1800 my $datum = $data->[$datum_idx];
1802 for my $col_idx (0..$#$cols) {
1803 my $val = $datum->[$col_idx];
1804 my $sqla_bind = $colvalues{ $cols->[$col_idx] };
1805 my $is_literal_sql = (ref $sqla_bind) eq 'SCALAR';
1807 if ($is_literal_sql) {
1809 $bad_slice->('bind found where literal SQL expected', $col_idx, $datum_idx);
1811 elsif ((my $reftype = ref $val) ne 'SCALAR') {
1812 $bad_slice->("$reftype reference found where literal SQL expected",
1813 $col_idx, $datum_idx);
1815 elsif ($$val ne $$sqla_bind){
1816 $bad_slice->("inconsistent literal SQL value, expecting: '$$sqla_bind'",
1817 $col_idx, $datum_idx);
1820 elsif (my $reftype = ref $val) {
1822 if (overload::Method($val, '""')) {
1823 $datum->[$col_idx] = "".$val;
1826 $bad_slice->("$reftype reference found where bind expected",
1827 $col_idx, $datum_idx);
1833 my ($sql, $bind) = $self->_prep_for_execute (
1834 'insert', undef, $source, [\%colvalues]
1838 # if the bindlist is empty - make sure all "values" are in fact
1839 # literal scalarrefs. If not the case this means the storage ate
1840 # them away (e.g. the NoBindVars component) and interpolated them
1841 # directly into the SQL. This obviosly can't be good for multi-inserts
1843 $self->throw_exception('Cannot insert_bulk without support for placeholders')
1844 if first { ref $_ ne 'SCALAR' } values %colvalues;
1847 # neither _execute_array, nor _execute_inserts_with_no_binds are
1848 # atomic (even if _execute _array is a single call). Thus a safety
1850 my $guard = $self->txn_scope_guard;
1852 $self->_query_start( $sql, @$bind ? [ dummy => '__BULK_INSERT__' ] : () );
1853 my $sth = $self->sth($sql);
1856 #@bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
1857 $self->_execute_array( $source, $sth, $bind, $cols, $data );
1860 # bind_param_array doesn't work if there are no binds
1861 $self->_dbh_execute_inserts_with_no_binds( $sth, scalar @$data );
1865 $self->_query_end( $sql, @$bind ? [ dummy => '__BULK_INSERT__' ] : () );
1869 return (wantarray ? ($rv, $sth, @$bind) : $rv);
1872 sub _execute_array {
1873 my ($self, $source, $sth, $bind, $cols, $data, @extra) = @_;
1875 ## This must be an arrayref, else nothing works!
1876 my $tuple_status = [];
1878 ## Get the bind_attributes, if any exist
1879 my $bind_attributes = $self->source_bind_attributes($source);
1881 ## Bind the values and execute
1882 my $placeholder_index = 1;
1884 foreach my $bound (@$bind) {
1886 my $attributes = {};
1887 my ($column_name, $data_index) = @$bound;
1889 if( $bind_attributes ) {
1890 $attributes = $bind_attributes->{$column_name}
1891 if defined $bind_attributes->{$column_name};
1894 my @data = map { $_->[$data_index] } @$data;
1896 $sth->bind_param_array(
1899 (%$attributes ? $attributes : ()),
1901 $placeholder_index++;
1906 $rv = $self->_dbh_execute_array($sth, $tuple_status, @extra);
1912 # Not all DBDs are create equal. Some throw on error, some return
1913 # an undef $rv, and some set $sth->err - try whatever we can
1914 $err = ($sth->errstr || 'UNKNOWN ERROR ($sth->errstr is unset)') if (
1917 ( !defined $rv or $sth->err )
1920 # Statement must finish even if there was an exception.
1925 $err = shift unless defined $err
1930 ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i];
1932 $self->throw_exception("Unexpected populate error: $err")
1933 if ($i > $#$tuple_status);
1935 require Data::Dumper::Concise;
1936 $self->throw_exception(sprintf "%s for populate slice:\n%s",
1937 ($tuple_status->[$i][1] || $err),
1938 Data::Dumper::Concise::Dumper( { map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) } ),
1945 sub _dbh_execute_array {
1946 my ($self, $sth, $tuple_status, @extra) = @_;
1948 return $sth->execute_array({ArrayTupleStatus => $tuple_status});
1951 sub _dbh_execute_inserts_with_no_binds {
1952 my ($self, $sth, $count) = @_;
1956 my $dbh = $self->_get_dbh;
1957 local $dbh->{RaiseError} = 1;
1958 local $dbh->{PrintError} = 0;
1960 $sth->execute foreach 1..$count;
1966 # Make sure statement is finished even if there was an exception.
1971 $err = shift unless defined $err;
1974 $self->throw_exception($err) if defined $err;
1980 my ($self, $source, @args) = @_;
1982 my $bind_attrs = $self->source_bind_attributes($source);
1984 return $self->_execute('update' => [], $source, $bind_attrs, @args);
1989 my ($self, $source, @args) = @_;
1991 my $bind_attrs = $self->source_bind_attributes($source);
1993 return $self->_execute('delete' => [], $source, $bind_attrs, @args);
1996 # We were sent here because the $rs contains a complex search
1997 # which will require a subquery to select the correct rows
1998 # (i.e. joined or limited resultsets, or non-introspectable conditions)
2000 # Generating a single PK column subquery is trivial and supported
2001 # by all RDBMS. However if we have a multicolumn PK, things get ugly.
2002 # Look at _multipk_update_delete()
2003 sub _subq_update_delete {
2005 my ($rs, $op, $values) = @_;
2007 my $rsrc = $rs->result_source;
2009 # quick check if we got a sane rs on our hands
2010 my @pcols = $rsrc->_pri_cols;
2012 my $sel = $rs->_resolved_attrs->{select};
2013 $sel = [ $sel ] unless ref $sel eq 'ARRAY';
2016 join ("\x00", map { join '.', $rs->{attrs}{alias}, $_ } sort @pcols)
2018 join ("\x00", sort @$sel )
2020 $self->throw_exception (
2021 '_subq_update_delete can not be called on resultsets selecting columns other than the primary keys'
2028 $op eq 'update' ? $values : (),
2029 { $pcols[0] => { -in => $rs->as_query } },
2034 return $self->_multipk_update_delete (@_);
2038 # ANSI SQL does not provide a reliable way to perform a multicol-PK
2039 # resultset update/delete involving subqueries. So by default resort
2040 # to simple (and inefficient) delete_all style per-row opearations,
2041 # while allowing specific storages to override this with a faster
2044 sub _multipk_update_delete {
2045 return shift->_per_row_update_delete (@_);
2048 # This is the default loop used to delete/update rows for multi PK
2049 # resultsets, and used by mysql exclusively (because it can't do anything
2052 # We do not use $row->$op style queries, because resultset update/delete
2053 # is not expected to cascade (this is what delete_all/update_all is for).
2055 # There should be no race conditions as the entire operation is rolled
2058 sub _per_row_update_delete {
2060 my ($rs, $op, $values) = @_;
2062 my $rsrc = $rs->result_source;
2063 my @pcols = $rsrc->_pri_cols;
2065 my $guard = $self->txn_scope_guard;
2067 # emulate the return value of $sth->execute for non-selects
2068 my $row_cnt = '0E0';
2070 my $subrs_cur = $rs->cursor;
2071 my @all_pk = $subrs_cur->all;
2072 for my $pks ( @all_pk) {
2075 for my $i (0.. $#pcols) {
2076 $cond->{$pcols[$i]} = $pks->[$i];
2081 $op eq 'update' ? $values : (),
2095 $self->_execute($self->_select_args(@_));
2098 sub _select_args_to_query {
2101 # my ($op, $bind, $ident, $bind_attrs, $select, $cond, $rs_attrs, $rows, $offset)
2102 # = $self->_select_args($ident, $select, $cond, $attrs);
2103 my ($op, $bind, $ident, $bind_attrs, @args) =
2104 $self->_select_args(@_);
2106 # my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, [ $select, $cond, $rs_attrs, $rows, $offset ]);
2107 my ($sql, $prepared_bind) = $self->_prep_for_execute($op, $bind, $ident, \@args);
2108 $prepared_bind ||= [];
2111 ? ($sql, $prepared_bind, $bind_attrs)
2112 : \[ "($sql)", @$prepared_bind ]
2117 my ($self, $ident, $select, $where, $attrs) = @_;
2119 my $sql_maker = $self->sql_maker;
2120 my ($alias2source, $rs_alias) = $self->_resolve_ident_sources ($ident);
2127 $rs_alias && $alias2source->{$rs_alias}
2128 ? ( _rsroot_rsrc => $alias2source->{$rs_alias} )
2133 # calculate bind_attrs before possible $ident mangling
2134 my $bind_attrs = {};
2135 for my $alias (keys %$alias2source) {
2136 my $bindtypes = $self->source_bind_attributes ($alias2source->{$alias}) || {};
2137 for my $col (keys %$bindtypes) {
2139 my $fqcn = join ('.', $alias, $col);
2140 $bind_attrs->{$fqcn} = $bindtypes->{$col} if $bindtypes->{$col};
2142 # Unqialified column names are nice, but at the same time can be
2143 # rather ambiguous. What we do here is basically go along with
2144 # the loop, adding an unqualified column slot to $bind_attrs,
2145 # alongside the fully qualified name. As soon as we encounter
2146 # another column by that name (which would imply another table)
2147 # we unset the unqualified slot and never add any info to it
2148 # to avoid erroneous type binding. If this happens the users
2149 # only choice will be to fully qualify his column name
2151 if (exists $bind_attrs->{$col}) {
2152 $bind_attrs->{$col} = {};
2155 $bind_attrs->{$col} = $bind_attrs->{$fqcn};
2160 # Sanity check the attributes (SQLMaker does it too, but
2161 # in case of a software_limit we'll never reach there)
2162 if (defined $attrs->{offset}) {
2163 $self->throw_exception('A supplied offset attribute must be a non-negative integer')
2164 if ( $attrs->{offset} =~ /\D/ or $attrs->{offset} < 0 );
2166 $attrs->{offset} ||= 0;
2168 if (defined $attrs->{rows}) {
2169 $self->throw_exception("The rows attribute must be a positive integer if present")
2170 if ( $attrs->{rows} =~ /\D/ or $attrs->{rows} <= 0 );
2172 elsif ($attrs->{offset}) {
2173 # MySQL actually recommends this approach. I cringe.
2174 $attrs->{rows} = $sql_maker->__max_int;
2179 # see if we need to tear the prefetch apart otherwise delegate the limiting to the
2180 # storage, unless software limit was requested
2183 ( $attrs->{rows} && keys %{$attrs->{collapse}} )
2185 # grouped prefetch (to satisfy group_by == select)
2186 ( $attrs->{group_by}
2188 @{$attrs->{group_by}}
2190 $attrs->{_prefetch_selector_range}
2193 ($ident, $select, $where, $attrs)
2194 = $self->_adjust_select_args_for_complex_prefetch ($ident, $select, $where, $attrs);
2196 elsif (! $attrs->{software_limit} ) {
2197 push @limit, $attrs->{rows}, $attrs->{offset};
2200 # try to simplify the joinmap further (prune unreferenced type-single joins)
2201 $ident = $self->_prune_unused_joins ($ident, $select, $where, $attrs);
2204 # This would be the point to deflate anything found in $where
2205 # (and leave $attrs->{bind} intact). Problem is - inflators historically
2206 # expect a row object. And all we have is a resultsource (it is trivial
2207 # to extract deflator coderefs via $alias2source above).
2209 # I don't see a way forward other than changing the way deflators are
2210 # invoked, and that's just bad...
2213 return ('select', $attrs->{bind}, $ident, $bind_attrs, $select, $where, $attrs, @limit);
2216 # Returns a counting SELECT for a simple count
2217 # query. Abstracted so that a storage could override
2218 # this to { count => 'firstcol' } or whatever makes
2219 # sense as a performance optimization
2221 #my ($self, $source, $rs_attrs) = @_;
2222 return { count => '*' };
2226 sub source_bind_attributes {
2227 my ($self, $source) = @_;
2229 my $bind_attributes;
2231 my $colinfo = $source->columns_info;
2233 for my $col (keys %$colinfo) {
2234 if (my $dt = $colinfo->{$col}{data_type} ) {
2235 $bind_attributes->{$col} = $self->bind_attribute_by_data_type($dt)
2239 return $bind_attributes;
2246 =item Arguments: $ident, $select, $condition, $attrs
2250 Handle a SQL select statement.
2256 my ($ident, $select, $condition, $attrs) = @_;
2257 return $self->cursor_class->new($self, \@_, $attrs);
2262 my ($rv, $sth, @bind) = $self->_select(@_);
2263 my @row = $sth->fetchrow_array;
2264 my @nextrow = $sth->fetchrow_array if @row;
2265 if(@row && @nextrow) {
2266 carp "Query returned more than one row. SQL that returns multiple rows is DEPRECATED for ->find and ->single";
2268 # Need to call finish() to work round broken DBDs
2273 =head2 sql_limit_dialect
2275 This is an accessor for the default SQL limit dialect used by a particular
2276 storage driver. Can be overridden by supplying an explicit L</limit_dialect>
2277 to L<DBIx::Class::Schema/connect>. For a list of available limit dialects
2278 see L<DBIx::Class::SQLMaker::LimitDialects>.
2284 =item Arguments: $sql
2288 Returns a L<DBI> sth (statement handle) for the supplied SQL.
2293 my ($self, $dbh, $sql) = @_;
2295 # 3 is the if_active parameter which avoids active sth re-use
2296 my $sth = $self->disable_sth_caching
2297 ? $dbh->prepare($sql)
2298 : $dbh->prepare_cached($sql, {}, 3);
2300 # XXX You would think RaiseError would make this impossible,
2301 # but apparently that's not true :(
2302 $self->throw_exception(
2305 sprintf( "\$dbh->prepare() of '%s' through %s failed *silently* without "
2306 .'an exception and/or setting $dbh->errstr',
2308 ? substr($sql, 0, 20) . '...'
2311 'DBD::' . $dbh->{Driver}{Name},
2319 my ($self, $sql) = @_;
2320 $self->dbh_do('_dbh_sth', $sql); # retry over disconnects
2323 sub _dbh_columns_info_for {
2324 my ($self, $dbh, $table) = @_;
2326 if ($dbh->can('column_info')) {
2330 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
2331 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
2333 while ( my $info = $sth->fetchrow_hashref() ){
2335 $column_info{data_type} = $info->{TYPE_NAME};
2336 $column_info{size} = $info->{COLUMN_SIZE};
2337 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
2338 $column_info{default_value} = $info->{COLUMN_DEF};
2339 my $col_name = $info->{COLUMN_NAME};
2340 $col_name =~ s/^\"(.*)\"$/$1/;
2342 $result{$col_name} = \%column_info;
2347 return \%result if !$caught && scalar keys %result;
2351 my $sth = $dbh->prepare($self->sql_maker->select($table, undef, \'1 = 0'));
2353 my @columns = @{$sth->{NAME_lc}};
2354 for my $i ( 0 .. $#columns ){
2356 $column_info{data_type} = $sth->{TYPE}->[$i];
2357 $column_info{size} = $sth->{PRECISION}->[$i];
2358 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
2360 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
2361 $column_info{data_type} = $1;
2362 $column_info{size} = $2;
2365 $result{$columns[$i]} = \%column_info;
2369 foreach my $col (keys %result) {
2370 my $colinfo = $result{$col};
2371 my $type_num = $colinfo->{data_type};
2373 if(defined $type_num && $dbh->can('type_info')) {
2374 my $type_info = $dbh->type_info($type_num);
2375 $type_name = $type_info->{TYPE_NAME} if $type_info;
2376 $colinfo->{data_type} = $type_name if $type_name;
2383 sub columns_info_for {
2384 my ($self, $table) = @_;
2385 $self->_dbh_columns_info_for ($self->_get_dbh, $table);
2388 =head2 last_insert_id
2390 Return the row id of the last insert.
2394 sub _dbh_last_insert_id {
2395 my ($self, $dbh, $source, $col) = @_;
2397 my $id = try { $dbh->last_insert_id (undef, undef, $source->name, $col) };
2399 return $id if defined $id;
2401 my $class = ref $self;
2402 $self->throw_exception ("No storage specific _dbh_last_insert_id() method implemented in $class, and the generic DBI::last_insert_id() failed");
2405 sub last_insert_id {
2407 $self->_dbh_last_insert_id ($self->_dbh, @_);
2410 =head2 _native_data_type
2414 =item Arguments: $type_name
2418 This API is B<EXPERIMENTAL>, will almost definitely change in the future, and
2419 currently only used by L<::AutoCast|DBIx::Class::Storage::DBI::AutoCast> and
2420 L<::Sybase::ASE|DBIx::Class::Storage::DBI::Sybase::ASE>.
2422 The default implementation returns C<undef>, implement in your Storage driver if
2423 you need this functionality.
2425 Should map types from other databases to the native RDBMS type, for example
2426 C<VARCHAR2> to C<VARCHAR>.
2428 Types with modifiers should map to the underlying data type. For example,
2429 C<INTEGER AUTO_INCREMENT> should become C<INTEGER>.
2431 Composite types should map to the container type, for example
2432 C<ENUM(foo,bar,baz)> becomes C<ENUM>.
2436 sub _native_data_type {
2437 #my ($self, $data_type) = @_;
2441 # Check if placeholders are supported at all
2442 sub _determine_supports_placeholders {
2444 my $dbh = $self->_get_dbh;
2446 # some drivers provide a $dbh attribute (e.g. Sybase and $dbh->{syb_dynamic_supported})
2447 # but it is inaccurate more often than not
2449 local $dbh->{PrintError} = 0;
2450 local $dbh->{RaiseError} = 1;
2451 $dbh->do('select ?', {}, 1);
2459 # Check if placeholders bound to non-string types throw exceptions
2461 sub _determine_supports_typeless_placeholders {
2463 my $dbh = $self->_get_dbh;
2466 local $dbh->{PrintError} = 0;
2467 local $dbh->{RaiseError} = 1;
2468 # this specifically tests a bind that is NOT a string
2469 $dbh->do('select 1 where 1 = ?', {}, 1);
2479 Returns the database driver name.
2484 shift->_get_dbh->{Driver}->{Name};
2487 =head2 bind_attribute_by_data_type
2489 Given a datatype from column info, returns a database specific bind
2490 attribute for C<< $dbh->bind_param($val,$attribute) >> or nothing if we will
2491 let the database planner just handle it.
2493 Generally only needed for special case column types, like bytea in postgres.
2497 sub bind_attribute_by_data_type {
2501 =head2 is_datatype_numeric
2503 Given a datatype from column_info, returns a boolean value indicating if
2504 the current RDBMS considers it a numeric value. This controls how
2505 L<DBIx::Class::Row/set_column> decides whether to mark the column as
2506 dirty - when the datatype is deemed numeric a C<< != >> comparison will
2507 be performed instead of the usual C<eq>.
2511 sub is_datatype_numeric {
2512 my ($self, $dt) = @_;
2514 return 0 unless $dt;
2516 return $dt =~ /^ (?:
2517 numeric | int(?:eger)? | (?:tiny|small|medium|big)int | dec(?:imal)? | real | float | double (?: \s+ precision)? | (?:big)?serial
2522 =head2 create_ddl_dir
2526 =item Arguments: $schema \@databases, $version, $directory, $preversion, \%sqlt_args
2530 Creates a SQL file based on the Schema, for each of the specified
2531 database engines in C<\@databases> in the given directory.
2532 (note: specify L<SQL::Translator> names, not L<DBI> driver names).
2534 Given a previous version number, this will also create a file containing
2535 the ALTER TABLE statements to transform the previous schema into the
2536 current one. Note that these statements may contain C<DROP TABLE> or
2537 C<DROP COLUMN> statements that can potentially destroy data.
2539 The file names are created using the C<ddl_filename> method below, please
2540 override this method in your schema if you would like a different file
2541 name format. For the ALTER file, the same format is used, replacing
2542 $version in the name with "$preversion-$version".
2544 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
2545 The most common value for this would be C<< { add_drop_table => 1 } >>
2546 to have the SQL produced include a C<DROP TABLE> statement for each table
2547 created. For quoting purposes supply C<quote_table_names> and
2548 C<quote_field_names>.
2550 If no arguments are passed, then the following default values are assumed:
2554 =item databases - ['MySQL', 'SQLite', 'PostgreSQL']
2556 =item version - $schema->schema_version
2558 =item directory - './'
2560 =item preversion - <none>
2564 By default, C<\%sqlt_args> will have
2566 { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
2568 merged with the hash passed in. To disable any of those features, pass in a
2569 hashref like the following
2571 { ignore_constraint_names => 0, # ... other options }
2574 WARNING: You are strongly advised to check all SQL files created, before applying
2579 sub create_ddl_dir {
2580 my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
2583 carp "No directory given, using ./\n";
2588 (require File::Path and File::Path::make_path ("$dir")) # make_path does not like objects (i.e. Path::Class::Dir)
2590 $self->throw_exception(
2591 "Failed to create '$dir': " . ($! || $@ || 'error unknown')
2595 $self->throw_exception ("Directory '$dir' does not exist\n") unless(-d $dir);
2597 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
2598 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
2600 my $schema_version = $schema->schema_version || '1.x';
2601 $version ||= $schema_version;
2604 add_drop_table => 1,
2605 ignore_constraint_names => 1,
2606 ignore_index_names => 1,
2610 unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy')) {
2611 $self->throw_exception("Can't create a ddl file without " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2614 my $sqlt = SQL::Translator->new( $sqltargs );
2616 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
2617 my $sqlt_schema = $sqlt->translate({ data => $schema })
2618 or $self->throw_exception ($sqlt->error);
2620 foreach my $db (@$databases) {
2622 $sqlt->{schema} = $sqlt_schema;
2623 $sqlt->producer($db);
2626 my $filename = $schema->ddl_filename($db, $version, $dir);
2627 if (-e $filename && ($version eq $schema_version )) {
2628 # if we are dumping the current version, overwrite the DDL
2629 carp "Overwriting existing DDL file - $filename";
2633 my $output = $sqlt->translate;
2635 carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
2638 if(!open($file, ">$filename")) {
2639 $self->throw_exception("Can't open $filename for writing ($!)");
2642 print $file $output;
2645 next unless ($preversion);
2647 require SQL::Translator::Diff;
2649 my $prefilename = $schema->ddl_filename($db, $preversion, $dir);
2650 if(!-e $prefilename) {
2651 carp("No previous schema file found ($prefilename)");
2655 my $difffile = $schema->ddl_filename($db, $version, $dir, $preversion);
2657 carp("Overwriting existing diff file - $difffile");
2663 my $t = SQL::Translator->new($sqltargs);
2668 or $self->throw_exception ($t->error);
2670 my $out = $t->translate( $prefilename )
2671 or $self->throw_exception ($t->error);
2673 $source_schema = $t->schema;
2675 $source_schema->name( $prefilename )
2676 unless ( $source_schema->name );
2679 # The "new" style of producers have sane normalization and can support
2680 # diffing a SQL file against a DBIC->SQLT schema. Old style ones don't
2681 # And we have to diff parsed SQL against parsed SQL.
2682 my $dest_schema = $sqlt_schema;
2684 unless ( "SQL::Translator::Producer::$db"->can('preprocess_schema') ) {
2685 my $t = SQL::Translator->new($sqltargs);
2690 or $self->throw_exception ($t->error);
2692 my $out = $t->translate( $filename )
2693 or $self->throw_exception ($t->error);
2695 $dest_schema = $t->schema;
2697 $dest_schema->name( $filename )
2698 unless $dest_schema->name;
2701 my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
2705 if(!open $file, ">$difffile") {
2706 $self->throw_exception("Can't write to $difffile ($!)");
2714 =head2 deployment_statements
2718 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
2722 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
2724 The L<SQL::Translator> (not L<DBI>) database driver name can be explicitly
2725 provided in C<$type>, otherwise the result of L</sqlt_type> is used as default.
2727 C<$directory> is used to return statements from files in a previously created
2728 L</create_ddl_dir> directory and is optional. The filenames are constructed
2729 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
2731 If no C<$directory> is specified then the statements are constructed on the
2732 fly using L<SQL::Translator> and C<$version> is ignored.
2734 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
2738 sub deployment_statements {
2739 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
2740 $type ||= $self->sqlt_type;
2741 $version ||= $schema->schema_version || '1.x';
2743 my $filename = $schema->ddl_filename($type, $version, $dir);
2746 # FIXME replace this block when a proper sane sql parser is available
2748 open($file, "<$filename")
2749 or $self->throw_exception("Can't open $filename ($!)");
2752 return join('', @rows);
2755 unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy') ) {
2756 $self->throw_exception("Can't deploy without a ddl_dir or " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2759 # sources needs to be a parser arg, but for simplicty allow at top level
2761 $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
2762 if exists $sqltargs->{sources};
2764 my $tr = SQL::Translator->new(
2765 producer => "SQL::Translator::Producer::${type}",
2767 parser => 'SQL::Translator::Parser::DBIx::Class',
2773 @ret = $tr->translate;
2776 $ret[0] = $tr->translate;
2779 $self->throw_exception( 'Unable to produce deployment statements: ' . $tr->error)
2780 unless (@ret && defined $ret[0]);
2782 return wantarray ? @ret : $ret[0];
2785 # FIXME deploy() currently does not accurately report sql errors
2786 # Will always return true while errors are warned
2788 my ($self, $schema, $type, $sqltargs, $dir) = @_;
2792 return if($line =~ /^--/);
2793 # next if($line =~ /^DROP/m);
2794 return if($line =~ /^BEGIN TRANSACTION/m);
2795 return if($line =~ /^COMMIT/m);
2796 return if $line =~ /^\s+$/; # skip whitespace only
2797 $self->_query_start($line);
2799 # do a dbh_do cycle here, as we need some error checking in
2800 # place (even though we will ignore errors)
2801 $self->dbh_do (sub { $_[1]->do($line) });
2803 carp qq{$_ (running "${line}")};
2805 $self->_query_end($line);
2807 my @statements = $schema->deployment_statements($type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );
2808 if (@statements > 1) {
2809 foreach my $statement (@statements) {
2810 $deploy->( $statement );
2813 elsif (@statements == 1) {
2814 # split on single line comments and end of statements
2815 foreach my $line ( split(/\s*--.*\n|;\n/, $statements[0])) {
2821 =head2 datetime_parser
2823 Returns the datetime parser class
2827 sub datetime_parser {
2829 return $self->{datetime_parser} ||= do {
2830 $self->build_datetime_parser(@_);
2834 =head2 datetime_parser_type
2836 Defines the datetime parser class - currently defaults to L<DateTime::Format::MySQL>
2838 =head2 build_datetime_parser
2840 See L</datetime_parser>
2844 sub build_datetime_parser {
2846 my $type = $self->datetime_parser_type(@_);
2851 =head2 is_replicating
2853 A boolean that reports if a particular L<DBIx::Class::Storage::DBI> is set to
2854 replicate from a master database. Default is undef, which is the result
2855 returned by databases that don't support replication.
2859 sub is_replicating {
2864 =head2 lag_behind_master
2866 Returns a number that represents a certain amount of lag behind a master db
2867 when a given storage is replicating. The number is database dependent, but
2868 starts at zero and increases with the amount of lag. Default in undef
2872 sub lag_behind_master {
2876 =head2 relname_to_table_alias
2880 =item Arguments: $relname, $join_count
2884 L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
2887 This hook is to allow specific L<DBIx::Class::Storage> drivers to change the
2888 way these aliases are named.
2890 The default behavior is C<< "$relname_$join_count" if $join_count > 1 >>,
2891 otherwise C<"$relname">.
2895 sub relname_to_table_alias {
2896 my ($self, $relname, $join_count) = @_;
2898 my $alias = ($join_count && $join_count > 1 ?
2899 join('_', $relname, $join_count) : $relname);
2904 # The size in bytes to use for DBI's ->bind_param_inout, this is the generic
2905 # version and it may be necessary to amend or override it for a specific storage
2906 # if such binds are necessary.
2907 sub _max_column_bytesize {
2908 my ($self, $source, $col) = @_;
2910 my $inf = $source->column_info($col);
2911 return $inf->{_max_bytesize} ||= do {
2915 if (my $data_type = $inf->{data_type}) {
2916 $data_type = lc($data_type);
2918 # String/sized-binary types
2919 if ($data_type =~ /^(?:l?(?:var)?char(?:acter)?(?:\s*varying)?
2920 |(?:var)?binary(?:\s*varying)?|raw)\b/x
2922 $max_size = $inf->{size};
2924 # Other charset/unicode types, assume scale of 4
2925 elsif ($data_type =~ /^(?:national\s*character(?:\s*varying)?|nchar
2929 $max_size = $inf->{size} * 4 if $inf->{size};
2932 elsif ($self->_is_lob_type($data_type)) {
2933 # default to longreadlen
2936 $max_size = 100; # for all other (numeric?) datatypes
2940 $max_size ||= $self->_get_dbh->{LongReadLen} || 8000;
2944 # Determine if a data_type is some type of BLOB
2945 # FIXME: these regexes are expensive, result of these checks should be cached in
2948 my ($self, $data_type) = @_;
2949 $data_type && ($data_type =~ /lob|bfile|text|image|bytea|memo/i
2950 || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary
2951 |varchar|character\s*varying|nvarchar
2952 |national\s*character\s*varying))?\z/xi);
2955 sub _is_binary_lob_type {
2956 my ($self, $data_type) = @_;
2957 $data_type && ($data_type =~ /blob|bfile|image|bytea/i
2958 || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary))?\z/xi);
2961 sub _is_text_lob_type {
2962 my ($self, $data_type) = @_;
2963 $data_type && ($data_type =~ /^(?:clob|memo)\z/i
2964 || $data_type =~ /^long(?:\s+(?:varchar|character\s*varying|nvarchar
2965 |national\s*character\s*varying))\z/xi);
2972 =head2 DBIx::Class and AutoCommit
2974 DBIx::Class can do some wonderful magic with handling exceptions,
2975 disconnections, and transactions when you use C<< AutoCommit => 1 >>
2976 (the default) combined with C<txn_do> for transaction support.
2978 If you set C<< AutoCommit => 0 >> in your connect info, then you are always
2979 in an assumed transaction between commits, and you're telling us you'd
2980 like to manage that manually. A lot of the magic protections offered by
2981 this module will go away. We can't protect you from exceptions due to database
2982 disconnects because we don't know anything about how to restart your
2983 transactions. You're on your own for handling all sorts of exceptional
2984 cases if you choose the C<< AutoCommit => 0 >> path, just as you would
2990 Matt S. Trout <mst@shadowcatsystems.co.uk>
2992 Andy Grundman <andy@hybridized.org>
2996 You may distribute this code under the same terms as Perl itself.