blib/lib/DBIO/PostgreSQL/Storage.pm

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