1 package DBIx::Class::Storage::DBI::Sybase;
7 DBIx::Class::Storage::DBI::Sybase::Common
8 DBIx::Class::Storage::DBI::AutoCast
11 use Carp::Clan qw/^DBIx::Class/;
15 __PACKAGE__->mk_group_accessors('simple' =>
16 qw/_identity _blob_log_on_update _insert_storage _identity_method/
19 my @delegate_to_insert_storage = qw/
20 disconnect _connect_info _sql_maker _sql_maker_opts disable_sth_caching
21 auto_savepoint unsafe cursor_class debug debugobj schema
26 DBIx::Class::Storage::DBI::Sybase - Sybase support for DBIx::Class
30 This subclass supports L<DBD::Sybase> for real Sybase databases. If you are
31 using an MSSQL database via L<DBD::Sybase>, your storage will be reblessed to
32 L<DBIx::Class::Storage::DBI::Sybase::Microsoft_SQL_Server>.
36 If your version of Sybase does not support placeholders, then your storage
37 will be reblessed to L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>. You can
38 also enable that driver explicitly, see the documentation for more details.
40 With this driver there is unfortunately no way to get the C<last_insert_id>
41 without doing a C<SELECT MAX(col)>. This is done safely in a transaction
42 (locking the table.) See L</INSERTS WITH PLACEHOLDERS>.
44 A recommended L<DBIx::Class::Storage::DBI/connect_info> setting:
46 on_connect_call => [['datetime_setup'], ['blob_setup', log_on_update => 0]]
55 if (ref($self) eq 'DBIx::Class::Storage::DBI::Sybase') {
57 @{$self->_get_dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2]
62 my $subclass = "DBIx::Class::Storage::DBI::Sybase::${dbtype}";
64 if (!$exception && $dbtype && $self->load_optional_class($subclass)) {
65 bless $self, $subclass;
67 } else { # real Sybase
68 my $no_bind_vars = 'DBIx::Class::Storage::DBI::Sybase::NoBindVars';
70 if ($self->using_freetds) {
71 carp <<'EOF' unless $ENV{DBIC_SYBASE_FREETDS_NOWARN};
73 You are using FreeTDS with Sybase.
75 We will do our best to support this configuration, but please consider this
78 TEXT/IMAGE columns will definitely not work.
80 You are encouraged to recompile DBD::Sybase with the Sybase Open Client libraries
83 See perldoc DBIx::Class::Storage::DBI::Sybase for more details.
85 To turn off this warning set the DBIC_SYBASE_FREETDS_NOWARN environment
88 if (not $self->_typeless_placeholders_supported) {
89 if ($self->_placeholders_supported) {
92 $self->ensure_class_loaded($no_bind_vars);
93 bless $self, $no_bind_vars;
98 elsif (not $self->_get_dbh->{syb_dynamic_supported}) {
99 # not necessarily FreeTDS, but no placeholders nevertheless
100 $self->ensure_class_loaded($no_bind_vars);
101 bless $self, $no_bind_vars;
103 } elsif (not $self->_typeless_placeholders_supported) {
104 # this is highly unlikely, but we check just in case
113 $self->_set_max_connect(256);
115 # based on LongReadLen in connect_info
116 $self->set_textsize if $self->using_freetds;
118 # create storage for insert transactions
119 $self->_insert_storage((ref $self)->new);
120 $self->_insert_storage->connect_info($self->connect_info);
122 $self->_insert_storage->set_textsize if $self->using_freetds;
125 for my $method (@delegate_to_insert_storage) {
128 *{$method} = Sub::Name::subname $method => sub {
130 $self->_insert_storage->$method(@_) if $self->_insert_storage;
131 return $self->next::method(@_);
135 # Make sure we have CHAINED mode turned on if AutoCommit is off in non-FreeTDS
136 # DBD::Sybase (since we don't know how DBD::Sybase was compiled.) If however
137 # we're using FreeTDS, CHAINED mode turns on an implicit transaction which we
138 # only want when AutoCommit is off.
142 $self->next::method(@_);
144 if (not $self->using_freetds) {
145 $self->_dbh->{syb_chained_txn} = 1;
147 if ($self->_dbh_autocommit) {
148 $self->_dbh->do('SET CHAINED OFF');
150 $self->_dbh->do('SET CHAINED ON');
155 =head2 connect_call_blob_setup
159 on_connect_call => [ [ 'blob_setup', log_on_update => 0 ] ]
161 Does C<< $dbh->{syb_binary_images} = 1; >> to return C<IMAGE> data as raw binary
162 instead of as a hex string.
166 Also sets the C<log_on_update> value for blob write operations. The default is
167 C<1>, but C<0> is better if your database is configured for it.
170 L<DBD::Sybase/Handling_IMAGE/TEXT_data_with_syb_ct_get_data()/syb_ct_send_data()>.
174 sub connect_call_blob_setup {
177 my $dbh = $self->_dbh;
178 $dbh->{syb_binary_images} = 1;
180 $self->_blob_log_on_update($args{log_on_update})
181 if exists $args{log_on_update};
187 $type && $type =~ /(?:text|image|lob|bytea|binary|memo)/i;
190 sub _prep_for_execute {
192 my ($op, $extra_bind, $ident, $args) = @_;
194 my ($sql, $bind) = $self->next::method (@_);
196 if ($op eq 'insert') {
197 my $table = $ident->from;
199 my $bind_info = $self->_resolve_column_info(
200 $ident, [map $_->[0], @{$bind}]
202 my $identity_col = List::Util::first
203 { $bind_info->{$_}{is_auto_increment} }
209 "SET IDENTITY_INSERT $table ON",
211 "SET IDENTITY_INSERT $table OFF",
215 $identity_col = List::Util::first
216 { $ident->column_info($_)->{is_auto_increment} }
224 $self->_fetch_identity_sql($ident, $identity_col);
228 return ($sql, $bind);
231 # Stolen from SQLT, with some modifications. This is a makeshift
232 # solution before a sane type-mapping library is available, thus
233 # the 'our' for easy overrides.
234 our %TYPE_MAPPING = (
237 varchar => 'varchar',
238 varchar2 => 'varchar',
239 timestamp => 'datetime',
241 real => 'double precision',
244 tinyint => 'smallint',
245 float => 'double precision',
247 bigserial => 'numeric',
248 boolean => 'varchar',
252 sub _native_data_type {
253 my ($self, $type) = @_;
256 $type =~ s/\s* identity//x;
258 return uc($TYPE_MAPPING{$type} || $type);
261 sub _fetch_identity_sql {
262 my ($self, $source, $col) = @_;
264 return sprintf ("SELECT MAX(%s) FROM %s",
265 map { $self->sql_maker->_quote ($_) } ($col, $source->from)
273 my ($rv, $sth, @bind) = $self->dbh_do($self->can('_dbh_execute'), @_);
275 if ($op eq 'insert') {
276 $self->_identity($sth->fetchrow_array);
280 return wantarray ? ($rv, $sth, @bind) : $rv;
283 sub last_insert_id { shift->_identity }
285 # handles TEXT/IMAGE and transaction for last_insert_id
288 my ($source, $to_insert) = @_;
290 my $blob_cols = $self->_remove_blob_cols($source, $to_insert);
292 my $identity_col = List::Util::first
293 { $source->column_info($_)->{is_auto_increment} }
296 # do we need the horrific SELECT MAX(COL) hack?
297 my $dumb_last_insert_id =
299 && (not exists $to_insert->{$identity_col})
300 && ($self->_identity_method||'') ne '@@IDENTITY';
302 my $next = $self->next::can;
304 # we are already in a transaction, or there are no blobs
305 # and we don't need the PK - just (try to) do it
306 if ($self->{transaction_depth}
307 || (!$blob_cols && !$dumb_last_insert_id)
309 return $self->_insert (
310 $next, $source, $to_insert, $blob_cols, $identity_col
314 # otherwise use the _insert_storage to do the insert+transaction on another
316 my $guard = $self->_insert_storage->txn_scope_guard;
318 my $updated_cols = $self->_insert_storage->_insert (
319 $next, $source, $to_insert, $blob_cols, $identity_col
322 $self->_identity($self->_insert_storage->_identity);
326 return $updated_cols;
330 my ($self, $next, $source, $to_insert, $blob_cols, $identity_col) = @_;
332 my $updated_cols = $self->$next ($source, $to_insert);
335 $identity_col => $self->last_insert_id($source, $identity_col),
340 $self->_insert_blobs ($source, $blob_cols, $final_row) if $blob_cols;
342 return $updated_cols;
347 my ($source, $fields, $where) = @_;
349 my $wantarray = wantarray;
350 my $blob_cols = $self->_remove_blob_cols($source, $fields);
352 if (not $blob_cols) {
353 return $self->next::method(@_);
356 # update+blob update(s) done atomically on separate connection
357 $self = $self->_insert_storage;
359 my $guard = $self->txn_scope_guard;
363 @res = $self->next::method(@_);
365 elsif (defined $wantarray) {
366 $res[0] = $self->next::method(@_);
369 $self->next::method(@_);
372 $self->_update_blobs($source, $blob_cols, $where);
376 return $wantarray ? @res : $res[0];
379 sub _remove_blob_cols {
380 my ($self, $source, $fields) = @_;
384 for my $col (keys %$fields) {
385 if ($self->_is_lob_type($source->column_info($col)->{data_type})) {
386 $blob_cols{$col} = delete $fields->{$col};
387 $fields->{$col} = \"''";
391 return keys %blob_cols ? \%blob_cols : undef;
395 my ($self, $source, $blob_cols, $where) = @_;
397 my (@primary_cols) = $source->primary_columns;
399 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
400 unless @primary_cols;
402 # check if we're updating a single row by PK
403 my $pk_cols_in_where = 0;
404 for my $col (@primary_cols) {
405 $pk_cols_in_where++ if defined $where->{$col};
409 if ($pk_cols_in_where == @primary_cols) {
411 @row_to_update{@primary_cols} = @{$where}{@primary_cols};
412 @rows = \%row_to_update;
414 my $cursor = $self->select ($source, \@primary_cols, $where, {});
416 my %row; @row{@primary_cols} = @$_; \%row
420 for my $row (@rows) {
421 $self->_insert_blobs($source, $blob_cols, $row);
426 my ($self, $source, $blob_cols, $row) = @_;
427 my $dbh = $self->_get_dbh;
429 my $table = $source->from;
432 my (@primary_cols) = $source->primary_columns;
434 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
435 unless @primary_cols;
437 if ((grep { defined $row{$_} } @primary_cols) != @primary_cols) {
438 croak "Cannot update TEXT/IMAGE column(s) without primary key values";
441 for my $col (keys %$blob_cols) {
442 my $blob = $blob_cols->{$col};
444 my %where = map { ($_, $row{$_}) } @primary_cols;
446 my $cursor = $self->select ($source, [$col], \%where, {});
448 my $sth = $cursor->sth;
452 $sth->func('CS_GET', 1, 'ct_data_info') or die $sth->errstr;
455 $sth->func('ct_prepare_send') or die $sth->errstr;
457 my $log_on_update = $self->_blob_log_on_update;
458 $log_on_update = 1 if not defined $log_on_update;
460 $sth->func('CS_SET', 1, {
461 total_txtlen => length($blob),
462 log_on_update => $log_on_update
463 }, 'ct_data_info') or die $sth->errstr;
465 $sth->func($blob, length($blob), 'ct_send_data') or die $sth->errstr;
467 $sth->func('ct_finish_send') or die $sth->errstr;
470 $sth->finish if $sth;
472 if ($self->using_freetds) {
474 'TEXT/IMAGE operation failed, probably because you are using FreeTDS: '
484 =head2 connect_call_datetime_setup
488 on_connect_call => 'datetime_setup'
490 In L<DBIx::Class::Storage::DBI/connect_info> to set:
492 $dbh->syb_date_fmt('ISO_strict'); # output fmt: 2004-08-21T14:36:48.080Z
493 $dbh->do('set dateformat mdy'); # input fmt: 08/13/1979 18:08:55.080
495 On connection for use with L<DBIx::Class::InflateColumn::DateTime>, using
496 L<DateTime::Format::Sybase>, which you will need to install.
498 This works for both C<DATETIME> and C<SMALLDATETIME> columns, although
499 C<SMALLDATETIME> columns only have minute precision.
504 my $old_dbd_warned = 0;
506 sub connect_call_datetime_setup {
508 my $dbh = $self->_dbh;
510 if ($dbh->can('syb_date_fmt')) {
511 # amazingly, this works with FreeTDS
512 $dbh->syb_date_fmt('ISO_strict');
513 } elsif (not $old_dbd_warned) {
514 carp "Your DBD::Sybase is too old to support ".
515 "DBIx::Class::InflateColumn::DateTime, please upgrade!";
519 $dbh->do('SET DATEFORMAT mdy');
525 sub datetime_parser_type { "DateTime::Format::Sybase" }
527 # ->begin_work and such have no effect with FreeTDS but we run them anyway to
528 # let the DBD keep any state it needs to.
530 # If they ever do start working, the extra statements will do no harm (because
531 # Sybase supports nested transactions.)
533 sub _dbh_begin_work {
535 $self->next::method(@_);
536 if ($self->using_freetds) {
537 $self->_get_dbh->do('BEGIN TRAN');
543 if ($self->using_freetds) {
544 $self->_dbh->do('COMMIT');
546 return $self->next::method(@_);
551 if ($self->using_freetds) {
552 $self->_dbh->do('ROLLBACK');
554 return $self->next::method(@_);
557 # savepoint support using ASE syntax
560 my ($self, $name) = @_;
562 $self->_get_dbh->do("SAVE TRANSACTION $name");
565 # A new SAVE TRANSACTION with the same name releases the previous one.
566 sub _svp_release { 1 }
569 my ($self, $name) = @_;
571 $self->_get_dbh->do("ROLLBACK TRANSACTION $name");
576 =head1 Schema::Loader Support
578 There is an experimental branch of L<DBIx::Class::Schema::Loader> that will
579 allow you to dump a schema from most (if not all) versions of Sybase.
581 It is available via subversion from:
583 http://dev.catalyst.perl.org/repos/bast/branches/DBIx-Class-Schema-Loader/current/
587 This driver supports L<DBD::Sybase> compiled against FreeTDS
588 (L<http://www.freetds.org/>) to the best of our ability, however it is
589 recommended that you recompile L<DBD::Sybase> against the Sybase Open Client
590 libraries. They are a part of the Sybase ASE distribution:
592 The Open Client FAQ is here:
593 L<http://www.isug.com/Sybase_FAQ/ASE/section7.html>.
595 Sybase ASE for Linux (which comes with the Open Client libraries) may be
596 downloaded here: L<http://response.sybase.com/forms/ASE_Linux_Download>.
598 To see if you're using FreeTDS check C<< $schema->storage->using_freetds >>, or run:
600 perl -MDBI -le 'my $dbh = DBI->connect($dsn, $user, $pass); print $dbh->{syb_oc_version}'
602 Some versions of the libraries involved will not support placeholders, in which
603 case the storage will be reblessed to
604 L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>.
606 In some configurations, placeholders will work but will throw implicit type
607 conversion errors for anything that's not expecting a string. In such a case,
608 the C<auto_cast> option from L<DBIx::Class::Storage::DBI::AutoCast> is
609 automatically set, which you may enable on connection with
610 L<DBIx::Class::Storage::DBI::AutoCast/connect_call_set_auto_cast>. The type info
611 for the C<CAST>s is taken from the L<DBIx::Class::ResultSource/data_type>
612 definitions in your Result classes, and are mapped to a Sybase type (if it isn't
613 already) using a mapping based on L<SQL::Translator>.
615 In other configurations, placeholers will work just as they do with the Sybase
616 Open Client libraries.
618 Inserts or updates of TEXT/IMAGE columns will B<NOT> work with FreeTDS.
620 =head1 INSERTS WITH PLACEHOLDERS
622 With placeholders enabled, inserts are done in a transaction so that there are
623 no concurrency issues with getting the inserted identity value using
624 C<SELECT MAX(col)>, which is the only way to get the C<IDENTITY> value in this
627 In addition, they are done on a separate connection so that it's possible to
628 have active cursors when doing an insert.
630 When using C<DBIx::Class::Storage::DBI::Sybase::NoBindVars> transactions are
631 disabled, as there are no concurrency issues with C<SELECT @@IDENTITY> as it's a
636 Due to limitations of the TDS protocol, L<DBD::Sybase>, or both; you cannot
637 begin a transaction while there are active cursors. An active cursor is, for
638 example, a L<ResultSet|DBIx::Class::ResultSet> that has been executed using
639 C<next> or C<first> but has not been exhausted or
640 L<reset|DBIx::Class::ResultSet/reset>.
642 For example, this will not work:
644 $schema->txn_do(sub {
645 my $rs = $schema->resultset('Book');
646 while (my $row = $rs->next) {
647 $schema->resultset('MetaData')->create({
654 Transactions done for inserts in C<AutoCommit> mode when placeholders are in use
655 are not affected, as they are done on an extra database handle.
661 =item * use L<DBIx::Class::Storage::DBI::Replicated>
663 =item * L<connect|DBIx::Class::Schema/connect> another L<Schema|DBIx::Class::Schema>
665 =item * load the data from your cursor with L<DBIx::Class::ResultSet/all>
669 =head1 MAXIMUM CONNECTIONS
671 The TDS protocol makes separate connections to the server for active statements
672 in the background. By default the number of such connections is limited to 25,
673 on both the client side and the server side.
675 This is a bit too low for a complex L<DBIx::Class> application, so on connection
676 the client side setting is set to C<256> (see L<DBD::Sybase/maxConnect>.) You
677 can override it to whatever setting you like in the DSN.
680 L<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1272.htm>
681 for information on changing the setting on the server side.
685 See L</connect_call_datetime_setup> to setup date formats
686 for L<DBIx::Class::InflateColumn::DateTime>.
688 =head1 TEXT/IMAGE COLUMNS
690 L<DBD::Sybase> compiled with FreeTDS will B<NOT> allow you to insert or update
691 C<TEXT/IMAGE> columns.
693 Setting C<< $dbh->{LongReadLen} >> will also not work with FreeTDS use either:
695 $schema->storage->dbh->do("SET TEXTSIZE $bytes");
699 $schema->storage->set_textsize($bytes);
703 However, the C<LongReadLen> you pass in
704 L<DBIx::Class::Storage::DBI/connect_info> is used to execute the equivalent
705 C<SET TEXTSIZE> command on connection.
707 See L</connect_call_blob_setup> for a L<DBIx::Class::Storage::DBI/connect_info>
708 setting you need to work with C<IMAGE> columns.
712 See L<DBIx::Class/CONTRIBUTORS>.
716 You may distribute this code under the same terms as Perl itself.