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/;
14 __PACKAGE__->mk_group_accessors('simple' =>
15 qw/_identity _blob_log_on_update _insert_dbh _identity_method/
20 DBIx::Class::Storage::DBI::Sybase - Sybase support for DBIx::Class
24 This subclass supports L<DBD::Sybase> for real Sybase databases. If you are
25 using an MSSQL database via L<DBD::Sybase>, your storage will be reblessed to
26 L<DBIx::Class::Storage::DBI::Sybase::Microsoft_SQL_Server>.
30 If your version of Sybase does not support placeholders, then your storage
31 will be reblessed to L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>. You can
32 also enable that driver explicitly, see the documentation for more details.
34 With this driver there is unfortunately no way to get the C<last_insert_id>
35 without doing a C<SELECT MAX(col)>. This is done safely in a transaction
36 (locking the table.) See L</INSERTS WITH PLACEHOLDERS>.
38 A recommended L<DBIx::Class::Storage::DBI/connect_info> setting:
40 on_connect_call => [['datetime_setup'], ['blob_setup', log_on_update => 0]]
49 if (ref($self) eq 'DBIx::Class::Storage::DBI::Sybase') {
51 @{$self->_get_dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2]
56 my $subclass = "DBIx::Class::Storage::DBI::Sybase::${dbtype}";
58 if (!$exception && $dbtype && $self->load_optional_class($subclass)) {
59 bless $self, $subclass;
61 } else { # real Sybase
62 my $no_bind_vars = 'DBIx::Class::Storage::DBI::Sybase::NoBindVars';
64 if ($self->using_freetds) {
65 carp <<'EOF' unless $ENV{DBIC_SYBASE_FREETDS_NOWARN};
67 You are using FreeTDS with Sybase.
69 We will do our best to support this configuration, but please consider this
72 TEXT/IMAGE columns will definitely not work.
74 You are encouraged to recompile DBD::Sybase with the Sybase Open Client libraries
77 See perldoc DBIx::Class::Storage::DBI::Sybase for more details.
79 To turn off this warning set the DBIC_SYBASE_FREETDS_NOWARN environment
82 if (not $self->_typeless_placeholders_supported) {
83 if ($self->_placeholders_supported) {
86 $self->ensure_class_loaded($no_bind_vars);
87 bless $self, $no_bind_vars;
92 elsif (not $self->_get_dbh->{syb_dynamic_supported}) {
93 # not necessarily FreeTDS, but no placeholders nevertheless
94 $self->ensure_class_loaded($no_bind_vars);
95 bless $self, $no_bind_vars;
97 } elsif (not $self->_typeless_placeholders_supported) {
98 # this is highly unlikely, but we check just in case
107 $self->_set_max_connect(256);
109 # based on LongReadLen in connect_info
110 $self->set_textsize if $self->using_freetds;
113 # Make sure we have CHAINED mode turned on if AutoCommit is off in non-FreeTDS
114 # DBD::Sybase (since we don't know how DBD::Sybase was compiled.) If however
115 # we're using FreeTDS, CHAINED mode turns on an implicit transaction which we
116 # only want when AutoCommit is off.
120 $self->next::method(@_);
122 if (not $self->using_freetds) {
123 $self->_dbh->{syb_chained_txn} = 1;
125 if ($self->_dbh_autocommit) {
126 $self->_dbh->do('SET CHAINED OFF');
128 $self->_dbh->do('SET CHAINED ON');
133 =head2 connect_call_blob_setup
137 on_connect_call => [ [ 'blob_setup', log_on_update => 0 ] ]
139 Does C<< $dbh->{syb_binary_images} = 1; >> to return C<IMAGE> data as raw binary
140 instead of as a hex string.
144 Also sets the C<log_on_update> value for blob write operations. The default is
145 C<1>, but C<0> is better if your database is configured for it.
148 L<DBD::Sybase/Handling_IMAGE/TEXT_data_with_syb_ct_get_data()/syb_ct_send_data()>.
152 sub connect_call_blob_setup {
155 my $dbh = $self->_dbh;
156 $dbh->{syb_binary_images} = 1;
158 $self->_blob_log_on_update($args{log_on_update})
159 if exists $args{log_on_update};
165 $type && $type =~ /(?:text|image|lob|bytea|binary|memo)/i;
168 sub _prep_for_execute {
170 my ($op, $extra_bind, $ident, $args) = @_;
172 my ($sql, $bind) = $self->next::method (@_);
174 if ($op eq 'insert') {
175 my $table = $ident->from;
177 my $bind_info = $self->_resolve_column_info(
178 $ident, [map $_->[0], @{$bind}]
180 my $identity_col = List::Util::first
181 { $bind_info->{$_}{is_auto_increment} }
187 "SET IDENTITY_INSERT $table ON",
189 "SET IDENTITY_INSERT $table OFF",
193 $identity_col = List::Util::first
194 { $ident->column_info($_)->{is_auto_increment} }
202 $self->_fetch_identity_sql($ident, $identity_col);
206 return ($sql, $bind);
209 # Stolen from SQLT, with some modifications. This is a makeshift
210 # solution before a sane type-mapping library is available, thus
211 # the 'our' for easy overrides.
212 our %TYPE_MAPPING = (
215 varchar => 'varchar',
216 varchar2 => 'varchar',
217 timestamp => 'datetime',
219 real => 'double precision',
222 tinyint => 'smallint',
223 float => 'double precision',
225 bigserial => 'numeric',
226 boolean => 'varchar',
230 sub _native_data_type {
231 my ($self, $type) = @_;
234 $type =~ s/\s* identity//x;
236 return uc($TYPE_MAPPING{$type} || $type);
239 sub _fetch_identity_sql {
240 my ($self, $source, $col) = @_;
242 return sprintf ("SELECT MAX(%s) FROM %s",
243 map { $self->sql_maker->_quote ($_) } ($col, $source->from)
251 my ($rv, $sth, @bind) = $self->dbh_do($self->can('_dbh_execute'), @_);
253 if ($op eq 'insert') {
254 $self->_identity($sth->fetchrow_array);
258 return wantarray ? ($rv, $sth, @bind) : $rv;
261 sub last_insert_id { shift->_identity }
263 # handles TEXT/IMAGE and transaction for last_insert_id
266 my ($source, $to_insert) = @_;
268 my $blob_cols = $self->_remove_blob_cols($source, $to_insert);
270 my $identity_col = List::Util::first
271 { $source->column_info($_)->{is_auto_increment} }
274 # do we need the horrific SELECT MAX(COL) hack?
275 my $dumb_last_insert_id =
277 && (not exists $to_insert->{$identity_col})
278 && ($self->_identity_method||'') ne '@@IDENTITY'
281 # we are already in a transaction, or there are no blobs
282 # and we don't need the PK - just (try to) do it
283 if ($self->{transaction_depth}
284 || (!$blob_cols && !$dumb_last_insert_id)
286 return $self->_insert ($source, $to_insert, $blob_cols, $identity_col);
289 # this is tricky: a transaction needs to take place if we need
290 # either a last_insert_id or we will be doing blob insert.
291 # This will happen on a *seperate* connection, thus the local()
296 # localize so it appears right if we blow out with an exception
297 local $self->{transaction_depth} = 0;
299 $self->_insert_dbh($self->_connect(@{ $self->_dbi_connect_info }))
300 unless $self->_insert_dbh;
302 $self->{_dbh} = $self->_insert_dbh;
303 my $guard = $self->txn_scope_guard;
305 # _dbh_begin_work in the guard may reconnect,
306 # so we update the accessor just in case
307 $self->_insert_dbh($self->_dbh);
309 my $updated_cols = $self->_insert ($source, $to_insert, $blob_cols, $identity_col);
313 return $updated_cols;
318 my ($self, $source, $to_insert, $blob_cols, $identity_col) = @_;
320 my $updated_cols = $self->next::method ($source, $to_insert);
323 $identity_col => $self->last_insert_id($source, $identity_col),
328 $self->_insert_blobs ($source, $blob_cols, $final_row) if $blob_cols;
330 return $updated_cols;
335 my ($source, $fields, $where) = @_;
337 my $wantarray = wantarray;
339 my $blob_cols = $self->_remove_blob_cols($source, $fields);
341 # update+blob update(s) done atomically
342 my $guard = $self->txn_scope_guard if $blob_cols;
346 @res = $self->next::method(@_);
348 elsif (defined $wantarray) {
349 $res[0] = $self->next::method(@_);
352 $self->next::method(@_);
355 $self->_update_blobs($source, $blob_cols, $where) if $blob_cols;
357 $guard->commit if $guard;
359 return $wantarray ? @res : $res[0];
362 sub _remove_blob_cols {
363 my ($self, $source, $fields) = @_;
367 for my $col (keys %$fields) {
368 if ($self->_is_lob_type($source->column_info($col)->{data_type})) {
369 $blob_cols{$col} = delete $fields->{$col};
370 $fields->{$col} = \"''";
374 return keys %blob_cols ? \%blob_cols : undef;
378 my ($self, $source, $blob_cols, $where) = @_;
380 my (@primary_cols) = $source->primary_columns;
382 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
383 unless @primary_cols;
385 # check if we're updating a single row by PK
386 my $pk_cols_in_where = 0;
387 for my $col (@primary_cols) {
388 $pk_cols_in_where++ if defined $where->{$col};
392 if ($pk_cols_in_where == @primary_cols) {
394 @row_to_update{@primary_cols} = @{$where}{@primary_cols};
395 @rows = \%row_to_update;
397 my $rs = $source->resultset->search(
400 result_class => 'DBIx::Class::ResultClass::HashRefInflator',
401 select => \@primary_cols
404 @rows = $rs->all; # statement must finish
407 for my $row (@rows) {
408 $self->_insert_blobs($source, $blob_cols, $row);
413 my ($self, $source, $blob_cols, $row) = @_;
414 my $dbh = $self->_get_dbh;
416 my $table = $source->from;
419 my (@primary_cols) = $source->primary_columns;
421 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
422 unless @primary_cols;
424 if ((grep { defined $row{$_} } @primary_cols) != @primary_cols) {
425 croak "Cannot update TEXT/IMAGE column(s) without primary key values";
428 for my $col (keys %$blob_cols) {
429 my $blob = $blob_cols->{$col};
431 my %where = map { ($_, $row{$_}) } @primary_cols;
432 my $cursor = $source->resultset->search(\%where, {
436 my $sth = $cursor->sth;
440 $sth->func('CS_GET', 1, 'ct_data_info') or die $sth->errstr;
443 $sth->func('ct_prepare_send') or die $sth->errstr;
445 my $log_on_update = $self->_blob_log_on_update;
446 $log_on_update = 1 if not defined $log_on_update;
448 $sth->func('CS_SET', 1, {
449 total_txtlen => length($blob),
450 log_on_update => $log_on_update
451 }, 'ct_data_info') or die $sth->errstr;
453 $sth->func($blob, length($blob), 'ct_send_data') or die $sth->errstr;
455 $sth->func('ct_finish_send') or die $sth->errstr;
458 $sth->finish if $sth;
460 if ($self->using_freetds) {
462 'TEXT/IMAGE operation failed, probably because you are using FreeTDS: '
472 =head2 connect_call_datetime_setup
476 on_connect_call => 'datetime_setup'
478 In L<DBIx::Class::Storage::DBI/connect_info> to set:
480 $dbh->syb_date_fmt('ISO_strict'); # output fmt: 2004-08-21T14:36:48.080Z
481 $dbh->do('set dateformat mdy'); # input fmt: 08/13/1979 18:08:55.080
483 On connection for use with L<DBIx::Class::InflateColumn::DateTime>, using
484 L<DateTime::Format::Sybase>, which you will need to install.
486 This works for both C<DATETIME> and C<SMALLDATETIME> columns, although
487 C<SMALLDATETIME> columns only have minute precision.
492 my $old_dbd_warned = 0;
494 sub connect_call_datetime_setup {
496 my $dbh = $self->_dbh;
498 if ($dbh->can('syb_date_fmt')) {
499 # amazingly, this works with FreeTDS
500 $dbh->syb_date_fmt('ISO_strict');
501 } elsif (not $old_dbd_warned) {
502 carp "Your DBD::Sybase is too old to support ".
503 "DBIx::Class::InflateColumn::DateTime, please upgrade!";
507 $dbh->do('SET DATEFORMAT mdy');
513 sub datetime_parser_type { "DateTime::Format::Sybase" }
515 # ->begin_work and such have no effect with FreeTDS but we run them anyway to
516 # let the DBD keep any state it needs to.
518 # If they ever do start working, the extra statements will do no harm (because
519 # Sybase supports nested transactions.)
521 sub _dbh_begin_work {
523 $self->next::method(@_);
524 if ($self->using_freetds) {
525 $self->_get_dbh->do('BEGIN TRAN');
531 if ($self->using_freetds) {
532 $self->_dbh->do('COMMIT');
534 return $self->next::method(@_);
539 if ($self->using_freetds) {
540 $self->_dbh->do('ROLLBACK');
542 return $self->next::method(@_);
545 # savepoint support using ASE syntax
548 my ($self, $name) = @_;
550 $self->_get_dbh->do("SAVE TRANSACTION $name");
553 # A new SAVE TRANSACTION with the same name releases the previous one.
554 sub _svp_release { 1 }
557 my ($self, $name) = @_;
559 $self->_get_dbh->do("ROLLBACK TRANSACTION $name");
564 =head1 Schema::Loader Support
566 There is an experimental branch of L<DBIx::Class::Schema::Loader> that will
567 allow you to dump a schema from most (if not all) versions of Sybase.
569 It is available via subversion from:
571 http://dev.catalyst.perl.org/repos/bast/branches/DBIx-Class-Schema-Loader/current/
575 This driver supports L<DBD::Sybase> compiled against FreeTDS
576 (L<http://www.freetds.org/>) to the best of our ability, however it is
577 recommended that you recompile L<DBD::Sybase> against the Sybase Open Client
578 libraries. They are a part of the Sybase ASE distribution:
580 The Open Client FAQ is here:
581 L<http://www.isug.com/Sybase_FAQ/ASE/section7.html>.
583 Sybase ASE for Linux (which comes with the Open Client libraries) may be
584 downloaded here: L<http://response.sybase.com/forms/ASE_Linux_Download>.
586 To see if you're using FreeTDS check C<< $schema->storage->using_freetds >>, or run:
588 perl -MDBI -le 'my $dbh = DBI->connect($dsn, $user, $pass); print $dbh->{syb_oc_version}'
590 Some versions of the libraries involved will not support placeholders, in which
591 case the storage will be reblessed to
592 L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>.
594 In some configurations, placeholders will work but will throw implicit type
595 conversion errors for anything that's not expecting a string. In such a case,
596 the C<auto_cast> option from L<DBIx::Class::Storage::DBI::AutoCast> is
597 automatically set, which you may enable on connection with
598 L<DBIx::Class::Storage::DBI::AutoCast/connect_call_set_auto_cast>. The type info
599 for the C<CAST>s is taken from the L<DBIx::Class::ResultSource/data_type>
600 definitions in your Result classes, and are mapped to a Sybase type (if it isn't
601 already) using a mapping based on L<SQL::Translator>.
603 In other configurations, placeholers will work just as they do with the Sybase
604 Open Client libraries.
606 Inserts or updates of TEXT/IMAGE columns will B<NOT> work with FreeTDS.
608 =head1 INSERTS WITH PLACEHOLDERS
610 With placeholders enabled, inserts are done in a transaction so that there are
611 no concurrency issues with getting the inserted identity value using
612 C<SELECT MAX(col)>, which is the only way to get the C<IDENTITY> value in this
615 When using C<DBIx::Class::Storage::DBI::Sybase::NoBindVars> transactions are
616 disabled, as there are no concurrency issues with C<SELECT @@IDENTITY> as it's a
621 Due to limitations of the TDS protocol, L<DBD::Sybase>, or both; you cannot
622 begin a transaction while there are active cursors. An active cursor is, for
623 example, a L<ResultSet|DBIx::Class::ResultSet> that has been executed using
624 C<next> or C<first> but has not been exhausted or
625 L<reset|DBIx::Class::ResultSet/reset>.
627 For example, this will not work:
629 $schema->txn_do(sub {
630 my $rs = $schema->resultset('Book');
631 while (my $row = $rs->next) {
632 $schema->resultset('MetaData')->create({
639 Transactions done for inserts in C<AutoCommit> mode when placeholders are in use
640 are not affected, as they use an extra database handle to do the insert.
646 =item * use L<DBIx::Class::Storage::DBI::Replicated>
648 =item * L<connect|DBIx::Class::Schema/connect> another L<Schema|DBIx::Class::Schema>
650 =item * load the data from your cursor with L<DBIx::Class::ResultSet/all>
654 =head1 MAXIMUM CONNECTIONS
656 The TDS protocol makes separate connections to the server for active statements
657 in the background. By default the number of such connections is limited to 25,
658 on both the client side and the server side.
660 This is a bit too low for a complex L<DBIx::Class> application, so on connection
661 the client side setting is set to C<256> (see L<DBD::Sybase/maxConnect>.) You
662 can override it to whatever setting you like in the DSN.
665 L<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1272.htm>
666 for information on changing the setting on the server side.
670 See L</connect_call_datetime_setup> to setup date formats
671 for L<DBIx::Class::InflateColumn::DateTime>.
673 =head1 TEXT/IMAGE COLUMNS
675 L<DBD::Sybase> compiled with FreeTDS will B<NOT> allow you to insert or update
676 C<TEXT/IMAGE> columns.
678 Setting C<< $dbh->{LongReadLen} >> will also not work with FreeTDS use either:
680 $schema->storage->dbh->do("SET TEXTSIZE $bytes");
684 $schema->storage->set_textsize($bytes);
688 However, the C<LongReadLen> you pass in
689 L<DBIx::Class::Storage::DBI/connect_info> is used to execute the equivalent
690 C<SET TEXTSIZE> command on connection.
692 See L</connect_call_blob_setup> for a L<DBIx::Class::Storage::DBI/connect_info>
693 setting you need to work with C<IMAGE> columns.
697 See L<DBIx::Class/CONTRIBUTORS>.
701 You may distribute this code under the same terms as Perl itself.