File Coverage

blib/lib/SQL/Translator/Parser/DBI/PostgreSQL.pm
Criterion Covered Total %
statement 15 82 18.2
branch 0 36 0.0
condition 0 10 0.0
subroutine 5 6 83.3
pod 0 1 0.0
total 20 135 14.8


line stmt bran cond sub pod time code
1             package SQL::Translator::Parser::DBI::PostgreSQL;
2              
3             =head1 NAME
4              
5             SQL::Translator::Parser::DBI::PostgreSQL - parser for DBD::Pg
6              
7             =head1 SYNOPSIS
8              
9             See SQL::Translator::Parser::DBI.
10              
11             =head1 DESCRIPTION
12              
13             Uses DBI to query PostgreSQL system tables to determine schema structure.
14              
15             =head1 CONFIGURATION
16              
17             You can specify the following for L :
18              
19             =head2 deconstruct_enum_types
20              
21             If set to a true value, the parser will look for column types which are user-defined Enums,
22             and generate a column definition like:
23              
24             {
25             data_type => 'enum',
26             extra => {
27             custom_type_name => 'MyEnumType',
28             list => [ 'enum_val_1', 'enum_val_2', ... ],
29             }
30             }
31              
32             This makes a proper round-trip with SQL::Translator::Producer::PostgreSQL (which re-creates the
33             custom enum type if C<< producer_args->{postgres_version} >= 8.003 >>) and can be translated to
34             other engines.
35              
36             If the option is false (the default) you would just get
37              
38             { data_type => 'MyEnumType' }
39              
40             with no provided method to translate it to other SQL engines.
41              
42             =cut
43              
44 1     1   10 use strict;
  1         3  
  1         73  
45 1     1   8 use warnings;
  1         3  
  1         82  
46 1     1   8 use DBI;
  1         2  
  1         90  
47 1     1   8 use Data::Dumper;
  1         2  
  1         233  
48 1     1   8 use SQL::Translator::Schema::Constants;
  1         3  
  1         1882  
