commit the version bump + Changes update for 0.03009
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / Pg.pm
1 package DBIx::Class::Schema::Loader::DBI::Pg;
2
3 use strict;
4 use warnings;
5 use base 'DBIx::Class::Schema::Loader::DBI';
6 use Carp::Clan qw/^DBIx::Class/;
7 use Class::C3;
8
9 =head1 NAME
10
11 DBIx::Class::Schema::Loader::DBI::Pg - DBIx::Class::Schema::Loader::DBI
12 PostgreSQL Implementation.
13
14 =head1 SYNOPSIS
15
16   package My::Schema;
17   use base qw/DBIx::Class::Schema::Loader/;
18
19   __PACKAGE__->loader_options(
20     relationships => 1,
21   );
22
23   1;
24
25 =head1 DESCRIPTION
26
27 See L<DBIx::Class::Schema::Loader::Base>.
28
29 =cut
30
31 sub _setup {
32     my $self = shift;
33
34     $self->next::method(@_);
35     $self->{db_schema} ||= 'public';
36 }
37
38 sub _table_uniq_info {
39     my ($self, $table) = @_;
40
41     my @uniqs;
42     my $dbh = $self->schema->storage->dbh;
43
44     # Most of the SQL here is mostly based on
45     #   Rose::DB::Object::Metadata::Auto::Pg, after some prodding from
46     #   John Siracusa to use his superior SQL code :)
47
48     my $attr_sth = $self->{_cache}->{pg_attr_sth} ||= $dbh->prepare(
49         q{SELECT attname FROM pg_catalog.pg_attribute
50         WHERE attrelid = ? AND attnum = ?}
51     );
52
53     my $uniq_sth = $self->{_cache}->{pg_uniq_sth} ||= $dbh->prepare(
54         q{SELECT x.indrelid, i.relname, x.indkey
55         FROM
56           pg_catalog.pg_index x
57           JOIN pg_catalog.pg_class c ON c.oid = x.indrelid
58           JOIN pg_catalog.pg_class i ON i.oid = x.indexrelid
59           JOIN pg_catalog.pg_constraint con ON con.conname = i.relname
60           LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
61         WHERE
62           x.indisunique = 't' AND
63           c.relkind     = 'r' AND
64           i.relkind     = 'i' AND
65           con.contype   = 'u' AND
66           n.nspname     = ? AND
67           c.relname     = ?}
68     );
69
70     $uniq_sth->execute($self->db_schema, $table);
71     while(my $row = $uniq_sth->fetchrow_arrayref) {
72         my ($tableid, $indexname, $col_nums) = @$row;
73         $col_nums =~ s/^\s+//;
74         my @col_nums = split(/\s+/, $col_nums);
75         my @col_names;
76
77         foreach (@col_nums) {
78             $attr_sth->execute($tableid, $_);
79             my $name_aref = $attr_sth->fetchrow_arrayref;
80             push(@col_names, $name_aref->[0]) if $name_aref;
81         }
82
83         if(!@col_names) {
84             warn "Failed to parse UNIQUE constraint $indexname on $table";
85         }
86         else {
87             push(@uniqs, [ $indexname => \@col_names ]);
88         }
89     }
90
91     return \@uniqs;
92 }
93
94 =head1 SEE ALSO
95
96 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
97 L<DBIx::Class::Schema::Loader::DBI>
98
99 =cut
100
101 1;