Fix dumping unique indexes with DBD::Pg < 1.50
[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 'DBIx::Class::Schema::Loader::DBI::Component::QuotedDefault';
6 use mro 'c3';
7
8 our $VERSION = '0.07039';
9
10 =head1 NAME
11
12 DBIx::Class::Schema::Loader::DBI::Pg - DBIx::Class::Schema::Loader::DBI
13 PostgreSQL Implementation.
14
15 =head1 DESCRIPTION
16
17 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
18
19 =cut
20
21 sub _setup {
22     my $self = shift;
23
24     $self->next::method(@_);
25
26     $self->{db_schema} ||= ['public'];
27
28     if (not defined $self->preserve_case) {
29         $self->preserve_case(0);
30     }
31     elsif ($self->preserve_case) {
32         $self->schema->storage->sql_maker->quote_char('"');
33         $self->schema->storage->sql_maker->name_sep('.');
34     }
35 }
36
37 sub _system_schemas {
38     my $self = shift;
39
40     return ($self->next::method(@_), 'pg_catalog');
41 }
42
43 my %pg_rules = (
44     a => 'NO ACTION',
45     r => 'RESTRICT',
46     c => 'CASCADE',
47     n => 'SET NULL',
48     d => 'SET DEFAULT',
49 );
50
51 sub _table_fk_info {
52     my ($self, $table) = @_;
53
54     my $sth = $self->dbh->prepare_cached(<<"EOF");
55       select constr.conname, to_ns.nspname, to_class.relname, from_col.attname, to_col.attname,
56              constr.confdeltype, constr.confupdtype, constr.condeferrable
57       from pg_catalog.pg_constraint constr
58       join pg_catalog.pg_namespace from_ns on constr.connamespace = from_ns.oid
59       join pg_catalog.pg_class from_class on constr.conrelid = from_class.oid and from_class.relnamespace = from_ns.oid
60       join pg_catalog.pg_class to_class on constr.confrelid = to_class.oid
61       join pg_catalog.pg_namespace to_ns on to_class.relnamespace = to_ns.oid
62       -- can't do unnest() until 8.4, so join against a series table instead
63       join pg_catalog.generate_series(1, pg_catalog.current_setting('max_index_keys')::integer) colnum(i)
64            on colnum.i <= pg_catalog.array_upper(constr.conkey,1)
65       join pg_catalog.pg_attribute to_col
66            on to_col.attrelid = constr.confrelid
67            and to_col.attnum = constr.confkey[colnum.i]
68       join pg_catalog.pg_attribute from_col
69            on from_col.attrelid = constr.conrelid
70            and from_col.attnum = constr.conkey[colnum.i]
71       where from_ns.nspname = ?
72         and from_class.relname = ?
73         and from_class.relkind = 'r'
74         and constr.contype = 'f'
75       order by constr.conname, colnum.i
76 EOF
77
78     $sth->execute($table->schema, $table->name);
79
80     my %rels;
81
82     while (my ($fk, $remote_schema, $remote_table, $col, $remote_col,
83                $delete_rule, $update_rule, $is_deferrable) = $sth->fetchrow_array) {
84         push @{ $rels{$fk}{local_columns}  }, $self->_lc($col);
85         push @{ $rels{$fk}{remote_columns} }, $self->_lc($remote_col);
86
87         $rels{$fk}{remote_table} = DBIx::Class::Schema::Loader::Table->new(
88             loader   => $self,
89             name     => $remote_table,
90             schema   => $remote_schema,
91         ) unless exists $rels{$fk}{remote_table};
92
93         $rels{$fk}{attrs} ||= {
94             on_delete     => $pg_rules{$delete_rule},
95             on_update     => $pg_rules{$update_rule},
96             is_deferrable => $is_deferrable,
97         };
98     }
99
100     return [ map { $rels{$_} } sort keys %rels ];
101 }
102
103
104 sub _table_uniq_info {
105     my ($self, $table) = @_;
106
107     # Use the default support if available
108     return $self->next::method($table)
109         if $DBD::Pg::VERSION >= 1.50;
110
111     my @uniqs;
112
113     # Most of the SQL here is mostly based on
114     #   Rose::DB::Object::Metadata::Auto::Pg, after some prodding from
115     #   John Siracusa to use his superior SQL code :)
116
117     my $attr_sth = $self->{_cache}->{pg_attr_sth} ||= $self->dbh->prepare(
118         q{SELECT attname FROM pg_catalog.pg_attribute
119         WHERE attrelid = ? AND attnum = ?}
120     );
121
122     my $uniq_sth = $self->{_cache}->{pg_uniq_sth} ||= $self->dbh->prepare(
123         q{SELECT x.indrelid, i.relname, x.indkey
124         FROM
125           pg_catalog.pg_index x
126           JOIN pg_catalog.pg_class c ON c.oid = x.indrelid
127           JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
128           JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
129         WHERE
130           x.indisunique = 't' AND
131           x.indpred     IS NULL AND
132           c.relkind     = 'r' AND
133           i.relkind     = 'i' AND
134           n.nspname     = ? AND
135           c.relname     = ?}
136     );
137
138     $uniq_sth->execute($table->schema, $table->name);
139     while(my $row = $uniq_sth->fetchrow_arrayref) {
140         my ($tableid, $indexname, $col_nums) = @$row;
141         $col_nums =~ s/^\s+//;
142         my @col_nums = split(/\s+/, $col_nums);
143         my @col_names;
144
145         foreach (@col_nums) {
146             $attr_sth->execute($tableid, $_);
147             my $name_aref = $attr_sth->fetchrow_arrayref;
148             push(@col_names, $self->_lc($name_aref->[0])) if $name_aref;
149         }
150
151         # skip indexes with missing column names (e.g. expression indexes)
152         if(@col_names == @col_nums) {
153             push(@uniqs, [ $indexname => \@col_names ]);
154         }
155     }
156
157     return \@uniqs;
158 }
159
160 sub _table_comment {
161     my $self = shift;
162     my ($table) = @_;
163
164     my $table_comment = $self->next::method(@_);
165
166     return $table_comment if $table_comment;
167
168     ($table_comment) = $self->dbh->selectrow_array(<<'EOF', {}, $table->name, $table->schema);
169 SELECT pg_catalog.obj_description(oid)
170 FROM pg_catalog.pg_class
171 WHERE relname=? AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=?)
172 EOF
173
174     return $table_comment
175 }
176
177
178 sub _column_comment {
179     my $self = shift;
180     my ($table, $column_number, $column_name) = @_;
181
182     my $column_comment = $self->next::method(@_);
183
184     return $column_comment if $column_comment;
185
186     my ($table_oid) = $self->dbh->selectrow_array(<<'EOF', {}, $table->name, $table->schema);
187 SELECT oid
188 FROM pg_catalog.pg_class
189 WHERE relname=? AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=?)
190 EOF
191
192     return $self->dbh->selectrow_array('SELECT pg_catalog.col_description(?,?)', {}, $table_oid, $column_number);
193 }
194
195 # Make sure data_type's that don't need it don't have a 'size' column_info, and
196 # set the correct precision for datetime and varbit types.
197 sub _columns_info_for {
198     my $self = shift;
199     my ($table) = @_;
200
201     my $result = $self->next::method(@_);
202
203     while (my ($col, $info) = each %$result) {
204         my $data_type = $info->{data_type};
205
206         # these types are fixed size
207         # XXX should this be a negative match?
208         if ($data_type =~
209 /^(?:bigint|int8|bigserial|serial8|bool(?:ean)?|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) {
210             delete $info->{size};
211         }
212 # for datetime types, check if it has a precision or not
213         elsif ($data_type =~ /^(?:interval|time|timestamp)\b/i) {
214             if (lc($data_type) eq 'timestamp without time zone') {
215                 $info->{data_type} = 'timestamp';
216             }
217             elsif (lc($data_type) eq 'time without time zone') {
218                 $info->{data_type} = 'time';
219             }
220
221             my ($precision) = $self->schema->storage->dbh
222                 ->selectrow_array(<<EOF, {}, $table->name, $col);
223 SELECT datetime_precision
224 FROM information_schema.columns
225 WHERE table_name = ? and column_name = ?
226 EOF
227
228             if ($data_type =~ /^time\b/i) {
229                 if ((not $precision) || $precision !~ /^\d/) {
230                     delete $info->{size};
231                 }
232                 else {
233                     my ($integer_datetimes) = $self->dbh
234                         ->selectrow_array('show integer_datetimes');
235
236                     my $max_precision =
237                         $integer_datetimes =~ /^on\z/i ? 6 : 10;
238
239                     if ($precision == $max_precision) {
240                         delete $info->{size};
241                     }
242                     else {
243                         $info->{size} = $precision;
244                     }
245                 }
246             }
247             elsif ((not $precision) || $precision !~ /^\d/ || $precision == 6) {
248                 delete $info->{size};
249             }
250             else {
251                 $info->{size} = $precision;
252             }
253         }
254         elsif ($data_type =~ /^(?:bit(?: varying)?|varbit)\z/i) {
255             $info->{data_type} = 'varbit' if $data_type =~ /var/i;
256
257             my ($precision) = $self->dbh->selectrow_array(<<EOF, {}, $table->name, $col);
258 SELECT character_maximum_length
259 FROM information_schema.columns
260 WHERE table_name = ? and column_name = ?
261 EOF
262
263             $info->{size} = $precision if $precision;
264
265             $info->{size} = 1 if (not $precision) && lc($data_type) eq 'bit';
266         }
267         elsif ($data_type =~ /^(?:numeric|decimal)\z/i && (my $size = $info->{size})) {
268             $size =~ s/\s*//g;
269
270             my ($scale, $precision) = split /,/, $size;
271
272             $info->{size} = [ $precision, $scale ];
273         }
274         elsif (lc($data_type) eq 'character varying') {
275             $info->{data_type} = 'varchar';
276
277             if (not $info->{size}) {
278                 $info->{data_type}           = 'text';
279                 $info->{original}{data_type} = 'varchar';
280             }
281         }
282         elsif (lc($data_type) eq 'character') {
283             $info->{data_type} = 'char';
284         }
285         else {
286             my ($typetype) = $self->schema->storage->dbh
287                 ->selectrow_array(<<EOF, {}, $data_type);
288 SELECT typtype
289 FROM pg_catalog.pg_type
290 WHERE typname = ?
291 EOF
292             if ($typetype && $typetype eq 'e') {
293                 # The following will extract a list of allowed values for the
294                 # enum.
295                 my $order_column = $self->dbh->{pg_server_version} >= 90100 ? 'enumsortorder' : 'oid';
296                 my $typevalues = $self->dbh
297                     ->selectall_arrayref(<<EOF, {}, $info->{data_type});
298 SELECT e.enumlabel
299 FROM pg_catalog.pg_enum e
300 JOIN pg_catalog.pg_type t ON t.oid = e.enumtypid
301 WHERE t.typname = ?
302 ORDER BY e.$order_column
303 EOF
304
305                 $info->{extra}{list} = [ map { $_->[0] } @$typevalues ];
306
307                 # Store its original name in extra for SQLT to pick up.
308                 $info->{extra}{custom_type_name} = $info->{data_type};
309
310                 $info->{data_type} = 'enum';
311
312                 delete $info->{size};
313             }
314         }
315
316 # process SERIAL columns
317         if (ref($info->{default_value}) eq 'SCALAR'
318                 && ${ $info->{default_value} } =~ /\bnextval\('([^:]+)'/i) {
319             $info->{is_auto_increment} = 1;
320             $info->{sequence}          = $1;
321             delete $info->{default_value};
322         }
323
324 # alias now() to current_timestamp for deploying to other DBs
325         if ((eval { lc ${ $info->{default_value} } }||'') eq 'now()') {
326             # do not use a ref to a constant, that breaks Data::Dump output
327             ${$info->{default_value}} = 'current_timestamp';
328
329             my $now = 'now()';
330             $info->{original}{default_value} = \$now;
331         }
332
333 # detect 0/1 for booleans and rewrite
334         if ($data_type =~ /^bool/i && exists $info->{default_value}) {
335             if ($info->{default_value} eq '0') {
336                 my $false = 'false';
337                 $info->{default_value} = \$false;
338             }
339             elsif ($info->{default_value} eq '1') {
340                 my $true = 'true';
341                 $info->{default_value} = \$true;
342             }
343         }
344     }
345
346     return $result;
347 }
348
349 =head1 SEE ALSO
350
351 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
352 L<DBIx::Class::Schema::Loader::DBI>
353
354 =head1 AUTHOR
355
356 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
357
358 =head1 LICENSE
359
360 This library is free software; you can redistribute it and/or modify it under
361 the same terms as Perl itself.
362
363 =cut
364
365 1;