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