take out duplicate docs
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Parser / DBI / PostgreSQL.pm
1 package SQL::Translator::Parser::DBI::PostgreSQL;
2
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 # 02111-1307  USA
19 # -------------------------------------------------------------------
20
21 =head1 NAME
22
23 SQL::Translator::Parser::DBI::PostgreSQL - parser for DBD::Pg
24
25 =head1 SYNOPSIS
26
27 See SQL::Translator::Parser::DBI.
28
29 =head1 DESCRIPTION
30
31 Uses DBI to query PostgreSQL system tables to determine schema structure.
32
33 =cut
34
35 use strict;
36 use DBI;
37 use Data::Dumper;
38 use SQL::Translator::Schema::Constants;
39
40 use vars qw[ $DEBUG $VERSION @EXPORT_OK ];
41 $VERSION = '1.59';
42 $DEBUG   = 0 unless defined $DEBUG;
43
44 my $actions = {c => 'cascade',
45                r => 'restrict',
46                a => 'no action',
47                n => 'set null',
48                d => 'set default',
49            };
50
51 sub parse {
52     my ( $tr, $dbh ) = @_;
53
54     my $schema = $tr->schema;
55
56     my $column_select = $dbh->prepare(
57       "SELECT a.attname, format_type(t.oid, a.atttypmod) as typname, a.attnum,
58               a.atttypmod as length, a.attnotnull, a.atthasdef, ad.adsrc,
59               d.description
60        FROM pg_type t, pg_attribute a
61        LEFT JOIN pg_attrdef ad ON (ad.adrelid = a.attrelid AND a.attnum = ad.adnum)
62        LEFT JOIN pg_description d ON (a.attrelid=d.objoid AND a.attnum=d.objsubid)
63        WHERE a.attrelid=? AND attnum>0
64          AND a.atttypid=t.oid
65        ORDER BY a.attnum"
66     );
67
68     my $index_select  = $dbh->prepare(
69       "SELECT oid, c.relname, i.indkey, i.indnatts, i.indisunique,
70               ARRAY(SELECT a.attname
71                   FROM pg_attribute a
72                   WHERE a.attrelid=i.indrelid AND a.attnum = ANY(i.indkey)
73               ) AS attname,
74               i.indisprimary, pg_get_indexdef(oid) AS create_string
75        FROM pg_class c,pg_index i
76        WHERE c.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname='public') AND c.relkind='i'
77          AND c.oid=i.indexrelid AND i.indrelid=?"
78     );
79
80     my $table_select  = $dbh->prepare(
81       "SELECT c.oid, c.relname, d.description
82        FROM pg_class c
83        LEFT JOIN pg_description d ON c.oid=d.objoid AND d.objsubid=0
84        WHERE relnamespace IN
85           (SELECT oid FROM pg_namespace WHERE nspname='public')
86           AND relkind='r';"
87     );
88
89     my $fk_select = $dbh->prepare(
90         q/
91 SELECT r.conname,
92        c.relname,
93        d.relname AS frelname,
94        r.conkey,
95        ARRAY(SELECT column_name::varchar
96                FROM information_schema.columns
97               WHERE ordinal_position = ANY  (r.conkey)
98                 AND table_schema = n.nspname
99                 AND table_name   =   c.relname ) AS fields,
100        r.confkey,
101        ARRAY(SELECT column_name::varchar
102                FROM information_schema.columns
103               WHERE ordinal_position = ANY  (r.confkey)
104                 AND table_schema =   n.nspname
105                 AND table_name   =   d.relname ) AS reference_fields,
106        r.confupdtype,
107        r.confdeltype,
108        r.confmatchtype
109
110 FROM pg_catalog.pg_constraint r
111
112 JOIN pg_catalog.pg_class c
113   ON c.oid = r.conrelid
114  AND r.contype = 'f'
115
116 JOIN pg_catalog.pg_class d
117   ON d.oid = r.confrelid
118
119 JOIN pg_catalog.pg_namespace n
120   ON n.oid = c.relnamespace
121
122 WHERE pg_catalog.pg_table_is_visible(c.oid)
123   AND n.nspname = ?
124   AND c.relname = ?
125 ORDER BY 1;
126         /) or die "Can't prepare: $@";
127
128     $table_select->execute();
129
130     while ( my $tablehash = $table_select->fetchrow_hashref ) {
131
132         my $table_name = $$tablehash{'relname'};
133         my $table_oid  = $$tablehash{'oid'};
134         my $table = $schema->add_table(
135                                        name => $table_name,
136               #what is type?               type => $table_info->{TABLE_TYPE},
137                                           ) || die $schema->error;
138
139         $table->comments($$tablehash{'description'}) if $$tablehash{'description'};
140
141         $column_select->execute($table_oid);
142
143         while (my $columnhash = $column_select->fetchrow_hashref ) {
144
145             #data_type seems to not be populated; perhaps there needs to
146             #be a mapping of query output to reserved constants in sqlt?
147
148             my $col = $table->add_field(
149                               name        => $$columnhash{'attname'},
150                               default_value => $$columnhash{'adsrc'},
151                               data_type   => $$columnhash{'typname'},
152                               order       => $$columnhash{'attnum'},
153                              ) || die $table->error;
154
155             $col->{size} = [$$columnhash{'length'}]
156                 if $$columnhash{'length'}>0 && $$columnhash{'length'}<=0xFFFF;
157             $col->{is_nullable} = $$columnhash{'attnotnull'} ? 0 : 1;
158             $col->comments($$columnhash{'description'}) if $$columnhash{'description'};
159         }
160
161         $index_select->execute($table_oid);
162
163         my @column_names = $table->field_names();
164         while (my $indexhash = $index_select->fetchrow_hashref ) {
165               #don't deal with function indexes at the moment
166             next if ($$indexhash{'indkey'} eq ''
167                      or !defined($$indexhash{'indkey'}) );
168
169             my $type;
170             if      ($$indexhash{'indisprimary'}) {
171                 $type = UNIQUE; #PRIMARY_KEY;
172
173                 #tell sqlt that this is the primary key:
174                 my $col_name=$column_names[($$indexhash{'indkey'} - 1)];
175                 $table->get_field($col_name)->{is_primary_key}=1;
176
177             } elsif ($$indexhash{'indisunique'}) {
178                 $type = UNIQUE;
179             } else {
180                 $type = NORMAL;
181             }
182
183
184             my @column_ids = split /\s+/, $$indexhash{'indkey'};
185             my @columns = split /\s+/, $$indexhash{'attname'};
186
187             $table->add_index(
188                               name         => $$indexhash{'relname'},
189                               type         => $type,
190                               fields       => \@columns,
191                              ) || die $table->error;
192         }
193
194         $fk_select->execute('public',$table_name) or die "Can't execute: $@";
195         my $fkeys = $fk_select->fetchall_arrayref({});
196         $DEBUG and print Dumper $fkeys;
197         for my $con (@$fkeys){
198             my $con_name         = $con->{conname};
199             my $fields           = $con->{fields};
200             my $reference_fields = $con->{reference_fields};
201             my $reference_table  = $con->{frelname};
202             my $on_upd           = $con->{confupdtype};
203             my $on_del           = $con->{confdeltype};
204             $table->add_constraint(
205                                    name   => $con_name,
206                                    type   => 'foreign_key',
207                                    fields =>  $fields,
208                                    reference_fields => $reference_fields,
209                                    reference_table => $reference_table,
210                                    on_delete  => $actions->{$on_upd},
211                                    on_update  => $actions->{$on_del},
212                                );
213         }
214     }
215
216
217     return 1;
218 }
219
220 1;
221
222 # -------------------------------------------------------------------
223 # Time is a waste of money.
224 # Oscar Wilde
225 # -------------------------------------------------------------------
226
227 =pod
228
229 =head1 AUTHOR
230
231 Scott Cain E<lt>cain@cshl.eduE<gt>, previous author:
232 Paul Harrington E<lt>harringp@deshaw.comE<gt>.
233
234 =head1 SEE ALSO
235
236 SQL::Translator, DBD::Pg.
237
238 =cut