more work on multi-db_schema
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / Pg.pm
1 package DBIx::Class::Schema::Loader::DBI::Pg;
2
3 use strict;
4 use warnings;
5 use base qw/
6     DBIx::Class::Schema::Loader::DBI::Component::QuotedDefault
7     DBIx::Class::Schema::Loader::DBI
8 /;
9 use mro 'c3';
10 use DBIx::Class::Schema::Loader::Table ();
11
12 our $VERSION = '0.07010';
13
14 =head1 NAME
15
16 DBIx::Class::Schema::Loader::DBI::Pg - DBIx::Class::Schema::Loader::DBI
17 PostgreSQL Implementation.
18
19 =head1 DESCRIPTION
20
21 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
22
23 =cut
24
25 sub _setup {
26     my $self = shift;
27
28     $self->next::method(@_);
29
30     $self->{db_schema} ||= ['public'];
31
32     if (not defined $self->preserve_case) {
33         $self->preserve_case(0);
34     }
35     elsif ($self->preserve_case) {
36         $self->schema->storage->sql_maker->quote_char('"');
37         $self->schema->storage->sql_maker->name_sep('.');
38     }
39 }
40
41 sub _tables_list {
42     my ($self, $opts) = @_;
43
44     my $dbh = $self->schema->storage->dbh;
45
46     my @tables;
47
48     foreach my $schema (@{ $self->db_schema }) {
49         my @raw_tables = $dbh->tables(undef, $schema, '%', '%');
50
51         foreach my $table_name (@raw_tables) {
52             my $schema_quoted = $table_name =~ /^"/;
53
54             if ($schema_quoted) {
55                 $table_name =~ s/^"([^"]+)"\.//;
56             }
57             else {
58                 $table_name =~ s/^([^.]+)\.//;
59             }
60             my $table = DBIx::Class::Schema::Loader::Table->new(schema => $1);
61
62             $table_name =~ s/^"([^"]+)"\z/$1/;
63
64             $table->name($table_name);
65
66             push @tables, $table;
67         }
68     }
69
70     return $self->_filter_tables(\@tables, $opts);
71 }
72
73 sub _table_uniq_info {
74     my ($self, $table) = @_;
75
76     # Use the default support if available
77     return $self->next::method($table)
78         if $DBD::Pg::VERSION >= 1.50;
79
80     my @uniqs;
81     my $dbh = $self->schema->storage->dbh;
82
83     # Most of the SQL here is mostly based on
84     #   Rose::DB::Object::Metadata::Auto::Pg, after some prodding from
85     #   John Siracusa to use his superior SQL code :)
86
87     my $attr_sth = $self->{_cache}->{pg_attr_sth} ||= $dbh->prepare(
88         q{SELECT attname FROM pg_catalog.pg_attribute
89         WHERE attrelid = ? AND attnum = ?}
90     );
91
92     my $uniq_sth = $self->{_cache}->{pg_uniq_sth} ||= $dbh->prepare(
93         q{SELECT x.indrelid, i.relname, x.indkey
94         FROM
95           pg_catalog.pg_index x
96           JOIN pg_catalog.pg_class c ON c.oid = x.indrelid
97           JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
98           JOIN pg_catalog.pg_constraint con ON con.conname = i.relname
99           LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
100         WHERE
101           x.indisunique = 't' AND
102           c.relkind     = 'r' AND
103           i.relkind     = 'i' AND
104           con.contype   = 'u' AND
105           n.nspname     = ? AND
106           c.relname     = ?}
107     );
108
109     $uniq_sth->execute($table->schema, $table);
110     while(my $row = $uniq_sth->fetchrow_arrayref) {
111         my ($tableid, $indexname, $col_nums) = @$row;
112         $col_nums =~ s/^\s+//;
113         my @col_nums = split(/\s+/, $col_nums);
114         my @col_names;
115
116         foreach (@col_nums) {
117             $attr_sth->execute($tableid, $_);
118             my $name_aref = $attr_sth->fetchrow_arrayref;
119             push(@col_names, $name_aref->[0]) if $name_aref;
120         }
121
122         if(!@col_names) {
123             warn "Failed to parse UNIQUE constraint $indexname on $table";
124         }
125         else {
126             push(@uniqs, [ $indexname => \@col_names ]);
127         }
128     }
129
130     return \@uniqs;
131 }
132
133 sub _table_comment {
134     my ( $self, $table ) = @_;
135      my ($table_comment) = $self->schema->storage->dbh->selectrow_array(
136         q{SELECT obj_description(oid) 
137             FROM pg_class 
138             WHERE relname=? AND relnamespace=(
139                 SELECT oid FROM pg_namespace WHERE nspname=?)
140         }, undef, $table, $table->schema
141         );   
142     return $table_comment
143 }
144
145
146 sub _column_comment {
147     my ( $self, $table, $column_number ) = @_;
148      my ($table_oid) = $self->schema->storage->dbh->selectrow_array(
149         q{SELECT oid
150             FROM pg_class 
151             WHERE relname=? AND relnamespace=(
152                 SELECT oid FROM pg_namespace WHERE nspname=?)
153         }, undef, $table, $table->schema
154         );   
155     return $self->schema->storage->dbh->selectrow_array('SELECT col_description(?,?)', undef, $table_oid,
156     $column_number );
157 }
158
159 # Make sure data_type's that don't need it don't have a 'size' column_info, and
160 # set the correct precision for datetime and varbit types.
161 sub _columns_info_for {
162     my $self = shift;
163     my ($table) = @_;
164
165     my $result = $self->next::method(@_);
166
167     while (my ($col, $info) = each %$result) {
168         my $data_type = $info->{data_type};
169
170         # these types are fixed size
171         # XXX should this be a negative match?
172         if ($data_type =~
173 /^(?:bigint|int8|bigserial|serial8|boolean|bool|box|bytea|cidr|circle|date|double precision|float8|inet|integer|int|int4|line|lseg|macaddr|money|path|point|polygon|real|float4|smallint|int2|serial|serial4|text)\z/i) {
174             delete $info->{size};
175         }
176 # for datetime types, check if it has a precision or not
177         elsif ($data_type =~ /^(?:interval|time|timestamp)\b/i) {
178             if (lc($data_type) eq 'timestamp without time zone') {
179                 $info->{data_type} = 'timestamp';
180             }
181             elsif (lc($data_type) eq 'time without time zone') {
182                 $info->{data_type} = 'time';
183             }
184
185             my ($precision) = $self->schema->storage->dbh
186                 ->selectrow_array(<<EOF, {}, $table, $col);
187 SELECT datetime_precision
188 FROM information_schema.columns
189 WHERE table_name = ? and column_name = ?
190 EOF
191
192             if ($data_type =~ /^time\b/i) {
193                 if ((not $precision) || $precision !~ /^\d/) {
194                     delete $info->{size};
195                 }
196                 else {
197                     my ($integer_datetimes) = $self->schema->storage->dbh
198                         ->selectrow_array('show integer_datetimes');
199
200                     my $max_precision =
201                         $integer_datetimes =~ /^on\z/i ? 6 : 10;
202
203                     if ($precision == $max_precision) {
204                         delete $info->{size};
205                     }
206                     else {
207                         $info->{size} = $precision;
208                     }
209                 }
210             }
211             elsif ((not $precision) || $precision !~ /^\d/ || $precision == 6) {
212                 delete $info->{size};
213             }
214             else {
215                 $info->{size} = $precision;
216             }
217         }
218         elsif ($data_type =~ /^(?:bit(?: varying)?|varbit)\z/i) {
219             $info->{data_type} = 'varbit' if $data_type =~ /var/i;
220
221             my ($precision) = $self->schema->storage->dbh
222                 ->selectrow_array(<<EOF, {}, $table, $col);
223 SELECT character_maximum_length
224 FROM information_schema.columns
225 WHERE table_name = ? and column_name = ?
226 EOF
227
228             $info->{size} = $precision if $precision;
229
230             $info->{size} = 1 if (not $precision) && lc($data_type) eq 'bit';
231         }
232         elsif ($data_type =~ /^(?:numeric|decimal)\z/i && (my $size = $info->{size})) {
233             $size =~ s/\s*//g;
234
235             my ($scale, $precision) = split /,/, $size;
236
237             $info->{size} = [ $precision, $scale ];
238         }
239         elsif (lc($data_type) eq 'character varying') {
240             $info->{data_type} = 'varchar';
241
242             if (not $info->{size}) {
243                 $info->{data_type}           = 'text';
244                 $info->{original}{data_type} = 'varchar';
245             }
246         }
247         elsif (lc($data_type) eq 'character') {
248             $info->{data_type} = 'char';
249         }
250         else {
251             my ($typetype) = $self->schema->storage->dbh
252                 ->selectrow_array(<<EOF, {}, $data_type);
253 SELECT typtype
254 FROM pg_catalog.pg_type
255 WHERE typname = ?
256 EOF
257             if ($typetype && $typetype eq 'e') {
258                 # The following will extract a list of allowed values for the
259                 # enum.
260                 my $typevalues = $self->schema->storage->dbh
261                     ->selectall_arrayref(<<EOF, {}, $info->{data_type});
262 SELECT e.enumlabel
263 FROM pg_catalog.pg_enum e
264 JOIN pg_catalog.pg_type t ON t.oid = e.enumtypid
265 WHERE t.typname = ?
266 EOF
267
268                 $info->{extra}{list} = [ map { $_->[0] } @$typevalues ];
269
270                 # Store its original name in extra for SQLT to pick up.
271                 $info->{extra}{custom_type_name} = $info->{data_type};
272
273                 $info->{data_type} = 'enum';
274                 
275                 delete $info->{size};
276             }
277         }
278
279 # process SERIAL columns
280         if (ref($info->{default_value}) eq 'SCALAR'
281                 && ${ $info->{default_value} } =~ /\bnextval\('([^:]+)'/i) {
282             $info->{is_auto_increment} = 1;
283             $info->{sequence}          = $1;
284             delete $info->{default_value};
285         }
286
287 # alias now() to current_timestamp for deploying to other DBs
288         if ((eval { lc ${ $info->{default_value} } }||'') eq 'now()') {
289             # do not use a ref to a constant, that breaks Data::Dump output
290             ${$info->{default_value}} = 'current_timestamp';
291
292             my $now = 'now()';
293             $info->{original}{default_value} = \$now;
294         }
295     }
296
297     return $result;
298 }
299
300 =head1 SEE ALSO
301
302 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
303 L<DBIx::Class::Schema::Loader::DBI>
304
305 =head1 AUTHOR
306
307 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
308
309 =head1 LICENSE
310
311 This library is free software; you can redistribute it and/or modify it under
312 the same terms as Perl itself.
313
314 =cut
315
316 1;