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_txn/
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.) The transaction can be turned off if concurrency is not an
37 issue, or you don't need the C<IDENTITY> value, see
38 L<DBIx::Class::Storage::DBI::Sybase/connect_call_unsafe_insert>.
40 But your queries will be cached.
42 A recommended L<DBIx::Class::Storage::DBI/connect_info> setting:
44 on_connect_call => [['datetime_setup'], ['blob_setup', log_on_update => 0]]
53 if (ref($self) eq 'DBIx::Class::Storage::DBI::Sybase') {
55 @{$self->_get_dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2]
60 my $subclass = "DBIx::Class::Storage::DBI::Sybase::${dbtype}";
62 if (!$exception && $dbtype && $self->load_optional_class($subclass)) {
63 bless $self, $subclass;
65 } else { # real Sybase
66 my $no_bind_vars = 'DBIx::Class::Storage::DBI::Sybase::NoBindVars';
68 # This is reset to 0 in ::NoBindVars, only necessary because we use max(col) to
72 if ($self->using_freetds) {
73 carp <<'EOF' unless $ENV{DBIC_SYBASE_FREETDS_NOWARN};
75 You are using FreeTDS with Sybase.
77 We will do our best to support this configuration, but please consider this
80 TEXT/IMAGE columns will definitely not work.
82 You are encouraged to recompile DBD::Sybase with the Sybase Open Client libraries
85 See perldoc DBIx::Class::Storage::DBI::Sybase for more details.
87 To turn off this warning set the DBIC_SYBASE_FREETDS_NOWARN environment
90 if (not $self->_typeless_placeholders_supported) {
91 if ($self->_placeholders_supported) {
94 $self->ensure_class_loaded($no_bind_vars);
95 bless $self, $no_bind_vars;
100 $self->set_textsize; # based on LongReadLen in connect_info
103 elsif (not $self->_get_dbh->{syb_dynamic_supported}) {
104 # not necessarily FreeTDS, but no placeholders nevertheless
105 $self->ensure_class_loaded($no_bind_vars);
106 bless $self, $no_bind_vars;
108 } elsif (not $self->_typeless_placeholders_supported) {
109 # this is highly unlikely, but we check just in case
113 $self->_set_max_connect(256);
118 # Make sure we have CHAINED mode turned on if AutoCommit is off in non-FreeTDS
119 # DBD::Sybase (since we don't know how DBD::Sybase was compiled.) If however
120 # we're using FreeTDS, CHAINED mode turns on an implicit transaction which we
121 # only want when AutoCommit is off.
125 $self->next::method(@_);
127 if (not $self->using_freetds) {
128 $self->_dbh->{syb_chained_txn} = 1;
130 if ($self->_dbh_autocommit) {
131 $self->_dbh->do('SET CHAINED OFF');
133 $self->_dbh->do('SET CHAINED ON');
138 =head2 connect_call_blob_setup
142 on_connect_call => [ [ 'blob_setup', log_on_update => 0 ] ]
144 Does C<< $dbh->{syb_binary_images} = 1; >> to return C<IMAGE> data as raw binary
145 instead of as a hex string.
149 Also sets the C<log_on_update> value for blob write operations. The default is
150 C<1>, but C<0> is better if your database is configured for it.
153 L<DBD::Sybase/Handling_IMAGE/TEXT_data_with_syb_ct_get_data()/syb_ct_send_data()>.
157 sub connect_call_blob_setup {
160 my $dbh = $self->_dbh;
161 $dbh->{syb_binary_images} = 1;
163 $self->_blob_log_on_update($args{log_on_update})
164 if exists $args{log_on_update};
167 =head2 connect_call_unsafe_insert
169 With placeholders enabled, inserts are done in a transaction so that there are
170 no concurrency issues with getting the inserted identity value using
171 C<SELECT MAX(col)> when placeholders are enabled.
173 When using C<DBIx::Class::Storage::DBI::Sybase::NoBindVars> transactions are
176 To turn off transactions for inserts (for an application that doesn't need
177 concurrency, or a loader, for example) use this setting in
178 L<DBIx::Class::Storage::DBI/connect_info>,
180 on_connect_call => ['unsafe_insert']
182 To manipulate this setting at runtime, use:
184 $schema->storage->insert_txn(0); # 1 to re-enable
188 sub connect_call_unsafe_insert {
190 $self->insert_txn(0);
196 $type && $type =~ /(?:text|image|lob|bytea|binary|memo)/i;
199 sub _prep_for_execute {
201 my ($op, $extra_bind, $ident, $args) = @_;
203 my ($sql, $bind) = $self->next::method (@_);
205 if ($op eq 'insert') {
206 my $table = $ident->from;
208 my $bind_info = $self->_resolve_column_info(
209 $ident, [map $_->[0], @{$bind}]
211 my $identity_col = List::Util::first
212 { $bind_info->{$_}{is_auto_increment} }
218 "SET IDENTITY_INSERT $table ON",
220 "SET IDENTITY_INSERT $table OFF",
224 $identity_col = List::Util::first
225 { $ident->column_info($_)->{is_auto_increment} }
233 $self->_fetch_identity_sql($ident, $identity_col);
237 return ($sql, $bind);
240 # Stolen from SQLT, with some modifications. This is a makeshift
241 # solution before a sane type-mapping library is available, thus
242 # the 'our' for easy overrides.
243 our %TYPE_MAPPING = (
246 varchar => 'varchar',
247 varchar2 => 'varchar',
248 timestamp => 'datetime',
250 real => 'double precision',
253 tinyint => 'smallint',
254 float => 'double precision',
256 bigserial => 'numeric',
257 boolean => 'varchar',
261 sub _native_data_type {
262 my ($self, $type) = @_;
265 $type =~ s/ identity//;
267 return uc($TYPE_MAPPING{$type} || $type);
270 sub _fetch_identity_sql {
271 my ($self, $source, $col) = @_;
273 return "SELECT MAX($col) FROM ".$source->from;
280 my ($rv, $sth, @bind) = $self->dbh_do($self->can('_dbh_execute'), @_);
282 if ($op eq 'insert') {
283 $self->_identity($sth->fetchrow_array);
287 return wantarray ? ($rv, $sth, @bind) : $rv;
290 sub last_insert_id { shift->_identity }
292 # override to handle TEXT/IMAGE and to do a transaction if necessary
295 my ($source, $to_insert) = @_;
297 my $blob_cols = $self->_remove_blob_cols($source, $to_insert);
299 my $need_last_insert_id = 0;
303 grep $_->[1]{is_auto_increment},
304 map [ $_, $source->column_info($_) ],
307 $need_last_insert_id = 1
308 if $identity_col && (not exists $to_insert->{$identity_col});
310 # We have to do the insert in a transaction to avoid race conditions with the
311 # SELECT MAX(COL) identity method used when placeholders are enabled.
312 my $updated_cols = do {
313 if ($need_last_insert_id && $self->insert_txn &&
314 (not $self->{transaction_depth})) {
315 my $guard = $self->txn_scope_guard;
316 my $upd_cols = $self->next::method (@_);
321 $self->next::method(@_);
325 $self->_insert_blobs($source, $blob_cols, $to_insert) if %$blob_cols;
327 return $updated_cols;
332 my ($source, $fields, $where) = @_;
334 my $wantarray = wantarray;
336 my $blob_cols = $self->_remove_blob_cols($source, $fields);
340 @res = $self->next::method(@_);
342 elsif (defined $wantarray) {
343 $res[0] = $self->next::method(@_);
346 $self->next::method(@_);
349 $self->_update_blobs($source, $blob_cols, $where) if %$blob_cols;
351 return $wantarray ? @res : $res[0];
354 sub _remove_blob_cols {
355 my ($self, $source, $fields) = @_;
359 for my $col (keys %$fields) {
360 if ($self->_is_lob_type($source->column_info($col)->{data_type})) {
361 $blob_cols{$col} = delete $fields->{$col};
362 $fields->{$col} = \"''";
370 my ($self, $source, $blob_cols, $where) = @_;
372 my (@primary_cols) = $source->primary_columns;
374 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
375 unless @primary_cols;
377 # check if we're updating a single row by PK
378 my $pk_cols_in_where = 0;
379 for my $col (@primary_cols) {
380 $pk_cols_in_where++ if defined $where->{$col};
384 if ($pk_cols_in_where == @primary_cols) {
386 @row_to_update{@primary_cols} = @{$where}{@primary_cols};
387 @rows = \%row_to_update;
389 my $rs = $source->resultset->search(
392 result_class => 'DBIx::Class::ResultClass::HashRefInflator',
393 select => \@primary_cols
396 @rows = $rs->all; # statement must finish
399 for my $row (@rows) {
400 $self->_insert_blobs($source, $blob_cols, $row);
405 my ($self, $source, $blob_cols, $row) = @_;
406 my $dbh = $self->_get_dbh;
408 my $table = $source->from;
411 my (@primary_cols) = $source->primary_columns;
413 croak "Cannot update TEXT/IMAGE column(s) without a primary key"
414 unless @primary_cols;
416 if ((grep { defined $row{$_} } @primary_cols) != @primary_cols) {
417 if (@primary_cols == 1) {
418 my $col = $primary_cols[0];
419 $row{$col} = $self->last_insert_id($source, $col);
421 croak "Cannot update TEXT/IMAGE column(s) without primary key values";
425 for my $col (keys %$blob_cols) {
426 my $blob = $blob_cols->{$col};
428 my %where = map { ($_, $row{$_}) } @primary_cols;
429 my $cursor = $source->resultset->search(\%where, {
433 my $sth = $cursor->sth;
437 $sth->func('CS_GET', 1, 'ct_data_info') or die $sth->errstr;
440 $sth->func('ct_prepare_send') or die $sth->errstr;
442 my $log_on_update = $self->_blob_log_on_update;
443 $log_on_update = 1 if not defined $log_on_update;
445 $sth->func('CS_SET', 1, {
446 total_txtlen => length($blob),
447 log_on_update => $log_on_update
448 }, 'ct_data_info') or die $sth->errstr;
450 $sth->func($blob, length($blob), 'ct_send_data') or die $sth->errstr;
452 $sth->func('ct_finish_send') or die $sth->errstr;
455 $sth->finish if $sth;
457 if ($self->using_freetds) {
459 'TEXT/IMAGE operation failed, probably because you are using FreeTDS: '
469 =head2 connect_call_datetime_setup
473 on_connect_call => 'datetime_setup'
475 In L<DBIx::Class::Storage::DBI/connect_info> to set:
477 $dbh->syb_date_fmt('ISO_strict'); # output fmt: 2004-08-21T14:36:48.080Z
478 $dbh->do('set dateformat mdy'); # input fmt: 08/13/1979 18:08:55.080
480 On connection for use with L<DBIx::Class::InflateColumn::DateTime>, using
481 L<DateTime::Format::Sybase>, which you will need to install.
483 This works for both C<DATETIME> and C<SMALLDATETIME> columns, although
484 C<SMALLDATETIME> columns only have minute precision.
489 my $old_dbd_warned = 0;
491 sub connect_call_datetime_setup {
493 my $dbh = $self->_dbh;
495 if ($dbh->can('syb_date_fmt')) {
496 # amazingly, this works with FreeTDS
497 $dbh->syb_date_fmt('ISO_strict');
498 } elsif (not $old_dbd_warned) {
499 carp "Your DBD::Sybase is too old to support ".
500 "DBIx::Class::InflateColumn::DateTime, please upgrade!";
504 $dbh->do('SET DATEFORMAT mdy');
510 sub datetime_parser_type { "DateTime::Format::Sybase" }
512 # ->begin_work and such have no effect with FreeTDS but we run them anyway to
513 # let the DBD keep any state it needs to.
515 # If they ever do start working, the extra statements will do no harm (because
516 # Sybase supports nested transactions.)
518 sub _dbh_begin_work {
520 $self->next::method(@_);
521 if ($self->using_freetds) {
522 $self->_get_dbh->do('BEGIN TRAN');
528 if ($self->using_freetds) {
529 $self->_dbh->do('COMMIT');
531 return $self->next::method(@_);
536 if ($self->using_freetds) {
537 $self->_dbh->do('ROLLBACK');
539 return $self->next::method(@_);
542 # savepoint support using ASE syntax
545 my ($self, $name) = @_;
547 $self->_get_dbh->do("SAVE TRANSACTION $name");
550 # A new SAVE TRANSACTION with the same name releases the previous one.
551 sub _svp_release { 1 }
554 my ($self, $name) = @_;
556 $self->_get_dbh->do("ROLLBACK TRANSACTION $name");
561 =head1 Schema::Loader Support
563 There is an experimental branch of L<DBIx::Class::Schema::Loader> that will
564 allow you to dump a schema from most (if not all) versions of Sybase.
566 It is available via subversion from:
568 http://dev.catalyst.perl.org/repos/bast/branches/DBIx-Class-Schema-Loader/current/
572 This driver supports L<DBD::Sybase> compiled against FreeTDS
573 (L<http://www.freetds.org/>) to the best of our ability, however it is
574 recommended that you recompile L<DBD::Sybase> against the Sybase Open Client
575 libraries. They are a part of the Sybase ASE distribution:
577 The Open Client FAQ is here:
578 L<http://www.isug.com/Sybase_FAQ/ASE/section7.html>.
580 Sybase ASE for Linux (which comes with the Open Client libraries) may be
581 downloaded here: L<http://response.sybase.com/forms/ASE_Linux_Download>.
583 To see if you're using FreeTDS check C<< $schema->storage->using_freetds >>, or run:
585 perl -MDBI -le 'my $dbh = DBI->connect($dsn, $user, $pass); print $dbh->{syb_oc_version}'
587 Some versions of the libraries involved will not support placeholders, in which
588 case the storage will be reblessed to
589 L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>.
591 In some configurations, placeholders will work but will throw implicit type
592 conversion errors for anything that's not expecting a string. In such a case,
593 the C<auto_cast> option from L<DBIx::Class::Storage::DBI::AutoCast> is
594 automatically set, which you may enable on connection with
595 L<DBIx::Class::Storage::DBI::AutoCast/connect_call_set_auto_cast>. The type info
596 for the C<CAST>s is taken from the L<DBIx::Class::ResultSource/data_type>
597 definitions in your Result classes, and are mapped to a Sybase type (if it isn't
598 already) using a mapping based on L<SQL::Translator>.
600 In other configurations, placeholers will work just as they do with the Sybase
601 Open Client libraries.
603 Inserts or updates of TEXT/IMAGE columns will B<NOT> work with FreeTDS.
607 Due to limitations of the TDS protocol, L<DBD::Sybase>, or both; you cannot
608 begin a transaction while there are active cursors. An active cursor is, for
609 example, a L<ResultSet|DBIx::Class::ResultSet> that has been executed using
610 C<next> or C<first> but has not been exhausted or
611 L<reset|DBIx::Class::ResultSet/reset>.
613 Transactions done for inserts in C<AutoCommit> mode when placeholders are in use
614 are also affected, so this won't work:
616 while (my $row = $rs1->next) {
617 $rs2->create({ foo => $row->foo });
624 =item * set C<< $schema->storage->insert_txn(0) >> temporarily (see
625 L</connect_call_unsafe_insert>)
627 =item * use L<DBIx::Class::Storage::DBI::Replicated>
629 =item * L<connect|DBIx::Class::Schema/connect> another L<Schema|DBIx::Class::Schema>
631 =item * load the data from your cursor with L<DBIx::Class::ResultSet/all>
633 =item * enlarge the scope of the transaction
637 =head1 MAXIMUM CONNECTIONS
639 The TDS protocol makes separate connections to the server for active statements
640 in the background. By default the number of such connections is limited to 25,
641 on both the client side and the server side.
643 This is a bit too low for a complex L<DBIx::Class> application, so on connection
644 the client side setting is set to C<256> (see L<DBD::Sybase/maxConnect>.) You
645 can override it to whatever setting you like in the DSN.
648 L<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1272.htm>
649 for information on changing the setting on the server side.
653 See L</connect_call_datetime_setup> to setup date formats
654 for L<DBIx::Class::InflateColumn::DateTime>.
656 =head1 TEXT/IMAGE COLUMNS
658 L<DBD::Sybase> compiled with FreeTDS will B<NOT> allow you to insert or update
659 C<TEXT/IMAGE> columns.
661 Setting C<< $dbh->{LongReadLen} >> will also not work with FreeTDS use either:
663 $schema->storage->dbh->do("SET TEXTSIZE $bytes");
667 $schema->storage->set_textsize($bytes);
671 However, the C<LongReadLen> you pass in
672 L<DBIx::Class::Storage::DBI/connect_info> is used to execute the equivalent
673 C<SET TEXTSIZE> command on connection.
675 See L</connect_call_blob_setup> for a L<DBIx::Class::Storage::DBI/connect_info>
676 setting you need to work with C<IMAGE> columns.
680 See L<DBIx::Class/CONTRIBUTORS>.
684 You may distribute this code under the same terms as Perl itself.