Merge 'trunk' into 'sybase'
Rafael Kitover [Wed, 22 Jul 2009 00:36:54 +0000 (00:36 +0000)]
r6075@hlagh (orig r7074):  tomboh | 2009-07-20 12:20:37 -0400
Fix POD changes from r7040.
r6081@hlagh (orig r7077):  norbi | 2009-07-20 18:59:30 -0400

r6082@hlagh (orig r7078):  norbi | 2009-07-20 18:59:58 -0400
 r7232@vger:  mendel | 2009-07-21 00:58:12 +0200
 Fixed documentation and added test for the "Arbitrary SQL through a custom ResultSource" Cookbook alternate (subclassing) recipe.

r6083@hlagh (orig r7079):  norbi | 2009-07-20 19:05:32 -0400
 r7235@vger:  mendel | 2009-07-21 01:05:18 +0200
 Fixed 'typo' (removed a word that I left there by accident).

r6084@hlagh (orig r7080):  norbi | 2009-07-21 04:06:21 -0400
 r7237@vger:  mendel | 2009-07-21 10:06:05 +0200
 Fixing what my svk client screwed up.

r6085@hlagh (orig r7081):  caelum | 2009-07-21 10:51:55 -0400
update Storage::Replicated prereqs
r6086@hlagh (orig r7082):  caelum | 2009-07-21 12:16:34 -0400
show Oracle datetime_setup alter session statements in debug output

Makefile.PL
lib/DBIx/Class/ResultSet.pm
lib/DBIx/Class/Storage/DBI.pm
lib/DBIx/Class/Storage/DBI/NoBindVars.pm
lib/DBIx/Class/Storage/DBI/Sybase.pm
lib/DBIx/Class/Storage/DBI/Sybase/Microsoft_SQL_Server.pm
lib/DBIx/Class/Storage/DBI/Sybase/NoBindVars.pm [new file with mode: 0644]
t/746sybase.t
t/inflate/datetime_sybase.t [new file with mode: 0644]
t/lib/DBICTest/Schema.pm
t/lib/DBICTest/Schema/SingleBlob.pm [new file with mode: 0644]

index 2c65cfe..9408b7b 100644 (file)
@@ -111,6 +111,12 @@ my %force_requires_if_author = (
       'DateTime::Format::Oracle' => 0,
     ) : ()
   ,
+
+  $ENV{DBICTEST_SYBASE_DSN}
+    ? (
+      'DateTime::Format::Sybase' => 0,
+    ) : ()
+  ,
 );
 
 if ($Module::Install::AUTHOR) {
index ed1cdc0..724b33f 100644 (file)
@@ -2780,7 +2780,10 @@ sub _resolved_attrs {
                       : "${alias}.$_"
                   )
             }
