PostgreSQL/Storage.pm

filter: Statementstmt 81.2% 230 / 283 Branchbran 73.8% 99 / 134 Conditioncond 71.8% 74 / 103 MC/DCmcdc 56.1% 32 / 57 Subroutinesub 80.3% 53 / 66 Podpod 100% 20 / 20 totaltotal 76.6% 508 / 663 CC 108 SCAR 22.0
CC
108
Cov
78%
_dbh_get_autoinc_seq
56.0
bind_attribute_by_data_type
42.0
last_insert_id
20.0
CRAP 9.0
« PostgreSQL/Introspect/Normalize.pm ↑ Summary PostgreSQL/Diff/Sequence.pm »
1 package DBIO::PostgreSQL::Storage;
2 # ABSTRACT: PostgreSQL storage layer for DBIO
3  
4 131 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 131 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 131 our $VERSION = '0.900004';
8  
9 131 ▶use base qw/DBIO::Storage::DBI/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 131 ▶use mro 'c3';
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 131 __PACKAGE__->register_driver('Pg' => __PACKAGE__);
13  
14 6 ▶sub dbio_deploy_class { 'DBIO::PostgreSQL::Deploy' }
Subroutine dbio_deploy_class: called CC=1 SCAR=0.0
Pod documented
15  
16  
17 131 __PACKAGE__->register_type('jsonb', {
18 cake_options => [qw(inflate_json inflate_jsonb)],
19 components => ['InflateColumn::Serializer'],
20 col_attrs => { serializer_class => 'JSON' },
21 });
22  
23  
24 131 ▶use DBIO::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 131 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
26 131 ▶use DBIO::PostgreSQL::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
27 131 ▶use DBIO::PostgreSQL::Extension ();
Subroutine BEGIN: called CC=1 SCAR=0.0
28 131 ▶use DBIO::PostgreSQL::DDL ();
Subroutine BEGIN: called CC=1 SCAR=0.0
29 131 ▶use Context::Preserve 'preserve_context';
Subroutine BEGIN: called CC=1 SCAR=0.0
30 131 ▶use DBIO::Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 131 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 # PostgreSQL defaults
34 131 __PACKAGE__->sql_maker_class('DBIO::PostgreSQL::SQLMaker');
35 131 __PACKAGE__->sql_quote_char('"');
36 131 __PACKAGE__->datetime_parser_type('DateTime::Format::Pg');
37 131 __PACKAGE__->_use_multicolumn_in(1);
38  
39 # F02: PostgreSQL runs DDL inside an ordinary transaction -- CREATE TABLE and
40 # friends are rollbackable here, which is the exception among the engines, not
41 # the rule. DBIO::Deploy::Base::_execute_ddl brackets DDL in $storage->txn_do
42 # only when this reports true, so declaring it is what makes a multi-statement
43 # install or upgrade atomic: a failure on statement 7 of 12 rolls the preceding
44 # six back instead of leaving the schema half migrated.
45 #
46 # What it does NOT declare is one transaction per batch, and both limits are
47 # load-bearing enough to name here. Core groups the batch by
48 # _ddl_statement_is_transactional below, so an ALTER TYPE ... ADD VALUE runs on
49 # its own while the rest keeps its bracket (core k132); and core brackets only a
50 # handle this storage owns, so the temp-database deploy behind
51 # DBIO::PostgreSQL::Deploy->diff -- which runs on a handle TempDatabase opened
52 # itself -- stays unbracketed (core k131). Both arrived in DBIO 0.900004, which
53 # is why the cpanfile pins it: on an older core this declaration would put a
54 # transaction on the live connection around DDL executing somewhere else.
55 #
56 # Declared rather than left to core's default, which is 0. That default is the
57 # conservative answer for an engine nobody has checked, and inheriting it here
58 # meant this driver silently deployed statement-at-a-time -- while
59 # DBIO::PostgreSQL::EV::Storage::deploy_async already bracketed its own DDL for
60 # exactly the reason spelled out above. Pinned by t/43-capabilities.t.
61 131 __PACKAGE__->_use_transactional_ddl(1);
62  
63 # ADR 0037: core's base rendering of _exists_value_sql is
64 #
65 # SELECT CASE WHEN EXISTS <inner> THEN 1 ELSE 0 END
66 #
67 # and it is checked against PostgreSQL rather than assumed, because that is the
68 # whole content of this flag -- it asserts that somebody looked. The statement
69 # makes three demands and PostgreSQL documents all three:
70 #
71 # * EXISTS used as a VALUE, not a predicate. "Subquery Expressions" opens
72 # with "All of the expression forms documented in this section return
73 # Boolean (true/false) results", EXISTS among them -- PostgreSQL has a real
74 # boolean type, so the CASE condition is an ordinary boolean expression.
75 # * A SELECT with no FROM. The SELECT reference states it outright under
76 # Compatibility: "PostgreSQL allows one to omit the FROM clause. It has a
77 # straightforward use to compute the results of simple expressions".
78 # * Nothing else -- core adds only parentheses around the fragment for
79 # results_exist_as_query, and a parenthesised scalar subquery is universal.
80 #
81 # So this driver does NOT override _exists_value_sql; it takes the base form.
82 # The three engines that do override it are the ones that also refuse a
83 # FROM-less SELECT (Oracle, DB2, Firebird), which PostgreSQL does not.
84 #
85 # Declaring it is what makes results_exist / results_exist_async /
86 # results_exist_as_query work at all: core's default is 0 and all three throw
87 # on an undeclared engine rather than ship SQL it may not parse. The
88 # declaration on this class is also the ONLY one the driver family needs --
89 # see the "Extensions and the async backends" note below and
90 # t/44-exists-query-seam.t, which pins both halves.
91 131 __PACKAGE__->_use_supports_exists_query(1);
92  
93 # karr k48 / core ADR 0040: this driver does NOT override _explain_query. Core's
94 # base operation -- EXPLAIN <sql> through _execute_rendered, rows back -- is the
95 # right one for PostgreSQL, and taking it unchanged is a decision, not an
96 # omission, so it is recorded here where the override used to sit.
97 #
98 # What used to sit here was
99 #
100 # sub _explain_sql { "EXPLAIN ANALYZE $_[1]" }
101 #
102 # and it is gone for two independent reasons.
103 #
104 # 1. It was already dead. ADR 0040 REMOVED the _explain_sql string hook and put
105 # _explain_query in its slot -- not deprecated, not aliased -- so from DBIO
106 # 0.900004 on (the version the cpanfile already pins) core never called it
107 # and $rs->explain here was silently already a plain EXPLAIN. Leaving the sub
108 # in place would have kept claiming a behaviour the code no longer had.
109 #
110 # 2. It should not come back. explain must not have side effects, and on
111 # PostgreSQL ANALYZE does not just add measured timings -- it EXECUTES the
112 # query. Full runtime, plus everything the query touches: nextval() and other
113 # volatile functions advance, a data-modifying CTE writes, triggers fire. A
114 # caller asking what the planner intends does not expect its sequence counter
115 # to move. Real timings are a thing to ask for, not to receive unasked.
116 #
117 # There is deliberately no option: the seam is a method. A caller who wants
118 # ANALYZE overrides _explain_query on a storage subclass and connects through it
119 # -- routing the statement through _execute_rendered as the contract requires,
120 # never $self->dbh. The POD above has the worked example. Pinned by
121 # t/46-explain-query-seam.t, which asserts on the statement the mock captured,
122 # not on a string.
123  
124 # Async is an explicit, per-connection mode (core ADR 0030): a connection opened
125 # with connect(..., { async => 'ev' }) resolves the 'ev' mode through the mode
126 # registry to the native EV backend below. Registering on this driver storage
127 # class MRO-shadows the generic modes (forked/future_io) registered on the base
128 # storage, so 'ev' picks the PostgreSQL-specific backend. There is no auto-
129 # fallback and no silent degrade: a mode that is neither requested nor registered
130 # is simply unavailable, and requesting an unregistered/uninstalled mode croaks
131 # (see DBIO::Storage::DBI::_async_storage). This only stores the class name --
132 # DBIO::PostgreSQL::EV::Storage (the optional dbio-postgresql-ev dist) is loaded
133 # lazily on first use, so registering it here is safe when the dist is absent.
134 131 __PACKAGE__->register_async_mode( ev => 'DBIO::PostgreSQL::EV::Storage' );
135  
136 # This is the ONLY async registration this driver needs, and it stays as-is
137 # under the storage-layer composition model (core karr k70): a mode maps to a
138 # transport BASE class, once, on this concrete driver storage. PostgreSQL
139 # EXTENSIONS (AGE, PostGIS, ...) no longer subclass storage_type nor add shadow
140 # register_async_mode / ::Async registrations -- they register plain storage
141 # LAYERS (DBIO::Schema::register_storage_layer) whose async mirrors compose ON
142 # TOP of the resolved transport via DBIO::Storage::Composed. Composition rides
143 # on top of this base; the mode->transport-base map does not grow per extension.
144  
145  
146 249 ▶sub sql_maker {
Subroutine sql_maker: called CC=1 SCAR=0.0
Pod documented
147 249 my $self = shift;
148 # Core quotes by default (this class's sql_quote_char / sql_name_sep) and
149 # leaves out what the connection turned off; it is not filled in again here.
150 249 return $self->next::method(@_);
151 }
152  
153 12 ▶sub _determine_supports_insert_returning {
Subroutine _determine_supports_insert_returning: called CC=2 SCAR=6.9
154 12 ▶ return shift->_server_info->{normalized_dbms_version} >= 8.002
Branch: 1 branch
BranchTrueFalseTotal
+(shift())->_server_info->{'normalized_dbms_version'} >= 8.002 ? : 10 2 12
155 ? 1
156 : 0
157 ;
158 }
159  
160 14 ▶sub _determine_supports_supports_upsert {
Subroutine _determine_supports_supports_upsert: called CC=3 SCAR=11.0
161 14 my $self = shift;
162  
163 # INSERT ... ON CONFLICT exists since PostgreSQL 9.5; before that there is
164 # no atomic upsert on this engine at all and DBIO::ResultSet::upsert has to
165 # throw rather than emit a statement the server cannot parse.
166 14 ▶ return 0 unless $self->_server_info->{normalized_dbms_version} >= 9.005;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_server_info->{"normalized_dbms_version"} >= "9.005" 3 11 14
167  
168 # ADR 0036 section 4: a driver may only declare the capability if the row it
169 # hands back is provably the row that was written. On PostgreSQL that proof
170 # is RETURNING. Without it, core falls back to last_insert_id -- and the
171 # DO UPDATE branch still burns a nextval() from the column default, so that
172 # id belongs to no row at all. Refusing the capability is the honest answer;
173 # returning a confidently wrong row would not be.
174 11 ▶ return $self->_use_insert_returning ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->_use_insert_returning ? : 10 1 11
175 }
176  
177 # ADR 0036 section 3 (core k134): the capability is DECLARED, not derived
178 # from supports_upsert. It answers about the conditional branch itself, and
179 # PostgreSQL has had the WHERE since 9.5, together with the ON CONFLICT
180 # grammar it hangs off -- there is no version that speaks the conflict clause
181 # but not its condition, so a static 1 loses nothing. Deriving would import
182 # supports_upsert's extra RETURNING demand, which is about naming the row
183 # that was written, a requirement the branch does not add to (a condition
184 # that does not hold writes no row by design) -- and core probes
185 # supports_upsert first and throws there, so a second 0 would carry no
186 # information and no better message.
187 #
188 # Declared through _determine_supports_* like the driver's other
189 # capabilities, rather than as _use_ class data, so the per-storage force
190 # slot stays the caller's.
191 4 ▶sub _determine_supports_supports_upsert_where { 1 }
Subroutine _determine_supports_supports_upsert_where: called CC=1 SCAR=0.0
192  
193 29 ▶sub _ddl_statement_is_transactional {
Subroutine _ddl_statement_is_transactional: called CC=3 SCAR=11.0
194 29 my ($self, $stmt) = @_;
195  
196 # ADR 0026 addendum (core k132). PostgreSQL's DDL is transactional with one
197 # exception this driver can actually emit: ALTER TYPE ... ADD VALUE. Before
198 # server 12 the engine rejects it outright inside a transaction block; from
199 # 12 on it is accepted, but the new label stays unusable until that
200 # transaction commits -- so a diff that adds an enum value and then
201 # references it (a column default, a data migration) fails on every version,
202 # just with a different error. Answering false here takes that one statement
203 # out of the txn_do bracket and leaves the rest of the batch atomic.
204 #
205 # Anchored on the form DBIO::PostgreSQL::Diff::Type emits for
206 # action => 'add_value' rather than on anything an ALTER TYPE could be. That
207 # is the whole population: _execute_ddl only ever sees DDL this driver
208 # generated. The narrowness is the point -- ALTER TYPE ... RENAME VALUE and
209 # ALTER TYPE ... ADD ATTRIBUTE are transactional and must keep their
210 # bracket, and a broad /ALTER\s+TYPE/ would quietly cost them it.
211 29 ▶ return 0 if $stmt =~ /\A \s* ALTER \s+ TYPE \b [^;]*? \b ADD \s+ VALUE \b/xi;
Branch: 1 branch
BranchTrueFalseTotal
if $stmt =~ /\A \s* ALTER \s+ TYPE \b [^;]*? \b ADD \s+ VALUE \b/xi 6 23 29
212  
213 # karr k145: the VALIDATE CONSTRAINT behind an ADD CONSTRAINT ... NOT VALID
214 # (DBIO::PostgreSQL::Diff::ForeignKey, action 'validate'). The statement is
215 # transactional in itself; it is taken out of the bracket so that it runs
216 # after the COMMIT of the add, in a transaction of its own: the lock the add
217 # takes is not held over the reading of the rows, and a validation that
218 # fails leaves the key NOT VALID (the next diff validates it again) instead
219 # of taking the add back. Anchored on the form the op emits, two
220 # identifiers (each bare or quoted, the quotes may hold ';' and '.') between
221 # ALTER TABLE and VALIDATE CONSTRAINT; the other ALTER TABLE forms keep
222 # their bracket.
223 23 my $ident = qr/(?: "(?:[^"]|"")+" | [^\s".;]+ )/x;
224 23 ▶ return 0 if $stmt =~ /\A \s* ALTER \s+ TABLE \s+ $ident (?: \. $ident )? \s+ VALIDATE \s+ CONSTRAINT \s/xi;
Branch: 1 branch
BranchTrueFalseTotal
if $stmt =~ /\A \s* ALTER \s+ TABLE \s+ $ident (?: \. $ident )? \s+ VALIDATE \s+ CONSTRAINT \s/xi 3 20 23
225  
226 20 return 1;
227 }
228  
229  
230 21 ▶sub _ddl_sql_dialect { 'postgresql' }
Subroutine _ddl_sql_dialect: called CC=1 SCAR=0.0
231  
232  
233  
234 25 ▶sub _set_connection_schema {
Subroutine _set_connection_schema: called CC=1 SCAR=0.0
235 25 my ($self, $name, $activation) = @_;
236  
237 $self->_do_query('SET search_path TO ' . join ', ',
238 25 map { DBIO::PostgreSQL::Util::quote_ident($_) }
239 $self->_connection_search_path($name, $activation));
240  
241 25 return $self;
242 }
243  
244  
245 25 ▶sub _connection_search_path {
Subroutine _connection_search_path: called CC=7 SCAR=19.8
246 25 my ($self, $name, $activation) = @_;
247  
248 25 my $schema = $self->schema;
249 25 ▶ my $declares = $schema
Condition83%5/6
$schema && $schema->can('pg_extensions') && $schema->can('pg_extension_schemas')
!ll&&!rl&&r
2023
$schema and $schema->can("pg_extensions")
!ll&&!rl&&r
1123
MC/DC66%2/3
$schema && $schema->can('pg_extensions') && $schema->can('pg_extension_schemas')
$schema $schema->can("pg_extensions") $schema->can('pg_extension_schemas')
Truth table75%3/4
A and B && C
A= $schemaB= $schema->can("pg_extensions")C= $schema->can('pg_extension_schemas')
ABCresult
0XX0
10X0
1100
1111
250 && $schema->can('pg_extensions') && $schema->can('pg_extension_schemas');
251 25 ▶ $activation //= $self->_extension_activation($name);
Condition33%1/3
$activation //= $self->_extension_activation($name)
l!l&&r!l&&!r
2500
MC/DC0%0/2
$activation //= $self->_extension_activation($name)
$activation $self->_extension_activation($name)
Truth table33%1/3
A //= B
A= $activationB= $self->_extension_activation($name)
ABresult
1X1
011
000
252  
253 25 ▶ my ($extensions, $given) = $declares
Branch: 1 branch
BranchTrueFalseTotal
$declares ? : 23 2 25
254 ? ([ $schema->pg_extensions ], $schema->pg_extension_schemas) : ([], {});
255 25 my @open = grep { !defined $given->{$_} } @$extensions;
256 25 my %control;
257 25 ▶ if (@open) {
Branch: 1 branch
BranchTrueFalseTotal
if (@open) 12 13 25
258 12 ▶ my $rows = $self->_pool_connect_rows(
Condition50%1/2
$self->_pool_connect_rows(DBIO::PostgreSQL::DDL::control_schemas_sql(@open)) // []
l!l
120
MC/DC0%0/1
$self->_pool_connect_rows(DBIO::PostgreSQL::DDL::control_schemas_sql(@open)) // []
$self->_pool_connect_rows(DBIO::PostgreSQL::DDL::control_schemas_sql(@open))
Truth table50%1/2
A
A= $self->_pool_connect_rows(DBIO::PostgreSQL::DDL::control_schemas_sql(@open))
Aresult
11
00
259 DBIO::PostgreSQL::DDL::control_schemas_sql(@open)) // [];
260 0 %control = map { $_->[0] => $_->[1] } @$rows;
261 }
262  
263 return DBIO::PostgreSQL::Util::connection_search_path(
264 25 $name, $extensions, $given, $activation->{search_path}, \%control,
265 );
266 }
267  
268  
269 38 ▶sub _declared_search_path {
Subroutine _declared_search_path: called CC=5 SCAR=17.5
270 38 my ($self, $activation) = @_;
271  
272 38 my $schema = $self->schema;
273 38 ▶ return unless $schema && $schema->can('pg_search_path_declared')
Branch: 1 branch
BranchTrueFalseTotal
unless $schema and $schema->can("pg_search_path_declared") and $schema->pg_search_path_declared 24 14 38
Condition50%3/6
$schema and $schema->can("pg_search_path_declared") and $schema->pg_search_path_declared
!ll&&!rl&&r
02414
$schema and $schema->can("pg_search_path_declared")
!ll&&!rl&&r
0038
MC/DC33%1/3
$schema and $schema->can("pg_search_path_declared") and $schema->pg_search_path_declared
$schema $schema->can("pg_search_path_declared") $schema->pg_search_path_declared
Truth table50%2/4
A and B and C
A= $schemaB= $schema->can("pg_search_path_declared")C= $schema->pg_search_path_declared
ABCresult
0XX0
10X0
1100
1111
274 && $schema->pg_search_path_declared;
275 14 ▶ $activation //= $self->_extension_activation(undef);
Condition33%1/3
$activation //= $self->_extension_activation(undef)
l!l&&r!l&&!r
1400
MC/DC0%0/2
$activation //= $self->_extension_activation(undef)
$activation $self->_extension_activation(undef)
Truth table33%1/3
A //= B
A= $activationB= $self->_extension_activation(undef)
ABresult
1X1
011
000
276  
277 return DBIO::PostgreSQL::Util::declared_search_path(
278 [ $schema->pg_search_path ],
279 [ $schema->pg_extensions ],
280 $schema->pg_extension_schemas,
281 $activation->{search_path},
282 14 );
283 }
284  
285  
286 52 ▶sub _extension_activation {
Subroutine _extension_activation: called CC=2 SCAR=6.9
287 52 my ($self, $name) = @_;
288 52 my $none = { load => [], search_path => [] };
289  
290 52 ▶ my $list = DBIO::PostgreSQL::Extension->resolve_list($self->schema)
Branch: 1 branch
BranchTrueFalseTotal
my $list = "DBIO::PostgreSQL::Extension"->resolve_list($self->schema) or return $none 28 23 51
291 or return $none;
292  
293 28 require DBIO::Extension::Protocol;
294 28 return DBIO::Extension::Protocol->new(
295 entries => [ $list->entries ],
296 driver => DBIO::PostgreSQL::Extension->driver_helpers,
297 connection_schema => $name,
298 restricted => 0,
299 )->activation;
300 }
301  
302  
303 52 ▶sub _apply_connection_schema {
Subroutine _apply_connection_schema: called CC=5 SCAR=16.1
304 52 my ($self) = @_;
305 52 my $name = $self->connection_schema;
306 52 my $activation = $self->_extension_activation($name);
307  
308 $self->_do_query('LOAD ' . DBIO::PostgreSQL::Util::quote_literal($_))
309 50 for @{ $activation->{load} };
310  
311 50 ▶ if (defined $name) {
Branch: 3 branches
BranchTrueFalseTotal
if (defined $name) { } 25 25 50
elsif (my(@declared) = $self->_declared_search_path($activation)) { } 14 11 25
elsif (my(@path) = @{$activation->{'search_path'};}) { } 4 7 11
312 25 $self->_set_connection_schema($name, $activation);
313 }
314 elsif (my @declared = $self->_declared_search_path($activation)) {
315 $self->_do_query('SET search_path TO ' . join ', ',
316 14 map { DBIO::PostgreSQL::Util::quote_search_path_entry($_) } @declared);
317 }
318 11 elsif (my @path = @{ $activation->{search_path} }) {
319 4 my $add = join ', ', map { DBIO::PostgreSQL::Util::quote_ident($_) } @path;
320 4 $self->_do_query(
321 q{SELECT pg_catalog.set_config('search_path', pg_catalog.current_setting('search_path') || }
322 . DBIO::PostgreSQL::Util::quote_literal(", $add") . ', false)');
323 }
324  
325 48 return $self;
326 }
327  
328  
329 8 ▶sub _connect_params_dsn {
Subroutine _connect_params_dsn: called CC=7 SCAR=19.6
330 8 my ($self, $driver, $params) = @_;
331  
332 8 my @parts;
333 # A part without a value is as none given, as on the future_io transport.
334 8 ▶ for my $key (grep { defined $params->{$_} && (ref $params->{$_} || length $params->{$_}) } qw(dbname host port)) {
Condition83%5/6
defined $params->{$_} && (ref $params->{$_} || length $params->{$_})
!ll&&!rl&&r
1725
ref $params->{$_} or length $params->{$_}
l!l&&r!l&&!r
052
MC/DC66%2/3
defined $params->{$_} && (ref $params->{$_} || length $params->{$_})
defined $params->{$_} ref $params->{$_} length $params->{$_}
Truth table75%3/4
A && B or C
A= defined $params->{$_}B= ref $params->{$_}C= length $params->{$_}
ABCresult
0XX0
1000
11X1
1011
335 5 my $value = $params->{$key};
336 5 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 0 5 5
337 "Cannot build a DBD::Pg DSN from the connection parameter '$key': its "
338 . 'value is a reference, not a value.'
339 ) if ref $value;
340 # The DSN is a C string from DBD::Pg on: it would end at the NUL, and the
341 # parts behind this one would be gone with it.
342 5 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /\0/ 0 5 5
343 "Cannot build a DBD::Pg DSN from the connection parameter '$key': its "
344 . 'value contains a NUL character, which no connection string can carry.'
345 ) if $value =~ /\0/;
346 5 push @parts, "$key=" . DBIO::PostgreSQL::Util::quote_dsn_value($value);
347 }
348  
349 # "dbi:Pg:" alone leaves the target to libpq's environment (PGHOST,
350 # PGDATABASE, a service file): the credentials would go wherever it says.
351 $self->throw_exception(
352 8 ▶ 'Cannot build a DBD::Pg DSN: the connection parameters name no dbname, '
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 4 4 8
353 . 'host or port, so libpq would take the target from its environment '
354 . '(PGHOST, PGDATABASE, ...). Give at least one of dbname, host or port.'
355 ) unless @parts;
356  
357 4 return "dbi:$driver:" . join ';', @parts;
358 }
359  
360  
361 74 ▶sub _refuse_dsn_without_target {
Subroutine _refuse_dsn_without_target: called CC=6 SCAR=18.0
362 74 my ($self, $dsn) = @_;
363  
364 74 ▶ return unless defined $dsn && !ref $dsn && length $dsn;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $dsn and not ref $dsn and length $dsn 13 61 74
Condition83%5/6
defined $dsn and not ref $dsn and length $dsn
!ll&&!rl&&r
13061
defined $dsn and not ref $dsn
!ll&&!rl&&r
11261
MC/DC66%2/3
defined $dsn and not ref $dsn and length $dsn
defined $dsn not ref $dsn length $dsn
Truth table75%3/4
A and not(B) and C
A= defined $dsnB= not ref $dsnC= length $dsn
ABCresult
0XX0
10X0
1100
1111
365 61 ▶ return if $dsn !~ /\Adbi:Pg\b/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $dsn =~ /\Adbi:Pg\b/i 0 61 61
366 61 ▶ return if DBIO::PostgreSQL::Util::dsn_names_target($dsn);
Branch: 1 branch
BranchTrueFalseTotal
if DBIO::PostgreSQL::Util::dsn_names_target($dsn) 17 44 61
367  
368 44 $self->throw_exception(
369 'Cannot connect with a DBD::Pg DSN that names no dbname, host or port, '
370 . 'so libpq would take the target from its environment (PGHOST, '
371 . 'PGDATABASE, ...). Give at least one of dbname, host or port (or '
372 . 'service, hostaddr) in the DSN.'
373 );
374 }
375  
376  
377 74 ▶sub _connect {
Subroutine _connect: called CC=2 SCAR=6.9
378 74 my $self = shift;
379  
380 74 ▶ $self->_refuse_dsn_without_target($self->_dbi_connect_info->[0])
Branch: 1 branch
BranchTrueFalseTotal
unless $self->access_broker 50 24 74
381 unless $self->access_broker;
382  
383 52 return $self->next::method(@_);
384 }
385  
386  
387 24 ▶sub _access_broker_dbi_args {
Subroutine _access_broker_dbi_args: called CC=2 SCAR=7.0
388 24 my ($self, $mode, %for) = @_;
389  
390 24 my ($args, $attrs) = $self->next::method($mode, %for);
391 24 ▶ $self->_refuse_dsn_without_target($args->[0]) if $for{connecting};
Branch: 1 branch
BranchTrueFalseTotal
if $for{"connecting"} 24 0 24
392  
393 2 return ($args, $attrs);
394 }
395  
396  
397 31 ▶sub _bind_host_into_dsn {
Subroutine _bind_host_into_dsn: called CC=14 SCAR=26.5
398 31 my ($self, $driver, $dsn, $host, $port) = @_;
399  
400 31 ▶ if (defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is) 31 0 31
Condition33%1/3
defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
!ll&&!rl&&r
0031
MC/DC0%0/2
defined $dsn and $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
defined $dsn $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
Truth table33%1/3
A and B
A= defined $dsnB= $dsn =~ /^(dbi:[^:]*:)(.*)\z/is
ABresult
0X0
100
111
401 31 my ($prefix, $rest) = ($1, $2);
402 31 my @tokens = split /;/, $rest, -1;
403  
404 31 for my $token (@tokens) {
405 66 ▶ next unless $token =~ /^(\w+)=(.*)\z/s;
Branch: 1 branch
BranchTrueFalseTotal
unless $token =~ /^(\w+)=(.*)\z/s 0 66 66
406 66 my ($key, $value, $lkey) = ($1, $2, lc $1);
407  
408 66 ▶ return (undef, "the key '$key' (a service file may name hostaddr)")
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "service" 5 61 66
409 if $lkey eq 'service';
410  
411 61 ▶ return (undef, "the key '$key' holding a connection string")
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "dbname" || $lkey eq "db" || $lkey eq "database" and $value =~ m[^postgres(?:ql)?://]i || $value =~ /=/ 5 56 61
Condition100%12/12
$lkey eq "dbname" || $lkey eq "db" || $lkey eq "database" and $value =~ m[^postgres(?:ql)?://]i || $value =~ /=/
!ll&&!rl&&r
36205
$lkey eq "dbname" or $lkey eq "db" or $lkey eq "database"
l!l&&r!l&&!r
24136
$lkey eq "dbname" or $lkey eq "db"
l!l&&r!l&&!r
23137
$value =~ m[^postgres(?:ql)?://]i or $value =~ /=/
l!l&&r!l&&!r
4120
MC/DC100%5/5
$lkey eq "dbname" || $lkey eq "db" || $lkey eq "database" and $value =~ m[^postgres(?:ql)?://]i || $value =~ /=/
$lkey eq "dbname" $lkey eq "db" $lkey eq "database" $value =~ m[^postgres(?:ql)?://]i $value =~ /=/
Truth table60%6/10
A or B or C and D or E
A= $lkey eq "dbname"B= $lkey eq "db"C= $lkey eq "database"D= $value =~ m[^postgres(?:ql)?://]iE= $value =~ /=/
ABCDEresult
000XX0
1XX000
01X000
001000
1XX1X1
1XX011
01X1X1
01X011
0011X1
001011
412 if ($lkey eq 'dbname' or $lkey eq 'db' or $lkey eq 'database')
413 and $value =~ m{^postgres(?:ql)?://}i || $value =~ /=/;
414  
415 56 ▶ return (undef, 'a port list without a port in the view')
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq "port" and not defined $port and $value =~ /,/ 1 55 56
Condition100%6/6
$lkey eq "port" and not defined $port and $value =~ /,/
!ll&&!rl&&r
5411
$lkey eq "port" and not defined $port
!ll&&!rl&&r
5042
MC/DC100%3/3
$lkey eq "port" and not defined $port and $value =~ /,/
$lkey eq "port" not defined $port $value =~ /,/
Truth table100%4/4
A and not(B) and C
A= $lkey eq "port"B= not defined $portC= $value =~ /,/
ABCresult
0XX0
10X0
1100
1111
416 if $lkey eq 'port' and !defined $port and $value =~ /,/;
417 }
418  
419 # libpq lets hostaddr win over host: with it gone, the host is the view's
420 20 $dsn = $prefix . join ';', grep { !/^hostaddr=/i } @tokens;
421 }
422  
423 20 return $self->next::method($driver, $dsn, $host, $port);
424 }
425  
426  
427 8 ▶sub _dbi_error_fields {
Subroutine _dbi_error_fields: called CC=10 SCAR=23.0
428 8 my ($self, $h) = @_;
429  
430 8 my $fields = $self->next::method($h);
431  
432 8 my $dbh = eval {
433 Scalar::Util::blessed($h) && $h->can('pg_error_field') ? $h
434 : Scalar::Util::blessed($h) ? scalar $h->{Database}
435 : undef
436 8 ▶ };
Branch: 2 branches
BranchTrueFalseTotal
builtin::blessed($h) && $h->can('pg_error_field') ? : 4 4 8
builtin::blessed($h) ? : 2 2 4
Condition100%3/3
builtin::blessed($h) and $h->can("pg_error_field")
!ll&&!rl&&r
224
MC/DC100%2/2
builtin::blessed($h) and $h->can("pg_error_field")
builtin::blessed($h) $h->can("pg_error_field")
Truth table100%3/3
A and B
A= builtin::blessed($h)B= $h->can("pg_error_field")
ABresult
0X0
100
111
437 8 ▶ return $fields
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($dbh) and $dbh->can("pg_error_field") 3 5 8
Condition66%2/3
builtin::blessed($dbh) and $dbh->can("pg_error_field")
!ll&&!rl&&r
305
MC/DC50%1/2
builtin::blessed($dbh) and $dbh->can("pg_error_field")
builtin::blessed($dbh) $dbh->can("pg_error_field")
Truth table66%2/3
A and B
A= builtin::blessed($dbh)B= $dbh->can("pg_error_field")
ABresult
0X0
100
111
438 unless Scalar::Util::blessed($dbh) && $dbh->can('pg_error_field');
439  
440 5 my %field = (
441 constraint => 'constraint',
442 table => 'table',
443 detail => 'detail',
444 );
445 5 for my $key (sort keys %field) {
446 15 my $value = eval { $dbh->pg_error_field($field{$key}) };
447 15 ▶ next unless defined $value && length $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value and length $value 6 9 15
Condition100%3/3
defined $value and length $value
!ll&&!rl&&r
519
MC/DC100%2/2
defined $value and length $value
defined $value length $value
Truth table100%3/3
A and B
A= defined $valueB= length $value
ABresult
0X0
100
111
448 9 ▶ $value = DBIO::PostgreSQL::Util::mask_detail_values($value) if $key eq 'detail';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "detail" 3 6 9
449 9 $fields->{$key} = $value;
450 }
451  
452 5 return $fields;
453 }
454  
455  
456 3 ▶sub _mask_error_values {
Subroutine _mask_error_values: called CC=4 SCAR=14.0
457 3 my ($self, $text, $values, $statement) = @_;
458  
459 3 my $masked = $self->next::method($text, $values, $statement);
460 3 ▶ return $masked unless defined $masked and !ref $masked;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $masked and not ref $masked 1 2 3
Condition66%2/3
defined $masked and not ref $masked
!ll&&!rl&&r
102
MC/DC50%1/2
defined $masked and not ref $masked
defined $masked not ref $masked
Truth table66%2/3
A and not(B)
A= defined $maskedB= not ref $masked
ABresult
0X0
100
111
461  
462 2 my $details = eval { DBIO::PostgreSQL::Util::mask_error_details($masked) };
463 2 ▶ return defined $details ? $details : $masked;
Branch: 1 branch
BranchTrueFalseTotal
defined $details ? : 2 0 2
464 }
465  
466  
467 0 ▶sub with_deferred_fk_checks {
Subroutine with_deferred_fk_checks: not called CC=1 SCAR=6.9
Pod documented
468 0 my ($self, $sub) = @_;
469  
470 0 my $txn_scope_guard = $self->txn_scope_guard;
471  
472 0 $self->_do_query('SET CONSTRAINTS ALL DEFERRED');
473  
474 0 ▶ my $sg = DBIO::Util::scope_guard {
Subroutine __ANON__: not called CC=1 SCAR=6.9
475 0 $self->_do_query('SET CONSTRAINTS ALL IMMEDIATE');
476 0 };
477  
478 0 ▶ return preserve_context { $sub->() } after => sub { $txn_scope_guard->commit };
Subroutine __ANON__: not called CC=1 SCAR=6.9
Subroutine __ANON__: not called CC=1 SCAR=6.9
479 }
480  
481  
482 4 ▶sub pg_advisory_lock {
Subroutine pg_advisory_lock: called CC=1 SCAR=0.0
Pod documented
483 4 my ($self, @keys) = @_;
484 4 $self->_pg_advisory_run('pg_advisory_lock', @keys);
485 2 return 1;
486 }
487  
488  
489 1 ▶sub pg_advisory_lock_shared {
Subroutine pg_advisory_lock_shared: called CC=1 SCAR=0.0
Pod documented
490 1 my ($self, @keys) = @_;
491 1 $self->_pg_advisory_run('pg_advisory_lock_shared', @keys);
492 1 return 1;
493 }
494  
495  
496 2 ▶sub pg_try_advisory_lock {
Subroutine pg_try_advisory_lock: called CC=1 SCAR=0.0
Pod documented
497 2 my ($self, @keys) = @_;
498 2 return $self->_pg_advisory_bool(
499 $self->_pg_advisory_run('pg_try_advisory_lock', @keys)
500 );
501 }
502  
503  
504 0 ▶sub pg_try_advisory_lock_shared {
Subroutine pg_try_advisory_lock_shared: not called CC=1 SCAR=6.9
Pod documented
505 0 my ($self, @keys) = @_;
506 0 return $self->_pg_advisory_bool(
507 $self->_pg_advisory_run('pg_try_advisory_lock_shared', @keys)
508 );
509 }
510  
511  
512 2 ▶sub pg_advisory_unlock {
Subroutine pg_advisory_unlock: called CC=1 SCAR=0.0
Pod documented
513 2 my ($self, @keys) = @_;
514 2 return $self->_pg_advisory_bool(
515 $self->_pg_advisory_run('pg_advisory_unlock', @keys)
516 );
517 }
518  
519  
520 0 ▶sub pg_advisory_unlock_shared {
Subroutine pg_advisory_unlock_shared: not called CC=1 SCAR=6.9
Pod documented
521 0 my ($self, @keys) = @_;
522 0 return $self->_pg_advisory_bool(
523 $self->_pg_advisory_run('pg_advisory_unlock_shared', @keys)
524 );
525 }
526  
527  
528 2 ▶sub pg_advisory_unlock_all {
Subroutine pg_advisory_unlock_all: called CC=2 SCAR=6.9
Pod documented
529 2 my ($self, @args) = @_;
530 2 ▶ $self->throw_exception('pg_advisory_unlock_all takes no key arguments')
Branch: 1 branch
BranchTrueFalseTotal
if @args 1 1 2
531 if @args;
532 1 $self->_execute_rendered('SELECT pg_advisory_unlock_all()', []);
533 1 return 1;
534 }
535  
536  
537 1 ▶sub pg_advisory_xact_lock {
Subroutine pg_advisory_xact_lock: called CC=1 SCAR=0.0
Pod documented
538 1 my ($self, @keys) = @_;
539 1 $self->_pg_advisory_run('pg_advisory_xact_lock', @keys);
540 1 return 1;
541 }
542  
543  
544 1 ▶sub pg_advisory_xact_lock_shared {
Subroutine pg_advisory_xact_lock_shared: called CC=1 SCAR=0.0
Pod documented
545 1 my ($self, @keys) = @_;
546 1 $self->_pg_advisory_run('pg_advisory_xact_lock_shared', @keys);
547 1 return 1;
548 }
549  
550  
551 2 ▶sub pg_try_advisory_xact_lock {
Subroutine pg_try_advisory_xact_lock: called CC=1 SCAR=0.0
Pod documented
552 2 my ($self, @keys) = @_;
553 2 return $self->_pg_advisory_bool(
554 $self->_pg_advisory_run('pg_try_advisory_xact_lock', @keys)
555 );
556 }
557  
558  
559 0 ▶sub pg_try_advisory_xact_lock_shared {
Subroutine pg_try_advisory_xact_lock_shared: not called CC=1 SCAR=6.9
Pod documented
560 0 my ($self, @keys) = @_;
561 0 return $self->_pg_advisory_bool(
562 $self->_pg_advisory_run('pg_try_advisory_xact_lock_shared', @keys)
563 );
564 }
565  
566 # Shared body of the advisory-lock helpers. Each lock function takes either a
567 # single bigint key or a pair of int keys; the keys are bound as placeholders,
568 # never interpolated. The statement is a FROM-less SELECT that reads back the
569 # function's single-column result, so it goes down the rendered-statement path
570 # (_execute_rendered) exactly as results_exist does -- the same path the mock
571 # storage captures. Returns the function's single scalar return value.
572 13 ▶sub _pg_advisory_run {
Subroutine _pg_advisory_run: called CC=4 SCAR=13.9
573 13 my ($self, $func, @keys) = @_;
574  
575 13 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless @keys == 1 or @keys == 2 2 11 13
Condition100%3/3
@keys == 1 or @keys == 2
l!l&&r!l&&!r
1012
MC/DC100%2/2
@keys == 1 or @keys == 2
@keys == 1 @keys == 2
Truth table100%3/3
A or B
A= @keys == 1B= @keys == 2
ABresult
1X1
011
000
576 "$func requires either one bigint key or two int keys"
577 ) unless @keys == 1 || @keys == 2;
578  
579 11 my $placeholders = join(', ', ('?') x @keys);
580 11 my $bind = [ map { [ {}, $_ ] } @keys ];
581  
582 11 my (undef, $sth) = $self->_execute_rendered("SELECT $func($placeholders)", $bind);
583  
584 11 my $row = $sth->fetchall_arrayref->[0];
585 11 ▶ return $row ? $row->[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$row ? : 6 5 11
586 }
587  
588 # Normalise a PostgreSQL boolean column to a Perl boolean. DBD::Pg hands back
589 # either 't'/'f' (with pg_bool_tf on) or '1'/'0', so both spellings are folded
590 # to 1/0 here.
591 6 ▶sub _pg_advisory_bool {
Subroutine _pg_advisory_bool: called CC=5 SCAR=16.2
592 6 my ($self, $val) = @_;
593 6 ▶ return 0 if !defined $val || $val eq 'f' || $val eq '0' || $val eq '';
Branch: 1 branch
BranchTrueFalseTotal
if not defined $val or $val eq "f" or $val eq 0 or $val eq "" 3 3 6
Condition77%7/9
not defined $val or $val eq "f" or $val eq 0 or $val eq ""
l!l&&r!l&&!r
303
not defined $val or $val eq "f" or $val eq 0
l!l&&r!l&&!r
213
not defined $val or $val eq "f"
l!l&&r!l&&!r
024
MC/DC50%2/4
not defined $val or $val eq "f" or $val eq 0 or $val eq ""
not defined $val $val eq "f" $val eq 0 $val eq ""
Truth table60%3/5
not(A) or B or C or D
A= not defined $valB= $val eq "f"C= $val eq 0D= $val eq ""
ABCDresult
1XXX1
01XX1
001X1
00011
00000
594 3 return 1;
595 }
596  
597  
598 # only used when INSERT ... RETURNING is disabled
599 0 ▶sub last_insert_id {
Subroutine last_insert_id: not called CC=4 SCAR=30.0
Pod documented
600 0 my ($self, $source, @cols) = @_;
601  
602 0 my @values;
603 0 my $col_info = $source->columns_info(\@cols);
604  
605 0 for my $col (@cols) {
606 0 ▶ my $seq = ( $col_info->{$col}{sequence} ||= $self->dbh_do('_dbh_get_autoinc_seq', $source, $col) )
Branch: 1 branch
BranchTrueFalseTotal
my $seq = ($col_info->{$col}{"sequence"} ||= $self->dbh_do("_dbh_get_autoinc_seq", $source, $col)) or $self->throw_exception(sprintf("Could not determine sequence for column '%s.%s', please consider adding a schema-qualified sequence to its column info", $source->name, $col)) 0 0 0
Condition0%0/3
$col_info->{$col}{"sequence"} ||= $self->dbh_do("_dbh_get_autoinc_seq", $source, $col)
l!l&&r!l&&!r
000
MC/DC0%0/2
$col_info->{$col}{"sequence"} ||= $self->dbh_do("_dbh_get_autoinc_seq", $source, $col)
$col_info->{$col}{"sequence"} $self->dbh_do("_dbh_get_autoinc_seq", $source, $col)
Truth table0%0/3
A ||= B
A= $col_info->{$col}{"sequence"}B= $self->dbh_do("_dbh_get_autoinc_seq", $source, $col)
ABresult
1X1
011
000
607 or $self->throw_exception( sprintf(
608 "Could not determine sequence for column '%s.%s', please consider adding a "
609 . "schema-qualified sequence to its column info",
610 $source->name,
611 $col,
612 ));
613  
614 0 push @values, $self->_dbh->last_insert_id(undef, undef, undef, undef, {sequence => $seq});
615 }
616  
617 0 return @values;
618 }
619  
620 3 ▶sub _sequence_fetch {
Subroutine _sequence_fetch: called CC=6 SCAR=18.2
621 3 my ($self, $function, $sequence) = @_;
622  
623 3 ▶ $self->throw_exception('No sequence to fetch') unless $sequence;
Branch: 1 branch
BranchTrueFalseTotal
unless $sequence 0 3 3
624  
625 # The function is one of the two the sequence protocol knows; the sequence
626 # name travels as a bind, cast to regclass, through the rendered-statement
627 # path (trace, masking and statement hooks included).
628 3 ▶ $self->throw_exception('Unknown sequence function')
Branch: 1 branch
BranchTrueFalseTotal
unless defined $function and $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i 1 2 3
Condition66%2/3
defined $function and $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i
!ll&&!rl&&r
012
MC/DC50%1/2
defined $function and $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i
defined $function $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i
Truth table66%2/3
A and B
A= defined $functionB= $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i
ABresult
0X0
100
111
629 unless defined $function && $function =~ /\A(?:NEXTVAL|CURRVAL)\z/i;
630  
631 2 ▶ my (undef, $sth) = $self->_execute_rendered(
Branch: 1 branch
BranchTrueFalseTotal
ref $sequence eq 'SCALAR' ? : 1 1 2
632 sprintf('SELECT %s(?::regclass)', lc $function),
633 [ [ {}, (ref $sequence eq 'SCALAR') ? $$sequence : $sequence ] ],
634 );
635 2 my $row = $sth->fetchall_arrayref->[0];
636  
637 2 ▶ return $row ? $row->[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$row ? : 2 0 2
638 }
639  
640 0 ▶sub _dbh_get_autoinc_seq {
Subroutine _dbh_get_autoinc_seq: not called CC=7 SCAR=40.3
641 0 my ($self, $dbh, $source, $col) = @_;
642  
643 0 my $schema;
644 0 my $table = $source->name;
645  
646 0 ▶ $table = $$table if ref $table eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
if ref $table eq "SCALAR" 0 0 0
647  
648 0 ▶ if ($table =~ /^(.+)\.(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($table =~ /^(.+)\.(.+)$/) 0 0 0
649 0 ($schema, $table) = ($1, $2);
650 }
651  
652 0 my $seq_expr = $self->_dbh_get_column_default($dbh, $schema, $table, $col);
653  
654 0 ▶ unless (defined $seq_expr and $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $seq_expr and $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i) 0 0 0
Condition0%0/3
defined $seq_expr and $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i
!ll&&!rl&&r
000
MC/DC0%0/2
defined $seq_expr and $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i
defined $seq_expr $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i
Truth table0%0/3
A and B
A= defined $seq_exprB= $seq_expr =~ /^nextval\(+'([^']+)'::(?:text|regclass)\)/i
ABresult
0X0
100
111
655 0 ▶ $seq_expr = '' unless defined $seq_expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $seq_expr 0 0 0
656 0 ▶ $self->throw_exception( sprintf(
Branch: 1 branch
BranchTrueFalseTotal
$schema ? : 0 0 0
657 "No sequence found for '%s%s.%s', check the RDBMS table definition or explicitly set the "
658 . "'sequence' for this column in %s",
659 $schema ? "$schema." : '',
660 $table,
661 $col,
662 $source->source_name,
663 ));
664 }
665  
666 0 return $1;
667 }
668  
669 0 ▶sub _dbh_get_column_default {
Subroutine _dbh_get_column_default: not called CC=3 SCAR=24.8
670 0 my ($self, $dbh, $schema, $table, $col) = @_;
671  
672 0 my $sqlmaker = $self->sql_maker;
673 0 local $sqlmaker->{bindtype} = 'normal';
674  
675 0 ▶ my ($where, @bind) = $sqlmaker->where({
Branch: 1 branch
BranchTrueFalseTotal
defined $schema && length $schema ? : 0 0 0
Condition0%0/3
defined $schema and length $schema
!ll&&!rl&&r
000
MC/DC0%0/2
defined $schema and length $schema
defined $schema length $schema
Truth table0%0/3
A and B
A= defined $schemaB= length $schema
ABresult
0X0
100
111
676 'a.attnum' => {'>', 0},
677 'c.relname' => $table,
678 'a.attname' => $col,
679 -not_bool => 'a.attisdropped',
680 (defined $schema && length $schema)
681 ? ('n.nspname' => $schema)
682 : (-bool => \'pg_catalog.pg_table_is_visible(c.oid)')
683 });
684  
685 0 my ($seq_expr) = $dbh->selectrow_array(<<"EOS", undef, @bind);
686  
687 SELECT
688 (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid)
689 FROM pg_catalog.pg_attrdef d
690 WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)
691 FROM pg_catalog.pg_class c
692 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
693 JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid
694 $where
695  
696 EOS
697  
698 0 return $seq_expr;
699 }
700  
701  
702 8 ▶sub sqlt_type { 'PostgreSQL' }
Subroutine sqlt_type: called CC=1 SCAR=0.0
Pod documented
703  
704 2 ▶sub _minmax_operator_for_datatype {
Subroutine _minmax_operator_for_datatype: called CC=4 SCAR=15.8
705 #my ($self, $datatype, $want_max) = @_;
706  
707 2 ▶ return ($_[2] ? 'BOOL_OR' : 'BOOL_AND')
Branch: 2 branches
BranchTrueFalseTotal
if ($_[1] || "") =~ /\Abool(?:ean)?\z/i 2 0 2
$_[2] ? : 1 1 2
Condition50%1/2
$_[1] || ''
l!l
20
MC/DC0%0/1
$_[1] || ''
$_[1]
Truth table50%1/2
A
A= $_[1]
Aresult
11
00
708 if ($_[1] || '') =~ /\Abool(?:ean)?\z/i;
709  
710 0 shift->next::method(@_);
711 }
712  
713  
714 0 ▶sub bind_attribute_by_data_type {
Subroutine bind_attribute_by_data_type: not called CC=6 SCAR=37.4
Pod documented
715 0 my ($self, $data_type) = @_;
716  
717 0 ▶ if ($self->_is_binary_lob_type($data_type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_binary_lob_type($data_type)) { } 0 0 0
718 0 ▶ unless ($DBD::Pg::__DBIO_DBD_VERSION_CHECK_DONE__) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($DBD::Pg::__DBIO_DBD_VERSION_CHECK_DONE__) 0 0 0
719 0 ▶ if ($self->_server_info->{normalized_dbms_version} >= 9.0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->_server_info->{'normalized_dbms_version'} >= 9.0) { } 0 0 0
elsif (not &try(sub { 'DBD::Pg'->VERSION('2.9.2'); 1; } )) { } 0 0 0
720 0 ▶ try { DBD::Pg->VERSION('2.17.2'); 1 } or carp(
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
&try(sub { "DBD::Pg"->VERSION("2.17.2"); 1; } ) or carp("DBIO::PostgreSQL::Storage: BYTEA columns are known to not work on Pg >= 9.0 with DBD::Pg < 2.17.2") 0 0 0
721 __PACKAGE__ . ': BYTEA columns are known to not work on Pg >= 9.0 with DBD::Pg < 2.17.2'
722 );
723 }
724 0 ▶ elsif (not try { DBD::Pg->VERSION('2.9.2'); 1 }) { carp(
Subroutine __ANON__: not called CC=1 SCAR=6.9
725 __PACKAGE__ . ': DBD::Pg 2.9.2 or greater is strongly recommended for BYTEA column support'
726 )}
727  
728 0 $DBD::Pg::__DBIO_DBD_VERSION_CHECK_DONE__ = 1;
729 }
730  
731 0 return { pg_type => DBD::Pg::PG_BYTEA() };
732 }
733 else {
734 0 return undef;
735 }
736 }
737  
738 # Savepoints via DBD::Pg native methods
739 # DBD::Pg writes the name into "savepoint %s" as it is, so the name is held
740 # to the plain form before it gets there; the message names the form, never
741 # the value.
742 25 ▶sub _check_savepoint_name {
Subroutine _check_savepoint_name: called CC=4 SCAR=13.9
743 25 my ($self, $name) = @_;
744 25 ▶ $self->throw_exception(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/ 18 7 25
Condition83%5/6
defined $name and not ref $name and $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/
!ll&&!rl&&r
3157
defined $name and not ref $name
!ll&&!rl&&r
3022
MC/DC66%2/3
defined $name and not ref $name and $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/
defined $name not ref $name $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/
Truth table75%3/4
A and not(B) and C
A= defined $nameB= not ref $nameC= $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/
ABCresult
0XX0
10X0
1100
1111
745 'A savepoint name is 1 to 63 characters of letters, digits and underscores, '
746 . 'beginning with a letter or an underscore'
747 ) unless defined $name && !ref $name && $name =~ /\A[A-Za-z_][A-Za-z0-9_]{0,62}\z/;
748 7 return $name;
749 }
750  
751 7 ▶sub _exec_svp_begin {
Subroutine _exec_svp_begin: called CC=1 SCAR=0.0
752 7 my ($self, $name) = @_;
753 7 $self->_dbh->pg_savepoint($self->_check_savepoint_name($name));
754 }
755  
756 7 ▶sub _exec_svp_release {
Subroutine _exec_svp_release: called CC=1 SCAR=0.0
757 7 my ($self, $name) = @_;
758 7 $self->_dbh->pg_release($self->_check_savepoint_name($name));
759 }
760  
761 7 ▶sub _exec_svp_rollback {
Subroutine _exec_svp_rollback: called CC=1 SCAR=0.0
762 7 my ($self, $name) = @_;
763 7 $self->_dbh->pg_rollback_to($self->_check_savepoint_name($name));
764 }
765  
766  
767 31 ▶sub is_replicating {
Subroutine is_replicating: called CC=2 SCAR=6.9
Pod documented
768 31 my $self = shift;
769  
770 31 ▶ my $status = $self->_replication_status_row
Branch: 1 branch
BranchTrueFalseTotal
my $status = $self->_replication_status_row or return 30 1 31
771 or return;
772  
773 30 return $self->_replication_status_streams($status);
774 }
775  
776  
777 32 ▶sub lag_behind_master {
Subroutine lag_behind_master: called CC=7 SCAR=19.5
Pod documented
778 32 my $self = shift;
779  
780 32 ▶ my $status = $self->_replication_status_row
Branch: 1 branch
BranchTrueFalseTotal
my $status = $self->_replication_status_row or return 31 1 32
781 or return;
782  
783 31 ▶ return unless $self->_replication_status_streams($status);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_replication_status_streams($status) 8 23 31
784  
785 23 my $backlog = $status->{replay_backlog};
786 23 ▶ return 0 if defined $backlog and $backlog <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if defined $backlog and $backlog <= 0 10 13 23
Condition100%3/3
defined $backlog and $backlog <= 0
!ll&&!rl&&r
21110
MC/DC100%2/2
defined $backlog and $backlog <= 0
defined $backlog $backlog <= 0
Truth table100%3/3
A and B
A= defined $backlogB= $backlog <= 0
ABresult
0X0
100
111
787  
788 13 my $age = $status->{replay_age};
789 13 ▶ return unless defined $age;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $age 4 9 13
790  
791 9 ▶ return $age < 1 ? 0 : int $age;
Branch: 1 branch
BranchTrueFalseTotal
$age < 1 ? : 2 7 9
792 }
793  
794 # Whether a status row describes a standby that is streaming. The one reading
795 # both public methods share, so that lag_behind_master never reports a lag for
796 # a server is_replicating calls detached.
797 61 ▶sub _replication_status_streams {
Subroutine _replication_status_streams: called CC=5 SCAR=16.1
798 61 my ($self, $status) = @_;
799  
800 61 ▶ return 0 unless $status->{in_recovery};
Branch: 1 branch
BranchTrueFalseTotal
unless $status->{"in_recovery"} 6 55 61
801 55 ▶ return 0 unless defined $status->{receiver_pid};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status->{"receiver_pid"} 6 49 55
802  
803 # pid without a state: the role is not in pg_read_all_stats. See the POD of
804 # is_replicating for why that reads as streaming.
805 49 my $state = $status->{receiver_status};
806 49 ▶ return 1 unless defined $state;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $state 3 46 49
807  
808 46 ▶ return $state eq 'streaming' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$state eq 'streaming' ? : 36 10 46
809 }
810  
811 # The engine seam: the facts both replication methods decide on, as a hashref,
812 # from one statement -- so that the two halves of an answer describe the same
813 # moment. Anything that needs replication state reads it here.
814 #
815 # in_recovery 1 on a standby, 0 on a primary or a promoted standby
816 # receiver_pid the WAL receiver's pid; undef when pg_stat_wal_receiver
817 # has no row
818 # receiver_status its state; undef as well when the role may not read it
819 # replay_backlog bytes received but not yet replayed; 0 or less when
820 # caught up, undef when nothing was ever received by
821 # streaming
822 # replay_age seconds since the last replayed transaction was committed
823 # on the primary; undef when none has been replayed
824 #
825 # Every function in it is executable by PUBLIC and the view is readable by
826 # PUBLIC, so no role gets an error here -- only fewer columns. Returns nothing
827 # for a server older than PostgreSQL 10, where the pg_last_wal_*_lsn functions
828 # still had their xlog names; an unknown version is taken to be a current one.
829 63 ▶sub _replication_status_row {
Subroutine _replication_status_row: called CC=4 SCAR=13.9
830 63 my $self = shift;
831  
832 63 my $version = $self->_server_info->{normalized_dbms_version};
833 63 ▶ return if $version and $version < 10;
Branch: 1 branch
BranchTrueFalseTotal
if $version and $version < 10 2 61 63
Condition100%3/3
$version and $version < 10
!ll&&!rl&&r
1602
MC/DC100%2/2
$version and $version < 10
$version $version < 10
Truth table100%3/3
A and B
A= $versionB= $version < 10
ABresult
0X0
100
111
834  
835 # By position, not selectrow_hashref: the key case of that one follows the
836 # handle's FetchHashKeyName.
837 61 ▶ my @row = $self->_get_dbh->selectrow_array(<<'EOS') or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@row) = $self->_get_dbh->selectrow_array("SELECT pg_catalog.pg_is_in_recovery()::int,\n r.pid,\n r.status,\n pg_catalog.pg_wal_lsn_diff(\n pg_catalog.pg_last_wal_receive_lsn(),\n pg_catalog.pg_last_wal_replay_lsn()\n ),\n EXTRACT(EPOCH FROM\n pg_catalog.clock_timestamp() - pg_catalog.pg_last_xact_replay_timestamp()\n )\n FROM (SELECT 1) AS one\n LEFT JOIN pg_catalog.pg_stat_wal_receiver AS r ON true\n") or return 61 0 61
838 SELECT pg_catalog.pg_is_in_recovery()::int,
839 r.pid,
840 r.status,
841 pg_catalog.pg_wal_lsn_diff(
842 pg_catalog.pg_last_wal_receive_lsn(),
843 pg_catalog.pg_last_wal_replay_lsn()
844 ),
845 EXTRACT(EPOCH FROM
846 pg_catalog.clock_timestamp() - pg_catalog.pg_last_xact_replay_timestamp()
847 )
848 FROM (SELECT 1) AS one
849 LEFT JOIN pg_catalog.pg_stat_wal_receiver AS r ON true
850 EOS
851  
852 61 my %status;
853 61 @status{qw( in_recovery receiver_pid receiver_status replay_backlog replay_age )} = @row;
854  
855 61 return \%status;
856 }
857  
858  
859  
860 1 ▶sub cake_defaults {
Subroutine cake_defaults: called CC=1 SCAR=0.0
Pod documented
861 return (
862 1 inflate_jsonb => 1,
863 inflate_datetime => 1,
864 retrieve_defaults => 1,
865 );
866 }
867  
868 131 1;
869  
870 __END__
« PostgreSQL/Introspect/Normalize.pm ↑ Summary PostgreSQL/Diff/Sequence.pm »