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