49              
50             our ($DEBUG, @EXPORT_OK);
51             our $VERSION = '1.66';
52             $DEBUG = 0 unless defined $DEBUG;
53              
54             my $actions = {
55             c => 'cascade',
56             r => 'restrict',
57             a => 'no action',
58             n => 'set null',
59             d => 'set default',
60             };
61              
62             sub parse {
63 0     0 0   my ($tr, $dbh) = @_;
64              
65 0           my $schema = $tr->schema;
66 0           my $deconstruct_enum_types = $tr->parser_args->{deconstruct_enum_types};
67              
68 0           my $column_select = $dbh->prepare(
69             "SELECT a.attname, a.atttypid, t.typtype, format_type(t.oid, a.atttypmod) as typname, a.attnum,
70             a.atttypmod as length, a.attnotnull, a.atthasdef, pg_get_expr(ad.adbin, ad.adrelid) as adsrc,
71             d.description
72             FROM pg_type t, pg_attribute a
73             LEFT JOIN pg_attrdef ad ON (ad.adrelid = a.attrelid AND a.attnum = ad.adnum)
74             LEFT JOIN pg_description d ON (a.attrelid=d.objoid AND a.attnum=d.objsubid)
75             WHERE a.attrelid=? AND attnum>0
76             AND a.atttypid=t.oid
77             ORDER BY a.attnum"
78             );
79              
80 0           my $index_select = $dbh->prepare(
81             "SELECT oid, c.relname, i.indkey, i.indnatts, i.indisunique,
82             i.indisprimary, pg_get_indexdef(oid) AS create_string
83             FROM pg_class c,pg_index i
84             WHERE c.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname='public') AND c.relkind='i'
85             AND c.oid=i.indexrelid AND i.indrelid=?"
86             );
87              
88 0           my $table_select = $dbh->prepare(
89             "SELECT c.oid, c.relname, d.description
90             FROM pg_class c
91             LEFT JOIN pg_description d ON c.oid=d.objoid AND d.objsubid=0
92             WHERE relnamespace IN
93             (SELECT oid FROM pg_namespace WHERE nspname='public')
94             AND relkind='r';"
95             );
96              
97 0 0         my $fk_select = $dbh->prepare(
98             q/
99             SELECT r.conname,
100             c.relname,
101             d.relname AS frelname,
102             r.conkey,
103             ARRAY(SELECT column_name::varchar
104             FROM information_schema.columns
105             WHERE ordinal_position = ANY (r.conkey)
106             AND table_schema = n.nspname
107             AND table_name = c.relname ) AS fields,
108             r.confkey,
109             ARRAY(SELECT column_name::varchar
110             FROM information_schema.columns
111             WHERE ordinal_position = ANY (r.confkey)
112             AND table_schema = n.nspname
113             AND table_name = d.relname ) AS reference_fields,
114             r.confupdtype,
115             r.confdeltype,
116             r.confmatchtype
117              
118             FROM pg_catalog.pg_constraint r
119              
120             JOIN pg_catalog.pg_class c
121             ON c.oid = r.conrelid
122             AND r.contype = 'f'
123              
124             JOIN pg_catalog.pg_class d
125             ON d.oid = r.confrelid
126              
127             JOIN pg_catalog.pg_namespace n
128             ON n.oid = c.relnamespace
129              
130             WHERE pg_catalog.pg_table_is_visible(c.oid)
131             AND n.nspname = ?
132             AND c.relname = ?
133             ORDER BY 1;
134             /
135             ) or die "Can't prepare: $@";
136              
137 0           my %enum_types;
138 0 0         if ($deconstruct_enum_types) {
139 0 0         my $enum_select = $dbh->prepare('SELECT enumtypid, enumlabel FROM pg_enum ORDER BY oid, enumsortorder')
140             or die "Can't prepare: $@";
141 0           $enum_select->execute();
142 0           while (my $enumval = $enum_select->fetchrow_hashref) {
143 0           push @{ $enum_types{ $enumval->{enumtypid} } }, $enumval->{enumlabel};
  0            
144             }
145             }
146              
147 0           $table_select->execute();
148              
149 0           while (my $tablehash = $table_select->fetchrow_hashref) {
150              
151 0           my $table_name = $$tablehash{'relname'};
152 0           my $table_oid = $$tablehash{'oid'};
153 0   0       my $table = $schema->add_table(
154             name => $table_name,
155              
156             #what is type? type => $table_info->{TABLE_TYPE},
157             ) || die $schema->error;
158              
159             $table->comments($$tablehash{'description'})
160 0 0         if $$tablehash{'description'};
161              
162 0           $column_select->execute($table_oid);
163              
164 0           my %column_by_attrid;
165 0           while (my $columnhash = $column_select->fetchrow_hashref) {
166 0           my $type = $$columnhash{'typname'};
167              
168             # For the case of character varying(50), atttypmod will be 54 and the (50)
169             # will be listed as part of the type. For numeric(8,5) the atttypmod will
170             # be a meaningless large number. To make this compatible with the
171             # rest of SQL::Translator, remove the size from the type and change the
172             # size to whatever was removed from the type.
173 0 0         my @size = ($type =~ s/\(([0-9,]+)\)$//) ? (split /,/, $1) : ();
174             my $col = $table->add_field(
175             name => $$columnhash{'attname'},
176             data_type => $type,
177 0   0       order => $$columnhash{'attnum'},
178             ) || die $table->error;
179 0 0         $col->size(\@size) if @size;
180              
181             # default values are a DDL expression. Convert the obvious ones like '...'::text
182             # to a plain value and let the rest be scalarrefs.
183 0           my $default = $$columnhash{'adsrc'};
184 0 0         if (defined $default) {
185 0 0         if ($default =~ /^[0-9.]+$/) { $col->default_value($default) }
  0 0          
186             elsif ($default =~ /^'(.*?)'(::\Q$type\E)?$/) {
187 0           my $str = $1;
188 0           $str =~ s/''/'/g;
189 0           $col->default_value($str);
190             } else {
191 0           $col->default_value(\$default);
192             }
193             }
194 0 0 0       if ( $deconstruct_enum_types
195             && $enum_types{ $columnhash->{atttypid} }) {
196 0           $col->extra->{custom_type_name} = $col->data_type;
197 0           $col->extra->{list} = [ @{ $enum_types{ $columnhash->{atttypid} } } ];
  0            
198 0           $col->data_type('enum');
199             }
200 0 0         $col->is_nullable($$columnhash{'attnotnull'} ? 0 : 1);
201             $col->comments($$columnhash{'description'})
202 0 0         if $$columnhash{'description'};
203 0           $column_by_attrid{ $$columnhash{'attnum'} } = $$columnhash{'attname'};
204             }
205              
206 0           $index_select->execute($table_oid);
207              
208 0           while (my $indexhash = $index_select->fetchrow_hashref) {
209              
210             #don't deal with function indexes at the moment
211             next
212             if ($$indexhash{'indkey'} eq ''
213 0 0 0       or !defined($$indexhash{'indkey'}));
214              
215 0           my @columns = map $column_by_attrid{$_}, split /\s+/, $$indexhash{'indkey'};
216              
217 0           my $type;
218 0 0         if ($$indexhash{'indisprimary'}) {
    0          
219 0           $type = UNIQUE; #PRIMARY_KEY;
220              
221             #tell sqlt that this is the primary key:
222 0           for my $column (@columns) {
223 0           $table->get_field($column)->{is_primary_key} = 1;
224             }
225              
226             } elsif ($$indexhash{'indisunique'}) {
227 0           $type = UNIQUE;
228             } else {
229 0           $type = NORMAL;
230             }
231              
232             $table->add_index(
233 0 0         name => $$indexhash{'relname'},
234             type => $type,
235             fields => \@columns,
236             ) || die $table->error;
237             }
238              
239 0 0         $fk_select->execute('public', $table_name) or die "Can't execute: $@";
240 0           my $fkeys = $fk_select->fetchall_arrayref({});
241 0 0         $DEBUG and print Dumper $fkeys;
242 0           for my $con (@$fkeys) {
243 0           my $con_name = $con->{conname};
244 0           my $fields = $con->{fields};
245 0           my $reference_fields = $con->{reference_fields};
246 0           my $reference_table = $con->{frelname};
247 0           my $on_upd = $con->{confupdtype};
248 0           my $on_del = $con->{confdeltype};
249             $table->add_constraint(
250             name => $con_name,
251             type => 'foreign_key',
252             fields => $fields,
253             reference_fields => $reference_fields,
254             reference_table => $reference_table,
255             on_update => $actions->{$on_upd},
256 0           on_delete => $actions->{$on_del},
257             );
258             }
259             }
260              
261 0           return 1;
262             }
263              
264             1;
265              
266             # -------------------------------------------------------------------
267             # Time is a waste of money.
268             # Oscar Wilde
269             # -------------------------------------------------------------------
270              
271             =pod
272              
273             =head1 AUTHOR
274              
275             Scott Cain Ecain@cshl.eduE, previous author:
276             Paul Harrington Eharringp@deshaw.comE.
277              
278             =head1 SEE ALSO
279              
280             SQL::Translator, DBD::Pg.
281              
282             =cut