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