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