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