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