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