Merge 'trunk' into 'sybase'
Rafael Kitover [Thu, 9 Jul 2009 05:35:56 +0000 (05:35 +0000)]
r5891@hlagh (orig r6947):  ribasushi | 2009-07-02 13:20:21 -0700
Last part of the join handling puzzle
r5894@hlagh (orig r6950):  ribasushi | 2009-07-02 15:14:50 -0700
 r6360@Thesaurus (orig r6359):  arcanez | 2009-05-21 20:18:52 +0200
 branch to work on prefetch/select
 r6361@Thesaurus (orig r6360):  arcanez | 2009-05-21 20:32:46 +0200
 failing test
 r6373@Thesaurus (orig r6372):  ribasushi | 2009-05-22 11:07:26 +0200
 Simplify unresolvable test by arcanez
 r6905@Thesaurus (orig r6904):  ribasushi | 2009-07-01 12:54:03 +0200
 Extend test
 r6950@Thesaurus (orig r6949):  ribasushi | 2009-07-03 00:14:09 +0200
 Apparent fix - simply delay the in_storage flagging of the main object until all prefetched objects are inflated. The rest of the changes are just cosmetics, preparing for the collapse_result rewrite

r5896@hlagh (orig r6952):  ribasushi | 2009-07-02 15:17:22 -0700
Changes
r5909@hlagh (orig r6964):  ribasushi | 2009-07-03 04:19:27 -0700
Add set_ansi_mode on_connect_call for mysql
Also switch to _do_query instead of plain dbh->do (shows up in the trace)
r5910@hlagh (orig r6965):  ribasushi | 2009-07-03 04:37:06 -0700
Capitalize mysql commands
r5911@hlagh (orig r6966):  ribasushi | 2009-07-03 06:07:49 -0700
Double an existing might_have test as has_one
r5912@hlagh (orig r6967):  ribasushi | 2009-07-03 07:36:32 -0700
Extra test to demonstrate has_one working, and a POD clarification of multicreate
r5917@hlagh (orig r6972):  ribasushi | 2009-07-03 11:20:42 -0700
 r6554@Thesaurus (orig r6553):  frew | 2009-06-09 00:06:42 +0200
 branch for mssql top issues
 r6572@Thesaurus (orig r6571):  frew | 2009-06-09 23:18:46 +0200
 more tests for SQL Server!
 r6573@Thesaurus (orig r6572):  frew | 2009-06-09 23:49:10 +0200
 Added AmbiguousGlob.pm for silly servers like mssql and mysql.  See docs for more info
 r6574@Thesaurus (orig r6573):  frew | 2009-06-09 23:55:22 +0200
 fix plan
 r6602@Thesaurus (orig r6601):  frew | 2009-06-10 17:03:30 +0200
 more failing tests
 r6608@Thesaurus (orig r6607):  frew | 2009-06-10 20:05:53 +0200
 don't use eval!
 r6610@Thesaurus (orig r6609):  frew | 2009-06-10 20:07:49 +0200
 beginning of DWIM for IDENTITY_INSERT
 r6628@Thesaurus (orig r6627):  frew | 2009-06-11 18:13:02 +0200
 still busted :-(
 r6631@Thesaurus (orig r6630):  frew | 2009-06-11 19:39:00 +0200
 general function to go from column names and ident to result source
 r6632@Thesaurus (orig r6631):  frew | 2009-06-11 19:40:11 +0200
 Use new _resolve_column_sources method and begin insert_bulk method
 r6635@Thesaurus (orig r6634):  frew | 2009-06-11 20:12:38 +0200
 updated _resolve_column_source to _resolve_column_info as per ribasushi's suggestion
 r6650@Thesaurus (orig r6649):  frew | 2009-06-12 17:13:32 +0200
 Now I just need to check if the actual values are set...
 r6651@Thesaurus (orig r6650):  frew | 2009-06-12 17:26:53 +0200
 Insert Identity works!
 r6652@Thesaurus (orig r6651):  frew | 2009-06-12 17:34:13 +0200
 silly warns.
 r6684@Thesaurus (orig r6683):  frew | 2009-06-15 16:49:00 +0200
 failing test
 r6686@Thesaurus (orig r6685):  ribasushi | 2009-06-15 18:10:26 +0200
 make all resolved attrs visible to sqla
 r6698@Thesaurus (orig r6697):  ribasushi | 2009-06-17 02:31:37 +0200
 Half way working stuff, needs a LOT of tweaking still
 r6729@Thesaurus (orig r6728):  ribasushi | 2009-06-19 19:49:27 +0200
 Merge badness
 r6730@Thesaurus (orig r6729):  ribasushi | 2009-06-19 19:49:40 +0200
 fix eol
 r6731@Thesaurus (orig r6730):  ribasushi | 2009-06-19 19:55:47 +0200
 augment inheritance
 r6735@Thesaurus (orig r6734):  ribasushi | 2009-06-20 10:34:42 +0200
 Maybe I've nailed it
 r6746@Thesaurus (orig r6745):  ribasushi | 2009-06-20 23:53:55 +0200
 Test and merge fixes
 r6747@Thesaurus (orig r6746):  ribasushi | 2009-06-21 00:01:09 +0200
 Really fix tests
 r6748@Thesaurus (orig r6747):  ribasushi | 2009-06-21 00:01:54 +0200
 Really fix tests
 r6749@Thesaurus (orig r6748):  ribasushi | 2009-06-21 00:18:33 +0200
 Now really final
 r6750@Thesaurus (orig r6749):  ribasushi | 2009-06-21 00:22:23 +0200
 whoops
 r6751@Thesaurus (orig r6750):  ribasushi | 2009-06-21 00:42:18 +0200
 That should be all
 r6752@Thesaurus (orig r6751):  ribasushi | 2009-06-21 08:54:00 +0200
 Make sure quoting works
 r6755@Thesaurus (orig r6754):  ribasushi | 2009-06-21 15:21:23 +0200
 Groundwork for sanification of the toplimit test
 r6863@Thesaurus (orig r6862):  ribasushi | 2009-06-30 01:13:49 +0200
 Make sure storage classes use c3, just like the rest of dbic (tested on 5.8 as well)
 r6869@Thesaurus (orig r6868):  ribasushi | 2009-06-30 09:53:27 +0200
 Some fixes after review
 r6874@Thesaurus (orig r6873):  ribasushi | 2009-06-30 11:54:34 +0200
 Fix borked next invocation
 r6896@Thesaurus (orig r6895):  frew | 2009-06-30 21:38:26 +0200
 silly misspells and trailing whitespace
 r6955@Thesaurus (orig r6954):  ribasushi | 2009-07-03 01:21:28 +0200
 Some hack consolidation
 r6962@Thesaurus (orig r6961):  ribasushi | 2009-07-03 12:06:57 +0200
 Fix some mssql shortcommings when confronted with the new subequeried prefetch sql
 r6963@Thesaurus (orig r6962):  ribasushi | 2009-07-03 12:47:57 +0200
 Ask for newer DBD::Pg in author mode, suggest the newer version otherwise (proper array support). Make test more resilient as well
 r6964@Thesaurus (orig r6963):  ribasushi | 2009-07-03 12:49:16 +0200
 Switch to C3 mro throughout the ::Storage hierarchy (DBIx::Class brings in MRO::Compat, and all ::Storage's are based on it, tested on 5.8
 r6969@Thesaurus (orig r6968):  ribasushi | 2009-07-03 19:54:04 +0200
 Duh
 r6970@Thesaurus (orig r6969):  frew | 2009-07-03 19:59:48 +0200
 fix tests for new codez
 r6971@Thesaurus (orig r6970):  ribasushi | 2009-07-03 20:18:53 +0200
 detabify
 r6972@Thesaurus (orig r6971):  ribasushi | 2009-07-03 20:20:07 +0200
 changes

r5920@hlagh (orig r6979):  ribasushi | 2009-07-04 02:34:08 -0700
Hide devel documentation from the indexer
r5921@hlagh (orig r6980):  ribasushi | 2009-07-04 02:37:25 -0700
Add set_ansi_mode POD
r5922@hlagh (orig r6981):  ribasushi | 2009-07-04 02:45:24 -0700
Backout mysql changes for further polishing
r5925@hlagh (orig r6984):  ribasushi | 2009-07-04 03:08:16 -0700
Missing newline
r5926@hlagh (orig r6985):  ribasushi | 2009-07-04 03:11:18 -0700
typo
r5927@hlagh (orig r6986):  ribasushi | 2009-07-04 03:40:47 -0700
Fix POD
r5928@hlagh (orig r6987):  ribasushi | 2009-07-04 04:09:39 -0700
todos are shorter now
r5929@hlagh (orig r6989):  castaway | 2009-07-05 13:00:55 -0700
Added Pod::Inherit use to Makefile.PL at author-time, comments/suggestions as to whether its too "noisy" welcome.

r5930@hlagh (orig r6990):  ribasushi | 2009-07-05 15:06:52 -0700
Couple of makefile fixes:
use is compile time, use require
recommends is for distro maintainers only, push the dependency into the authors hash (it is not to be executed by mere mortals)

r5931@hlagh (orig r6991):  ribasushi | 2009-07-05 15:55:36 -0700
Forgotten pod exclusions
r5932@hlagh (orig r6992):  ribasushi | 2009-07-05 16:07:05 -0700
Temporarily backout Pod::Inherit changes
r5933@hlagh (orig r6993):  ribasushi | 2009-07-05 16:10:22 -0700
Put Pod::Inherit stuff back after proper copy

Makefile.PL
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]

index 044802d..38de3ff 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 95f1cac..511b0ad 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 = $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 || 'me';
+
+    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..fed74c8 100644 (file)
@@ -5,58 +5,275 @@ 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.
+
+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
+      if (not $self->dbh->{syb_dynamic_supported}) {
+        $self->ensure_class_loaded('DBIx::Class::Storage::DBI::Sybase::NoBindVars');
+        bless $self, 'DBIx::Class::Storage::DBI::Sybase::NoBindVars';
+        $self->_rebless;
+      }
+    }
+  }
+}
+
+=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;
+  shift =~ /(?:text|image|lob|bytea|binary)/i;
+}
+
+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->_update_blobs($source, $blob_cols, $to_insert) if %$blob_cols;
+
+  return $updated_cols;
+}
+
+#sub update {
+#  my ($self, $source) = splice @_, 0, 2;
+#  my ($fields)        = @_;
+#
+#  my $blob_cols = $self->_remove_blob_cols($source, $fields);
+#
+#  my @res = 1;
+#
+#  if (%$fields) {
+#    if (wantarray) {
+#      @res    = $self->next::method($source, @_);
+#    } else {
+#      $res[0] = $self->next::method($source, @_);
+#    }
+#  }
+#
+#  $self->_update_blobs($source, $blob_cols, $fields) if %$blob_cols;
+#
+#  return wantarray ? @res : $res[0];
+#}
+
+sub _remove_blob_cols {
+  my ($self, $source, $fields) = @_;
+
+  my %blob_cols;
+
+  for my $col (keys %$fields) {
+    $blob_cols{$col} = delete $fields->{$col}
+      if $self->_is_lob_type($source->column_info($col)->{data_type});
+  }
+
+  return \%blob_cols;
+}
+
+sub _update_blobs {
+  my ($self, $source, $blob_cols, $inserted) = @_;
+  my $dbh = $self->dbh;
+
+  my $table = $source->from;
+
+  my (@primary_cols) = $source->primary_columns;
+
+  croak "Cannot update TEXT/IMAGE without a primary key!"
+    unless @primary_cols;
+
+  my $search_cond = join ',' => map "$_ = ?", @primary_cols;
+
+  for my $col (keys %$blob_cols) {
+    my $blob = $blob_cols->{$col};
+
+# First update to empty string in case it's NULL, can't update a NULL blob using
+# the API.
+    my $sth = $dbh->prepare_cached(
+      qq{update $table set $col = '' where $search_cond}
+    );
+    $sth->execute(map $inserted->{$_}, @primary_cols) or die $sth->errstr;
+    $sth->finish;
+
+    $sth = $dbh->prepare_cached(
+      "select $col from $table where $search_cond"
+    );
+    $sth->execute(map $inserted->{$_}, @primary_cols);
+
+    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 = $dbh->prepare_cached("select max($col) from ".$source->from);
+  return ($dbh->selectrow_array($sth))[0];
 }
 
 1;
 
-=head1 NAME
-
-DBIx::Class::Storage::DBI::Sybase - Storage::DBI subclass for Sybase
+=head1 DATES
 
-=head1 SYNOPSIS
+See L</connect_call_datetime_setup> to setup date formats
+for L<DBIx::Class::InflateColumn::DateTime>.
 
-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>.
+=head1 IMAGE AND TEXT COLUMNS
 
-=head1 CAVEATS
+See L</connect_call_blob_setup> for a L<DBIx::Class::Storage::DBI/connect_info>
+setting you need to work with C<IMAGE> columns.
 
-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.
-
-More importantly this means that caching of prepared statements is explicitly
-disabled, as the interpolation renders it useless.
+Due to limitations in L<DBD::Sybase> and this driver, it is only possible to
+select one C<TEXT> or C<IMAGE> column at a time.
 
 =head1 AUTHORS
 
-Brandon L Black <blblack@gmail.com>
-
-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..fd27287 100644 (file)
@@ -6,6 +6,7 @@ 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';
 
@@ -29,11 +30,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..8c63d8c
--- /dev/null
@@ -0,0 +1,94 @@
+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 _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);
+  }
+
+## 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. You can check with:
+
+  $dbh->{syb_dynamic_supported}
+
+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..2eeeb11 100644 (file)
@@ -1,5 +1,6 @@
 use strict;
 use warnings;  
