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