ORM/Db/DBI/PgSQL.pm untested

filter: Statementstmt 0.0% 0 / 145 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 34 MC/DCmcdc 0.0% 0 / 20 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 296 CC 34 SCAR 52.2
CC
34
Cov
0%
_PgPP_last_insert_id
420.0
table_struct
72.0
new
12.0
CRAP 185.8
1 #
2 # DESCRIPTION
3 # PerlORM - Object relational mapper (ORM) for Perl. PerlORM is Perl
4 # library that implements object-relational mapping. Its features are
5 # much similar to those of Java's Hibernate library, but interface is
6 # much different and easier to use.
7 #
8 # AUTHOR
9 # Alexey V. Akimov <akimov_alexey@sourceforge.net>
10 #
11 # COPYRIGHT
12 # Copyright (C) 2005-2006 Alexey V. Akimov
13 #
14 # This library is free software; you can redistribute it and/or
15 # modify it under the terms of the GNU Lesser General Public
16 # License as published by the Free Software Foundation; either
17 # version 2.1 of the License, or (at your option) any later version.
18 #
19 # This library is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 # Lesser General Public License for more details.
23 #
24 # You should have received a copy of the GNU Lesser General Public
25 # License along with this library; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27 #
28  
29 package ORM::Db::DBI::PgSQL;
30  
31 $VERSION = 0.83;
32  
33 use base 'ORM::Db::DBI';
34  
35 ##
36 ## CONSTRUCTORS
37 ##
38  
39 ## use: ORM::Db::DBI::PgSQL->new
40 ## (
41 ## host => string,
42 ## database => string,
43 ## namespace => string || undef,
44 ## user => string,
45 ## password => string,
46 ## pure_perl_driver => boolean,
47 ## );
48 ##
49 sub new
50 {
51 my $class = shift;
52 my %arg = @_;
53 my $self;
54  
55 unless( $arg{pure_perl_driver} )
56 {
57 $arg{data_source} = "DBI:Pg:dbname='$arg{database}';host='$arg{host}';port=".($arg{port}||5432);
58 }
59  
60 $arg{driver} = $arg{pure_perl_driver} ? 'PgPP' : 'Pg';
61 $self = $class->SUPER::new( %arg );
62  
63 $self->{pure_perl_driver} = $arg{pure_perl_driver};
64 $self->{namespace} = $arg{namespace} || 'public';
65  
66 return $self;
67 }
68  
69 ##
70 ## CLASS METHODS
71 ##
72  
73 sub qc
74 {
75 my $self = shift;
76 my $str = shift;
77  
78 if( defined $str )
79 {
80 $str =~ s/\'/\'\'/g;
81 $str = "'$str'";
82 }
83 else
84 {
85 $str = 'NULL';
86 }
87  
88 return $str;
89 }
90  
91 sub qi
92 {
93 my $self = shift;
94 my $str = shift;
95  
96 $str =~ s/\"/\"\"/g;
97 $str = "\"$str\"";
98  
99 return $str;
100 }
101  
102 sub qt { $_[0]->qi( $_[1] ); }
103 sub qf { $_[0]->qi( $_[1] ); }
104  
105 ##
106 ## OBJECT METHODS
107 ##
108  
109 sub _namespace { $_[0]->{namespace}; }
110 sub _pure_perl_driver { $_[0]->{pure_perl_driver}; }
111  
112 ## use: $id = $db->insertid()
113 ##
114 sub insertid
115 {
116 my $self = shift;
117 my $id;
118  
119 if( !$self->_db_handler )
120 {
121 $id = undef;
122 }
123 elsif( $self->_pure_perl_driver )
124 {
125 $id = $self->_PgPP_last_insert_id
126 (
127 $self->_db_handler,
128 $self->database,
129 undef,
130 $self->{last_insert_table},
131 undef
132 );
133 }
134 else
135 {
136 $id = $self->_db_handler->last_insert_id
137 (
138 $self->database,
139 undef,
140 $self->{last_insert_table},
141 undef
142 );
143 }
144  
145 return $id;
146 }
147  
148 sub insert_object
149 {
150 my $self = shift;
151 my %arg = @_;
152  
153 $self->{last_insert_table} = (ref $arg{object})->_db_table( 0 );
154  
155 $self->SUPER::insert_object( %arg )
156 }
157  
158 sub table_struct
159 {
160 my $self = shift;
161 my %arg = @_;
162 my $error = ORM::Error->new;
163 my %field;
164 my %defaults;
165 my $res;
166  
167 ## Fetch table structure
168  
169 # WARNING! DBD::PgPP driver does not support the following
170 # so version detection probably should be rewriten to use
171 # "SELECT version()" or something else.
172  
173 my $version = $self->_db_handler->{pg_server_version} || 0;
174 my $old_ver = $version < 70300;
175 my $catalog = $old_ver ? '' : 'pg_catalog.';
176  
177 #ORM::DbLog->write_to_stderr(1);
178 $res = $self->select
179 (
180 error => $error,
181 query =>
182 (
183 # This SQL query was crafted from DBD::Pg::column_info,
184 # the reason it was not used itself is because it is
185 # not supported by DBD::PgPP.
186 'SELECT
187 a.attnum AS "Index",
188 a.attname AS "Field",
189 (
190 t.typname ||
191 CASE WHEN a.atttypmod = -1
192 THEN \'\'
193 ELSE \'(\' || a.atttypmod || \')\'
194 END
195 ) AS "Type",
196 af.adsrc AS "Default"
197 FROM
198 '.$catalog.'pg_type t
199 JOIN '.$catalog.'pg_attribute a ON (t.oid = a.atttypid)
200 JOIN '.$catalog.'pg_class c ON (a.attrelid = c.oid)
201 LEFT JOIN '.$catalog.'pg_attrdef af ON (a.attnum = af.adnum AND a.attrelid = af.adrelid)
202 '.( $old_ver ? '' : "JOIN ${catalog}pg_namespace n ON (n.oid = c.relnamespace)" ).'
203 WHERE
204 a.attnum >= 0
205 AND c.relkind IN (\'r\',\'v\')
206 AND c.relname = ' . $self->qc( $arg{table} ) . '
207 '.( $old_ver ? '' : 'AND n.nspname = '.$self->qc( $self->_namespace ) ).'
208 ORDER BY "Index"'
209 )
210 );
211 #ORM::DbLog->write_to_stderr(0);
212  
213 unless( $error->fatal )
214 {
215 while( $data = $res->next_row )
216 {
217 $defaults{$data->{Field}} = $self->_parse_default_value( $data->{Default} );
218 $field{$data->{Field}} = $arg{class}->_db_type_to_class( $data->{Field}, $data->{Type} );
219 }
220 }
221  
222 ## Fetch class references
223 if( scalar( %field ) )
224 {
225 $res = $self->select
226 (
227 error => $error,
228 query => 'SELECT * FROM '.$self->qt('_ORM_refs').' WHERE class='.$self->qc( $arg{class} ),
229 );
230 unless( $error->fatal )
231 {
232 while( $data = $res->next_row )
233 {
234 if( exists $field{$data->{prop}} )
235 {
236 $field{$data->{prop}} = $data->{ref_class};
237 }
238 }
239 }
240 }
241  
242 $error->upto( $arg{error} );
243 return \%field, \%defaults;
244 }
245  
246 sub _sql_limit
247 {
248 my $self = shift;
249 my $page = (int shift)||1;
250 my $pagesize = int shift;
251 my $sql;
252  
253 if( $pagesize )
254 {
255 $sql = "LIMIT $pagesize OFFSET ".(($page-1)*$pagesize);
256 }
257  
258 return $sql;
259 }
260  
261 sub _lost_connection
262 {
263 my $self = shift;
264 my $err = shift;
265  
266 # mysql: defined $err && ( $err == 2006 || $err == 2013 );
267 warn "Don't know how to verify whether error was caused by connection abort!";
268 undef;
269 }
270  
271 # PgSQL does not support FOR UPDATE together with SELECT DISTINCT
272 sub _ta_select { ''; }
273  
274 sub _parse_default_value
275 {
276 my $self = shift;
277 my $value = shift;
278  
279 if( defined $value && $value =~ /^'(.*)'::[^:]+$/ )
280 {
281 $value = $1;
282 $value =~ s/''/'/g;
283 }
284 else
285 {
286 $value = undef;
287 }
288  
289 return $value;
290 }
291  
292 # Cloned from DBD::Pg
293 sub _PgPP_last_insert_id
294 {
295 my ($self, $dbh, $catalog, $schema, $table, $col, $attr) = @_;
296  
297 ## Our ultimate goal is to get a sequence
298 my ($sth, $count, $SQL, $sequence);
299  
300 ## Cache all of our table lookups? Default is yes
301 my $cache = 1;
302  
303 ## Catalog and col are not used
304 $schema = '' if ! defined $schema;
305 $table = '' if ! defined $table;
306 my $cachename = "lii$table$schema";
307  
308 my $version = $self->_db_handler->{pg_server_version} || 0;
309 my $old_ver = $version < 70300;
310 my $use_cat = $old_ver ? '' : 'pg_catalog.';
311  
312 if (defined $attr and length $attr) {
313 ## If not a hash, assume it is a sequence name
314 if (! ref $attr) {
315 $attr = {sequence => $attr};
316 }
317 elsif (ref $attr ne 'HASH') {
318 return $dbh->set_err(1, "last_insert_id must be passed a hashref as the final argument");
319 }
320 ## Named sequence overrides any table or schema settings
321 if (exists $attr->{sequence} and length $attr->{sequence}) {
322 $sequence = $attr->{sequence};
323 }
324 if (exists $attr->{pg_cache}) {
325 $cache = $attr->{pg_cache};
326 }
327 }
328  
329 if (! defined $sequence and exists $dbh->{private_dbdpg}{$cachename} and $cache) {
330 $sequence = $dbh->{private_dbdpg}{$cachename};
331 }
332 elsif (! defined $sequence) {
333 ## At this point, we must have a valid table name
334 if (! length $table) {
335 return $dbh->set_err(1, "last_insert_id needs at least a sequence or table name");
336 }
337 my @args = ($table);
338  
339 ## Only 7.3 and up can use schemas
340 $schema = '' if( $old_ver );
341  
342 ## Make sure the table in question exists and grab its oid
343 my ($schemajoin,$schemawhere) = ('','');
344 if (length $schema) {
345 $schemajoin = "\n JOIN pg_catalog.pg_namespace n ON (n.oid = c.relnamespace)";
346 $schemawhere = "\n AND n.nspname = ?";
347 push @args, $schema;
348 }
349 $SQL = "SELECT c.oid FROM ${use_cat}pg_class c $schemajoin\n WHERE relname = ?$schemawhere";
350 $sth = $dbh->prepare($SQL);
351 $count = $sth->execute(@args);
352 if (!defined $count or $count eq '0E0') {
353 $sth->finish();
354 my $message = qq{Could not find the table "$table"};
355 length $schema and $message .= qq{ in the schema "$schema"};
356 return $dbh->set_err(1, $message);
357 }
358 my $oid = $sth->fetchall_arrayref()->[0][0];
359 ## This table has a primary key. Is there a sequence associated with it via a unique, indexed column?
360 $SQL = "SELECT a.attname, i.indisprimary, substring(d.adsrc for 128) AS def\n".
361 "FROM ${use_cat}pg_index i, ${use_cat}pg_attribute a, ${use_cat}pg_attrdef d\n ".
362 "WHERE i.indrelid = $oid AND d.adrelid=a.attrelid AND d.adnum=a.attnum\n".
363 " AND a.attrelid=$oid AND i.indisunique IS TRUE\n".
364 " AND a.atthasdef IS TRUE AND i.indkey[0]=a.attnum\n".
365 " AND d.adsrc ~ '^nextval'";
366 $sth = $dbh->prepare($SQL);
367 $count = $sth->execute();
368 if (!defined $count or $count eq '0E0') {
369 $sth->finish();
370 $dbh->set_err(1, qq{No suitable column found for last_insert_id of table "$table"});
371 }
372 my $info = $sth->fetchall_arrayref();
373  
374 ## We have at least one with a default value. See if we can determine sequences
375 my @def;
376 for (@$info) {
377 next unless $_->[2] =~ /^nextval\('([^']+)'::/o;
378 push @$_, $1;
379 push @def, $_;
380 }
381 if (!@def) {
382 $dbh->set_err(1, qq{No suitable column found for last_insert_id of table "$table"\n});
383 }
384 ## Tiebreaker goes to the primary keys
385 if (@def > 1) {
386 my @pri = grep { $_->[1] } @def;
387 if (1 != @pri) {
388 $dbh->set_Err(1, qq{No suitable column found for last_insert_id of table "$table"\n});
389 }
390 @def = @pri;
391 }
392 $sequence = $def[0]->[3];
393 ## Cache this information for subsequent calls
394 $dbh->{private_dbdpg}{$cachename} = $sequence;
395 }
396  
397 $sth = $dbh->prepare("SELECT currval(?)");
398 $sth->execute($sequence);
399 return $sth->fetchall_arrayref()->[0][0];
400  
401 }
402  
403 ##
404 ## SQL FUNCTIONS
405 ##
406