+no warnings 'uninitialized';
 
 use Test::More;
 use Test::Exception;
@@ -8,84 +9,176 @@ 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);
+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 => (27 + 2)*2;
+}
 
-plan tests => 13;
+my @storage_types = (
+  'DBI::Sybase',
+  'DBI::Sybase::NoBindVars',
+);
+my $schema;
 
-my $schema = DBICTest::Schema->connect($dsn, $user, $pass, {AutoCommit => 1});
+for my $storage_type (@storage_types) {
+  $schema = DBICTest::Schema->clone;
 
-# start disconnected to test reconnection
-$schema->storage->ensure_connected;
-$schema->storage->_dbh->disconnect;
+  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
+    ],
+  });
 
-isa_ok( $schema->storage, 'DBIx::Class::Storage::DBI::Sybase' );
+  $schema->storage->ensure_connected;
+  $schema->storage->_dbh->disconnect;
 
-my $dbh;
-lives_ok (sub {
-  $dbh = $schema->storage->dbh;
-}, 'reconnect works');
+  isa_ok( $schema->storage, "DBIx::Class::Storage::$storage_type" );
 
-$schema->storage->dbh_do (sub {
-    my ($storage, $dbh) = @_;
-    eval { $dbh->do("DROP TABLE artist") };
-    $dbh->do(<<'SQL');
+  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" );
 
-    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->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 stole the blob stuff Nniuq wrote for t/73oracle.t
+  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   PRIMARY KEY,
+        bytea INT   NULL,
+        blob  IMAGE NULL,
+        clob  TEXT  NULL
+      )
+    ],{ RaiseError => 1, PrintError => 1 });
+  }
+
+  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;
+
+  my $rs = $schema->resultset('BindType');
+  my $id = 0;
+
+  foreach my $type (qw(blob clob)) {
+    foreach my $size (qw(small large)) {
+      no warnings 'uninitialized';
+      $id++;
+
+      eval { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) };
+      ok(!$@, "inserted $size $type without dying");
+      diag $@ if $@;
+
+      my $got = eval {
+        $rs->search({ id=> $id }, { select => [$type] })->single->$type
+      };
+      diag $@ if $@;
+      ok($got eq $binstr{$size}, "verified inserted $size $type");
+    }
+  }
+
+  # try a blob update
+  TODO: {
+    local $TODO = 'updating TEXT/IMAGE does not work yet';
+
+    my $new_str = $binstr{large} . 'foo';
+    eval { $rs->search({ id => $id })->update({ blob => $new_str }) };
+    ok !$@, 'updated blob successfully';
+    diag $@ if $@;
+    ok(eval {
+      $rs->search({ id=> $id }, { select => ['blob'] })->single->blob
+    } eq $new_str, "verified updated blob" );
+    diag $@ if $@;
+  }
+}
 
 # 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');
+    $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');
+  }
+}