woops, pg search path fix needed support for quoted schema names in search paths
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / Storage / DBI / Pg.pm
index f53de4b..2e516fd 100644 (file)
@@ -9,7 +9,7 @@ use mro 'c3';
 use DBD::Pg qw(:pg_types);
 
 # Ask for a DBD::Pg with array support
-warn "DBD::Pg 2.9.2 or greater is strongly recommended"
+warn "DBD::Pg 2.9.2 or greater is strongly recommended\n"
   if ($DBD::Pg::VERSION < 2.009002);  # pg uses (used?) version::qv()
 
 sub with_deferred_fk_checks {
@@ -36,21 +36,47 @@ sub last_insert_id {
 sub _dbh_get_autoinc_seq {
   my ($self, $dbh, $schema, $table, @pri) = @_;
 
-  while (my $col = shift @pri) {
-    my $info = $dbh->column_info(undef,$schema,$table,$col)->fetchrow_hashref;
-    if(defined $info->{COLUMN_DEF} and
-       $info->{COLUMN_DEF} =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/) {
-      my $seq = $1;
-      # may need to strip quotes -- see if this works
-      return $seq =~ /\./ ? $seq : $info->{TABLE_SCHEM} . "." . $seq;
-    }
+  # get the list of postgres schemas to search.  if we have a schema
+  # specified, use that.  otherwise, use the search path
+  my @search_path;
+  if( defined $schema and length $schema ) {
+      @search_path = ( $schema );
+  } else {
+      my ($search_path) = $dbh->selectrow_array('SHOW search_path');
+      while( $search_path =~ s/("[^"]+"|[^,]+),?// ) {
+          unless( defined $1 and length $1 ) {
+              $self->throw_exception("search path sanity check failed: '$1'")
+          }
+          push @search_path, $1;
+      }
+  }
+
+  foreach my $search_schema (@search_path) {
+      foreach my $col (@pri) {
+          my $info = $dbh->column_info(undef,$search_schema,$table,$col)->fetchrow_hashref;
+          if($info) {
+              # if we get here, we have definitely found the right
+              # column.
+              if( defined $info->{COLUMN_DEF} and
+                  $info->{COLUMN_DEF}
+                    =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i
+                ) {
+                  my $seq = $1;
+                  return $seq =~ /\./ ? $seq : $info->{TABLE_SCHEM} . "." . $seq;
+              } else {
+                  # we have found the column, but cannot figure out
+                  # the nextval seq
+                  return;
+              }
+          }
+      }
   }
   return;
 }
 
 sub get_autoinc_seq {
   my ($self,$source,$col) = @_;
-    
+
   my @pri = $source->primary_columns;
   my ($schema,$table) = $source->name =~ /^(.+)\.(.+)$/ ? ($1,$2)
     : (undef,$source->name);
@@ -71,7 +97,7 @@ sub bind_attribute_by_data_type {
     bytea => { pg_type => DBD::Pg::PG_BYTEA },
     blob  => { pg_type => DBD::Pg::PG_BYTEA },
   };
+
   if( defined $bind_attributes->{$data_type} ) {
     return $bind_attributes->{$data_type};
   }