| 1 | package SPOPS::DBI::Pg; | ||
| 2 | |||
| 3 | # $Id: Pg.pm,v 3.6 2004/06/02 00:48:22 lachoy Exp $ | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use Log::Log4perl qw( get_logger ); | ||
| 7 | use SPOPS; | ||
| 8 | use SPOPS::Exception qw( spops_error ); | ||
| 9 | |||
| 10 | $SPOPS::DBI::Pg::VERSION = sprintf("%d.%02d", q$Revision: 3.6 $ =~ /(\d+)\.(\d+)/); | ||
| 11 | |||
| 12 | use constant PG_SEQUENCE_NEXT => q{SELECT NEXTVAL( '%s' )}; | ||
| 13 | use constant PG_SEQUENCE_CURRENT => q{SELECT CURRVAL( '%s' )}; | ||
| 14 | |||
| 15 | my $log = get_logger(); | ||
| 16 | |||
| 17 | sub sql_current_date { return 'CURRENT_TIMESTAMP()' } | ||
| 18 | sub sql_case_insensitive { return '~*' } | ||
| 19 | |||
| 20 | sub pre_fetch_id { | ||
| 21 | my ( $item, $p ) = @_; | ||
| 22 | my ( $seq_name ); | ||
| 23 | return undef unless ( $item->CONFIG->{increment_field} ); | ||
| 24 | return undef unless ( $seq_name = $item->CONFIG->{sequence_name} ); | ||
| 25 | my ( $sth ); | ||
| 26 | eval { | ||
| 27 | $sth = $p->{db}->prepare( sprintf( PG_SEQUENCE_NEXT, $seq_name ) ); | ||
| 28 | $sth->execute; | ||
| 29 | }; | ||
| 30 | if ( $@ ) { | ||
| 31 | spops_error "Failed to retrieve ID from sequence '$seq_name': $@"; | ||
| 32 | } | ||
| 33 | return ( $sth->fetchrow_arrayref->[0], undef ); | ||
| 34 | } | ||
| 35 | |||
| 36 | |||
| 37 | sub post_fetch_id { | ||
| 38 | my ( $item, $p ) = @_; | ||
| 39 | return undef unless ( $item->CONFIG->{increment_field} ); | ||
| 40 | return undef if ( $item->CONFIG->{sequence_name} ); | ||
| 41 | |||
| 42 | # If it's a SERIAL datatype try to fetch the value just inserted | ||
| 43 | |||
| 44 | my $seq_name = $item->CONFIG->{sequence_name} | ||
| 45 | || join( '_', $item->CONFIG->{base_table}, | ||
| 46 | $item->CONFIG->{id_field}, | ||
| 47 | 'seq' ); | ||
| 48 | return undef unless ( $seq_name ); | ||
| 49 | my $sth = $p->{db}->prepare( sprintf( PG_SEQUENCE_CURRENT, $seq_name ) ); | ||
| 50 | $sth->execute; | ||
| 51 | return ($sth->fetchrow_array)[0]; | ||
| 52 | } | ||
| 53 | |||
| 54 | 1; | ||
| 55 | |||
| 56 | __END__ |