1 package DBIx::Class::Storage::DBI::Pg;
6 use base qw/DBIx::Class::Storage::DBI::MultiColumnIn/;
9 use DBD::Pg qw(:pg_types);
11 use Context::Preserve ();
13 # Ask for a DBD::Pg with array support
14 warn __PACKAGE__.": DBD::Pg 2.9.2 or greater is strongly recommended\n"
15 if ($DBD::Pg::VERSION < 2.009002); # pg uses (used?) version::qv()
17 __PACKAGE__->mk_group_accessors(simple => qw/
21 sub _prep_for_execute {
23 my ($op, $extra_bind, $ident, $args) = @_;
25 if ($op eq 'insert') {
26 $self->_auto_cols([]);
29 @pk{$ident->primary_columns} = ();
31 my @auto_inc_cols = grep {
32 my $inserting = $args->[0]{$_};
34 ($ident->column_info($_)->{is_auto_increment}
37 (not defined $inserting)
39 (ref $inserting eq 'SCALAR' && $$inserting =~ /^null\z/i)
44 $args->[1]{returning} = \@auto_inc_cols;
46 $self->_auto_cols->[0] = \@auto_inc_cols;
50 return $self->next::method(@_);
57 my ($rv, $sth, @bind) = $self->dbh_do($self->can('_dbh_execute'), @_);
59 if ($op eq 'insert' && $self->_auto_cols) {
61 my (@auto_cols) = eval {
62 local $SIG{__WARN__} = sub {};
65 $self->_auto_cols->[1] = \@auto_cols;
69 return wantarray ? ($rv, $sth, @bind) : $rv;
73 sub with_deferred_fk_checks {
74 my ($self, $sub) = @_;
76 my $txn_scope_guard = $self->txn_scope_guard;
78 $self->_do_query('SET CONSTRAINTS ALL DEFERRED');
80 my $sg = Scope::Guard->new(sub {
81 $self->_do_query('SET CONSTRAINTS ALL IMMEDIATE');
84 return Context::Preserve::preserve_context(sub { $sub->() },
85 after => sub { $txn_scope_guard->commit });
91 my $updated_cols = $self->next::method(@_);
93 if ($self->_auto_cols->[0]) {
95 @auto_cols{ @{ $self->_auto_cols->[0] } } = @{ $self->_auto_cols->[1] };
97 $updated_cols = { %$updated_cols, %auto_cols };
100 return $updated_cols;
104 my ($self, $source, @cols) = @_;
108 @auto_cols{ @{ $self->_auto_cols->[0] } } =
109 @{ $self->_auto_cols->[1] };
111 push @result, $auto_cols{$_} for @cols;
116 sub _sequence_fetch {
117 my ($self, $function, $sequence) = @_;
119 $self->throw_exception('No sequence to fetch') unless $sequence;
121 my ($val) = $self->_get_dbh->selectrow_array(
122 sprintf "select $function('%s')",
129 sub _dbh_get_autoinc_seq {
130 my ($self, $dbh, $source, $col) = @_;
133 my $table = $source->name;
135 # deref table name if it needs it
137 if ref $table eq 'SCALAR';
139 # parse out schema name if present
140 if( $table =~ /^(.+)\.(.+)$/ ) {
141 ( $schema, $table ) = ( $1, $2 );
144 # get the column default using a Postgres-specific pg_catalog query
145 my $seq_expr = $self->_dbh_get_column_default( $dbh, $schema, $table, $col );
147 # if no default value is set on the column, or if we can't parse the
148 # default value as a sequence, throw.
149 unless ( defined $seq_expr and $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i ) {
150 $seq_expr = '' unless defined $seq_expr;
151 $schema = "$schema." if defined $schema && length $schema;
152 $self->throw_exception( sprintf (
153 'no sequence found for %s%s.%s, check the RDBMS table definition or explicitly set the '.
154 "'sequence' for this column in %s",
155 $schema ? "$schema." : '',
158 $source->source_name,
165 # custom method for fetching column default, since column_info has a
166 # bug with older versions of DBD::Pg
167 sub _dbh_get_column_default {
168 my ( $self, $dbh, $schema, $table, $col ) = @_;
170 # Build and execute a query into the pg_catalog to find the Pg
171 # expression for the default value for this column in this table.
172 # If the table name is schema-qualified, query using that specific
175 # Otherwise, find the table in the standard Postgres way, using the
176 # search path. This is done with the pg_catalog.pg_table_is_visible
177 # function, which returns true if a given table is 'visible',
178 # meaning the first table of that name to be found in the search
181 # I *think* we can be assured that this query will always find the
182 # correct column according to standard Postgres semantics.
186 my $sqlmaker = $self->sql_maker;
187 local $sqlmaker->{bindtype} = 'normal';
189 my ($where, @bind) = $sqlmaker->where ({
190 'a.attnum' => {'>', 0},
191 'c.relname' => $table,
193 -not_bool => 'a.attisdropped',
194 (defined $schema && length $schema)
195 ? ( 'n.nspname' => $schema )
196 : ( -bool => \'pg_catalog.pg_table_is_visible(c.oid)' )
199 my ($seq_expr) = $dbh->selectrow_array(<<EOS,undef,@bind);
202 (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
203 FROM pg_catalog.pg_attrdef d
204 WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
205 FROM pg_catalog.pg_class c
206 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
207 JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
220 sub datetime_parser_type { return "DateTime::Format::Pg"; }
222 sub bind_attribute_by_data_type {
223 my ($self,$data_type) = @_;
225 my $bind_attributes = {
226 bytea => { pg_type => DBD::Pg::PG_BYTEA },
227 blob => { pg_type => DBD::Pg::PG_BYTEA },
230 if( defined $bind_attributes->{$data_type} ) {
231 return $bind_attributes->{$data_type};
239 my ($self, $name) = @_;
241 $self->_get_dbh->pg_savepoint($name);
245 my ($self, $name) = @_;
247 $self->_get_dbh->pg_release($name);
251 my ($self, $name) = @_;
253 $self->_get_dbh->pg_rollback_to($name);
262 DBIx::Class::Storage::DBI::Pg - Automatic primary key class for PostgreSQL
266 # In your result (table) classes
267 use base 'DBIx::Class::Core';
268 __PACKAGE__->set_primary_key('id');
269 __PACKAGE__->sequence('mysequence');
273 This class implements autoincrements for PostgreSQL.
275 =head1 POSTGRESQL SCHEMA SUPPORT
277 This driver supports multiple PostgreSQL schemas, with one caveat: for
278 performance reasons, data about the search path, sequence names, and
279 so forth is queried as needed and CACHED for subsequent uses.
281 For this reason, once your schema is instantiated, you should not
282 change the PostgreSQL schema search path for that schema's database
283 connection. If you do, Bad Things may happen.
285 You should do any necessary manipulation of the search path BEFORE
286 instantiating your schema object, or as part of the on_connect_do
287 option to connect(), for example:
289 my $schema = My::Schema->connect
292 [ 'SET search_path TO myschema, foo, public' ],
298 See L<DBIx::Class/CONTRIBUTORS>
302 You may distribute this code under the same terms as Perl itself.