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';
19 # default cursor class, overridable in connect_info attributes
20 __PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
22 __PACKAGE__->mk_group_accessors('inherited' => qw/
23 sql_limit_dialect sql_quote_char sql_name_sep
26 __PACKAGE__->mk_group_accessors('component_class' => qw/sql_maker_class datetime_parser_type/);
28 __PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker');
29 __PACKAGE__->datetime_parser_type('DateTime::Format::MySQL'); # historic default
31 __PACKAGE__->sql_name_sep('.');
33 __PACKAGE__->mk_group_accessors('simple' => qw/
34 _connect_info _dbi_connect_info _dbic_connect_attributes _driver_determined
35 _dbh _dbh_details _conn_pid _sql_maker _sql_maker_opts _dbh_autocommit
38 # the values for these accessors are picked out (and deleted) from
39 # the attribute hashref passed to connect_info
40 my @storage_options = qw/
41 on_connect_call on_disconnect_call on_connect_do on_disconnect_do
42 disable_sth_caching unsafe auto_savepoint
44 __PACKAGE__->mk_group_accessors('simple' => @storage_options);
47 # capability definitions, using a 2-tiered accessor system
50 # A driver/user may define _use_X, which blindly without any checks says:
51 # "(do not) use this capability", (use_dbms_capability is an "inherited"
54 # If _use_X is undef, _supports_X is then queried. This is a "simple" style
55 # accessor, which in turn calls _determine_supports_X, and stores the return
56 # in a special slot on the storage object, which is wiped every time a $dbh
57 # reconnection takes place (it is not guaranteed that upon reconnection we
58 # will get the same rdbms version). _determine_supports_X does not need to
59 # exist on a driver, as we ->can for it before calling.
61 my @capabilities = (qw/
63 insert_returning_bound
68 __PACKAGE__->mk_group_accessors( dbms_capability => map { "_supports_$_" } @capabilities );
69 __PACKAGE__->mk_group_accessors( use_dbms_capability => map { "_use_$_" } (@capabilities ) );
71 # on by default, not strictly a capability (pending rewrite)
72 __PACKAGE__->_use_join_optimizer (1);
73 sub _determine_supports_join_optimizer { 1 };
75 # Each of these methods need _determine_driver called before itself
76 # in order to function reliably. This is a purely DRY optimization
78 # get_(use)_dbms_capability need to be called on the correct Storage
79 # class, as _use_X may be hardcoded class-wide, and _supports_X calls
80 # _determine_supports_X which obv. needs a correct driver as well
81 my @rdbms_specific_methods = qw/
96 get_use_dbms_capability
103 for my $meth (@rdbms_specific_methods) {
105 my $orig = __PACKAGE__->can ($meth)
106 or die "$meth is not a ::Storage::DBI method!";
109 no warnings qw/redefine/;
110 *{__PACKAGE__ ."::$meth"} = subname $meth => sub {
112 # only fire when invoked on an instance, a valid class-based invocation
113 # would e.g. be setting a default for an inherited accessor
116 ! $_[0]->_driver_determined
118 ! $_[0]->{_in_determine_driver}
120 $_[0]->_determine_driver;
122 # This for some reason crashes and burns on perl 5.8.1
123 # IFF the method ends up throwing an exception
124 #goto $_[0]->can ($meth);
126 my $cref = $_[0]->can ($meth);
136 DBIx::Class::Storage::DBI - DBI storage handler
140 my $schema = MySchema->connect('dbi:SQLite:my.db');
142 $schema->storage->debug(1);
144 my @stuff = $schema->storage->dbh_do(
146 my ($storage, $dbh, @args) = @_;
147 $dbh->do("DROP TABLE authors");
152 $schema->resultset('Book')->search({
153 written_on => $schema->storage->datetime_parser->format_datetime(DateTime->now)
158 This class represents the connection to an RDBMS via L<DBI>. See
159 L<DBIx::Class::Storage> for general information. This pod only
160 documents DBI-specific methods and behaviors.
167 my $new = shift->next::method(@_);
169 $new->_sql_maker_opts({});
170 $new->_dbh_details({});
171 $new->{_in_do_block} = 0;
172 $new->{_dbh_gen} = 0;
174 # read below to see what this does
175 $new->_arm_global_destructor;
180 # This is hack to work around perl shooting stuff in random
181 # order on exit(). If we do not walk the remaining storage
182 # objects in an END block, there is a *small but real* chance
183 # of a fork()ed child to kill the parent's shared DBI handle,
184 # *before perl reaches the DESTROY in this package*
185 # Yes, it is ugly and effective.
186 # Additionally this registry is used by the CLONE method to
187 # make sure no handles are shared between threads
189 my %seek_and_destroy;
191 sub _arm_global_destructor {
193 my $key = refaddr ($self);
194 $seek_and_destroy{$key} = $self;
195 weaken ($seek_and_destroy{$key});
199 local $?; # just in case the DBI destructor changes it somehow
201 # destroy just the object if not native to this process/thread
202 $_->_verify_pid for (grep
204 values %seek_and_destroy
209 # As per DBI's recommendation, DBIC disconnects all handles as
210 # soon as possible (DBIC will reconnect only on demand from within
212 for (values %seek_and_destroy) {
214 $_->{_dbh_gen}++; # so that existing cursors will drop as well
217 $_->transaction_depth(0);
226 # some databases spew warnings on implicit disconnect
227 local $SIG{__WARN__} = sub {};
230 # this op is necessary, since the very last perl runtime statement
231 # triggers a global destruction shootout, and the $SIG localization
232 # may very well be destroyed before perl actually gets to do the
237 # handle pid changes correctly - do not destroy parent's connection
241 my $pid = $self->_conn_pid;
242 if( defined $pid and $pid != $$ and my $dbh = $self->_dbh ) {
243 $dbh->{InactiveDestroy} = 1;
246 $self->transaction_depth(0);
247 $self->savepoints([]);
255 This method is normally called by L<DBIx::Class::Schema/connection>, which
256 encapsulates its argument list in an arrayref before passing them here.
258 The argument list may contain:
264 The same 4-element argument set one would normally pass to
265 L<DBI/connect>, optionally followed by
266 L<extra attributes|/DBIx::Class specific connection attributes>
267 recognized by DBIx::Class:
269 $connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
273 A single code reference which returns a connected
274 L<DBI database handle|DBI/connect> optionally followed by
275 L<extra attributes|/DBIx::Class specific connection attributes> recognized
278 $connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
282 A single hashref with all the attributes and the dsn/user/password
285 $connect_info_args = [{
293 $connect_info_args = [{
294 dbh_maker => sub { DBI->connect (...) },
299 This is particularly useful for L<Catalyst> based applications, allowing the
300 following config (L<Config::General> style):
305 dsn dbi:mysql:database=test
312 The C<dsn>/C<user>/C<password> combination can be substituted by the
313 C<dbh_maker> key whose value is a coderef that returns a connected
314 L<DBI database handle|DBI/connect>
318 Please note that the L<DBI> docs recommend that you always explicitly
319 set C<AutoCommit> to either I<0> or I<1>. L<DBIx::Class> further
320 recommends that it be set to I<1>, and that you perform transactions
321 via our L<DBIx::Class::Schema/txn_do> method. L<DBIx::Class> will set it
322 to I<1> if you do not do explicitly set it to zero. This is the default
323 for most DBDs. See L</DBIx::Class and AutoCommit> for details.
325 =head3 DBIx::Class specific connection attributes
327 In addition to the standard L<DBI|DBI/ATTRIBUTES_COMMON_TO_ALL_HANDLES>
328 L<connection|DBI/Database_Handle_Attributes> attributes, DBIx::Class recognizes
329 the following connection options. These options can be mixed in with your other
330 L<DBI> connection attributes, or placed in a separate hashref
331 (C<\%extra_attributes>) as shown above.
333 Every time C<connect_info> is invoked, any previous settings for
334 these options will be cleared before setting the new ones, regardless of
335 whether any options are specified in the new C<connect_info>.
342 Specifies things to do immediately after connecting or re-connecting to
343 the database. Its value may contain:
349 This contains one SQL statement to execute.
351 =item an array reference
353 This contains SQL statements to execute in order. Each element contains
354 a string or a code reference that returns a string.
356 =item a code reference
358 This contains some code to execute. Unlike code references within an
359 array reference, its return value is ignored.
363 =item on_disconnect_do
365 Takes arguments in the same form as L</on_connect_do> and executes them
366 immediately before disconnecting from the database.
368 Note, this only runs if you explicitly call L</disconnect> on the
371 =item on_connect_call
373 A more generalized form of L</on_connect_do> that calls the specified
374 C<connect_call_METHOD> methods in your storage driver.
376 on_connect_do => 'select 1'
380 on_connect_call => [ [ do_sql => 'select 1' ] ]
382 Its values may contain:
388 Will call the C<connect_call_METHOD> method.
390 =item a code reference
392 Will execute C<< $code->($storage) >>
394 =item an array reference
396 Each value can be a method name or code reference.
398 =item an array of arrays
400 For each array, the first item is taken to be the C<connect_call_> method name
401 or code reference, and the rest are parameters to it.
405 Some predefined storage methods you may use:
411 Executes a SQL string or a code reference that returns a SQL string. This is
412 what L</on_connect_do> and L</on_disconnect_do> use.
420 Will execute the scalar as SQL.
424 Taken to be arguments to L<DBI/do>, the SQL string optionally followed by the
425 attributes hashref and bind values.
427 =item a code reference
429 Will execute C<< $code->($storage) >> and execute the return array refs as
436 Execute any statements necessary to initialize the database session to return
437 and accept datetime/timestamp values used with
438 L<DBIx::Class::InflateColumn::DateTime>.
440 Only necessary for some databases, see your specific storage driver for
441 implementation details.
445 =item on_disconnect_call
447 Takes arguments in the same form as L</on_connect_call> and executes them
448 immediately before disconnecting from the database.
450 Calls the C<disconnect_call_METHOD> methods as opposed to the
451 C<connect_call_METHOD> methods called by L</on_connect_call>.
453 Note, this only runs if you explicitly call L</disconnect> on the
456 =item disable_sth_caching
458 If set to a true value, this option will disable the caching of
459 statement handles via L<DBI/prepare_cached>.
463 Sets a specific SQL::Abstract::Limit-style limit dialect, overriding the
464 default L</sql_limit_dialect> setting of the storage (if any). For a list
465 of available limit dialects see L<DBIx::Class::SQLMaker::LimitDialects>.
469 When true automatically sets L</quote_char> and L</name_sep> to the characters
470 appropriate for your particular RDBMS. This option is preferred over specifying
471 L</quote_char> directly.
475 Specifies what characters to use to quote table and column names.
477 C<quote_char> expects either a single character, in which case is it
478 is placed on either side of the table/column name, or an arrayref of length
479 2 in which case the table/column name is placed between the elements.
481 For example under MySQL you should use C<< quote_char => '`' >>, and for
482 SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
486 This parameter is only useful in conjunction with C<quote_char>, and is used to
487 specify the character that separates elements (schemas, tables, columns) from
488 each other. If unspecified it defaults to the most commonly used C<.>.
492 This Storage driver normally installs its own C<HandleError>, sets
493 C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
494 all database handles, including those supplied by a coderef. It does this
495 so that it can have consistent and useful error behavior.
497 If you set this option to a true value, Storage will not do its usual
498 modifications to the database handle's attributes, and instead relies on
499 the settings in your connect_info DBI options (or the values you set in
500 your connection coderef, in the case that you are connecting via coderef).
502 Note that your custom settings can cause Storage to malfunction,
503 especially if you set a C<HandleError> handler that suppresses exceptions
504 and/or disable C<RaiseError>.
508 If this option is true, L<DBIx::Class> will use savepoints when nesting
509 transactions, making it possible to recover from failure in the inner
510 transaction without having to abort all outer transactions.
514 Use this argument to supply a cursor class other than the default
515 L<DBIx::Class::Storage::DBI::Cursor>.
519 Some real-life examples of arguments to L</connect_info> and
520 L<DBIx::Class::Schema/connect>
522 # Simple SQLite connection
523 ->connect_info([ 'dbi:SQLite:./foo.db' ]);
526 ->connect_info([ sub { DBI->connect(...) } ]);
528 # Connect via subref in hashref
530 dbh_maker => sub { DBI->connect(...) },
531 on_connect_do => 'alter session ...',
534 # A bit more complicated
541 { quote_char => q{"} },
545 # Equivalent to the previous example
551 { AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
555 # Same, but with hashref as argument
556 # See parse_connect_info for explanation
559 dsn => 'dbi:Pg:dbname=foo',
561 password => 'my_pg_password',
568 # Subref + DBIx::Class-specific connection options
571 sub { DBI->connect(...) },
575 on_connect_do => ['SET search_path TO myschema,otherschema,public'],
576 disable_sth_caching => 1,
586 my ($self, $info) = @_;
588 return $self->_connect_info if !$info;
590 $self->_connect_info($info); # copy for _connect_info
592 $info = $self->_normalize_connect_info($info)
593 if ref $info eq 'ARRAY';
595 for my $storage_opt (keys %{ $info->{storage_options} }) {
596 my $value = $info->{storage_options}{$storage_opt};
598 $self->$storage_opt($value);
601 # Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
602 # the new set of options
603 $self->_sql_maker(undef);
604 $self->_sql_maker_opts({});
606 for my $sql_maker_opt (keys %{ $info->{sql_maker_options} }) {
607 my $value = $info->{sql_maker_options}{$sql_maker_opt};
609 $self->_sql_maker_opts->{$sql_maker_opt} = $value;
613 %{ $self->_default_dbi_connect_attributes || {} },
614 %{ $info->{attributes} || {} },
617 my @args = @{ $info->{arguments} };
619 if (keys %attrs and ref $args[0] ne 'CODE') {
621 'You provided explicit AutoCommit => 0 in your connection_info. '
622 . 'This is almost universally a bad idea (see the footnotes of '
623 . 'DBIx::Class::Storage::DBI for more info). If you still want to '
624 . 'do this you can set $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK} to disable '
626 if ! $attrs{AutoCommit} and ! $ENV{DBIC_UNSAFE_AUTOCOMMIT_OK};
628 push @args, \%attrs if keys %attrs;
630 $self->_dbi_connect_info(\@args);
633 # save attributes them in a separate accessor so they are always
634 # introspectable, even in case of a CODE $dbhmaker
635 $self->_dbic_connect_attributes (\%attrs);
637 return $self->_connect_info;
640 sub _normalize_connect_info {
641 my ($self, $info_arg) = @_;
644 my @args = @$info_arg; # take a shallow copy for further mutilation
646 # combine/pre-parse arguments depending on invocation style
649 if (ref $args[0] eq 'CODE') { # coderef with optional \%extra_attributes
650 %attrs = %{ $args[1] || {} };
653 elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
654 %attrs = %{$args[0]};
656 if (my $code = delete $attrs{dbh_maker}) {
659 my @ignored = grep { delete $attrs{$_} } (qw/dsn user password/);
662 'Attribute(s) %s in connect_info were ignored, as they can not be applied '
663 . "to the result of 'dbh_maker'",
665 join (', ', map { "'$_'" } (@ignored) ),
670 @args = delete @attrs{qw/dsn user password/};
673 else { # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
675 % { $args[3] || {} },
676 % { $args[4] || {} },
678 @args = @args[0,1,2];
681 $info{arguments} = \@args;
683 my @storage_opts = grep exists $attrs{$_},
684 @storage_options, 'cursor_class';
686 @{ $info{storage_options} }{@storage_opts} =
687 delete @attrs{@storage_opts} if @storage_opts;
689 my @sql_maker_opts = grep exists $attrs{$_},
690 qw/limit_dialect quote_char name_sep quote_names/;
692 @{ $info{sql_maker_options} }{@sql_maker_opts} =
693 delete @attrs{@sql_maker_opts} if @sql_maker_opts;
695 $info{attributes} = \%attrs if %attrs;
700 sub _default_dbi_connect_attributes () {
705 ShowErrorStatement => 1,
711 This method is deprecated in favour of setting via L</connect_info>.
715 =head2 on_disconnect_do
717 This method is deprecated in favour of setting via L</connect_info>.
721 sub _parse_connect_do {
722 my ($self, $type) = @_;
724 my $val = $self->$type;
725 return () if not defined $val;
730 push @res, [ 'do_sql', $val ];
731 } elsif (ref($val) eq 'CODE') {
733 } elsif (ref($val) eq 'ARRAY') {
734 push @res, map { [ 'do_sql', $_ ] } @$val;
736 $self->throw_exception("Invalid type for $type: ".ref($val));
744 Arguments: ($subref | $method_name), @extra_coderef_args?
746 Execute the given $subref or $method_name using the new exception-based
747 connection management.
749 The first two arguments will be the storage object that C<dbh_do> was called
750 on and a database handle to use. Any additional arguments will be passed
751 verbatim to the called subref as arguments 2 and onwards.
753 Using this (instead of $self->_dbh or $self->dbh) ensures correct
754 exception handling and reconnection (or failover in future subclasses).
756 Your subref should have no side-effects outside of the database, as
757 there is the potential for your subref to be partially double-executed
758 if the database connection was stale/dysfunctional.
762 my @stuff = $schema->storage->dbh_do(
764 my ($storage, $dbh, @cols) = @_;
765 my $cols = join(q{, }, @cols);
766 $dbh->selectrow_array("SELECT $cols FROM foo");
777 my $dbh = $self->_get_dbh;
779 return $self->$code($dbh, @_)
780 if ( $self->{_in_do_block} || $self->{transaction_depth} );
782 local $self->{_in_do_block} = 1;
784 # take a ref instead of a copy, to preserve coderef @_ aliasing semantics
788 $self->$code ($dbh, @$args);
790 $self->throw_exception($_) if $self->connected;
792 # We were not connected - reconnect and retry, but let any
793 # exception fall right through this time
794 carp "Retrying dbh_do($code) after catching disconnected exception: $_"
795 if $ENV{DBIC_STORAGE_RETRY_DEBUG};
797 $self->_populate_dbh;
798 $self->$code($self->_dbh, @$args);
803 # connects or reconnects on pid change, necessary to grab correct txn_depth
805 local $_[0]->{_in_do_block} = 1;
806 shift->next::method(@_);
811 Our C<disconnect> method also performs a rollback first if the
812 database is not in C<AutoCommit> mode.
822 push @actions, ( $self->on_disconnect_call || () );
823 push @actions, $self->_parse_connect_do ('on_disconnect_do');
825 $self->_do_connection_actions(disconnect_call_ => $_) for @actions;
827 # stops the "implicit rollback on disconnect" warning
828 $self->_exec_txn_rollback unless $self->_dbh_autocommit;
830 %{ $self->_dbh->{CachedKids} } = ();
831 $self->_dbh->disconnect;
837 =head2 with_deferred_fk_checks
841 =item Arguments: C<$coderef>
843 =item Return Value: The return value of $coderef
847 Storage specific method to run the code ref with FK checks deferred or
848 in MySQL's case disabled entirely.
852 # Storage subclasses should override this
853 sub with_deferred_fk_checks {
854 my ($self, $sub) = @_;
862 =item Arguments: none
864 =item Return Value: 1|0
868 Verifies that the current database handle is active and ready to execute
869 an SQL statement (e.g. the connection did not get stale, server is still
870 answering, etc.) This method is used internally by L</dbh>.
876 return 0 unless $self->_seems_connected;
879 local $self->_dbh->{RaiseError} = 1;
884 sub _seems_connected {
889 my $dbh = $self->_dbh
892 return $dbh->FETCH('Active');
898 my $dbh = $self->_dbh or return 0;
903 sub ensure_connected {
906 unless ($self->connected) {
907 $self->_populate_dbh;
913 Returns a C<$dbh> - a data base handle of class L<DBI>. The returned handle
914 is guaranteed to be healthy by implicitly calling L</connected>, and if
915 necessary performing a reconnection before returning. Keep in mind that this
916 is very B<expensive> on some database engines. Consider using L</dbh_do>
924 if (not $self->_dbh) {
925 $self->_populate_dbh;
927 $self->ensure_connected;
932 # this is the internal "get dbh or connect (don't check)" method
936 $self->_populate_dbh unless $self->_dbh;
942 unless ($self->_sql_maker) {
943 my $sql_maker_class = $self->sql_maker_class;
945 my %opts = %{$self->_sql_maker_opts||{}};
949 $self->sql_limit_dialect
952 my $s_class = (ref $self) || $self;
954 "Your storage class ($s_class) does not set sql_limit_dialect and you "
955 . 'have not supplied an explicit limit_dialect in your connection_info. '
956 . 'DBIC will attempt to use the GenericSubQ dialect, which works on most '
957 . 'databases but can be (and often is) painfully slow. '
958 . "Please file an RT ticket against '$s_class' ."
965 my ($quote_char, $name_sep);
967 if ($opts{quote_names}) {
968 $quote_char = (delete $opts{quote_char}) || $self->sql_quote_char || do {
969 my $s_class = (ref $self) || $self;
971 "You requested 'quote_names' but your storage class ($s_class) does "
972 . 'not explicitly define a default sql_quote_char and you have not '
973 . 'supplied a quote_char as part of your connection_info. DBIC will '
974 .q{default to the ANSI SQL standard quote '"', which works most of }
975 . "the time. Please file an RT ticket against '$s_class'."
981 $name_sep = (delete $opts{name_sep}) || $self->sql_name_sep;
984 $self->_sql_maker($sql_maker_class->new(
986 array_datatypes => 1,
987 limit_dialect => $dialect,
988 ($quote_char ? (quote_char => $quote_char) : ()),
989 name_sep => ($name_sep || '.'),
993 return $self->_sql_maker;
996 # nothing to do by default
1003 my @info = @{$self->_dbi_connect_info || []};
1004 $self->_dbh(undef); # in case ->connected failed we might get sent here
1005 $self->_dbh_details({}); # reset everything we know
1007 $self->_dbh($self->_connect(@info));
1009 $self->_conn_pid($$) if $^O ne 'MSWin32'; # on win32 these are in fact threads
1011 $self->_determine_driver;
1013 # Always set the transaction depth on connect, since
1014 # there is no transaction in progress by definition
1015 $self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
1017 $self->_run_connection_actions unless $self->{_in_determine_driver};
1020 sub _run_connection_actions {
1024 push @actions, ( $self->on_connect_call || () );
1025 push @actions, $self->_parse_connect_do ('on_connect_do');
1027 $self->_do_connection_actions(connect_call_ => $_) for @actions;
1032 sub set_use_dbms_capability {
1033 $_[0]->set_inherited ($_[1], $_[2]);
1036 sub get_use_dbms_capability {
1037 my ($self, $capname) = @_;
1039 my $use = $self->get_inherited ($capname);
1042 : do { $capname =~ s/^_use_/_supports_/; $self->get_dbms_capability ($capname) }
1046 sub set_dbms_capability {
1047 $_[0]->_dbh_details->{capability}{$_[1]} = $_[2];
1050 sub get_dbms_capability {
1051 my ($self, $capname) = @_;
1053 my $cap = $self->_dbh_details->{capability}{$capname};
1055 unless (defined $cap) {
1056 if (my $meth = $self->can ("_determine$capname")) {
1057 $cap = $self->$meth ? 1 : 0;
1063 $self->set_dbms_capability ($capname, $cap);
1073 unless ($info = $self->_dbh_details->{info}) {
1077 my $server_version = try { $self->_get_server_version };
1079 if (defined $server_version) {
1080 $info->{dbms_version} = $server_version;
1082 my ($numeric_version) = $server_version =~ /^([\d\.]+)/;
1083 my @verparts = split (/\./, $numeric_version);
1089 # consider only up to 3 version parts, iff not more than 3 digits
1091 while (@verparts && @use_parts < 3) {
1092 my $p = shift @verparts;
1094 push @use_parts, $p;
1096 push @use_parts, 0 while @use_parts < 3;
1098 $info->{normalized_dbms_version} = sprintf "%d.%03d%03d", @use_parts;
1102 $self->_dbh_details->{info} = $info;
1108 sub _get_server_version {
1109 shift->_dbh_get_info(18);
1113 my ($self, $info) = @_;
1115 return try { $self->_get_dbh->get_info($info) } || undef;
1118 sub _determine_driver {
1121 if ((not $self->_driver_determined) && (not $self->{_in_determine_driver})) {
1122 my $started_connected = 0;
1123 local $self->{_in_determine_driver} = 1;
1125 if (ref($self) eq __PACKAGE__) {
1127 if ($self->_dbh) { # we are connected
1128 $driver = $self->_dbh->{Driver}{Name};
1129 $started_connected = 1;
1131 # if connect_info is a CODEREF, we have no choice but to connect
1132 if (ref $self->_dbi_connect_info->[0] &&
1133 reftype $self->_dbi_connect_info->[0] eq 'CODE') {
1134 $self->_populate_dbh;
1135 $driver = $self->_dbh->{Driver}{Name};
1138 # try to use dsn to not require being connected, the driver may still
1139 # force a connection in _rebless to determine version
1140 # (dsn may not be supplied at all if all we do is make a mock-schema)
1141 my $dsn = $self->_dbi_connect_info->[0] || $ENV{DBI_DSN} || '';
1142 ($driver) = $dsn =~ /dbi:([^:]+):/i;
1143 $driver ||= $ENV{DBI_DRIVER};
1148 my $storage_class = "DBIx::Class::Storage::DBI::${driver}";
1149 if ($self->load_optional_class($storage_class)) {
1150 mro::set_mro($storage_class, 'c3');
1151 bless $self, $storage_class;
1157 $self->_driver_determined(1);
1159 Class::C3->reinitialize() if DBIx::Class::_ENV_::OLD_MRO;
1161 $self->_init; # run driver-specific initializations
1163 $self->_run_connection_actions
1164 if !$started_connected && defined $self->_dbh;
1168 sub _do_connection_actions {
1170 my $method_prefix = shift;
1173 if (not ref($call)) {
1174 my $method = $method_prefix . $call;
1176 } elsif (ref($call) eq 'CODE') {
1178 } elsif (ref($call) eq 'ARRAY') {
1179 if (ref($call->[0]) ne 'ARRAY') {
1180 $self->_do_connection_actions($method_prefix, $_) for @$call;
1182 $self->_do_connection_actions($method_prefix, @$_) for @$call;
1185 $self->throw_exception (sprintf ("Don't know how to process conection actions of type '%s'", ref($call)) );
1191 sub connect_call_do_sql {
1193 $self->_do_query(@_);
1196 sub disconnect_call_do_sql {
1198 $self->_do_query(@_);
1201 # override in db-specific backend when necessary
1202 sub connect_call_datetime_setup { 1 }
1205 my ($self, $action) = @_;
1207 if (ref $action eq 'CODE') {
1208 $action = $action->($self);
1209 $self->_do_query($_) foreach @$action;
1212 # Most debuggers expect ($sql, @bind), so we need to exclude
1213 # the attribute hash which is the second argument to $dbh->do
1214 # furthermore the bind values are usually to be presented
1215 # as named arrayref pairs, so wrap those here too
1216 my @do_args = (ref $action eq 'ARRAY') ? (@$action) : ($action);
1217 my $sql = shift @do_args;
1218 my $attrs = shift @do_args;
1219 my @bind = map { [ undef, $_ ] } @do_args;
1221 $self->_query_start($sql, \@bind);
1222 $self->_get_dbh->do($sql, $attrs, @do_args);
1223 $self->_query_end($sql, \@bind);
1230 my ($self, @info) = @_;
1232 $self->throw_exception("You failed to provide any connection info")
1235 my ($old_connect_via, $dbh);
1237 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
1238 $old_connect_via = $DBI::connect_via;
1239 $DBI::connect_via = 'connect';
1243 if(ref $info[0] eq 'CODE') {
1244 $dbh = $info[0]->();
1248 $dbh = DBI->connect(@info);
1255 unless ($self->unsafe) {
1257 $self->throw_exception(
1258 'Refusing clobbering of {HandleError} installed on externally supplied '
1259 ."DBI handle $dbh. Either remove the handler or use the 'unsafe' attribute."
1260 ) if $dbh->{HandleError} and ref $dbh->{HandleError} ne '__DBIC__DBH__ERROR__HANDLER__';
1262 # Default via _default_dbi_connect_attributes is 1, hence it was an explicit
1263 # request, or an external handle. Complain and set anyway
1264 unless ($dbh->{RaiseError}) {
1265 carp( ref $info[0] eq 'CODE'
1267 ? "The 'RaiseError' of the externally supplied DBI handle is set to false. "
1268 ."DBIx::Class will toggle it back to true, unless the 'unsafe' connect "
1269 .'attribute has been supplied'
1271 : 'RaiseError => 0 supplied in your connection_info, without an explicit '
1272 .'unsafe => 1. Toggling RaiseError back to true'
1275 $dbh->{RaiseError} = 1;
1278 # this odd anonymous coderef dereference is in fact really
1279 # necessary to avoid the unwanted effect described in perl5
1282 my $weak_self = $_[0];
1285 # the coderef is blessed so we can distinguish it from externally
1286 # supplied handles (which must be preserved)
1287 $_[1]->{HandleError} = bless sub {
1289 $weak_self->throw_exception("DBI Exception: $_[0]");
1292 # the handler may be invoked by something totally out of
1294 DBIx::Class::Exception->throw("DBI Exception (unhandled by DBIC, ::Schema GCed): $_[0]");
1296 }, '__DBIC__DBH__ERROR__HANDLER__';
1301 $self->throw_exception("DBI Connection failed: $_")
1304 $DBI::connect_via = $old_connect_via if $old_connect_via;
1307 $self->_dbh_autocommit($dbh->{AutoCommit});
1314 # this means we have not yet connected and do not know the AC status
1315 # (e.g. coderef $dbh), need a full-fledged connection check
1316 if (! defined $self->_dbh_autocommit) {
1317 $self->ensure_connected;
1319 # Otherwise simply connect or re-connect on pid changes
1324 $self->next::method(@_);
1327 sub _exec_txn_begin {
1330 # if the user is utilizing txn_do - good for him, otherwise we need to
1331 # ensure that the $dbh is healthy on BEGIN.
1332 # We do this via ->dbh_do instead of ->dbh, so that the ->dbh "ping"
1333 # will be replaced by a failure of begin_work itself (which will be
1334 # then retried on reconnect)
1335 if ($self->{_in_do_block}) {
1336 $self->_dbh->begin_work;
1338 $self->dbh_do(sub { $_[1]->begin_work });
1345 $self->_verify_pid if $self->_dbh;
1346 $self->throw_exception("Unable to txn_commit() on a disconnected storage")
1349 # esoteric case for folks using external $dbh handles
1350 if (! $self->transaction_depth and ! $self->_dbh->FETCH('AutoCommit') ) {
1351 carp "Storage transaction_depth 0 does not match "
1352 ."false AutoCommit of $self->{_dbh}, attempting COMMIT anyway";
1353 $self->transaction_depth(1);
1356 $self->next::method(@_);
1358 # if AutoCommit is disabled txn_depth never goes to 0
1359 # as a new txn is started immediately on commit
1360 $self->transaction_depth(1) if (
1361 !$self->transaction_depth
1363 defined $self->_dbh_autocommit
1365 ! $self->_dbh_autocommit
1369 sub _exec_txn_commit {
1370 shift->_dbh->commit;
1376 $self->_verify_pid if $self->_dbh;
1377 $self->throw_exception("Unable to txn_rollback() on a disconnected storage")
1380 # esoteric case for folks using external $dbh handles
1381 if (! $self->transaction_depth and ! $self->_dbh->FETCH('AutoCommit') ) {
1382 carp "Storage transaction_depth 0 does not match "
1383 ."false AutoCommit of $self->{_dbh}, attempting ROLLBACK anyway";
1384 $self->transaction_depth(1);
1387 $self->next::method(@_);
1389 # if AutoCommit is disabled txn_depth never goes to 0
1390 # as a new txn is started immediately on commit
1391 $self->transaction_depth(1) if (
1392 !$self->transaction_depth
1394 defined $self->_dbh_autocommit
1396 ! $self->_dbh_autocommit
1400 sub _exec_txn_rollback {
1401 shift->_dbh->rollback;
1404 # generate some identical methods
1405 for my $meth (qw/svp_begin svp_release svp_rollback/) {
1407 *{__PACKAGE__ ."::$meth"} = subname $meth => sub {
1409 $self->_verify_pid if $self->_dbh;
1410 $self->throw_exception("Unable to $meth() on a disconnected storage")
1412 $self->next::method(@_);
1416 # This used to be the top-half of _execute. It was split out to make it
1417 # easier to override in NoBindVars without duping the rest. It takes up
1418 # all of _execute's args, and emits $sql, @bind.
1419 sub _prep_for_execute {
1420 #my ($self, $op, $ident, $args) = @_;
1421 return shift->_gen_sql_bind(@_)
1425 my ($self, $op, $ident, $args) = @_;
1427 my ($sql, @bind) = $self->sql_maker->$op(
1428 blessed($ident) ? $ident->from : $ident,
1432 my (@final_bind, $colinfos);
1433 my $resolve_bindinfo = sub {
1434 $colinfos ||= $self->_resolve_column_info($ident);
1435 if (my $col = $_[1]->{dbic_colname}) {
1436 $_[1]->{sqlt_datatype} ||= $colinfos->{$col}{data_type}
1437 if $colinfos->{$col}{data_type};
1438 $_[1]->{sqlt_size} ||= $colinfos->{$col}{size}
1439 if $colinfos->{$col}{size};
1444 for my $e (@{$args->[2]{bind}||[]}, @bind) {
1445 push @final_bind, [ do {
1446 if (ref $e ne 'ARRAY') {
1449 elsif (! defined $e->[0]) {
1452 elsif (ref $e->[0] eq 'HASH') {
1454 (first { $e->[0]{$_} } qw/dbd_attrs sqlt_datatype/) ? $e->[0] : $self->$resolve_bindinfo($e->[0]),
1458 elsif (ref $e->[0] eq 'SCALAR') {
1459 ( { sqlt_datatype => ${$e->[0]} }, $e->[1] )
1462 ( $self->$resolve_bindinfo({ dbic_colname => $e->[0] }), $e->[1] )
1467 ($sql, \@final_bind);
1470 sub _format_for_trace {
1471 #my ($self, $bind) = @_;
1473 ### Turn @bind from something like this:
1474 ### ( [ "artist", 1 ], [ \%attrs, 3 ] )
1476 ### ( "'1'", "'3'" )
1479 defined( $_ && $_->[1] )
1486 my ( $self, $sql, $bind ) = @_;
1488 $self->debugobj->query_start( $sql, $self->_format_for_trace($bind) )
1493 my ( $self, $sql, $bind ) = @_;
1495 $self->debugobj->query_end( $sql, $self->_format_for_trace($bind) )
1500 sub _dbi_attrs_for_bind {
1501 my ($self, $ident, $bind) = @_;
1503 if (! defined $sba_compat) {
1504 $self->_determine_driver;
1505 $sba_compat = $self->can('source_bind_attributes') == \&source_bind_attributes
1513 my $class = ref $self;
1515 "The source_bind_attributes() override in $class relies on a deprecated codepath. "
1516 .'You are strongly advised to switch your code to override bind_attribute_by_datatype() '
1517 .'instead. This legacy compat shim will also disappear some time before DBIC 0.09'
1520 my $sba_attrs = $self->source_bind_attributes
1525 for (map { $_->[0] } @$bind) {
1527 if (exists $_->{dbd_attrs}) {
1530 elsif($_->{sqlt_datatype}) {
1531 $self->bind_attribute_by_data_type($_->{sqlt_datatype}) || undef;
1533 elsif ($sba_attrs and $_->{dbic_colname}) {
1534 $sba_attrs->{$_->{dbic_colname}} || undef;
1537 undef; # always push something at this position
1546 my ($self, $op, $ident, @args) = @_;
1548 my ($sql, $bind) = $self->_prep_for_execute($op, $ident, \@args);
1550 shift->dbh_do( # retry over disconnects
1554 $self->_dbi_attrs_for_bind($ident, $bind)
1559 my ($self, undef, $sql, $bind, $bind_attrs) = @_;
1561 $self->_query_start( $sql, $bind );
1562 my $sth = $self->_sth($sql);
1564 for my $i (0 .. $#$bind) {
1565 if (ref $bind->[$i][1] eq 'SCALAR') { # any scalarrefs are assumed to be bind_inouts
1566 $sth->bind_param_inout(
1567 $i + 1, # bind params counts are 1-based
1569 $bind->[$i][0]{dbd_size} || $self->_max_column_bytesize($bind->[$i][0]), # size
1576 (ref $bind->[$i][1] and overload::Method($bind->[$i][1], '""'))
1585 # Can this fail without throwing an exception anyways???
1586 my $rv = $sth->execute();
1587 $self->throw_exception(
1588 $sth->errstr || $sth->err || 'Unknown error: execute() returned false, but error flags were not set...'
1591 $self->_query_end( $sql, $bind );
1593 return (wantarray ? ($rv, $sth, @$bind) : $rv);
1596 sub _prefetch_autovalues {
1597 my ($self, $source, $to_insert) = @_;
1599 my $colinfo = $source->columns_info;
1602 for my $col (keys %$colinfo) {
1604 $colinfo->{$col}{auto_nextval}
1607 ! exists $to_insert->{$col}
1609 ref $to_insert->{$col} eq 'SCALAR'
1611 (ref $to_insert->{$col} eq 'REF' and ref ${$to_insert->{$col}} eq 'ARRAY')
1614 $values{$col} = $self->_sequence_fetch(
1616 ( $colinfo->{$col}{sequence} ||=
1617 $self->_dbh_get_autoinc_seq($self->_get_dbh, $source, $col)
1627 my ($self, $source, $to_insert) = @_;
1629 my $prefetched_values = $self->_prefetch_autovalues($source, $to_insert);
1631 # fuse the values, but keep a separate list of prefetched_values so that
1632 # they can be fused once again with the final return
1633 $to_insert = { %$to_insert, %$prefetched_values };
1635 my $col_infos = $source->columns_info;
1636 my %pcols = map { $_ => 1 } $source->primary_columns;
1638 for my $col ($source->columns) {
1639 # nothing to retrieve when explicit values are supplied
1640 next if (defined $to_insert->{$col} and ! (
1641 ref $to_insert->{$col} eq 'SCALAR'
1643 (ref $to_insert->{$col} eq 'REF' and ref ${$to_insert->{$col}} eq 'ARRAY')
1646 # the 'scalar keys' is a trick to preserve the ->columns declaration order
1647 $retrieve_cols{$col} = scalar keys %retrieve_cols if (
1650 $col_infos->{$col}{retrieve_on_insert}
1654 my ($sqla_opts, @ir_container);
1655 if (%retrieve_cols and $self->_use_insert_returning) {
1656 $sqla_opts->{returning_container} = \@ir_container
1657 if $self->_use_insert_returning_bound;
1659 $sqla_opts->{returning} = [
1660 sort { $retrieve_cols{$a} <=> $retrieve_cols{$b} } keys %retrieve_cols
1664 my ($rv, $sth) = $self->_execute('insert', $source, $to_insert, $sqla_opts);
1666 my %returned_cols = %$to_insert;
1667 if (my $retlist = $sqla_opts->{returning}) { # if IR is supported - we will get everything in one set
1668 @ir_container = try {
1669 local $SIG{__WARN__} = sub {};
1670 my @r = $sth->fetchrow_array;
1673 } unless @ir_container;
1675 @returned_cols{@$retlist} = @ir_container if @ir_container;
1678 # pull in PK if needed and then everything else
1679 if (my @missing_pri = grep { $pcols{$_} } keys %retrieve_cols) {
1681 $self->throw_exception( "Missing primary key but Storage doesn't support last_insert_id" )
1682 unless $self->can('last_insert_id');
1684 my @pri_values = $self->last_insert_id($source, @missing_pri);
1686 $self->throw_exception( "Can't get last insert id" )
1687 unless (@pri_values == @missing_pri);
1689 @returned_cols{@missing_pri} = @pri_values;
1690 delete $retrieve_cols{$_} for @missing_pri;
1693 # if there is more left to pull
1694 if (%retrieve_cols) {
1695 $self->throw_exception(
1696 'Unable to retrieve additional columns without a Primary Key on ' . $source->source_name
1699 my @left_to_fetch = sort { $retrieve_cols{$a} <=> $retrieve_cols{$b} } keys %retrieve_cols;
1701 my $cur = DBIx::Class::ResultSet->new($source, {
1702 where => { map { $_ => $returned_cols{$_} } (keys %pcols) },
1703 select => \@left_to_fetch,
1706 @returned_cols{@left_to_fetch} = $cur->next;
1708 $self->throw_exception('Duplicate row returned for PK-search after fresh insert')
1709 if scalar $cur->next;
1713 return { %$prefetched_values, %returned_cols };
1717 my ($self, $source, $cols, $data) = @_;
1719 # FIXME - perhaps this is not even needed? does DBI stringify?
1721 # forcibly stringify whatever is stringifiable
1722 for my $r (0 .. $#$data) {
1723 for my $c (0 .. $#{$data->[$r]}) {
1724 $data->[$r][$c] = "$data->[$r][$c]"
1725 if ( ref $data->[$r][$c] and overload::Method($data->[$r][$c], '""') );
1729 # check the data for consistency
1730 # report a sensible error on bad data
1732 # also create a list of dynamic binds (ones that will be changing
1735 for my $col_idx (0..$#$cols) {
1737 # the first "row" is used as a point of reference
1738 my $reference_val = $data->[0][$col_idx];
1739 my $is_literal = ref $reference_val eq 'SCALAR';
1740 my $is_literal_bind = ( !$is_literal and (
1741 ref $reference_val eq 'REF'
1743 ref $$reference_val eq 'ARRAY'
1746 $dyn_bind_idx->{$col_idx} = 1
1747 if (!$is_literal and !$is_literal_bind);
1749 # use a closure for convenience (less to pass)
1750 my $bad_slice = sub {
1751 my ($msg, $slice_idx) = @_;
1752 $self->throw_exception(sprintf "%s for column '%s' in populate slice:\n%s",
1756 require Data::Dumper::Concise;
1757 local $Data::Dumper::Maxdepth = 2;
1758 Data::Dumper::Concise::Dumper ({
1759 map { $cols->[$_] =>
1760 $data->[$slice_idx][$_]
1767 for my $row_idx (1..$#$data) { # we are comparing against what we got from [0] above, hence start from 1
1768 my $val = $data->[$row_idx][$col_idx];
1771 if (ref $val ne 'SCALAR') {
1773 "Incorrect value (expecting SCALAR-ref \\'$$reference_val')",
1777 elsif ($$val ne $$reference_val) {
1779 "Inconsistent literal SQL value (expecting \\'$$reference_val')",
1784 elsif ($is_literal_bind) {
1785 if (ref $val ne 'REF' or ref $$val ne 'ARRAY') {
1787 "Incorrect value (expecting ARRAYREF-ref \\['${$reference_val}->[0]', ... ])",
1791 elsif (${$val}->[0] ne ${$reference_val}->[0]) {
1793 "Inconsistent literal SQL-bind value (expecting \\['${$reference_val}->[0]', ... ])",
1799 if (ref $val eq 'SCALAR' or (ref $val eq 'REF' and ref $$val eq 'ARRAY') ) {
1800 $bad_slice->("Literal SQL found where a plain bind value is expected", $row_idx);
1803 $bad_slice->("$val reference found where bind expected", $row_idx);
1809 # Get the sql with bind values interpolated where necessary. For dynamic
1810 # binds convert the values of the first row into a literal+bind combo, with
1811 # extra positional info in the bind attr hashref. This will allow us to match
1812 # the order properly, and is so contrived because a user-supplied literal
1813 # bind (or something else specific to a resultsource and/or storage driver)
1814 # can inject extra binds along the way, so one can't rely on "shift
1815 # positions" ordering at all. Also we can't just hand SQLA a set of some
1816 # known "values" (e.g. hashrefs that can be later matched up by address),
1817 # because we want to supply a real value on which perhaps e.g. datatype
1818 # checks will be performed
1819 my ($sql, $proto_bind) = $self->_prep_for_execute (
1822 [ { map { $cols->[$_] => $dyn_bind_idx->{$_}
1824 { dbic_colname => $cols->[$_], _bind_data_slice_idx => $_ }
1832 if (! @$proto_bind and keys %$dyn_bind_idx) {
1833 # if the bindlist is empty and we had some dynamic binds, this means the
1834 # storage ate them away (e.g. the NoBindVars component) and interpolated
1835 # them directly into the SQL. This obviosly can't be good for multi-inserts
1836 $self->throw_exception('Cannot insert_bulk without support for placeholders');
1839 # neither _execute_array, nor _execute_inserts_with_no_binds are
1840 # atomic (even if _execute _array is a single call). Thus a safety
1842 my $guard = $self->txn_scope_guard;
1844 $self->_query_start( $sql, @$proto_bind ? [[undef => '__BULK_INSERT__' ]] : () );
1845 my $sth = $self->_sth($sql);
1848 # proto bind contains the information on which pieces of $data to pull
1849 # $cols is passed in only for prettier error-reporting
1850 $self->_execute_array( $source, $sth, $proto_bind, $cols, $data );
1853 # bind_param_array doesn't work if there are no binds
1854 $self->_dbh_execute_inserts_with_no_binds( $sth, scalar @$data );
1858 $self->_query_end( $sql, @$proto_bind ? [[ undef => '__BULK_INSERT__' ]] : () );
1862 return (wantarray ? ($rv, $sth, @$proto_bind) : $rv);
1865 sub _execute_array {
1866 my ($self, $source, $sth, $proto_bind, $cols, $data, @extra) = @_;
1868 ## This must be an arrayref, else nothing works!
1869 my $tuple_status = [];
1871 my $bind_attrs = $self->_dbi_attrs_for_bind($source, $proto_bind);
1873 # Bind the values by column slices
1874 for my $i (0 .. $#$proto_bind) {
1875 my $data_slice_idx = (
1876 ref $proto_bind->[$i][0] eq 'HASH'
1878 exists $proto_bind->[$i][0]{_bind_data_slice_idx}
1879 ) ? $proto_bind->[$i][0]{_bind_data_slice_idx} : undef;
1881 $sth->bind_param_array(
1882 $i+1, # DBI bind indexes are 1-based
1883 defined $data_slice_idx
1884 # either get a "column" of dynamic values, or just repeat the same
1885 # bind over and over
1886 ? [ map { $_->[$data_slice_idx] } @$data ]
1887 : [ ($proto_bind->[$i][1]) x @$data ]
1889 defined $bind_attrs->[$i] ? $bind_attrs->[$i] : (), # some DBDs throw up when given an undef
1895 $rv = $self->_dbh_execute_array($sth, $tuple_status, @extra);
1901 # Not all DBDs are create equal. Some throw on error, some return
1902 # an undef $rv, and some set $sth->err - try whatever we can
1903 $err = ($sth->errstr || 'UNKNOWN ERROR ($sth->errstr is unset)') if (
1906 ( !defined $rv or $sth->err )
1909 # Statement must finish even if there was an exception.
1914 $err = shift unless defined $err
1919 ++$i while $i <= $#$tuple_status && !ref $tuple_status->[$i];
1921 $self->throw_exception("Unexpected populate error: $err")
1922 if ($i > $#$tuple_status);
1924 require Data::Dumper::Concise;
1925 $self->throw_exception(sprintf "execute_array() aborted with '%s' at populate slice:\n%s",
1926 ($tuple_status->[$i][1] || $err),
1927 Data::Dumper::Concise::Dumper( { map { $cols->[$_] => $data->[$i][$_] } (0 .. $#$cols) } ),
1934 sub _dbh_execute_array {
1935 #my ($self, $sth, $tuple_status, @extra) = @_;
1936 return $_[1]->execute_array({ArrayTupleStatus => $_[2]});
1939 sub _dbh_execute_inserts_with_no_binds {
1940 my ($self, $sth, $count) = @_;
1944 my $dbh = $self->_get_dbh;
1945 local $dbh->{RaiseError} = 1;
1946 local $dbh->{PrintError} = 0;
1948 $sth->execute foreach 1..$count;
1954 # Make sure statement is finished even if there was an exception.
1959 $err = shift unless defined $err;
1962 $self->throw_exception($err) if defined $err;
1968 #my ($self, $source, @args) = @_;
1969 shift->_execute('update', @_);
1974 #my ($self, $source, @args) = @_;
1975 shift->_execute('delete', @_);
1978 # We were sent here because the $rs contains a complex search
1979 # which will require a subquery to select the correct rows
1980 # (i.e. joined or limited resultsets, or non-introspectable conditions)
1982 # Generating a single PK column subquery is trivial and supported
1983 # by all RDBMS. However if we have a multicolumn PK, things get ugly.
1984 # Look at _multipk_update_delete()
1985 sub _subq_update_delete {
1987 my ($rs, $op, $values) = @_;
1989 my $rsrc = $rs->result_source;
1991 # quick check if we got a sane rs on our hands
1992 my @pcols = $rsrc->_pri_cols;
1994 my $sel = $rs->_resolved_attrs->{select};
1995 $sel = [ $sel ] unless ref $sel eq 'ARRAY';
1998 join ("\x00", map { join '.', $rs->{attrs}{alias}, $_ } sort @pcols)
2000 join ("\x00", sort @$sel )
2002 $self->throw_exception (
2003 '_subq_update_delete can not be called on resultsets selecting columns other than the primary keys'
2010 $op eq 'update' ? $values : (),
2011 { $pcols[0] => { -in => $rs->as_query } },
2016 return $self->_multipk_update_delete (@_);
2020 # ANSI SQL does not provide a reliable way to perform a multicol-PK
2021 # resultset update/delete involving subqueries. So by default resort
2022 # to simple (and inefficient) delete_all style per-row opearations,
2023 # while allowing specific storages to override this with a faster
2026 sub _multipk_update_delete {
2027 return shift->_per_row_update_delete (@_);
2030 # This is the default loop used to delete/update rows for multi PK
2031 # resultsets, and used by mysql exclusively (because it can't do anything
2034 # We do not use $row->$op style queries, because resultset update/delete
2035 # is not expected to cascade (this is what delete_all/update_all is for).
2037 # There should be no race conditions as the entire operation is rolled
2040 sub _per_row_update_delete {
2042 my ($rs, $op, $values) = @_;
2044 my $rsrc = $rs->result_source;
2045 my @pcols = $rsrc->_pri_cols;
2047 my $guard = $self->txn_scope_guard;
2049 # emulate the return value of $sth->execute for non-selects
2050 my $row_cnt = '0E0';
2052 my $subrs_cur = $rs->cursor;
2053 my @all_pk = $subrs_cur->all;
2054 for my $pks ( @all_pk) {
2057 for my $i (0.. $#pcols) {
2058 $cond->{$pcols[$i]} = $pks->[$i];
2063 $op eq 'update' ? $values : (),
2077 $self->_execute($self->_select_args(@_));
2080 sub _select_args_to_query {
2083 # my ($op, $ident, $select, $cond, $rs_attrs, $rows, $offset)
2084 # = $self->_select_args($ident, $select, $cond, $attrs);
2085 my ($op, $ident, @args) =
2086 $self->_select_args(@_);
2088 # my ($sql, $prepared_bind) = $self->_gen_sql_bind($op, $ident, [ $select, $cond, $rs_attrs, $rows, $offset ]);
2089 my ($sql, $prepared_bind) = $self->_gen_sql_bind($op, $ident, \@args);
2090 $prepared_bind ||= [];
2093 ? ($sql, $prepared_bind)
2094 : \[ "($sql)", @$prepared_bind ]
2099 my ($self, $ident, $select, $where, $attrs) = @_;
2101 my $sql_maker = $self->sql_maker;
2102 my ($alias2source, $rs_alias) = $self->_resolve_ident_sources ($ident);
2109 $rs_alias && $alias2source->{$rs_alias}
2110 ? ( _rsroot_rsrc => $alias2source->{$rs_alias} )
2115 # Sanity check the attributes (SQLMaker does it too, but
2116 # in case of a software_limit we'll never reach there)
2117 if (defined $attrs->{offset}) {
2118 $self->throw_exception('A supplied offset attribute must be a non-negative integer')
2119 if ( $attrs->{offset} =~ /\D/ or $attrs->{offset} < 0 );
2122 if (defined $attrs->{rows}) {
2123 $self->throw_exception("The rows attribute must be a positive integer if present")
2124 if ( $attrs->{rows} =~ /\D/ or $attrs->{rows} <= 0 );
2126 elsif ($attrs->{offset}) {
2127 # MySQL actually recommends this approach. I cringe.
2128 $attrs->{rows} = $sql_maker->__max_int;
2133 # see if we need to tear the prefetch apart otherwise delegate the limiting to the
2134 # storage, unless software limit was requested
2137 ( $attrs->{rows} && keys %{$attrs->{collapse}} )
2139 # grouped prefetch (to satisfy group_by == select)
2140 ( $attrs->{group_by}
2142 @{$attrs->{group_by}}
2144 $attrs->{_prefetch_selector_range}
2147 ($ident, $select, $where, $attrs)
2148 = $self->_adjust_select_args_for_complex_prefetch ($ident, $select, $where, $attrs);
2150 elsif (! $attrs->{software_limit} ) {
2152 $attrs->{rows} || (),
2153 $attrs->{offset} || (),
2157 # try to simplify the joinmap further (prune unreferenced type-single joins)
2158 $ident = $self->_prune_unused_joins ($ident, $select, $where, $attrs);
2161 # This would be the point to deflate anything found in $where
2162 # (and leave $attrs->{bind} intact). Problem is - inflators historically
2163 # expect a row object. And all we have is a resultsource (it is trivial
2164 # to extract deflator coderefs via $alias2source above).
2166 # I don't see a way forward other than changing the way deflators are
2167 # invoked, and that's just bad...
2170 return ('select', $ident, $select, $where, $attrs, @limit);
2173 # Returns a counting SELECT for a simple count
2174 # query. Abstracted so that a storage could override
2175 # this to { count => 'firstcol' } or whatever makes
2176 # sense as a performance optimization
2178 #my ($self, $source, $rs_attrs) = @_;
2179 return { count => '*' };
2182 sub source_bind_attributes {
2183 shift->throw_exception(
2184 'source_bind_attributes() was never meant to be a callable public method - '
2185 .'please contact the DBIC dev-team and describe your use case so that a reasonable '
2186 .'solution can be provided'
2187 ."\nhttp://search.cpan.org/dist/DBIx-Class/lib/DBIx/Class.pm#GETTING_HELP/SUPPORT"
2195 =item Arguments: $ident, $select, $condition, $attrs
2199 Handle a SQL select statement.
2205 my ($ident, $select, $condition, $attrs) = @_;
2206 return $self->cursor_class->new($self, \@_, $attrs);
2211 my ($rv, $sth, @bind) = $self->_select(@_);
2212 my @row = $sth->fetchrow_array;
2213 my @nextrow = $sth->fetchrow_array if @row;
2214 if(@row && @nextrow) {
2215 carp "Query returned more than one row. SQL that returns multiple rows is DEPRECATED for ->find and ->single";
2217 # Need to call finish() to work round broken DBDs
2222 =head2 sql_limit_dialect
2224 This is an accessor for the default SQL limit dialect used by a particular
2225 storage driver. Can be overridden by supplying an explicit L</limit_dialect>
2226 to L<DBIx::Class::Schema/connect>. For a list of available limit dialects
2227 see L<DBIx::Class::SQLMaker::LimitDialects>.
2233 =item Arguments: $sql
2237 Returns a L<DBI> sth (statement handle) for the supplied SQL.
2242 my ($self, $dbh, $sql) = @_;
2244 # 3 is the if_active parameter which avoids active sth re-use
2245 my $sth = $self->disable_sth_caching
2246 ? $dbh->prepare($sql)
2247 : $dbh->prepare_cached($sql, {}, 3);
2249 # XXX You would think RaiseError would make this impossible,
2250 # but apparently that's not true :(
2251 $self->throw_exception(
2254 sprintf( "\$dbh->prepare() of '%s' through %s failed *silently* without "
2255 .'an exception and/or setting $dbh->errstr',
2257 ? substr($sql, 0, 20) . '...'
2260 'DBD::' . $dbh->{Driver}{Name},
2268 carp_unique 'sth was mistakenly marked/documented as public, stop calling it (will be removed before DBIC v0.09)';
2273 my ($self, $sql) = @_;
2274 $self->dbh_do('_dbh_sth', $sql); # retry over disconnects
2277 sub _dbh_columns_info_for {
2278 my ($self, $dbh, $table) = @_;
2280 if ($dbh->can('column_info')) {
2284 my ($schema,$tab) = $table =~ /^(.+?)\.(.+)$/ ? ($1,$2) : (undef,$table);
2285 my $sth = $dbh->column_info( undef,$schema, $tab, '%' );
2287 while ( my $info = $sth->fetchrow_hashref() ){
2289 $column_info{data_type} = $info->{TYPE_NAME};
2290 $column_info{size} = $info->{COLUMN_SIZE};
2291 $column_info{is_nullable} = $info->{NULLABLE} ? 1 : 0;
2292 $column_info{default_value} = $info->{COLUMN_DEF};
2293 my $col_name = $info->{COLUMN_NAME};
2294 $col_name =~ s/^\"(.*)\"$/$1/;
2296 $result{$col_name} = \%column_info;
2301 return \%result if !$caught && scalar keys %result;
2305 my $sth = $dbh->prepare($self->sql_maker->select($table, undef, \'1 = 0'));
2307 my @columns = @{$sth->{NAME_lc}};
2308 for my $i ( 0 .. $#columns ){
2310 $column_info{data_type} = $sth->{TYPE}->[$i];
2311 $column_info{size} = $sth->{PRECISION}->[$i];
2312 $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
2314 if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
2315 $column_info{data_type} = $1;
2316 $column_info{size} = $2;
2319 $result{$columns[$i]} = \%column_info;
2323 foreach my $col (keys %result) {
2324 my $colinfo = $result{$col};
2325 my $type_num = $colinfo->{data_type};
2327 if(defined $type_num && $dbh->can('type_info')) {
2328 my $type_info = $dbh->type_info($type_num);
2329 $type_name = $type_info->{TYPE_NAME} if $type_info;
2330 $colinfo->{data_type} = $type_name if $type_name;
2337 sub columns_info_for {
2338 my ($self, $table) = @_;
2339 $self->_dbh_columns_info_for ($self->_get_dbh, $table);
2342 =head2 last_insert_id
2344 Return the row id of the last insert.
2348 sub _dbh_last_insert_id {
2349 my ($self, $dbh, $source, $col) = @_;
2351 my $id = try { $dbh->last_insert_id (undef, undef, $source->name, $col) };
2353 return $id if defined $id;
2355 my $class = ref $self;
2356 $self->throw_exception ("No storage specific _dbh_last_insert_id() method implemented in $class, and the generic DBI::last_insert_id() failed");
2359 sub last_insert_id {
2361 $self->_dbh_last_insert_id ($self->_dbh, @_);
2364 =head2 _native_data_type
2368 =item Arguments: $type_name
2372 This API is B<EXPERIMENTAL>, will almost definitely change in the future, and
2373 currently only used by L<::AutoCast|DBIx::Class::Storage::DBI::AutoCast> and
2374 L<::Sybase::ASE|DBIx::Class::Storage::DBI::Sybase::ASE>.
2376 The default implementation returns C<undef>, implement in your Storage driver if
2377 you need this functionality.
2379 Should map types from other databases to the native RDBMS type, for example
2380 C<VARCHAR2> to C<VARCHAR>.
2382 Types with modifiers should map to the underlying data type. For example,
2383 C<INTEGER AUTO_INCREMENT> should become C<INTEGER>.
2385 Composite types should map to the container type, for example
2386 C<ENUM(foo,bar,baz)> becomes C<ENUM>.
2390 sub _native_data_type {
2391 #my ($self, $data_type) = @_;
2395 # Check if placeholders are supported at all
2396 sub _determine_supports_placeholders {
2398 my $dbh = $self->_get_dbh;
2400 # some drivers provide a $dbh attribute (e.g. Sybase and $dbh->{syb_dynamic_supported})
2401 # but it is inaccurate more often than not
2403 local $dbh->{PrintError} = 0;
2404 local $dbh->{RaiseError} = 1;
2405 $dbh->do('select ?', {}, 1);
2413 # Check if placeholders bound to non-string types throw exceptions
2415 sub _determine_supports_typeless_placeholders {
2417 my $dbh = $self->_get_dbh;
2420 local $dbh->{PrintError} = 0;
2421 local $dbh->{RaiseError} = 1;
2422 # this specifically tests a bind that is NOT a string
2423 $dbh->do('select 1 where 1 = ?', {}, 1);
2433 Returns the database driver name.
2438 shift->_get_dbh->{Driver}->{Name};
2441 =head2 bind_attribute_by_data_type
2443 Given a datatype from column info, returns a database specific bind
2444 attribute for C<< $dbh->bind_param($val,$attribute) >> or nothing if we will
2445 let the database planner just handle it.
2447 Generally only needed for special case column types, like bytea in postgres.
2451 sub bind_attribute_by_data_type {
2455 =head2 is_datatype_numeric
2457 Given a datatype from column_info, returns a boolean value indicating if
2458 the current RDBMS considers it a numeric value. This controls how
2459 L<DBIx::Class::Row/set_column> decides whether to mark the column as
2460 dirty - when the datatype is deemed numeric a C<< != >> comparison will
2461 be performed instead of the usual C<eq>.
2465 sub is_datatype_numeric {
2466 #my ($self, $dt) = @_;
2468 return 0 unless $_[1];
2471 numeric | int(?:eger)? | (?:tiny|small|medium|big)int | dec(?:imal)? | real | float | double (?: \s+ precision)? | (?:big)?serial
2476 =head2 create_ddl_dir
2480 =item Arguments: $schema \@databases, $version, $directory, $preversion, \%sqlt_args
2484 Creates a SQL file based on the Schema, for each of the specified
2485 database engines in C<\@databases> in the given directory.
2486 (note: specify L<SQL::Translator> names, not L<DBI> driver names).
2488 Given a previous version number, this will also create a file containing
2489 the ALTER TABLE statements to transform the previous schema into the
2490 current one. Note that these statements may contain C<DROP TABLE> or
2491 C<DROP COLUMN> statements that can potentially destroy data.
2493 The file names are created using the C<ddl_filename> method below, please
2494 override this method in your schema if you would like a different file
2495 name format. For the ALTER file, the same format is used, replacing
2496 $version in the name with "$preversion-$version".
2498 See L<SQL::Translator/METHODS> for a list of values for C<\%sqlt_args>.
2499 The most common value for this would be C<< { add_drop_table => 1 } >>
2500 to have the SQL produced include a C<DROP TABLE> statement for each table
2501 created. For quoting purposes supply C<quote_table_names> and
2502 C<quote_field_names>.
2504 If no arguments are passed, then the following default values are assumed:
2508 =item databases - ['MySQL', 'SQLite', 'PostgreSQL']
2510 =item version - $schema->schema_version
2512 =item directory - './'
2514 =item preversion - <none>
2518 By default, C<\%sqlt_args> will have
2520 { add_drop_table => 1, ignore_constraint_names => 1, ignore_index_names => 1 }
2522 merged with the hash passed in. To disable any of those features, pass in a
2523 hashref like the following
2525 { ignore_constraint_names => 0, # ... other options }
2528 WARNING: You are strongly advised to check all SQL files created, before applying
2533 sub create_ddl_dir {
2534 my ($self, $schema, $databases, $version, $dir, $preversion, $sqltargs) = @_;
2537 carp "No directory given, using ./\n";
2542 (require File::Path and File::Path::make_path ("$dir")) # make_path does not like objects (i.e. Path::Class::Dir)
2544 $self->throw_exception(
2545 "Failed to create '$dir': " . ($! || $@ || 'error unknown')
2549 $self->throw_exception ("Directory '$dir' does not exist\n") unless(-d $dir);
2551 $databases ||= ['MySQL', 'SQLite', 'PostgreSQL'];
2552 $databases = [ $databases ] if(ref($databases) ne 'ARRAY');
2554 my $schema_version = $schema->schema_version || '1.x';
2555 $version ||= $schema_version;
2558 add_drop_table => 1,
2559 ignore_constraint_names => 1,
2560 ignore_index_names => 1,
2564 unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy')) {
2565 $self->throw_exception("Can't create a ddl file without " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2568 my $sqlt = SQL::Translator->new( $sqltargs );
2570 $sqlt->parser('SQL::Translator::Parser::DBIx::Class');
2571 my $sqlt_schema = $sqlt->translate({ data => $schema })
2572 or $self->throw_exception ($sqlt->error);
2574 foreach my $db (@$databases) {
2576 $sqlt->{schema} = $sqlt_schema;
2577 $sqlt->producer($db);
2580 my $filename = $schema->ddl_filename($db, $version, $dir);
2581 if (-e $filename && ($version eq $schema_version )) {
2582 # if we are dumping the current version, overwrite the DDL
2583 carp "Overwriting existing DDL file - $filename";
2587 my $output = $sqlt->translate;
2589 carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
2592 if(!open($file, ">$filename")) {
2593 $self->throw_exception("Can't open $filename for writing ($!)");
2596 print $file $output;
2599 next unless ($preversion);
2601 require SQL::Translator::Diff;
2603 my $prefilename = $schema->ddl_filename($db, $preversion, $dir);
2604 if(!-e $prefilename) {
2605 carp("No previous schema file found ($prefilename)");
2609 my $difffile = $schema->ddl_filename($db, $version, $dir, $preversion);
2611 carp("Overwriting existing diff file - $difffile");
2617 my $t = SQL::Translator->new($sqltargs);
2622 or $self->throw_exception ($t->error);
2624 my $out = $t->translate( $prefilename )
2625 or $self->throw_exception ($t->error);
2627 $source_schema = $t->schema;
2629 $source_schema->name( $prefilename )
2630 unless ( $source_schema->name );
2633 # The "new" style of producers have sane normalization and can support
2634 # diffing a SQL file against a DBIC->SQLT schema. Old style ones don't
2635 # And we have to diff parsed SQL against parsed SQL.
2636 my $dest_schema = $sqlt_schema;
2638 unless ( "SQL::Translator::Producer::$db"->can('preprocess_schema') ) {
2639 my $t = SQL::Translator->new($sqltargs);
2644 or $self->throw_exception ($t->error);
2646 my $out = $t->translate( $filename )
2647 or $self->throw_exception ($t->error);
2649 $dest_schema = $t->schema;
2651 $dest_schema->name( $filename )
2652 unless $dest_schema->name;
2655 my $diff = SQL::Translator::Diff::schema_diff($source_schema, $db,
2659 if(!open $file, ">$difffile") {
2660 $self->throw_exception("Can't write to $difffile ($!)");
2668 =head2 deployment_statements
2672 =item Arguments: $schema, $type, $version, $directory, $sqlt_args
2676 Returns the statements used by L</deploy> and L<DBIx::Class::Schema/deploy>.
2678 The L<SQL::Translator> (not L<DBI>) database driver name can be explicitly
2679 provided in C<$type>, otherwise the result of L</sqlt_type> is used as default.
2681 C<$directory> is used to return statements from files in a previously created
2682 L</create_ddl_dir> directory and is optional. The filenames are constructed
2683 from L<DBIx::Class::Schema/ddl_filename>, the schema name and the C<$version>.
2685 If no C<$directory> is specified then the statements are constructed on the
2686 fly using L<SQL::Translator> and C<$version> is ignored.
2688 See L<SQL::Translator/METHODS> for a list of values for C<$sqlt_args>.
2692 sub deployment_statements {
2693 my ($self, $schema, $type, $version, $dir, $sqltargs) = @_;
2694 $type ||= $self->sqlt_type;
2695 $version ||= $schema->schema_version || '1.x';
2697 my $filename = $schema->ddl_filename($type, $version, $dir);
2700 # FIXME replace this block when a proper sane sql parser is available
2702 open($file, "<$filename")
2703 or $self->throw_exception("Can't open $filename ($!)");
2706 return join('', @rows);
2709 unless (DBIx::Class::Optional::Dependencies->req_ok_for ('deploy') ) {
2710 $self->throw_exception("Can't deploy without a ddl_dir or " . DBIx::Class::Optional::Dependencies->req_missing_for ('deploy') );
2713 # sources needs to be a parser arg, but for simplicty allow at top level
2715 $sqltargs->{parser_args}{sources} = delete $sqltargs->{sources}
2716 if exists $sqltargs->{sources};
2718 my $tr = SQL::Translator->new(
2719 producer => "SQL::Translator::Producer::${type}",
2721 parser => 'SQL::Translator::Parser::DBIx::Class',
2727 @ret = $tr->translate;
2730 $ret[0] = $tr->translate;
2733 $self->throw_exception( 'Unable to produce deployment statements: ' . $tr->error)
2734 unless (@ret && defined $ret[0]);
2736 return wantarray ? @ret : $ret[0];
2739 # FIXME deploy() currently does not accurately report sql errors
2740 # Will always return true while errors are warned
2742 my ($self, $schema, $type, $sqltargs, $dir) = @_;
2746 return if($line =~ /^--/);
2747 # next if($line =~ /^DROP/m);
2748 return if($line =~ /^BEGIN TRANSACTION/m);
2749 return if($line =~ /^COMMIT/m);
2750 return if $line =~ /^\s+$/; # skip whitespace only
2751 $self->_query_start($line);
2753 # do a dbh_do cycle here, as we need some error checking in
2754 # place (even though we will ignore errors)
2755 $self->dbh_do (sub { $_[1]->do($line) });
2757 carp qq{$_ (running "${line}")};
2759 $self->_query_end($line);
2761 my @statements = $schema->deployment_statements($type, undef, $dir, { %{ $sqltargs || {} }, no_comments => 1 } );
2762 if (@statements > 1) {
2763 foreach my $statement (@statements) {
2764 $deploy->( $statement );
2767 elsif (@statements == 1) {
2768 # split on single line comments and end of statements
2769 foreach my $line ( split(/\s*--.*\n|;\n/, $statements[0])) {
2775 =head2 datetime_parser
2777 Returns the datetime parser class
2781 sub datetime_parser {
2783 return $self->{datetime_parser} ||= do {
2784 $self->build_datetime_parser(@_);
2788 =head2 datetime_parser_type
2790 Defines the datetime parser class - currently defaults to L<DateTime::Format::MySQL>
2792 =head2 build_datetime_parser
2794 See L</datetime_parser>
2798 sub build_datetime_parser {
2800 my $type = $self->datetime_parser_type(@_);
2805 =head2 is_replicating
2807 A boolean that reports if a particular L<DBIx::Class::Storage::DBI> is set to
2808 replicate from a master database. Default is undef, which is the result
2809 returned by databases that don't support replication.
2813 sub is_replicating {
2818 =head2 lag_behind_master
2820 Returns a number that represents a certain amount of lag behind a master db
2821 when a given storage is replicating. The number is database dependent, but
2822 starts at zero and increases with the amount of lag. Default in undef
2826 sub lag_behind_master {
2830 =head2 relname_to_table_alias
2834 =item Arguments: $relname, $join_count
2838 L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
2841 This hook is to allow specific L<DBIx::Class::Storage> drivers to change the
2842 way these aliases are named.
2844 The default behavior is C<< "$relname_$join_count" if $join_count > 1 >>,
2845 otherwise C<"$relname">.
2849 sub relname_to_table_alias {
2850 my ($self, $relname, $join_count) = @_;
2852 my $alias = ($join_count && $join_count > 1 ?
2853 join('_', $relname, $join_count) : $relname);
2858 # The size in bytes to use for DBI's ->bind_param_inout, this is the generic
2859 # version and it may be necessary to amend or override it for a specific storage
2860 # if such binds are necessary.
2861 sub _max_column_bytesize {
2862 my ($self, $attr) = @_;
2866 if ($attr->{sqlt_datatype}) {
2867 my $data_type = lc($attr->{sqlt_datatype});
2869 if ($attr->{sqlt_size}) {
2871 # String/sized-binary types
2872 if ($data_type =~ /^(?:
2873 l? (?:var)? char(?:acter)? (?:\s*varying)?
2875 (?:var)? binary (?:\s*varying)?
2880 $max_size = $attr->{sqlt_size};
2882 # Other charset/unicode types, assume scale of 4
2883 elsif ($data_type =~ /^(?:
2884 national \s* character (?:\s*varying)?
2893 $max_size = $attr->{sqlt_size} * 4;
2897 if (!$max_size and !$self->_is_lob_type($data_type)) {
2898 $max_size = 100 # for all other (numeric?) datatypes
2902 $max_size || $self->_dbic_connect_attributes->{LongReadLen} || $self->_get_dbh->{LongReadLen} || 8000;
2905 # Determine if a data_type is some type of BLOB
2907 my ($self, $data_type) = @_;
2908 $data_type && ($data_type =~ /lob|bfile|text|image|bytea|memo/i
2909 || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary
2910 |varchar|character\s*varying|nvarchar
2911 |national\s*character\s*varying))?\z/xi);
2914 sub _is_binary_lob_type {
2915 my ($self, $data_type) = @_;
2916 $data_type && ($data_type =~ /blob|bfile|image|bytea/i
2917 || $data_type =~ /^long(?:\s+(?:raw|bit\s*varying|varbit|binary))?\z/xi);
2920 sub _is_text_lob_type {
2921 my ($self, $data_type) = @_;
2922 $data_type && ($data_type =~ /^(?:clob|memo)\z/i
2923 || $data_type =~ /^long(?:\s+(?:varchar|character\s*varying|nvarchar
2924 |national\s*character\s*varying))\z/xi);
2931 =head2 DBIx::Class and AutoCommit
2933 DBIx::Class can do some wonderful magic with handling exceptions,
2934 disconnections, and transactions when you use C<< AutoCommit => 1 >>
2935 (the default) combined with L<txn_do|DBIx::Class::Storage/txn_do> for
2936 transaction support.
2938 If you set C<< AutoCommit => 0 >> in your connect info, then you are always
2939 in an assumed transaction between commits, and you're telling us you'd
2940 like to manage that manually. A lot of the magic protections offered by
2941 this module will go away. We can't protect you from exceptions due to database
2942 disconnects because we don't know anything about how to restart your
2943 transactions. You're on your own for handling all sorts of exceptional
2944 cases if you choose the C<< AutoCommit => 0 >> path, just as you would
2950 Matt S. Trout <mst@shadowcatsystems.co.uk>
2952 Andy Grundman <andy@hybridized.org>
2956 You may distribute this code under the same terms as Perl itself.