-- Fixed tabs to spaces issue
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Pg.pm
1 package DBIx::Class::Storage::DBI::Pg;
2
3 use strict;
4 use warnings;
5
6 use DBD::Pg qw(:pg_types);
7
8 use base qw/DBIx::Class::Storage::DBI/;
9
10 # __PACKAGE__->load_components(qw/PK::Auto/);
11
12 # Warn about problematic versions of DBD::Pg
13 warn "DBD::Pg 1.49 is strongly recommended"
14   if ($DBD::Pg::VERSION < 1.49);
15
16 sub _dbh_last_insert_id {
17   my ($self, $dbh, $seq) = @_;
18   $dbh->last_insert_id(undef, undef, undef, undef, {sequence => $seq});
19 }
20
21 sub last_insert_id {
22   my ($self,$source,$col) = @_;
23   my $seq = ($source->column_info($col)->{sequence} ||= $self->get_autoinc_seq($source,$col));
24   $self->throw_exception("could not fetch primary key for " . $source->name . ", could not "
25     . "get autoinc sequence for $col (check that table and column specifications are correct "
26     . "and in the correct case)") unless defined $seq;
27   $self->dbh_do($self->can('_dbh_last_insert_id'), $seq);
28 }
29
30 sub _dbh_get_autoinc_seq {
31   my ($self, $dbh, $schema, $table, @pri) = @_;
32
33   while (my $col = shift @pri) {
34     my $info = $dbh->column_info(undef,$schema,$table,$col)->fetchrow_hashref;
35     if(defined $info->{COLUMN_DEF} and
36        $info->{COLUMN_DEF} =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/) {
37       my $seq = $1;
38       # may need to strip quotes -- see if this works
39       return $seq =~ /\./ ? $seq : $info->{TABLE_SCHEM} . "." . $seq;
40     }
41   }
42   return;
43 }
44
45 sub get_autoinc_seq {
46   my ($self,$source,$col) = @_;
47     
48   my @pri = $source->primary_columns;
49   my ($schema,$table) = $source->name =~ /^(.+)\.(.+)$/ ? ($1,$2)
50     : (undef,$source->name);
51
52   $self->dbh_do($self->can('_dbh_get_autoinc_seq'), $schema, $table, @pri);
53 }
54
55 sub sqlt_type {
56   return 'PostgreSQL';
57 }
58
59 sub datetime_parser_type { return "DateTime::Format::Pg"; }
60
61 sub bind_attribute_by_data_type {
62   my ($self,$data_type) = @_;
63
64   my $bind_attributes = {
65     bytea => { pg_type => DBD::Pg::PG_BYTEA },
66   };
67  
68   if( defined $bind_attributes->{$data_type} ) {
69     return $bind_attributes->{$data_type};
70   }
71   else {
72     return;
73   }
74 }
75
76 1;
77
78 =head1 NAME
79
80 DBIx::Class::Storage::DBI::Pg - Automatic primary key class for PostgreSQL
81
82 =head1 SYNOPSIS
83
84   # In your table classes
85   __PACKAGE__->load_components(qw/PK::Auto Core/);
86   __PACKAGE__->set_primary_key('id');
87   __PACKAGE__->sequence('mysequence');
88
89 =head1 DESCRIPTION
90
91 This class implements autoincrements for PostgreSQL.
92
93 =head1 AUTHORS
94
95 Marcus Ramberg <m.ramberg@cpan.org>
96
97 =head1 LICENSE
98
99 You may distribute this code under the same terms as Perl itself.
100
101 =cut