| 1 | # $Id$ | ||
| 2 | |||
| 3 | package Data::ObjectDriver::Driver::DBD::Pg; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | |||
| 7 | use base qw( Data::ObjectDriver::Driver::DBD ); | ||
| 8 | |||
| 9 | # No postgresql doesn't allow MySQL's REPLACE INTO syntax | ||
| 10 | sub can_replace { 0 } | ||
| 11 | |||
| 12 | |||
| 13 | sub init_dbh { | ||
| 14 | my $dbd = shift; | ||
| 15 | my($dbh) = @_; | ||
| 16 | $dbh->do("set timezone to 'UTC'"); | ||
| 17 | $dbh; | ||
| 18 | } | ||
| 19 | |||
| 20 | sub bind_param_attributes { | ||
| 21 | my ($dbd, $data_type) = @_; | ||
| 22 | if ($data_type && $data_type eq 'blob') { | ||
| 23 | return { pg_type => DBD::Pg::PG_BYTEA() }; | ||
| 24 | } | ||
| 25 | return; | ||
| 26 | } | ||
| 27 | |||
| 28 | sub sequence_name { | ||
| 29 | my $dbd = shift; | ||
| 30 | my($class, $driver) = @_; | ||
| 31 | |||
| 32 | my $datasource = $class ->datasource; | ||
| 33 | my $prefix = $driver->prefix; | ||
| 34 | $datasource = join('', $prefix, $datasource) if $prefix; | ||
| 35 | join '_', $datasource, | ||
| 36 | $dbd->db_column_name($class->datasource, $class->properties->{primary_key}), | ||
| 37 | 'seq'; | ||
| 38 | } | ||
| 39 | |||
| 40 | sub fetch_id { | ||
| 41 | my $dbd = shift; | ||
| 42 | my($class, $dbh, $sth, $driver) = @_; | ||
| 43 | $dbh->last_insert_id(undef, undef, undef, undef, | ||
| 44 | { sequence => $dbd->sequence_name($class, $driver) }); | ||
| 45 | } | ||
| 46 | |||
| 47 | sub bulk_insert { | ||
| 48 | my $dbd = shift; | ||
| 49 | my $dbh = shift; | ||
| 50 | my $table = shift; | ||
| 51 | |||
| 52 | my $cols = shift; | ||
| 53 | my $rows_ref = shift; | ||
| 54 | my $attrs = shift || {}; | ||
| 55 | |||
| 56 | if (%$attrs) { | ||
| 57 | my $sql = "INSERT INTO $table (" . join(',', @{$cols}) . ") VALUES\n"; | ||
| 58 | |||
| 59 | my $one_data_row = "(" . (join ',', (('?') x @$cols)) . ")"; | ||
| 60 | my $ph = join ",", (($one_data_row) x @$rows_ref); | ||
| 61 | $sql .= $ph; | ||
| 62 | |||
| 63 | my $sth = $dbh->prepare($sql); | ||
| 64 | my $i = 1; | ||
| 65 | for my $row (@$rows_ref) { | ||
| 66 | for (my $j = 0; $j < @$cols; $j++) { | ||
| 67 | $sth->bind_param($i++, $row->[$j], $attrs->{$cols->[$j]}); | ||
| 68 | } | ||
| 69 | } | ||
| 70 | $sth->execute; | ||
| 71 | } else { | ||
| 72 | my $sql = "COPY $table (" . join(',', @{$cols}) . ') from stdin'; | ||
| 73 | |||
| 74 | $dbh->do($sql); | ||
| 75 | foreach my $row (@{$rows_ref}) { | ||
| 76 | my $line = join("\t", map {$_ || '\N'} @{$row}); | ||
| 77 | $dbh->pg_putline("$line\n"); | ||
| 78 | } | ||
| 79 | return $dbh->pg_endcopy(); | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | sub map_error_code { | ||
| 84 | my $dbd = shift; | ||
| 85 | my($code, $msg) = @_; | ||
| 86 | |||
| 87 | if ($msg && $msg =~ /(?:violates unique constraint)/) { | ||
| 88 | return Data::ObjectDriver::Errors->UNIQUE_CONSTRAINT; | ||
| 89 | } else { | ||
| 90 | return; | ||
| 91 | } | ||
| 92 | } | ||
| 93 | |||
| 94 | 1; |