1 package DBIx::Class::Schema::Loader::DBI::Pg;
5 use base 'DBIx::Class::Schema::Loader::DBI::Component::QuotedDefault';
8 our $VERSION = '0.07047';
12 DBIx::Class::Schema::Loader::DBI::Pg - DBIx::Class::Schema::Loader::DBI
13 PostgreSQL Implementation.
17 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
24 $self->next::method(@_);
26 $self->{db_schema} ||= ['public'];
28 if (not defined $self->preserve_case) {
29 $self->preserve_case(0);
31 elsif ($self->preserve_case) {
32 $self->schema->storage->sql_maker->quote_char('"');
33 $self->schema->storage->sql_maker->name_sep('.');
40 return ($self->next::method(@_), 'pg_catalog');
52 my ($self, $table) = @_;
54 my $sth = $self->dbh->prepare_cached(<<"EOF");
55 select constr.conname, to_ns.nspname, to_class.relname, from_col.attname, to_col.attname,
56 constr.confdeltype, constr.confupdtype, constr.condeferrable
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
62 -- can't do unnest() until 8.4, so join against a series table instead
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)
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]
71 where from_ns.nspname = ?
72 and from_class.relname = ?
73 and from_class.relkind = 'r'
74 and constr.contype = 'f'
75 order by constr.conname, colnum.i
78 $sth->execute($table->schema, $table->name);
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);
87 $rels{$fk}{remote_table} = DBIx::Class::Schema::Loader::Table->new(
89 name => $remote_table,
90 schema => $remote_schema,
91 ) unless exists $rels{$fk}{remote_table};
93 $rels{$fk}{attrs} ||= {
94 on_delete => $pg_rules{$delete_rule},
95 on_update => $pg_rules{$update_rule},
96 is_deferrable => $is_deferrable,
100 return [ map { $rels{$_} } sort keys %rels ];
104 sub _table_uniq_info {
105 my ($self, $table) = @_;
107 # Use the default support if available
108 return $self->next::method($table)
109 if $DBD::Pg::VERSION >= 1.50;
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 :)
117 my $attr_sth = $self->{_cache}->{pg_attr_sth} ||= $self->dbh->prepare(
118 q{SELECT attname FROM pg_catalog.pg_attribute
119 WHERE attrelid = ? AND attnum = ?}
122 my $uniq_sth = $self->{_cache}->{pg_uniq_sth} ||= $self->dbh->prepare(
123 q{SELECT x.indrelid, i.relname, x.indkey
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_namespace n ON n.oid = c.relnamespace
130 x.indisunique = 't' AND
131 x.indpred IS NULL AND
139 $uniq_sth->execute($table->schema, $table->name);
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);
146 foreach (@col_nums) {
147 $attr_sth->execute($tableid, $_);
148 my $name_aref = $attr_sth->fetchrow_arrayref;
149 push(@col_names, $self->_lc($name_aref->[0])) if $name_aref;
152 # skip indexes with missing column names (e.g. expression indexes)
153 if(@col_names == @col_nums) {
154 push(@uniqs, [ $indexname => \@col_names ]);
165 my $table_comment = $self->next::method(@_);
167 return $table_comment if $table_comment;
169 ($table_comment) = $self->dbh->selectrow_array(<<'EOF', {}, $table->name, $table->schema);
170 SELECT pg_catalog.obj_description(oid)
171 FROM pg_catalog.pg_class
172 WHERE relname=? AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=?)
175 return $table_comment
179 sub _column_comment {
181 my ($table, $column_number, $column_name) = @_;
183 my $column_comment = $self->next::method(@_);
185 return $column_comment if $column_comment;
187 return $self->dbh->selectrow_array(<<'EOF', {}, $column_number, $table->name, $table->schema);
188 SELECT pg_catalog.col_description(oid, ?)
189 FROM pg_catalog.pg_class
190 WHERE relname=? AND relnamespace=(SELECT oid FROM pg_catalog.pg_namespace WHERE nspname=?)
194 # Make sure data_type's that don't need it don't have a 'size' column_info, and
195 # set the correct precision for datetime and varbit types.
196 sub _columns_info_for {
200 my $result = $self->next::method(@_);
202 while (my ($col, $info) = each %$result) {
203 my $data_type = $info->{data_type};
205 # these types are fixed size
206 # XXX should this be a negative match?
208 /^(?: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) {
209 delete $info->{size};
211 # for datetime types, check if it has a precision or not
212 elsif ($data_type =~ /^(?:interval|time|timestamp)\b/i) {
213 if (lc($data_type) eq 'timestamp without time zone') {
214 $info->{data_type} = 'timestamp';
216 elsif (lc($data_type) eq 'time without time zone') {
217 $info->{data_type} = 'time';
220 my ($precision) = $self->schema->storage->dbh
221 ->selectrow_array(<<EOF, {}, $table->name, $col);
222 SELECT datetime_precision
223 FROM information_schema.columns
224 WHERE table_name = ? and column_name = ?
227 if ($data_type =~ /^time\b/i) {
228 if ((not defined $precision) || $precision !~ /^\d/) {
229 delete $info->{size};
232 my ($integer_datetimes) = $self->dbh
233 ->selectrow_array('show integer_datetimes');
236 $integer_datetimes =~ /^on\z/i ? 6 : 10;
238 if ($precision == $max_precision) {
239 delete $info->{size};
242 $info->{size} = $precision;
246 elsif ((not defined $precision) || $precision !~ /^\d/ || $precision == 6) {
247 delete $info->{size};
250 $info->{size} = $precision;
253 elsif ($data_type =~ /^(?:bit(?: varying)?|varbit)\z/i) {
254 $info->{data_type} = 'varbit' if $data_type =~ /var/i;
256 my ($precision) = $self->dbh->selectrow_array(<<EOF, {}, $table->name, $col);
257 SELECT character_maximum_length
258 FROM information_schema.columns
259 WHERE table_name = ? and column_name = ?
262 $info->{size} = $precision if $precision;
264 $info->{size} = 1 if (not $precision) && lc($data_type) eq 'bit';
266 elsif ($data_type =~ /^(?:numeric|decimal)\z/i && (my $size = $info->{size})) {
269 my ($scale, $precision) = split /,/, $size;
271 $info->{size} = [ $precision, $scale ];
273 elsif (lc($data_type) eq 'character varying') {
274 $info->{data_type} = 'varchar';
276 if (not $info->{size}) {
277 $info->{data_type} = 'text';
278 $info->{original}{data_type} = 'varchar';
281 elsif (lc($data_type) eq 'character') {
282 $info->{data_type} = 'char';
285 my ($typetype) = $self->schema->storage->dbh
286 ->selectrow_array(<<EOF, {}, $data_type);
288 FROM pg_catalog.pg_type
289 WHERE oid = ?::regtype
291 if ($typetype && $typetype eq 'e') {
292 # The following will extract a list of allowed values for the enum.
293 my $order_column = $self->dbh->{pg_server_version} >= 90100 ? 'enumsortorder' : 'oid';
294 $info->{extra}{list} = $self->dbh
295 ->selectcol_arrayref(<<EOF, {}, $data_type);
297 FROM pg_catalog.pg_enum e
298 WHERE e.enumtypid = ?::regtype
299 ORDER BY e.$order_column
302 # Store its original name in extra for SQLT to pick up.
303 $info->{extra}{custom_type_name} = $data_type;
305 $info->{data_type} = 'enum';
307 delete $info->{size};
311 if (ref($info->{default_value}) eq 'SCALAR') {
312 # process SERIAL columns
313 if (${ $info->{default_value} } =~ /\bnextval\('([^:]+)'/i) {
314 $info->{is_auto_increment} = 1;
315 $info->{sequence} = $1;
316 delete $info->{default_value};
318 # alias now() to current_timestamp for deploying to other DBs
319 elsif (lc ${ $info->{default_value} } eq 'now()') {
320 # do not use a ref to a constant, that breaks Data::Dump output
321 ${$info->{default_value}} = 'current_timestamp';
324 $info->{original}{default_value} = \$now;
326 elsif (${ $info->{default_value} } =~ /\bCURRENT_TIMESTAMP\b/) {
327 # PostgreSQL v10 upcases current_timestamp in default values
328 ${ $info->{default_value} } =~ s/\b(CURRENT_TIMESTAMP)\b/lc $1/ge;
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') {
336 $info->{default_value} = \$false;
338 elsif ($info->{default_value} eq '1') {
340 $info->{default_value} = \$true;
348 sub _view_definition {
349 my ($self, $view) = @_;
351 my $def = $self->schema->storage->dbh->selectrow_array(<<'EOF', {}, $view->schema, $view->name);
352 SELECT pg_catalog.pg_get_viewdef(oid)
353 FROM pg_catalog.pg_class
354 WHERE relnamespace = (SELECT OID FROM pg_catalog.pg_namespace WHERE nspname = ?)
357 # The definition is returned as a complete statement including the
358 # trailing semicolon, but that's not allowed in CREATE VIEW, so
360 $def =~ s/\s*;\s*\z//;
366 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
367 L<DBIx::Class::Schema::Loader::DBI>
371 See L<DBIx::Class::Schema::Loader/AUTHORS>.
375 This library is free software; you can redistribute it and/or modify it under
376 the same terms as Perl itself.