Pg reverse-engineering fix: now sets default
[DBIx-DBSchema.git] / DBSchema / DBD / Pg.pm
index b41a98c..20bd721 100644 (file)
@@ -1,9 +1,16 @@
 package DBIx::DBSchema::DBD::Pg;
 
 use strict;
-use vars qw($VERSION);
+use vars qw($VERSION @ISA %typemap);
+use DBIx::DBSchema::DBD;
 
-$VERSION = '0.01';
+$VERSION = '0.05';
+@ISA = qw(DBIx::DBSchema::DBD);
+
+%typemap = (
+  'BLOB' => 'BYTEA',
+  'LONG VARBINARY' => 'BYTEA',
+);
 
 =head1 NAME
 
@@ -26,21 +33,49 @@ This module implements a PostgreSQL-native driver for DBIx::DBSchema.
 sub columns {
   my($proto, $dbh, $table) = @_;
   my $sth = $dbh->prepare(<<END) or die $dbh->errstr;
-    SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull
+    SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull,
+           a.atthasdef, a.attnum
     FROM pg_class c, pg_attribute a, pg_type t
     WHERE c.relname = '$table'
       AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid
+    ORDER BY a.attnum
 END
   $sth->execute or die $sth->errstr;
+
   map {
+
+    my $default = '';
+    if ( $_->{atthasdef} ) {
+      my $attnum = $_->{attnum};
+      my $d_sth = $dbh->prepare(<<END) or die $dbh->errstr;
+        SELECT substring(d.adsrc for 128) FROM pg_attrdef d, pg_class c
+        WHERE c.relname = '$table' AND c.oid = d.adrelid AND d.adnum = $attnum
+END
+      $d_sth->execute or die $d_sth->errstr;
+
+      $default = $d_sth->fetchrow_arrayref->[0];
+    };
+
+    my $len = '';
+    if ( $_->{attlen} == -1 && $_->{typname} ne 'text' ) {
+      $len = $_->{atttypmod} - 4;
+      if ( $_->{typname} eq 'numeric' ) {
+        $len = ($len >> 16). ','. ($len & 0xffff);
+      }
+    }
+
+    my $type = $_->{'typname'};
+    $type = 'char' if $type eq 'bpchar';
+
     [
       $_->{'attname'},
-      $_->{'typname'},
+      $type,
       ! $_->{'attnotnull'},
-      $_->{'attlen'} == -1
-        ? $_->{'atttypmod'} - 4
-        : ''
-    ]
+      $len,
+      $default,
+      ''  #local
+    ];
+
   } @{ $sth->fetchall_arrayref({}) };
 }
 
@@ -126,6 +161,8 @@ the same terms as Perl itself.
 
 Yes.
 
+columns doesn't return column default information.
+
 =head1 SEE ALSO
 
 L<DBIx::DBSchema>, L<DBIx::DBSchema::DBD>, L<DBI>, L<DBI::DBD>