-      } ( ref($attrs->{columns}) eq 'ARRAY' ) ? @{ delete $attrs->{columns}} : (delete $attrs->{columns} || $source->columns );
+      } ( ref($attrs->{columns}) eq 'ARRAY' ) ?
+          @{ delete $attrs->{columns}} :
+            (delete $attrs->{columns} ||
+              $source->storage->order_columns_for_select($source) );
   }
   # add the additional columns on
   foreach ( 'include_columns', '+columns' ) {
index 1d1e57b..6eefbfa 100644 (file)
@@ -2277,6 +2277,23 @@ sub lag_behind_master {
     return;
 }
 
+=head2 order_columns_for_select
+
+Returns an ordered list of column names for use with a C<SELECT> when the column
+list is not explicitly specified.
+By default returns the result of L<DBIx::Class::ResultSource/columns>.
+
+This may be overridden in a specific storage when there are requirements such
+as moving C<BLOB> columns to the end of the list.
+
+=cut
+
+sub order_columns_for_select {
+  my ($self, $source) = @_;
+
+  return $source->columns;
+}
+
 sub DESTROY {
   my $self = shift;
   return if !$self->_dbh;
index 95f1cac..9424d45 100644 (file)
@@ -40,7 +40,7 @@ Manually subs in the values for the usual C<?> placeholders.
 sub _prep_for_execute {
   my $self = shift;
 
-  my ($op, $extra_bind, $ident) = @_;
+  my ($op, $extra_bind, $ident, $args) = @_;
 
   my ($sql, $bind) = $self->next::method(@_);
 
@@ -49,15 +49,27 @@ sub _prep_for_execute {
   my @sql_part = split /\?/, $sql;
   my $new_sql;
 
+  my ($alias2src, $rs_alias) = $self->_resolve_ident_sources($ident);
+
   foreach my $bound (@$bind) {
     my $col = shift @$bound;
-    my $datatype = 'FIXME!!!';
+
+    my $name_sep   = $self->_sql_maker_opts->{name_sep} || '.';
+
+    $col =~ s/^([^\Q${name_sep}\E]*)\Q${name_sep}\E//;
+    my $alias = $1 || $rs_alias;
+
+    my $rsrc = $alias2src->{$alias};
+
+    my $datatype = $rsrc && $rsrc->column_info($col)->{data_type};
+
     foreach my $data (@$bound) {
-        if(ref $data) {
-            $data = ''.$data;
-        }
-        $data = $self->_dbh->quote($data);
-        $new_sql .= shift(@sql_part) . $data;
+      $data = ''.$data if ref $data;
+
+      $data = $self->_dbh->quote($data)
+        if $self->should_quote_value($datatype, $data);
+
+      $new_sql .= shift(@sql_part) . $data;
     }
   }
   $new_sql .= join '', @sql_part;
@@ -65,6 +77,25 @@ sub _prep_for_execute {
   return ($new_sql, []);
 }
 
+=head2 should_quote_value
+                                
+This method is called by L</_prep_for_execute> for every column in
+order to determine if its value should be quoted or not. The arguments
+are the current column data type and the actual bind value. The return
+value is interpreted as: true - do quote, false - do not quote. You should
+override this in you Storage::DBI::<database> subclass, if your RDBMS
+does not like quotes around certain datatypes (e.g. Sybase and integer
+columns). The default method always returns true (do quote).
+                                
+ WARNING!!!                     
+                                
+ Always validate that the bind-value is valid for the current datatype.
+ Otherwise you may very well open the door to SQL injection attacks.
+                                
+=cut                            
+                                
+sub should_quote_value { 1 }
+
 =head1 AUTHORS
 
 Brandon Black <blblack@gmail.com>
index 0a2cfb8..c12c124 100644 (file)
@@ -5,58 +5,420 @@ use warnings;
 
 use base qw/
     DBIx::Class::Storage::DBI::Sybase::Base
-    DBIx::Class::Storage::DBI::NoBindVars
+    DBIx::Class::Storage::DBI
 /;
 use mro 'c3';
+use Carp::Clan qw/^DBIx::Class/;
+
+=head1 NAME
+
+DBIx::Class::Storage::DBI::Sybase - Storage::DBI subclass for Sybase
+
+=head1 SYNOPSIS
+
+This subclass supports L<DBD::Sybase> for real Sybase databases.  If you are
+using an MSSQL database via L<DBD::Sybase>, your storage will be reblessed to
+L<DBIx::Class::Storage::DBI::Sybase::Microsoft_SQL_Server>.
+
+=head1 DESCRIPTION
+
+If your version of Sybase does not support placeholders, then your storage
+will be reblessed to L<DBIx::Class::Storage::DBI::Sybase::NoBindVars>. You can
+also enable that driver explicitly, see the documentation for more details.
+
+With this driver there is unfortunately no way to get the C<last_insert_id>
+without doing a C<select max(col)>.
+
+But your queries will be cached.
+
+You need a version of L<DBD::Sybase> compiled with the Sybase OpenClient
+libraries, B<NOT> FreeTDS, for placeholder support. Otherwise your storage will
+be automatically reblessed into C<::NoBindVars>.
+
+A recommended L<DBIx::Class::Storage::DBI/connect_info> settings:
+
+  on_connect_call => [['datetime_setup'], [blob_setup => log_on_update => 0]]
+
+=head1 METHODS
+
+=cut
+
+__PACKAGE__->mk_group_accessors('simple' =>
+    qw/_blob_log_on_update/
+);
 
 sub _rebless {
+  my $self = shift;
+
+  if (ref($self) eq 'DBIx::Class::Storage::DBI::Sybase') {
+    my $dbtype = eval {
+      @{$self->dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2]
+    } || '';
+
+    my $exception = $@;
+    $dbtype =~ s/\W/_/gi;
+    my $subclass = "DBIx::Class::Storage::DBI::Sybase::${dbtype}";
+
+    if (!$exception && $dbtype && $self->load_optional_class($subclass)) {
+      bless $self, $subclass;
+      $self->_rebless;
+    } else { # real Sybase
+      my $no_bind_vars = 'DBIx::Class::Storage::DBI::Sybase::NoBindVars';
+
+      if (not $self->dbh->{syb_dynamic_supported}) {
+        $self->ensure_class_loaded($no_bind_vars);
+        bless $self, $no_bind_vars;
+        $self->_rebless;
+      }
+      
+      if ($self->_using_freetds) {
+        carp <<'EOF';
+
+Your version of Sybase potentially supports placeholders and query caching,
+however you seem to be using FreeTDS which does not (yet?) support this.
+
+Please recompile DBD::Sybase with the Sybase OpenClient libraries if you want
+these features.
+
+TEXT/IMAGE column support will also not work under FreeTDS.
+
+See perldoc DBIx::Class::Storage::DBI::Sybase for more details.
+EOF
+        $self->ensure_class_loaded($no_bind_vars);
+        bless $self, $no_bind_vars;
+        $self->_rebless;
+      }
+      $self->_set_maxConnect;
+    }
+  }
+}
+
+{
+  my $using_freetds = undef;
+
+  sub _using_freetds {
+    my $self = shift;
+    my $dbh  = $self->_dbh;
+
+    return $using_freetds if defined $using_freetds;
+
+#    local $dbh->{syb_rowcount} = 1; # this is broken in freetds
+#    $using_freetds = @{ $dbh->selectall_arrayref('sp_help') } != 1;
+
+    $using_freetds = $dbh->{syb_oc_version} =~ /freetds/i;
+
+    return $using_freetds;
+  }
+}
+
+sub _set_maxConnect {
+  my $self = shift;
+
+  my $dsn = $self->_dbi_connect_info->[0];
+
+  return if ref($dsn) eq 'CODE';
+
+  if ($dsn !~ /maxConnect=/) {
+    $self->_dbi_connect_info->[0] = "$dsn;maxConnect=256";
+    my $connected = defined $self->_dbh;
+    $self->disconnect;
+    $self->ensure_connected if $connected;
+  }
+}
+
+=head2 connect_call_blob_setup
+
+Used as:
+
+  on_connect_call => [ [ blob_setup => log_on_update => 0 ] ]
+
+Does C<< $dbh->{syb_binary_images} = 1; >> to return C<IMAGE> data as raw binary
+instead of as a hex string.
+
+Recommended.
+
+Also sets the C<log_on_update> value for blob write operations. The default is
+C<1>, but C<0> is better if your database is configured for it.
+
+See
+L<DBD::Sybase/Handling_IMAGE/TEXT_data_with_syb_ct_get_data()/syb_ct_send_data()>.
+
+=cut
+
+sub connect_call_blob_setup {
+  my $self = shift;
+  my %args = @_;
+  my $dbh = $self->_dbh;
+  $dbh->{syb_binary_images} = 1;
+
+  $self->_blob_log_on_update($args{log_on_update})
+    if exists $args{log_on_update};
+}
+
+sub _is_lob_type {
+  my $self = shift;
+  my $type = shift;
+  $type && $type =~ /(?:text|image|lob|bytea|binary|memo)/i;
+}
+
+## This will be useful if we ever implement BLOB filehandle inflation and will
+## need to use the API, but for now it isn't.
+#
+#sub order_columns_for_select {
+#  my ($self, $source) = @_;
+#
+#  my (@non_blobs, @blobs);
+#
+#  for my $col ($source->columns) {
+#    if ($self->_is_lob_type($source->column_info($col)->{data_type})) {
+#      push @blobs, $col;
+#    } else {
+#      push @non_blobs, $col;
+#    }
+#  }
+#
+#  croak "cannot select more than a one TEXT/IMAGE column at a time"
+#    if @blobs > 1;
+#
+#  return (@non_blobs, @blobs);
+#}
+
+# override to handle TEXT/IMAGE
+sub insert {
+  my ($self, $source, $to_insert) = splice @_, 0, 3;
+
+  my $blob_cols = $self->_remove_blob_cols($source, $to_insert);
+
+  my $updated_cols = $self->next::method($source, $to_insert, @_);
+
+  $self->_insert_blobs($source, $blob_cols, $to_insert) if %$blob_cols;
+
+  return $updated_cols;
+}
+
+sub update {
+  my ($self, $source)  = splice @_, 0, 2;
+  my ($fields, $where) = @_;
+  my $wantarray        = wantarray;
+
+  my $blob_cols = $self->_remove_blob_cols($source, $fields);
+
+  my @res;
+  if ($wantarray) {
+    @res    = $self->next::method($source, @_);
+  } else {
+    $res[0] = $self->next::method($source, @_);
+  }
+
+  $self->_update_blobs($source, $blob_cols, $where) if %$blob_cols;
+
+  return $wantarray ? @res : $res[0];
+}
+
+sub _remove_blob_cols {
+  my ($self, $source, $fields) = @_;
+
+  my %blob_cols;
+
+  for my $col (keys %$fields) {
+    if ($self->_is_lob_type($source->column_info($col)->{data_type})) {
+      $blob_cols{$col} = delete $fields->{$col};
+      $fields->{$col} = \"''";
+    }
+  }
+
+  return \%blob_cols;
+}
+
+sub _update_blobs {
+  my ($self, $source, $blob_cols, $where) = @_;
+
+  my (@primary_cols) = $source->primary_columns;
+
+  croak "Cannot update TEXT/IMAGE column(s) without a primary key"
+    unless @primary_cols;
+
+# check if we're updating a single row by PK
+  my $pk_cols_in_where = 0;
+  for my $col (@primary_cols) {
+    $pk_cols_in_where++ if defined $where->{$col};
+  }
+  my @rows;
+
+  if ($pk_cols_in_where == @primary_cols) {
+    my %row_to_update;
+    @row_to_update{@primary_cols} = @{$where}{@primary_cols};
+    @rows = \%row_to_update;
+  } else {
+    my $rs = $source->resultset->search(
+      $where,
+      {
+        result_class => 'DBIx::Class::ResultClass::HashRefInflator',
+        select => \@primary_cols
+      }
+    );
+    @rows = $rs->all; # statement must finish
+  }
+
+  for my $row (@rows) {
+    $self->_insert_blobs($source, $blob_cols, $row);
+  }
+}
+
+sub _insert_blobs {
+  my ($self, $source, $blob_cols, $row) = @_;
+  my $dbh = $self->dbh;
+
+  my $table = $source->from;
+
+  my %row = %$row;
+  my (@primary_cols) = $source->primary_columns;
+
+  croak "Cannot update TEXT/IMAGE column(s) without a primary key"
+    unless @primary_cols;
+
+  if ((grep { defined $row{$_} } @primary_cols) != @primary_cols) {
+    if (@primary_cols == 1) {
+      my $col = $primary_cols[0];
+      $row{$col} = $self->last_insert_id($source, $col);
+    } else {
+      croak "Cannot update TEXT/IMAGE column(s) without primary key values";
+    }
+  }
+
+  for my $col (keys %$blob_cols) {
+    my $blob = $blob_cols->{$col};
+    my $sth;
+
+    if (not $self->isa('DBIx::Class::Storage::DBI::NoBindVars')) {
+      my $search_cond = join ',' => map "$_ = ?", @primary_cols;
+
+      $sth = $self->sth(
+        "select $col from $table where $search_cond"
+      );
+      $sth->execute(map $row{$_}, @primary_cols);
+    } else {
+      my $search_cond = join ',' => map "$_ = $row{$_}", @primary_cols;
+
+      $sth = $dbh->prepare(
+        "select $col from $table where $search_cond"
+      );
+      $sth->execute;
+    }
+
+    eval {
+      while ($sth->fetch) {
+        $sth->func('CS_GET', 1, 'ct_data_info') or die $sth->errstr;
+      }
+      $sth->func('ct_prepare_send') or die $sth->errstr;
+
+      my $log_on_update = $self->_blob_log_on_update;
+      $log_on_update    = 1 if not defined $log_on_update;
+
+      $sth->func('CS_SET', 1, {
+        total_txtlen => length($blob),
+        log_on_update => $log_on_update
+      }, 'ct_data_info') or die $sth->errstr;
+
+      $sth->func($blob, length($blob), 'ct_send_data') or die $sth->errstr;
+
+      $sth->func('ct_finish_send') or die $sth->errstr;
+    };
+    my $exception = $@;
+    $sth->finish;
+    croak $exception if $exception;
+  }
+}
+
+=head2 connect_call_datetime_setup
+
+Used as:
+
+  on_connect_call => 'datetime_setup'
+
+In L<DBIx::Class::Storage::DBI/connect_info> to set:
+
+  $dbh->syb_date_fmt('ISO_strict'); # output fmt: 2004-08-21T14:36:48.080Z
+  $dbh->do('set dateformat mdy');   # input fmt:  08/13/1979 18:08:55.080
+
+On connection for use with L<DBIx::Class::InflateColumn::DateTime>, using
+L<DateTime::Format::Sybase>, which you will need to install.
+
+This works for both C<DATETIME> and C<SMALLDATETIME> columns, although
+C<SMALLDATETIME> columns only have minute precision.
+
+=cut
+
+{
+  my $old_dbd_warned = 0;
+
+  sub connect_call_datetime_setup {
     my $self = shift;
+    my $dbh = $self->_dbh;
 
-    my $dbtype = eval { @{$self->dbh->selectrow_arrayref(qq{sp_server_info \@attribute_id=1})}[2] };
-    unless ( $@ ) {
-        $dbtype =~ s/\W/_/gi;
-        my $subclass = "DBIx::Class::Storage::DBI::Sybase::${dbtype}";
-        if ($self->load_optional_class($subclass) && !$self->isa($subclass)) {
-            bless $self, $subclass;
-            $self->_rebless;
-        }
+    if ($dbh->can('syb_date_fmt')) {
+      $dbh->syb_date_fmt('ISO_strict');
+    } elsif (not $old_dbd_warned) {
+      carp "Your DBD::Sybase is too old to support ".
+      "DBIx::Class::InflateColumn::DateTime, please upgrade!";
+      $old_dbd_warned = 1;
     }
+
+    $dbh->do('set dateformat mdy');
+
+    1;
+  }
 }
 
+sub datetime_parser_type { "DateTime::Format::Sybase" }
+
 sub _dbh_last_insert_id {
-    my ($self, $dbh, $source, $col) = @_;
-    return ($dbh->selectrow_array('select @@identity'))[0];
+  my ($self, $dbh, $source, $col) = @_;
+
+  # sorry, there's no other way!
+  my $sth = $self->sth("select max($col) from ".$source->from);
+  my ($id) = $dbh->selectrow_array($sth);
+  $sth->finish;
+
+  return $id;
 }
 
 1;
 
-=head1 NAME
+=head1 MAXIMUM CONNECTIONS
 
-DBIx::Class::Storage::DBI::Sybase - Storage::DBI subclass for Sybase
+L<DBD::Sybase> makes separate connections to the server for active statements in
+the background. By default the number of such connections is limited to 25, on
+both the client side and the server side.
 
-=head1 SYNOPSIS
+This is a bit too low, so on connection the clientside setting is set to C<256>
+(see L<DBD::Sybase/maxConnect>.) You can override it to whatever setting you
+like in the DSN.
 
-This subclass supports L<DBD::Sybase> for real Sybase databases.  If
-you are using an MSSQL database via L<DBD::Sybase>, see
-L<DBIx::Class::Storage::DBI::Sybase::MSSQL>.
+See
+L<http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.sag1/html/sag1/sag1272.htm>
+for information on changing the setting on the server side.
 
-=head1 CAVEATS
+=head1 DATES
 
-This storage driver uses L<DBIx::Class::Storage::DBI::NoBindVars> as a base.
-This means that bind variables will be interpolated (properly quoted of course)
-into the SQL query itself, without using bind placeholders.
+See L</connect_call_datetime_setup> to setup date formats
+for L<DBIx::Class::InflateColumn::DateTime>.
 
-More importantly this means that caching of prepared statements is explicitly
-disabled, as the interpolation renders it useless.
+=head1 IMAGE AND TEXT COLUMNS
 
-=head1 AUTHORS
+L<DBD::Sybase> compiled with FreeTDS will B<NOT> work with C<TEXT/IMAGE>
+columns.
+
+See L</connect_call_blob_setup> for a L<DBIx::Class::Storage::DBI/connect_info>
+setting you need to work with C<IMAGE> columns.
 
-Brandon L Black <blblack@gmail.com>
+=head1 AUTHORS
 
-Justin Hunter <justin.d.hunter@gmail.com>
+See L<DBIx::Class/CONTRIBUTORS>.
 
 =head1 LICENSE
 
 You may distribute this code under the same terms as Perl itself.
 
 =cut
+# vim:sts=2 sw=2:
index 600db7a..b0462f9 100644 (file)
@@ -6,9 +6,25 @@ use warnings;
 use base qw/
   DBIx::Class::Storage::DBI::Sybase::Base
   DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server
+  DBIx::Class::Storage::DBI::NoBindVars
 /;
 use mro 'c3';
 
+sub _rebless {
+  my $self = shift;
+  $self->disable_sth_caching(1);
+
+# LongReadLen doesn't work with MSSQL through DBD::Sybase, and the default is
+# huge on some versions of SQL server and can cause memory problems, so we
+# fix it up here.
+  my $dbh = $self->_dbh;
+
+  my $text_size = eval { $self->_dbi_connect_info->[-1]->{LongReadLen} } ||
+    32768; # the DBD::Sybase default
+
+  $dbh->do("set textsize $text_size");
+}
+
 1;
 
 =head1 NAME
@@ -29,11 +45,12 @@ into the SQL query itself, without using bind placeholders.
 More importantly this means that caching of prepared statements is explicitly
 disabled, as the interpolation renders it useless.
 
-=head1 AUTHORS
+The actual driver code for MSSQL is in
+L<DBIx::Class::Storage::DBI::ODBC::Microsoft_SQL_Server>.
 
-Brandon L Black <blblack@gmail.com>
+=head1 AUTHORS
 
-Justin Hunter <justin.d.hunter@gmail.com>
+See L<DBIx::Class/CONTRIBUTORS>.
 
 =head1 LICENSE
 
diff --git a/lib/DBIx/Class/Storage/DBI/Sybase/NoBindVars.pm b/lib/DBIx/Class/Storage/DBI/Sybase/NoBindVars.pm
new file mode 100644 (file)
index 0000000..b918682
--- /dev/null
@@ -0,0 +1,109 @@
+package DBIx::Class::Storage::DBI::Sybase::NoBindVars;
+
+use Class::C3;
+use base qw/
+  DBIx::Class::Storage::DBI::NoBindVars
+  DBIx::Class::Storage::DBI::Sybase
+/;
+use List::Util ();
+use Scalar::Util ();
+
+sub _rebless {
+  my $self = shift;
+  $self->disable_sth_caching(1);
+}
+
+sub _dbh_last_insert_id {
+  my ($self, $dbh, $source, $col) = @_;
+
+  # @@identity works only if not using placeholders
+  # Should this query be cached?
+  return ($dbh->selectrow_array('select @@identity'))[0];
+}
+
+my $number = sub { Scalar::Util::looks_like_number($_[0]) };
+
+my $decimal = sub { $_[0] =~ /^ [-+]? \d+ (?:\.\d*)? \z/x };
+
+my %noquote = (
+    int => sub { $_[0] =~ /^ [-+]? \d+ \z/x },
+    bit => => sub { $_[0] =~ /^[01]\z/ },
+    money => sub { $_[0] =~ /^\$ \d+ (?:\.\d*)? \z/x },
+    float => $number,
+    real => $number,
+    double => $number,
+    decimal => $decimal,
+    numeric => $decimal,
+);
+
+sub should_quote_value {
+  my $self = shift;
+  my ($type, $value) = @_;
+
+  return $self->next::method(@_) if not defined $value or not defined $type;
+
+  if (my $key = List::Util::first { $type =~ /$_/i } keys %noquote) {
+    return 0 if $noquote{$key}->($value);
+  } elsif($self->is_datatype_numeric($type) && $number->($value)) {
+    return 0;
+  }
+
+## try to guess based on value
+#  elsif (not $type) {
+#    return 0 if $number->($value) || $noquote->{money}->($value);
+#  }
+
+  return $self->next::method(@_);
+}
+
+1;
+
+=head1 NAME
+
+DBIx::Class::Storage::DBI::Sybase::NoBindVars - Storage::DBI subclass for Sybase
+without placeholder support
+
+=head1 DESCRIPTION
+
+If you're using this driver than your version of Sybase does not support
+placeholders, or your version of L<DBD::Sybase> was compiled with FreeTDS rather
+than the Sybase OpenClient libraries. You can check with:
+
+  $dbh->{syb_dynamic_supported}
+
+To see if you are using FreeTDS, run:
+
+  perl -MDBD::Sybase -le 'print grep /Sybase\./, @DynaLoader::dl_shared_objects' | xargs ldd
+
+If you see C<libct.so> or similar, rather than C<libsybct.so> then you are using
+FreeTDS.
+
+You can also enable this driver explicitly using:
+
+  my $schema = SchemaClass->clone;
+  $schema->storage_type('::DBI::Sybase::NoBindVars');
+  $schema->connect($dsn, $user, $pass, \%opts);
+
+See the discussion in L<< DBD::Sybase/Using ? Placeholders & bind parameters to
+$sth->execute >> for details on the pros and cons of using placeholders.
+
+One advantage of not using placeholders is that C<select @@identity> will work
+for obtainging the last insert id of an C<IDENTITY> column, instead of having to
+do C<select max(col)> as the base Sybase driver does.
+
+When using this driver, bind variables will be interpolated (properly quoted of
+course) into the SQL query itself, without using placeholders.
+
+The caching of prepared statements is also explicitly disabled, as the
+interpolation renders it useless.
+
+=head1 AUTHORS
+
+See L<DBIx::Class/CONTRIBUTORS>.
+
+=head1 LICENSE
+
+You may distribute this code under the same terms as Perl itself.
+
+=cut
+# vim:sts=2 sw=2:
index 9fc87f0..91bfb24 100644 (file)
@@ -1,5 +1,6 @@
 use strict;
 use warnings;  
+no warnings 'uninitialized';
 
 use Test::More;
 use Test::Exception;
@@ -8,84 +9,217 @@ use DBICTest;
 
 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_SYBASE_${_}" } qw/DSN USER PASS/};
 
-plan skip_all => 'Set $ENV{DBICTEST_SYBASE_DSN}, _USER and _PASS to run this test'
-  unless ($dsn && $user);
+my $TESTS = 29 + 2;
 
-plan tests => 13;
-
-my $schema = DBICTest::Schema->connect($dsn, $user, $pass, {AutoCommit => 1});
-
-# start disconnected to test reconnection
-$schema->storage->ensure_connected;
-$schema->storage->_dbh->disconnect;
-
-isa_ok( $schema->storage, 'DBIx::Class::Storage::DBI::Sybase' );
-
-my $dbh;
-lives_ok (sub {
-  $dbh = $schema->storage->dbh;
-}, 'reconnect works');
-
-$schema->storage->dbh_do (sub {
-    my ($storage, $dbh) = @_;
-    eval { $dbh->do("DROP TABLE artist") };
-    $dbh->do(<<'SQL');
+if (not ($dsn && $user)) {
+  plan skip_all =>
+    'Set $ENV{DBICTEST_SYBASE_DSN}, _USER and _PASS to run this test' .
+    "\nWarning: This test drops and creates the tables " .
+    "'artist' and 'bindtype_test'";
+} else {
+  plan tests => $TESTS*2;
+}
 
+my @storage_types = (
+  'DBI::Sybase',
+  'DBI::Sybase::NoBindVars',
+);
+my $schema;
+my $storage_idx = -1;
+
+for my $storage_type (@storage_types) {
+  $storage_idx++;
+  $schema = DBICTest::Schema->clone;
+
+  unless ($storage_type eq 'DBI::Sybase') { # autodetect
+    $schema->storage_type("::$storage_type");
+  }
+  $schema->connection($dsn, $user, $pass, {
+    AutoCommit => 1,
+    on_connect_call => [
+      [ blob_setup => log_on_update => 1 ], # this is a safer option
+    ],
+  });
+
+  $schema->storage->ensure_connected;
+  $schema->storage->_dbh->disconnect;
+
+  if ($storage_idx == 0 &&
+      $schema->storage->isa('DBIx::Class::Storage::DBI::Sybase::NoBindVars')) {
+# no placeholders in this version of Sybase or DBD::Sybase (or using FreeTDS)
+      my $tb = Test::More->builder;
+      $tb->skip('no placeholders') for 1..$TESTS;
+      next;
+  }
+
+  isa_ok( $schema->storage, "DBIx::Class::Storage::$storage_type" );
+
+  lives_ok (sub { $schema->storage->dbh }, 'reconnect works');
+
+  $schema->storage->dbh_do (sub {
+      my ($storage, $dbh) = @_;
+      eval { $dbh->do("DROP TABLE artist") };
+      $dbh->do(<<'SQL');
 CREATE TABLE artist (
-   artistid INT IDENTITY NOT NULL,
+   artistid INT IDENTITY PRIMARY KEY,
    name VARCHAR(100),
    rank INT DEFAULT 13 NOT NULL,
-   charfield CHAR(10) NULL,
-   primary key(artistid)
+   charfield CHAR(10) NULL
 )
-
 SQL
+  });
 
-});
+  my %seen_id;
 
-my %seen_id;
-
-# fresh $schema so we start unconnected
-$schema = DBICTest::Schema->connect($dsn, $user, $pass, {AutoCommit => 1});
+# so we start unconnected
+  $schema->storage->disconnect;
 
 # test primary key handling
-my $new = $schema->resultset('Artist')->create({ name => 'foo' });
-ok($new->artistid > 0, "Auto-PK worked");
+  my $new = $schema->resultset('Artist')->create({ name => 'foo' });
+  ok($new->artistid > 0, "Auto-PK worked");
 
-$seen_id{$new->artistid}++;
+  $seen_id{$new->artistid}++;
 
-# test LIMIT support
-for (1..6) {
+  for (1..6) {
     $new = $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
     is ( $seen_id{$new->artistid}, undef, "id for Artist $_ is unique" );
     $seen_id{$new->artistid}++;
-}
+  }
 
-my $it;
+# test simple count
+  is ($schema->resultset('Artist')->count, 7, 'count(*) of whole table ok');
 
-$it = $schema->resultset('Artist')->search( {}, {
+# test LIMIT support
+  my $it = $schema->resultset('Artist')->search({
+    artistid => { '>' => 0 }
+  }, {
     rows => 3,
     order_by => 'artistid',
-});
-
-TODO: {
-    local $TODO = 'Sybase is very very fucked in the limit department';
-
-    is( $it->count, 3, "LIMIT count ok" );
-}
+  });
 
-# The iterator still works correctly with rows => 3, even though the sql is
-# fucked, very interesting.
+  is( $it->count, 3, "LIMIT count ok" );
 
-is( $it->next->name, "foo", "iterator->next ok" );
-$it->next;
-is( $it->next->name, "Artist 2", "iterator->next ok" );
-is( $it->next, undef, "next past end of resultset ok" );
+  is( $it->next->name, "foo", "iterator->next ok" );
+  $it->next;
+  is( $it->next->name, "Artist 2", "iterator->next ok" );
+  is( $it->next, undef, "next past end of resultset ok" );
 
+# now try with offset
+  $it = $schema->resultset('Artist')->search({}, {
+    rows => 3,
+    offset => 3,
+    order_by => 'artistid',
+  });
+
+  is( $it->count, 3, "LIMIT with offset count ok" );
+
+  is( $it->next->name, "Artist 3", "iterator->next ok" );
+  $it->next;
+  is( $it->next->name, "Artist 5", "iterator->next ok" );
+  is( $it->next, undef, "next past end of resultset ok" );
+
+# now try a grouped count
+  $schema->resultset('Artist')->create({ name => 'Artist 6' })
+    for (1..6);
+
+  $it = $schema->resultset('Artist')->search({}, {
+    group_by => 'name'
+  });
+
+  is( $it->count, 7, 'COUNT of GROUP_BY ok' );
+
+# mostly stolen from the blob stuff Nniuq wrote for t/73oracle.t
+  SKIP: {
+    skip 'TEXT/IMAGE support does not work with FreeTDS', 12
+      if $schema->storage->_using_freetds;
+
+    my $dbh = $schema->storage->dbh;
+    {
+      local $SIG{__WARN__} = sub {};
+      eval { $dbh->do('DROP TABLE bindtype_test') };
+
+      $dbh->do(qq[
+        CREATE TABLE bindtype_test 
+        (
+          id    INT   IDENTITY PRIMARY KEY,
+          bytea INT   NULL,
+          blob  IMAGE NULL,
+          clob  TEXT  NULL
+        )
+      ],{ RaiseError => 1, PrintError => 0 });
+    }
+
+    my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
+    $binstr{'large'} = $binstr{'small'} x 1024;
+
+    my $maxloblen = length $binstr{'large'};
+    note
+      "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
+    local $dbh->{'LongReadLen'} = $maxloblen * 2;
+
+    my $rs = $schema->resultset('BindType');
+    my $last_id;
+
+    foreach my $type (qw(blob clob)) {
+      foreach my $size (qw(small large)) {
+        no warnings 'uninitialized';
+
+        my $created = eval { $rs->create( { $type => $binstr{$size} } ) };
+        ok(!$@, "inserted $size $type without dying");
+        diag $@ if $@;
+
+        $last_id = $created->id if $created;
+
+        my $got = eval {
+          $rs->find($last_id)->$type
+        };
+        diag $@ if $@;
+        ok($got eq $binstr{$size}, "verified inserted $size $type");
+      }
+    }
+
+    # blob insert with explicit PK
+    {
+      local $SIG{__WARN__} = sub {};
+      eval { $dbh->do('DROP TABLE bindtype_test') };
+
+      $dbh->do(qq[
+        CREATE TABLE bindtype_test 
+        (
+          id    INT   PRIMARY KEY,
+          bytea INT   NULL,
+          blob  IMAGE NULL,
+          clob  TEXT  NULL
+        )
+      ],{ RaiseError => 1, PrintError => 0 });
+    }
+    my $created = eval { $rs->create( { id => 1, blob => $binstr{large} } ) };
+    ok(!$@, "inserted large blob without dying with manual PK");
+    diag $@ if $@;
+
+    my $got = eval {
+      $rs->find(1)->blob
+    };
+    diag $@ if $@;
+    ok($got eq $binstr{large}, "verified inserted large blob with manual PK");
+
+    # try a blob update
+    my $new_str = $binstr{large} . 'mtfnpy';
+    eval { $rs->search({ id => 1 })->update({ blob => $new_str }) };
+    ok !$@, 'updated blob successfully';
+    diag $@ if $@;
+    $got = eval {
+      $rs->find(1)->blob
+    };
+    diag $@ if $@;
+    ok($got eq $new_str, "verified updated blob");
+  }
+}
 
 # clean up our mess
 END {
-    my $dbh = eval { $schema->storage->_dbh };
-    $dbh->do('DROP TABLE artist') if $dbh;
+  if (my $dbh = eval { $schema->storage->_dbh }) {
+    $dbh->do('DROP TABLE artist');
+    eval { $dbh->do('DROP TABLE bindtype_test')    };
+  }
 }
-
diff --git a/t/inflate/datetime_sybase.t b/t/inflate/datetime_sybase.t
new file mode 100644 (file)
index 0000000..13edcb5
--- /dev/null
@@ -0,0 +1,83 @@
+use strict;
+use warnings;  
+
+use Test::More;
+use Test::Exception;
+use lib qw(t/lib);
+use DBICTest;
+
+my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_SYBASE_${_}" } qw/DSN USER PASS/};
+
+if (not ($dsn && $user)) {
+  plan skip_all =>
+    'Set $ENV{DBICTEST_SYBASE_DSN}, _USER and _PASS to run this test' .
+    "\nWarning: This test drops and creates a table called 'track'";
+} else {
+  eval "use DateTime; use DateTime::Format::Sybase;";
+  if ($@) {
+    plan skip_all => 'needs DateTime and DateTime::Format::Sybase for testing';
+  }
+  else {
+    plan tests => (4 * 2 * 2) + 2; # (tests * dt_types * storage_types) + storage_tests
+  }
+}
+
+my @storage_types = (
+  'DBI::Sybase',
+  'DBI::Sybase::NoBindVars',
+);
+my $schema;
+
+for my $storage_type (@storage_types) {
+  $schema = DBICTest::Schema->clone;
+
+  unless ($storage_type eq 'DBI::Sybase') { # autodetect
+    $schema->storage_type("::$storage_type");
+  }
+  $schema->connection($dsn, $user, $pass, {
+    AutoCommit => 1,
+    on_connect_call => [ 'datetime_setup' ],
+  });
+
+  $schema->storage->ensure_connected;
+
+  isa_ok( $schema->storage, "DBIx::Class::Storage::$storage_type" );
+
+  my @dt_types = (
+    ['DATETIME', '2004-08-21T14:36:48.080Z'],
+    ['SMALLDATETIME', '2004-08-21T14:36:00.000Z'], # minute precision
+  );
+  
+  for my $dt_type (@dt_types) {
+    my ($type, $sample_dt) = @$dt_type;
+
+    eval { $schema->storage->dbh->do("DROP TABLE track") };
+    $schema->storage->dbh->do(<<"SQL");
+CREATE TABLE track (
+   trackid INT IDENTITY PRIMARY KEY,
+   cd INT,
+   position INT,
+   last_updated_on $type,
+)
+SQL
+    ok(my $dt = DateTime::Format::Sybase->parse_datetime($sample_dt));
+
+    my $row;
+    ok( $row = $schema->resultset('Track')->create({
+          last_updated_on => $dt,
+          cd => 1,
+        }));
+    ok( $row = $schema->resultset('Track')
+      ->search({ trackid => $row->trackid }, { select => ['last_updated_on'] })
+      ->first
+    );
+    is( $row->updated_date, $dt, 'DateTime roundtrip' );
+  }
+}
+
+# clean up our mess
+END {
+  if (my $dbh = eval { $schema->storage->_dbh }) {
+    $dbh->do('DROP TABLE track');
+  }
+}
index ab5b098..9bf7805 100644 (file)
@@ -9,6 +9,7 @@ __PACKAGE__->load_classes(qw/
   Artist
   SequenceTest
   BindType
+  SingleBlob
   Employee
   CD
   FileColumn
diff --git a/t/lib/DBICTest/Schema/SingleBlob.pm b/t/lib/DBICTest/Schema/SingleBlob.pm
new file mode 100644 (file)
index 0000000..2818d33
--- /dev/null
@@ -0,0 +1,25 @@
+package # hide from PAUSE 
+    DBICTest::Schema::SingleBlob;
+
+use base qw/DBICTest::BaseResult/;
+
+__PACKAGE__->table('single_blob_test');
+
+__PACKAGE__->add_columns(
+  'id' => {
+    data_type => 'integer',
+    is_auto_increment => 1,
+  },
+  'blob' => {
+    data_type => 'blob',
+    is_nullable => 1,
+  },
+  'foo' => {
+    data_type => 'varchar',
+    is_nullable => 1,
+  }
+);
+
+__PACKAGE__->set_primary_key('id');
+
+1;