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