Merge 'trunk' into 'mssql_top_fixes'
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / ODBC / Microsoft_SQL_Server.pm
index 8fa8fe4..544e68c 100644 (file)
@@ -6,7 +6,34 @@ use base qw/DBIx::Class::Storage::DBI::MSSQL/;
 
 sub insert_bulk {
   my ($self, $source, $cols, $data) = @_;
+
+  my $identity_insert = 0;
+
+  COLUMNS:
+  foreach my $col (@{$cols}) {
+    if ($source->column_info($col)->{is_auto_increment}) {
+      $identity_insert = 1;
+      last COLUMNS;
+    }
+  }
+
+  my $table = $source->from;
+  if ($identity_insert) {
+    $source->storage->dbh_do(sub {
+       my ($storage, $dbh, @cols) = @_;
+       $dbh->do("SET IDENTITY_INSERT $table ON;");
+      });
+  }
+
   next::method(@_);
+
+  if ($identity_insert) {
+    $source->storage->dbh_do(sub {
+       my ($storage, $dbh, @cols) = @_;
+       $dbh->do("SET IDENTITY_INSERT $table OFF;");
+      });
+  }
+
 }
 
 sub _prep_for_execute {
@@ -17,13 +44,13 @@ sub _prep_for_execute {
   $sql .= ';SELECT SCOPE_IDENTITY()' if $op eq 'insert';
 
   my %identity_insert_tables;
-  my $col_sources = $self->_resolve_column_sources($ident, [map $_->[0], @{$bind}]);
+  my $col_info = $self->_resolve_column_info($ident, [map $_->[0], @{$bind}]);
 
   foreach my $bound (@{$bind}) {
     my $col = $bound->[0];
-    my $rsrc = $col_sources->{$col};
-    if ($rsrc && $rsrc->column_info($col)->{is_auto_increment}) {
-      $identity_insert_tables{$rsrc->from} = 1;
+    if ($col_info->{$col}->{is_auto_increment}) {
+      my $table = $col_info->{$col}->{-result_source}->from;
+      $identity_insert_tables{$table} = 1;
     }
   }