blib/lib/DBIx/QuickORM/Connection.pm

filter: Statementstmt 90.6% 952 / 1050 Branchbran 84.0% 410 / 488 Conditioncond 79.9% 318 / 398 MC/DCmcdc 62.3% 144 / 231 Subroutinesub 91.8% 102 / 111 Podpod 92.3% 24 / 26 totaltotal 84.6% 1950 / 2304 CC 815 SCAR 25.9
CC
815
Cov
87%
insert_many
38.8
insert_many
38.8
insert
30.6
CRAP 13.3
« blib/lib/DBIx/QuickORM/Map.pm ↑ Summary blib/lib/DBIx/QuickORM/AggregateRow.pm »
1 package DBIx::QuickORM::Connection;
2 260 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 260 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 260 our $VERSION = '0.000033';
6  
7 260 ▶use Carp qw/croak confess/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 260 ▶use Scalar::Util qw/blessed refaddr weaken/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 260 ▶use List::Util qw/first/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 260 ▶use DBIx::QuickORM::Dialect();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 260 ▶use DBIx::QuickORM::Exception::DB();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 260 ▶use DBIx::QuickORM::LookupTable::Identity();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 260 ▶use DBIx::QuickORM::RowState();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 260 ▶use DBIx::QuickORM::Map();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 260 ▶use DBIx::QuickORM::Txn();
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 260 ▶use Object::HashBase qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
19 <dbh
20 <db_map
21 <time_zone
22 <datetime_parsers
23 <retain_cache
24 <enforce_canon
25 <debug
26 <isolation
27 <dialect
28 <namespace
29 <pid
30 +lookup
31 <txns
32 +txn_count
33 +busy
34 +statements
35 +find_keys
36 +defaults
37 +rescan
38 +temps
39 +gone_temps
40 +row_states
41 <lookup_class
42 260 };
43  
44 # Scans by scan_cache_key, as maps that are only ever cloned (see "The scan cache").
45 260 my %SCAN_CACHE;
46  
47 # Connections with an async query pending, so a forked child can release them at exit (see END).
48 my %PENDING;
49  
50 =pod
51  
52 =encoding UTF-8
53  
54 =head1 NAME
55  
56 DBIx::QuickORM::Connection - One database handle and the state tied to it.
57  
58 =head1 DESCRIPTION
59  
60 A Connection holds one database handle and everything that must be reset when
61 that handle is replaced: its dialect, its namespace, the pid that opened it,
62 the open transactions (L<DBIx::QuickORM::Txn>), and the lookup table of canon
63 rows (L<DBIx::QuickORM::LookupTable>). The ORM replaces the whole Connection
64 at once, as it does in a forked child. The new one starts with no transaction
65 and an empty lookup table.
66  
67 It implements the ORM's CRUD operations on plain row data and knows nothing of
68 the ORM: it returns hashrefs, which L<DBIx::QuickORM> wraps. A row object
69 given is read through its C<row_data>. The rules shared by every CRUD
70 operation (row data, C<raw>, value markers, what comes back with and without
71 C<RETURNING>) are in L<DBIx::QuickORM/"CRUD operations">. The entries here add
72 what the Connection itself does.
73  
74 Construction prepares the handle:
75  
76 =over 4
77  
78 =item *
79  
80 C<RaiseError> must be on. C<PrintError> is turned off and
81 C<AutoInactiveDestroy> on.
82  
83 =item *
84  
85 C<AutoCommit> must be on, with no transaction open: the ORM manages
86 transactions.
87  
88 =item *
89  
90 Every database error on the handle is thrown as a
91 L<DBIx::QuickORM::Exception::DB>, classified by the dialect.
92  
93 =item *
94  
95 The dialect sets up the session.
96  
97 =item *
98  
99 The connection must have a current schema or database, or construction
100 croaks.
101  
102 =back
103  
104 Rows read go through the lookup table's C<ingest>. Rows written replace its
105 entry.
106  
107 The single-row CRUD operations build their SQL once per table and set of fields
108 and run it through C<prepare_cached>. SQL holding an C<sql()> or C<binary()>
109 marker, C<insert_many>, and queries built elsewhere are prepared each time.
110  
111 In a forked child, a Connection that is freed, or still held at exit, lets go
112 of its inherited handle (C<release_inherited>), so the parent's session
113 survives.
114  
115 =head2 The scan cache
116  
117 Scanning the database is the slowest part of building a Connection. The first
118 scan of a database in a process is kept, and later Connections built without a
119 C<db_map> start from a copy of it, so the database is scanned once per
120 process. The cache holds plain map data, never a handle, so a forked child
121 uses it too.
122  
123 It is keyed by which database the handle reaches and what the session sees
124 of it, as the dialect's C<scan_cache_key> says. By default that is the
125 driver, the DSN, the user name, and the namespace. PostgreSQL adds the
126 resolved host, port, database, and user, the server address, the current
127 user, the search path, and C<quote_all_identifiers>, and caches nothing for a
128 session that already has temporary tables. MySQL and MariaDB add the server, the resolved
129 account, the active roles, and on MySQL 8.0.30 and later whether the catalog
130 shows generated invisible primary keys. SQLite uses the
131 database file's path, and DuckDB its path and namespace. An in-memory SQLite
132 or DuckDB database is never cached.
133  
134 A table changed after the scan is not seen. Pass C<rescan> after changing
135 tables in a running process, or restart it.
136  
137 =head1 SYNOPSIS
138  
139 my $conn = $orm->connection; # the ORM's current Connection (a forked child gets a new one)
140  
141 my $dialect = $conn->dialect;
142 my $schema = $conn->namespace;
143 my $lookup = $conn->lookup;
144  
145 # CRUD on plain row data: hashrefs in, hashrefs out
146 my $ann = $conn->insert(users => {name => 'Ann'});
147 my $new = $conn->update_row(users => $ann, {email => 'ann@example.com'});
148 my $found = $conn->refresh_row(users => $new->{id}); # the canon entry update_row stored: $new
149 my $count = $conn->delete_row(users => $found); # 1
150  
151 A Connection also works without an ORM. Given only a handle, as here, it
152 scans the database for its map (or copies this process's cached scan), and no
153 field gets a type. So C<prefs> takes JSON text, not a Perl structure.
154  
155 use DBI;
156 use DBIx::QuickORM::Connection;
157  
158 my $dbh = DBI->connect(
159 $dsn, $user, $pass,
160 {
161 RaiseError => 1,
162 AutoCommit => 1,
163 },
164 );
165 my $solo = DBIx::QuickORM::Connection->new(dbh => $dbh);
166 my $row = $solo->insert(
167 users => {
168 name => 'Solo',
169 prefs => '{"theme":"dark"}',
170 },
171 );
172  
173 =head1 ATTRIBUTES
174  
175 =over 4
176  
177 =item $dbh = $conn->dbh
178  
179 The database handle. Required.
180  
181 =item $map = $conn->db_map
182  
183 The Connection's own L<DBIx::QuickORM::Map>. A given map is held as its
184 C<shallow_copy>: the table records stay shared, but the table hash is this
185 Connection's, so its temporary tables and views never reach another
186 Connection. When none is given, a copy of the cached scan of the database is
187 used, or the database is scanned (see L</"The scan cache">). The ORM then
188 adjusts it in place.
189  
190 =item rescan => $bool
191  
192 A construction argument, not kept: when true and no C<db_map> is given, the
193 database is scanned again and the cache refreshed.
194  
195 =item $tz = $conn->time_zone
196  
197 The session time zone, C<UTC> unless given.
198  
199 =item \@parsers = $conn->datetime_parsers
200  
201 The ORM's C<datetime_parsers>, for the DateTime type. Empty unless given.
202 Checked as the ORM's C<new> describes. C<set_datetime_parsers> changes it.
203  
204 =item $bool = $conn->retain_cache
205  
206 Passed to the lookup table as C<retain>. 0 unless given. Croaks when true and
207 the lookup table does not cache.
208  
209 =item $class = $conn->lookup_class
210  
211 The class of the lookup table, which is built on first use. The ORM resolves its
212 C<lookup> argument to it. L<DBIx::QuickORM::LookupTable::Identity> unless
213 given. It is loaded when needed, and construction croaks unless it composes
214 L<DBIx::QuickORM::Role::LookupTable>.
215  
216 =item $bool = $conn->enforce_canon
217  
218 The default C<enforce_canon> for C<update_row> and C<delete_row> outside a
219 transaction. 1 unless given. C<set_enforce_canon> changes it.
220  
221 =item $debug = $conn->debug
222  
223 The ORM's L<DBIx::QuickORM::Debug>, passed to the lookup table, or undef
224 (the default) when nothing is recorded.
225  
226 =item $level = $conn->isolation
227  
228 The isolation level a root transaction opens at when C<txn> names none, in
229 lower case: a level C<txn> takes, or C<'server'>. Undef unless given: then
230 C<'read committed'> where the dialect C<supports_isolation>, otherwise
231 C<'server'>. An unknown level croaks.
232  
233 =item $dialect = $conn->dialect
234  
235 The L<DBIx::QuickORM::Dialect> object for the handle, holding the server
236 version.
237  
238 =item $ns = $conn->namespace
239  
240 The current schema or database, from the dialect.
241  
242 =item $pid = $conn->pid
243  
244 The process that opened the connection.
245  
246 =item \@txns = $conn->txns
247  
248 The open transactions, outermost first, as L<DBIx::QuickORM::Txn> objects
249 (held weakly). Empty outside a transaction.
250  
251 =back
252  
253 =cut
254  
255 466 ▶sub init {
Subroutine init: called CC=8 SCAR=28.2
Pod undocumented
256 0 ▶ my $self = shift;
Subroutine init: not called CC=8 SCAR=28.2
Pod undocumented
257  
258 0 my $dbh = $self->{+DBH};
259 0 ▶ croak "The connection did not produce a DBI database handle" unless blessed($dbh) && $dbh->isa('DBI::db');
Branch: 2 branches
BranchTrueFalseTotal
unless builtin::blessed($dbh) and $dbh->isa("DBI::db") 2 464 466
unless builtin::blessed($dbh) and $dbh->isa("DBI::db") 0 0 0
Condition33%2/6
builtin::blessed($dbh) and $dbh->isa("DBI::db")
!ll&&!rl&&r
20464
builtin::blessed($dbh) and $dbh->isa("DBI::db")
!ll&&!rl&&r
000
MC/DC50%1/2
builtin::blessed($dbh) and $dbh->isa("DBI::db")
builtin::blessed($dbh) $dbh->isa("DBI::db")
MC/DC0%0/2
builtin::blessed($dbh) and $dbh->isa("DBI::db")
builtin::blessed($dbh) $dbh->isa("DBI::db")
Truth table66%2/3
A and B
A= builtin::blessed($dbh)B= $dbh->isa("DBI::db")
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= builtin::blessed($dbh)B= $dbh->isa("DBI::db")
ABresult
0X0
100
111
260 0 ▶ croak "The database handle must have RaiseError on" unless $dbh->{RaiseError};
Branch: 2 branches
BranchTrueFalseTotal
unless $dbh->{"RaiseError"} 16 448 464
unless $dbh->{"RaiseError"} 0 0 0
261 croak "The database handle must have AutoCommit on and no transaction open; the ORM manages transactions"
262 0 ▶ unless $dbh->{AutoCommit};
Branch: 2 branches
BranchTrueFalseTotal
unless $dbh->{"AutoCommit"} 20 428 448
unless $dbh->{"AutoCommit"} 0 0 0
263  
264 0 $self->_init_settings;
265  
266 0 $dbh->{PrintError} = 0;
267 0 $dbh->{AutoInactiveDestroy} = 1;
268  
269 0 my $dialect = $self->{+DIALECT} = DBIx::QuickORM::Dialect->for_dbh($dbh);
270 0 ▶ if (my $why = $dialect->unsupported) { croak $why }
Branch: 2 branches
BranchTrueFalseTotal
if (my $why = $dialect->unsupported) 1 415 416
if (my $why = $dialect->unsupported) 0 0 0
271 0 $dbh->{HandleError} = $self->_error_handler($dialect, $self->{+TXNS} = []);
272 0 $dialect->init_session($dbh, $self->{+TIME_ZONE});
273  
274 0 my $ns = $self->{+NAMESPACE} = $dialect->namespace($dbh);
275 0 ▶ croak "The connection has no current schema or database; select one in the DSN" unless defined $ns;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $ns 1 414 415
unless defined $ns 0 0 0
276  
277 0 my $rescan = delete $self->{+RESCAN};
278 0 ▶ $self->{+DB_MAP} = $self->{+DB_MAP} ? $self->{+DB_MAP}->shallow_copy : $self->_scanned_map($dialect, $dbh, $ns, $rescan);
Branch: 2 branches
BranchTrueFalseTotal
$self->{'db_map'} ? : 31 383 414
$self->{'db_map'} ? : 0 0 0
279 0 $self->{+PID} = $$;
280 }
281  
282 =head1 PUBLIC METHODS
283  
284 The examples use the ORM's Connection, on PostgreSQL with the C<users> and
285 C<posts> tables of L<DBIx::QuickORM::Manual::Quickstart>:
286  
287 my $conn = $orm->connection;
288  
289 =over 4
290  
291 =item $conn->set_enforce_canon($bool)
292  
293 Changes C<enforce_canon>. Each C<update_row> and C<delete_row> reads it when
294 it runs.
295  
296 =item $conn->set_datetime_parsers(\@parsers)
297  
298 Replaces C<datetime_parsers> with a copy of C<@parsers>, checked as the ORM's
299 C<new> checks them: it loads each class, and croaks on a bad parser.
300  
301 Values read after the call use the new parsers. A DateTime field read before
302 the call keeps the parsers it was read with, even while still unparsed.
303  
304 =back
305  
306 =cut
307  
308 2 ▶sub set_enforce_canon { $_[0]->{+ENFORCE_CANON} = $_[1] }
Subroutine set_enforce_canon: called CC=1 SCAR=0.0
Pod documented
309  
310 6 ▶sub set_datetime_parsers {
Subroutine set_datetime_parsers: called CC=1 SCAR=0.0
Pod documented
311 6 my $self = shift;
312 6 my ($parsers) = @_;
313 6 $self->{+DATETIME_PARSERS} = $self->_check_datetime_parsers($parsers);
314 }
315  
316 =over 4
317  
318 =item $lookup = $conn->lookup
319  
320 The Connection's lookup table, an instance of C<lookup_class> (see
321 L<DBIx::QuickORM::LookupTable>), built on first use.
322  
323 =back
324  
325 =cut
326  
327 1796 ▶sub lookup {
Subroutine lookup: called CC=2 SCAR=7.1
Pod documented
328 1796 my $self = shift;
329 1796 ▶ return $self->{+LOOKUP} //= $self->{+LOOKUP_CLASS}->new(connection => $self);
Condition66%2/3
$self->{"lookup"} //= $self->{"lookup_class"}->new("connection", $self)
l!l&&r!l&&!r
16561400
MC/DC0%0/2
$self->{"lookup"} //= $self->{"lookup_class"}->new("connection", $self)
$self->{"lookup"} $self->{"lookup_class"}->new("connection", $self)
Truth table66%2/3
A //= B
A= $self->{"lookup"}B= $self->{"lookup_class"}->new("connection", $self)
ABresult
1X1
011
000
330 }
331  
332 =over 4
333  
334 =item $rs = $conn->row_states
335  
336 The Connection's L<DBIx::QuickORM::RowState>, built on first use. Its
337 transaction code drives it, so marks follow transactions whatever the lookup
338 table.
339  
340 =back
341  
342 =cut
343  
344 942 ▶sub row_states { $_[0]->{+ROW_STATES} //= DBIx::QuickORM::RowState->new(debug => $_[0]->{+DEBUG}) }
Subroutine row_states: called CC=2 SCAR=7.2
Pod documented
Condition66%2/3
$_[0]{"row_states"} //= "DBIx::QuickORM::RowState"->new("debug", $_[0]{"debug"})
l!l&&r!l&&!r
8021400
MC/DC0%0/2
$_[0]{"row_states"} //= "DBIx::QuickORM::RowState"->new("debug", $_[0]{"debug"})
$_[0]{"row_states"} "DBIx::QuickORM::RowState"->new("debug", $_[0]{"debug"})
Truth table66%2/3
A //= B
A= $_[0]{"row_states"}B= "DBIx::QuickORM::RowState"->new("debug", $_[0]{"debug"})
ABresult
1X1
011
000
345  
346 =over 4
347  
348 =item $bool = $conn->is_canon($table, $row_or_data)
349  
350 The lookup table's C<is_canon> for the row data (or a row object's
351 C<row_data>): for the default, whether it is the entry for its primary key.
352 Croaks when the primary key cannot be determined, unless the row data is
353 deleted or not in the database.
354  
355 my $ann = $conn->insert(users => {name => 'Ann'});
356 my $copy = {%$ann};
357  
358 $conn->is_canon(users => $ann); # 1: the lookup table's entry
359 $conn->is_canon(users => $copy); # 0: the same row, but another hash
360  
361 =back
362  
363 =cut
364  
365 169 ▶sub is_canon {
Subroutine is_canon: called CC=1 SCAR=0.0
Pod documented
366 169 my $self = shift;
367 169 my ($table, $data) = @_;
368 169 return $self->lookup->is_canon($table, $self->_row_data($data));
369 }
370  
371 =over 4
372  
373 =item $status = $conn->canon_status($table, $row_or_data)
374  
375 The lookup table's C<canon_status> for the row data (or a row object's
376 C<row_data>): undef while canonical, otherwise why not.
377  
378 my $ann = $conn->insert(users => {name => 'Ann'});
379 $conn->canon_status(users => $ann); # undef: canonical
380  
381 my $anne = $conn->update_row(users => $ann, {name => 'Anne'});
382 $conn->canon_status(users => $ann); # {cause => 'replaced'}
383  
384 =back
385  
386 =cut
387  
388 26 ▶sub canon_status {
Subroutine canon_status: called CC=1 SCAR=0.0
Pod documented
389 26 my $self = shift;
390 26 my ($table, $data) = @_;
391 26 return $self->lookup->canon_status($table, $self->_row_data($data));
392 }
393  
394 =over 4
395  
396 =item $data = $conn->insert($table, \%fields, raw => $bool, as_given => $bool, void => $bool)
397  
398 Inserts one row and returns its new row data, now the lookup table's entry.
399 Where the primary key comes from, C<as_given>, and the croaks, are as
400 L<DBIx::QuickORM/"CRUD operations"> describes for C<insert>.
401  
402 # the row as the database holds it, its generated id included
403 my $ann = $conn->insert(users => {name => 'Ann'});
404  
405 # values already in database form
406 my $bo = $conn->insert(
407 users => {
408 name => 'Bo',
409 prefs => '{"theme":"dark"}',
410 },
411 raw => 1,
412 );
413  
414 # the values given plus the key the database generated: {id => $new_id, name => 'Cy'}
415 my $cy = $conn->insert(
416 users => {name => 'Cy'},
417 as_given => 1,
418 );
419  
420 # nothing read back or returned
421 $conn->insert(
422 users => {name => 'Di'},
423 void => 1,
424 );
425  
426 Primary key fields left out may get generated values first (see
427 C<_generate_keys>). C<as_given> includes them.
428  
429 A table without a primary key returns the C<RETURNING> row without storing it
430 in the lookup table.
431  
432 With C<as_given>, C<RETURNING> names only the primary key fields, and the
433 result is never stored.
434  
435 C<< void => 1 >> is what the ORM passes in void context: the row is inserted
436 without C<RETURNING>, nothing is stored or returned, and none of the primary
437 key croaks apply.
438  
439 =back
440  
441 =cut
442  
443 260 my %INSERT_ARGS = map { $_ => 1 } qw/raw void as_given/;
444  
445 363 ▶sub insert {
Subroutine insert: called CC=30 SCAR=34.2
Pod documented
446 363 my $self = shift;
447 363 my ($table, $fields, %params) = @_;
448  
449 363 $self->_check_params(insert => \%INSERT_ARGS, \%params);
450 362 my $t = $self->_table($table);
451 361 my $values = $self->_row_data($fields);
452 361 ▶ confess "insert() into '$table' needs at least one field" unless %$values;
Branch: 1 branch
BranchTrueFalseTotal
unless %$values 2 359 361
453 359 my $generated = $self->_generate_keys($t, $values);
454 359 $values = {%{$self->deflate($table, $values, raw => $params{raw})}, %{$self->deflate($table, $generated)}};
455 355 my @names = sort keys %$values;
456  
457 355 my $void = $params{void};
458 355 my $as_given = $params{as_given};
459 355 my $dialect = $self->{+DIALECT};
460 355 ▶ my $pk = $t->{pk} && @{$t->{pk}} ? $t->{pk} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$t->{'pk'} && @{$t->{'pk'};} ? : 351 4 355
Condition66%2/3
$t->{"pk"} and @{$t->{"pk"};}
!ll&&!rl&&r
40351
MC/DC50%1/2
$t->{"pk"} and @{$t->{"pk"};}
$t->{"pk"} @{$t->{"pk"};}
Truth table66%2/3
A and B
A= $t->{"pk"}B= @{$t->{"pk"};}
ABresult
0X0
100
111
461 355 ▶ my $returning = !$void && ($pk || !$as_given) && $dialect->supports_returning_insert;
Condition100%9/9
!$void && ($pk || !$as_given) && $dialect->supports_returning_insert
!ll&&!rl&&r
1731181
not $void and $pk || !$as_given
!ll&&!rl&&r
1721182
$pk or not $as_given
l!l&&r!l&&!r
18111
MC/DC100%4/4
!$void && ($pk || !$as_given) && $dialect->supports_returning_insert
not $void $pk not $as_given $dialect->supports_returning_insert
Truth table83%5/6
not(A) and B or not(C) && D
A= not $voidB= $pkC= not $as_givenD= $dialect->supports_returning_insert
ABCDresult
0XXX0
100X0
11X00
10100
11X11
10111
462 355 ▶ my $given_pk = $pk && !grep { !defined($values->{$_}) || $self->_is_sql($values->{$_}) } @$pk;
Condition100%6/6
$pk && !grep({not defined $values->{$_} or $self->_is_sql($values->{$_});} @$pk)
!ll&&!rl&&r
440311
!defined($values->{$_}) || $self->_is_sql($values->{$_})
l!l&&r!l&&!r
391326
MC/DC100%2/2
$pk && !grep({not defined $values->{$_} or $self->_is_sql($values->{$_});} @$pk)
$pk !grep({not defined $values->{$_} or $self->_is_sql($values->{$_});} @$pk)
MC/DC100%2/2
!defined($values->{$_}) || $self->_is_sql($values->{$_})
!defined($values->{$_}) $self->_is_sql($values->{$_})
Truth table100%3/3
A && not(B)
A= $pkB= !grep({not defined $values->{$_} or $self->_is_sql($values->{$_});} @$pk)
ABresult
0X0
100
111
Truth table100%3/3
not(A) || B
A= !defined($values->{$_})B= $self->_is_sql($values->{$_})
ABresult
1X1
011
000
463 355 ▶ unless ($void || $returning) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($void or $returning) 2 353 355
Condition100%3/3
$void or $returning
l!l&&r!l&&!r
1721812
MC/DC100%2/2
$void or $returning
$void $returning
Truth table100%3/3
A or B
A= $voidB= $returning
ABresult
1X1
011
000
464 2 ▶ confess "insert() into '$table' has nothing to return: the table has no primary key and the database cannot return the row; call it in void context" unless $pk || $as_given;
Branch: 1 branch
BranchTrueFalseTotal
unless $pk or $as_given 0 2 2
Condition66%2/3
$pk or $as_given
l!l&&r!l&&!r
110
MC/DC0%0/2
$pk or $as_given
$pk $as_given
Truth table66%2/3
A or B
A= $pkB= $as_given
ABresult
1X1
011
000
465 2 ▶ confess "insert() into '$table' needs every primary key field, since the database cannot return a compound key it generates" if $pk && !$given_pk && @$pk > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $pk and not $given_pk and @$pk > 1 0 2 2
Condition66%4/6
$pk and not $given_pk and @$pk > 1
!ll&&!rl&&r
110
$pk and not $given_pk
!ll&&!rl&&r
101
MC/DC0%0/3
$pk and not $given_pk and @$pk > 1
$pk not $given_pk @$pk > 1
Truth table50%2/4
A and not(B) and C
A= $pkB= not $given_pkC= @$pk > 1
ABCresult
0XX0
10X0
1100
1111
466 }
467  
468 355 my ($places, $binds, $marked) = $self->_value_sql($values, @names);
469 355 ▶ my $shape = $marked ? undef : join("\0" => 'insert', $table, ($returning ? ($as_given ? 'pk' : 'all') : ''), @names);
Branch: 3 branches
BranchTrueFalseTotal
$marked ? : 10 345 355
$returning ? : 179 166 345
$as_given ? : 7 172 179
470 my $sql = $self->_statement(
471 $shape,
472 204 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
473 204 my $sql = 'INSERT INTO ' . $dialect->quote_identifier($table) . ' (' . join(', ' => map { $dialect->quote_identifier($_) } @names) . ') VALUES (' . join(', ' => @$places) . ')';
474 204 ▶ $returning ? $sql . $self->_returning_sql($as_given ? $pk : $self->_read_back_fields($table, @names)) : $sql;
Branch: 2 branches
BranchTrueFalseTotal
$returning ? : 110 94 204
$as_given ? : 7 103 110
475 }
476 355 );
477 355 my $sth = $self->_run($t->{fields}, $sql, $binds, undef, defined $shape);
478 330 ▶ return if $void;
Branch: 1 branch
BranchTrueFalseTotal
if $void 153 177 330
479  
480 177 ▶ my $data = $returning ? $self->_fetch($t->{fields}, $sth)->[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$returning ? : 175 2 177
481 177 ▶ if ($pk && !$data && $given_pk) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pk and not $data and $given_pk) { } 0 177 177
elsif ($pk and not $data) { } 1 178 179
Condition83%5/6
$pk and not $data and $given_pk
!ll&&!rl&&r
17610
$pk and not $data
!ll&&!rl&&r
21741
MC/DC0%0/3
$pk and not $data and $given_pk
$pk not $data $given_pk
Truth table75%3/4
A and not(B) and C
A= $pkB= not $dataC= $given_pk
ABCresult
0XX0
10X0
1100
1111
482 0 $data = $self->_plain({map { $_ => $values->{$_} } @$pk});
483 }
484 ▶ elsif ($pk && !$data) {
Condition100%3/3
$pk and not $data
!ll&&!rl&&r
21741
MC/DC100%2/2
$pk and not $data
$pk not $data
Truth table100%3/3
A and not(B)
A= $pkB= not $data
ABresult
0X0
100
111
485 # Only MySQL gets here (no RETURNING). DBD::MariaDB gives 0 when the insert
486 # generated no key, and AUTO_INCREMENT never generates 0, so 0 is "none".
487 1 ▶ my $id = $dialect->last_insert_id($self->{+DBH}, $table, $pk->[0]) or confess "insert() into '$table' did not give a value for the primary key '$pk->[0]', and the database generated none";
Branch: 1 branch
BranchTrueFalseTotal
my $id = $dialect->last_insert_id($self->{"dbh"}, $table, $pk->[0]) or confess("insert() into '${table}' did not give a value for the primary key '$pk->[0]', and the database generated none") 1 0 1
488 1 $data = {$pk->[0] => $id};
489 }
490  
491 177 my $lookup = $self->lookup;
492 177 my $out;
493 177 ▶ if ($as_given) {
Branch: 1 branch
BranchTrueFalseTotal
if ($as_given) { } 9 168 177
494 9 my %copy = map { $_ => $values->{$_} } grep { !$self->_is_sql($values->{$_}) } @names;
495 9 ▶ $out = {%{$self->_plain(\%copy)}, %{$data // {}}};
Condition100%2/2
$data // {}
l!l
81
MC/DC100%1/1
$data // {}
$data
Truth table100%2/2
A
A= $data
Aresult
11
00
496 }
497 else {
498 168 ▶ $out = $pk ? $lookup->store($table, $data) : $data;
Branch: 1 branch
BranchTrueFalseTotal
$pk ? : 167 1 168
499 }
500  
501 177 $self->row_states->mark_inserted($out);
502 177 return $out;
503 }
504  
505 =over 4
506  
507 =item \@data = $conn->insert_many($table, \@rows, raw => $bool)
508  
509 =item $count = $conn->insert_many($table, \@rows, count => 1, raw => $bool)
510  
511 =item $conn->insert_many($table, \@rows, void => 1, raw => $bool)
512  
513 Generates missing primary key values for each row as C<insert> does, then
514 inserts the rows in multi-row C<INSERT> statements, each holding as many rows
515 as the dialect's C<bind_limit> allows. The batching, the transaction around
516 it, and the croaks are as L<DBIx::QuickORM/"CRUD operations"> describes for
517 C<insert_many>.
518  
519 # an arrayref of the new rows' row data
520 my $rows = $conn->insert_many(users => [{name => 'Ed'}, {name => 'Flo'}]);
521  
522 # how many went in: 2
523 my $count = $conn->insert_many(
524 users => [{name => 'Gus'}, {name => 'Hal'}],
525 count => 1,
526 );
527  
528 $conn->insert_many(
529 users => [{name => 'Ida'}],
530 void => 1,
531 );
532  
533 It returns an arrayref of the new rows' row data, now the lookup table's
534 entries (a table without a primary key bypasses it). Without C<RETURNING> each
535 holds the primary key taken from the given values.
536  
537 C<< count => 1 >> returns how many rows the database reports inserted
538 instead, and C<< void => 1 >> (what the ORM passes in void context) returns
539 nothing useful. Neither sends C<RETURNING> or stores anything.
540  
541 An empty C<\@rows> sends nothing and returns an empty arrayref, or 0 with
542 C<count>.
543  
544 The field list and the keys to generate are decided once per call. Each
545 value is deflated as C<deflate> would (C<_insert_many_chunks>, or
546 C<_insert_many_hashes> for a column with a format hint). Plain rows go out in
547 statements of as many rows as the bind limit allows, through C<_run_plain>.
548 When a value is a marker or a column has bind attributes (a binary field),
549 every row is batched by its actual binds through C<_batches>, and each
550 statement goes through C<_run_plain> when it holds neither a C<sql()> marker
551 nor a value needing bind attributes, else through C<_run>.
552  
553 =back
554  
555 =cut
556  
557 260 my %INSERT_MANY_ARGS = map { $_ => 1 } qw/raw count void/;
558  
559 71 ▶sub insert_many {
Subroutine insert_many: called CC=32 SCAR=36.6
Pod documented
560 71 my $self = shift;
561 71 my ($table, $rows, %params) = @_;
562  
563 71 $self->_check_params(insert_many => \%INSERT_MANY_ARGS, \%params);
564 67 my $t = $self->_table($table);
565 67 ▶ confess "insert_many() needs an arrayref of rows" unless ref($rows) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rows eq "ARRAY" 1 66 67
566 66 ▶ my $returning = !$params{void} && !$params{count};
Condition100%3/3
$params{'void'} || $params{'count'}
l!l&&r!l&&!r
34824
MC/DC100%2/2
$params{'void'} || $params{'count'}
$params{'void'} $params{'count'}
Truth table100%3/3
A || B
A= $params{'void'}B= $params{'count'}
ABresult
1X1
011
000
567 66 ▶ return $returning ? [] : 0 unless @$rows;
Branch: 2 branches
BranchTrueFalseTotal
unless @$rows 6 60 66
$returning ? : 3 3 6
568 60 my @values = map { $self->_row_data($_) } @$rows;
569 60 my @names = sort keys %{$values[0]};
570 60 ▶ confess "insert_many() into '$table' needs at least one field in each row" unless @names;
Branch: 1 branch
BranchTrueFalseTotal
unless @names 1 59 60
571  
572 59 for my $i (1 .. $#values) {
573 2769 my $v = $values[$i];
574 2769 ▶ confess "insert_many() into '$table' needs the same fields in every row, but row $i differs from the first" unless keys(%$v) == @names && !grep { !exists $v->{$_} } @names;
Branch: 1 branch
BranchTrueFalseTotal
unless keys %$v == @names and not grep({not exists $v->{$_};} @names) 2 2767 2769
Condition100%3/3
keys %$v == @names and not grep({not exists $v->{$_};} @names)
!ll&&!rl&&r
112767
MC/DC100%2/2
keys %$v == @names and not grep({not exists $v->{$_};} @names)
keys %$v == @names not grep({not exists $v->{$_};} @names)
Truth table100%3/3
A and not(B)
A= keys %$v == @namesB= not grep({not exists $v->{$_};} @names)
ABresult
0X0
100
111
575 }
576  
577 57 $self->_check_fields($table, @names);
578 56 my $fields = $t->{fields};
579 56 my $dialect = $self->{+DIALECT};
580  
581 # The keys to generate and the column list are decided once, since every row has the first row's fields. A
582 # format hint's result is used as it comes, so formatted columns keep the per-row deflate exactly as it was.
583 56 my @gen = $self->_key_generators($t, $values[0]);
584 56 my @cols = sort(@names, @gen);
585 56 ▶ my $per = int($dialect->bind_limit / @cols) || 1;
Condition50%1/2
int $dialect->bind_limit / @cols || 1
l!l
560
MC/DC0%0/1
int $dialect->bind_limit / @cols || 1
int $dialect->bind_limit / @cols
Truth table50%1/2
A
A= int $dialect->bind_limit / @cols
Aresult
11
00
586 56 my ($chunks, $hashes, $marked);
587 56 ▶ if (grep { $fields->{$_}->{format} } @cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$fields->{$_}{'format'};} @cols) { } 2 54 56
588 2 $hashes = $self->_insert_many_hashes($table, $t, \@values, \@names, \@gen, $params{raw});
589 2 @cols = sort keys %{$hashes->[0]};
590 }
591 54 else { ($chunks, $marked) = $self->_insert_many_chunks($table, $t, \@values, \@names, \@gen, \@cols, $per, $params{raw}) }
592  
593 # A marker or a column with bind attributes (a binary field) batches every row by its actual binds, through
594 # _batches as before. Each statement then goes through _run_plain when it holds only plain values.
595 55 my $binary = grep { defined $dialect->bind_attrs($fields->{$_}) } @cols;
596 55 ▶ $hashes //= $self->_insert_many_rows($chunks, \@cols) if $marked || $binary;
Branch: 1 branch
BranchTrueFalseTotal
if $marked or $binary 9 46 55
Condition66%4/6
$marked or $binary
l!l&&r!l&&!r
7246
$hashes //= $self->_insert_many_rows($chunks, \@cols)
l!l&&r!l&&!r
090
MC/DC100%2/2
$marked or $binary
$marked $binary
MC/DC0%0/2
$hashes //= $self->_insert_many_rows($chunks, \@cols)
$hashes $self->_insert_many_rows($chunks, \@cols)
Truth table100%3/3
A or B
A= $markedB= $binary
ABresult
1X1
011
000
Truth table33%1/3
A //= B
A= $hashesB= $self->_insert_many_rows($chunks, \@cols)
ABresult
1X1
011
000
597  
598 55 ▶ my $pk = $t->{pk} && @{$t->{pk}} ? $t->{pk} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$t->{'pk'} && @{$t->{'pk'};} ? : 51 4 55
Condition66%2/3
$t->{"pk"} and @{$t->{"pk"};}
!ll&&!rl&&r
4051
MC/DC50%1/2
$t->{"pk"} and @{$t->{"pk"};}
$t->{"pk"} @{$t->{"pk"};}
Truth table66%2/3
A and B
A= $t->{"pk"}B= @{$t->{"pk"};}
ABresult
0X0
100
111
599 55 ▶ my $sql_ret = $returning && $dialect->supports_returning_insert;
Condition66%2/3
$returning && $dialect->supports_returning_insert
!ll&&!rl&&r
34021
MC/DC50%1/2
$returning && $dialect->supports_returning_insert
$returning $dialect->supports_returning_insert
Truth table66%2/3
A && B
A= $returningB= $dialect->supports_returning_insert
ABresult
0X0
100
111
600 55 my @keys;
601 55 ▶ if ($returning && !$sql_ret) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returning and not $sql_ret) 0 55 55
Condition66%2/3
$returning and not $sql_ret
!ll&&!rl&&r
34210
MC/DC0%0/2
$returning and not $sql_ret
$returning not $sql_ret
Truth table66%2/3
A and not(B)
A= $returningB= not $sql_ret
ABresult
0X0
100
111
602 0 ▶ confess "insert_many() into '$table' cannot return rows: the table has no primary key and the database cannot return them; pass count => 1 for how many went in" unless $pk;
Branch: 1 branch
BranchTrueFalseTotal
unless $pk 0 0 0
603 @keys = map {
604 0 my $row = $_;
605 0 +{map { ($_ => $row->{$_}) } @$pk}
606 0 ▶ } @{$hashes // $self->_insert_many_rows($chunks, \@cols)};
Condition0%0/3
$hashes // $self->_insert_many_rows($chunks, \@cols)
l!l&&r!l&&!r
000
MC/DC0%0/2
$hashes // $self->_insert_many_rows($chunks, \@cols)
$hashes $self->_insert_many_rows($chunks, \@cols)
Truth table0%0/3
A // B
A= $hashesB= $self->_insert_many_rows($chunks, \@cols)
ABresult
1X1
011
000
607 confess "insert_many() into '$table' cannot return rows unless every row carries its whole primary key, since the database cannot return the keys it generates; pass count => 1 for how many went in"
608 if grep {
609 0 ▶ my $key = $_;
Branch: 1 branch
BranchTrueFalseTotal
if grep {my $key = $_; grep {not defined $_ or $self->_is_sql($_);} values %$key;} @keys 0 0 0
610 0 ▶ grep { !defined($_) || $self->_is_sql($_) } values %$key
Condition0%0/3
!defined($_) || $self->_is_sql($_)
l!l&&r!l&&!r
000
MC/DC0%0/2
!defined($_) || $self->_is_sql($_)
!defined($_) $self->_is_sql($_)
Truth table0%0/3
not(A) || B
A= !defined($_)B= $self->_is_sql($_)
ABresult
1X1
011
000
611 } @keys;
612 }
613  
614 55 my $into = 'INSERT INTO ' . $dialect->quote_identifier($table) . ' (' . join(', ' => map { $dialect->quote_identifier($_) } @cols) . ') VALUES ';
615 55 ▶ my $ret = $sql_ret ? $self->_returning_sql($self->_read_back_fields($table, @cols)) : '';
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 34 55
616 55 my $place = '(' . join(', ' => ('?') x @cols) . ')';
617 my @batches = $hashes
618 ? map {
619 12 my ($places, $binds, $marked) = @$_;
620 # A marker may leave a placeholder for _run's binding to treat as NULL, or need a bind attribute, so only
621 # statements without one go through _run_plain.
622 12 ▶ my $plain = !$binary && !$marked;
Condition100%3/3
$binary || $marked
l!l&&r!l&&!r
273
MC/DC100%2/2
$binary || $marked
$binary $marked
Truth table100%3/3
A || B
A= $binaryB= $marked
ABresult
1X1
011
000
623 12 ▶ [$plain, $into . join(', ' => @$places) . $ret, $plain ? [map { $_->[1] } @$binds] : $binds]
Branch: 1 branch
BranchTrueFalseTotal
$plain ? : 3 9 12
624 } $self->_batches($hashes, \@cols)
625 55 ▶ : map { [1, $into . join(', ' => ($place) x (@$_ / @cols)) . $ret, $_] } @$chunks;
Branch: 1 branch
BranchTrueFalseTotal
$hashes ? : 11 44 55
626  
627 55 ▶ my $send = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
628 55 my ($count, @got) = (0);
629 55 for my $batch (@batches) {
630 67 my ($plain, $sql, $binds) = @$batch;
631 67 ▶ my $sth = $plain ? $self->_run_plain($sql, $binds) : $self->_run($fields, $sql, $binds);
Branch: 1 branch
BranchTrueFalseTotal
$plain ? : 58 9 67
632 64 ▶ if ($sql_ret) { push @got => @{$self->_fetch($fields, $sth)} }
Branch: 1 branch
BranchTrueFalseTotal
if ($sql_ret) { } 24 40 64
633 40 else { $count += $sth->rows }
634 }
635 52 ▶ return $sql_ret ? \@got : $count;
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 31 52
636 55 };
637  
638 55 ▶ my $own_txn = @{$self->{+TXNS}} ? $dialect->supports_savepoints : @batches > 1;
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'txns'};} ? : 3 52 55
639 55 ▶ my $out = $own_txn ? $self->txn($send) : $send->();
Branch: 1 branch
BranchTrueFalseTotal
$own_txn ? : 9 46 55
640 52 ▶ return $out unless $returning;
Branch: 1 branch
BranchTrueFalseTotal
unless $returning 31 21 52
641  
642 # Without RETURNING each row is its primary key, taken from the given values.
643 0 ▶ my @got = $sql_ret ? @$out : map { $self->_plain($_) } @keys;
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 0 21
644  
645 21 my $lookup = $self->lookup;
646 21 ▶ @got = map { $lookup->store($table, $_) } @got if $pk;
Branch: 1 branch
BranchTrueFalseTotal
if $pk 20 1 21
647 21 $self->row_states->mark_inserted(@got);
648 21 return \@got;
649 }
650  
651 =pod
652  
653 =over 4
654  
655 =item (\@chunks, $marked) = $conn->_insert_many_chunks($table, \%table, \@values, \@names, \@generate, \@columns, $per, $raw)
656  
657 The rows' deflated values, packed in column order into flat arrays of up to
658 C<$per> rows each, one per statement. Each row's keys in C<@generate> are made
659 first, in primary key order. Then its given fields deflate in name order, then
660 its generated keys (without C<raw>). A plain value of an untyped column (with
661 C<$raw>, any plain value, and undef always) is used as is, and every other
662 value goes through C<_deflate_value>. C<$marked> is true when a deflated value
663 is a marker.
664  
665 =item \@rows = $conn->_insert_many_hashes($table, \%table, \@values, \@names, \@generate, $raw)
666  
667 The rows deflated one hash at a time, each value through C<_deflate_value> in
668 list context, for calls with a column that has a format hint, whose result is
669 used as it comes. Each row's keys in C<@generate> are made first and deflated
670 after its given fields.
671  
672 =item \@rows = $conn->_insert_many_rows(\@chunks, \@columns)
673  
674 The chunks' rows as hashes, for C<_batches> and for keys read back without
675 C<RETURNING>.
676  
677 =back
678  
679 =cut
680  
681 54 ▶sub _insert_many_chunks {
Subroutine _insert_many_chunks: called CC=18 SCAR=29.0
682 54 my $self = shift;
683 54 my ($table, $t, $values, $names, $gen, $cols, $per, $raw) = @_;
684  
685 54 my $fields = $t->{fields};
686 54 my $width = @$cols;
687 54 my %slot = map { ($cols->[$_] => $_) } 0 .. $#$cols;
688 54 ▶ my @given = map { [$_, $fields->{$_}, $fields->{$_}->{orm_type} ? 1 : 0, $slot{$_}] } @$names;
Branch: 1 branch
BranchTrueFalseTotal
$fields->{$_}{'orm_type'} ? : 8 171 179
689 54 my @generated = map { [$_, $fields->{$_}, $slot{$_}] } @$gen;
690  
691 54 my ($marked, $in, @chunks) = (0, $per);
692 54 for (@$values) { # $_ is this call's copy of the row while user code runs, as it was under the old map
693 2820 my $v = $_;
694 2820 ▶ push @chunks => [] and $in = 0 if $in == $per;
Branch: 1 branch
BranchTrueFalseTotal
if $in == $per 67 2753 2820
Condition50%3/6
$in == $per && (push(@chunks, []) && ($in = 0))
!ll&&!rl&&r
2753670
push @chunks, [] and $in = 0
!ll&&!rl&&r
0670
MC/DC0%0/3
$in == $per && (push(@chunks, []) && ($in = 0))
$in == $per push @chunks, [] $in = 0
Truth table0%0/4
A && B and C
A= $in == $perB= push @chunks, []C= $in = 0
ABCresult
0XX0
10X0
1100
1111
695 2820 my $buf = $chunks[-1];
696 2820 my $at = @$buf;
697 2820 my @made;
698 2820 for my $name (@$gen) { push @made => scalar $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
699 2820 $#$buf = $at + $width - 1;
700  
701 # While a type deflates, $_ is the field's name, as it was under the old map over the names.
702 2820 for my $p (@given) {
703 13106 my ($name, $field, $typed, $slot) = @$p;
704 13106 my $value = $v->{$name};
705 13106 ▶ if (ref($value) || (defined($value) && !$raw && $typed)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value or defined $value and not $raw and $typed) 30 13076 13106
Condition100%9/9
ref $value or defined $value and not $raw and $typed
l!l&&r!l&&!r
28213076
defined $value and not $raw and $typed
!ll&&!rl&&r
14130622
defined $value and not $raw
!ll&&!rl&&r
5913064
MC/DC100%4/4
ref $value or defined $value and not $raw and $typed
ref $value defined $value not $raw $typed
Truth table100%5/5
A or B and not(C) and D
A= ref $valueB= defined $valueC= not $rawD= $typed
ABCDresult
1XXX1
01111
00XX0
010X0
01100
706 30 local $_ = $name;
707 30 $value = $self->_deflate_value($table, $name, $field, $value, $raw);
708 29 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 7 22 29
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
2207
MC/DC50%1/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table66%2/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
709 }
710 13105 $buf->[$at + $slot] = $value;
711 }
712  
713 # Generated keys deflate in the order of a hash built as _generate_keys builds one, as they always did.
714 2819 my @order = 0 .. $#generated;
715 2819 ▶ if (@order > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@order > 1) 2 2817 2819
716 2 my %made;
717 2 $made{$gen->[$_]} = $_ for @order;
718 2 @order = map { $made{$_} } keys %made;
719 }
720 2819 for my $i (@order) {
721 14 my ($name, $field, $slot) = @{$generated[$i]};
722 14 local $_ = $name;
723 14 my $value = $self->_deflate_value($table, $name, $field, $made[$i]);
724 14 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 0 14 14
Condition33%1/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
1400
MC/DC0%0/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table33%1/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
725 14 $buf->[$at + $slot] = $value;
726 }
727 2819 $in++;
728 }
729  
730 53 return (\@chunks, $marked);
731 }
732  
733 2 ▶sub _insert_many_hashes {
Subroutine _insert_many_hashes: called CC=3 SCAR=11.0
734 2 my $self = shift;
735 2 my ($table, $t, $values, $names, $gen, $raw) = @_;
736  
737 2 my $fields = $t->{fields};
738 return [
739 map {
740 2 my $v = $_;
741 3 my %generated;
742 0 for my $name (@$gen) { $generated{$name} = $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
743 3 my %out = map { ($_ => $self->_deflate_value($table, $_, $fields->{$_}, $v->{$_}, $raw)) } @$names;
744 3 $out{$_} = $self->_deflate_value($table, $_, $fields->{$_}, $generated{$_}) for keys %generated;
745 3 \%out;
746 } @$values
747 ];
748 }
749  
750 9 ▶sub _insert_many_rows {
Subroutine _insert_many_rows: called CC=3 SCAR=11.0
751 9 my $self = shift;
752 9 my ($chunks, $cols) = @_;
753  
754 9 my @rows;
755 9 for my $chunk (@$chunks) {
756 11 ▶ for (my $at = 0; $at < @$chunk; $at += @$cols) {
Branch: 1 branch
BranchTrueFalseTotal
if ($at < @$chunk) 1347 11 1358
757 1347 push @rows => {map { ($cols->[$_] => $chunk->[$at + $_]) } 0 .. $#$cols};
758 }
759 }
760  
761 9 return \@rows;
762 }
763  
764 =over 4
765  
766 =item $data = $conn->update_row($table, \%data, \%changes, %opts)
767  
768 Updates one row, found by the primary key in the row data, and returns its new
769 row data, or undef when no row matched.
770  
771 my $ann = $conn->insert(users => {name => 'Ann'});
772  
773 # the new row data, now the lookup table's entry: $ann is stale
774 my $new = $conn->update_row(users => $ann, {email => 'ann@example.com'});
775  
776 # compare-and-swap: writes only while the database still holds the name
777 # $new read, else returns undef
778 my $renamed = $conn->update_row(
779 users => $new,
780 {name => 'Anne'},
781 cas => ['name'],
782 );
783 die "Ann was renamed elsewhere" unless $renamed;
784  
785 # auto_cas: compare every changed field the row data holds
786 my $again = $conn->update_row(
787 users => $renamed,
788 {name => 'Annie'},
789 auto_cas => 1,
790 );
791  
792 # stale row data croaks unless the check is off. Its name is not the
793 # database's any more, so this compare-and-swap misses: undef
794 my $missed = $conn->update_row(
795 users => $ann,
796 {name => 'Bob'},
797 cas => ['name'],
798 enforce_canon => 0,
799 );
800  
801 The new row data replaces the old in the lookup table, re-keyed when the
802 primary key changed. Undef leaves the lookup table alone. At least one change
803 is required. Setting a primary key field with C<sql()> croaks on a database
804 without C<RETURNING> for C<UPDATE>, since the new key could not be known.
805  
806 With C<RETURNING>, the new row data holds the default fields, the fields
807 changed, and the fields the old row data held, as the database returns them.
808  
809 The options C<enforce_canon>, C<cas>, and C<auto_cas> are as
810 L<DBIx::QuickORM/"CRUD operations"> describes for C<update_row>. Each C<cas>
811 field must be in the row data.
812  
813 =back
814  
815 =cut
816  
817 260 my %UPDATE_ARGS = map { $_ => 1 } qw/enforce_canon cas auto_cas raw/;
818  
819 166 ▶sub update_row {
Subroutine update_row: called CC=13 SCAR=25.7
Pod documented
820 166 my $self = shift;
821 166 my ($table, $data, $changes, %params) = @_;
822  
823 166 $self->_check_params(update_row => \%UPDATE_ARGS, \%params);
824 165 my $t = $self->_table($table);
825 164 $data = $self->_row_data($data);
826 163 ▶ confess "update_row() needs a hashref of at least one change" unless ref($changes) eq 'HASH' && %$changes;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $changes eq "HASH" and %$changes 2 161 163
Condition66%2/3
ref $changes eq "HASH" and %$changes
!ll&&!rl&&r
02161
MC/DC50%1/2
ref $changes eq "HASH" and %$changes
ref $changes eq "HASH" %$changes
Truth table66%2/3
A and B
A= ref $changes eq "HASH"B= %$changes
ABresult
0X0
100
111
827 161 my @set = sort keys %$changes;
828  
829 161 my $pk = $self->_pk_values($table, $data, $params{raw});
830 158 $self->_enforce_canon($table, $data, $params{enforce_canon});
831 135 my $where = {%{$self->deflate($table, {$self->_cas_values($table, $data, $changes, \%params)}, raw => $params{raw})}, %$pk};
832 130 $changes = $self->deflate($table, $changes, raw => $params{raw});
833  
834 129 my $dialect = $self->{+DIALECT};
835 129 my $returning = $dialect->supports_returning_update;
836 129 my @sql_pk = grep { $self->_is_sql($changes->{$_}) } keys %$pk;
837 129 ▶ confess "update_row() cannot set the primary key of '$table' with sql() on a database without RETURNING for UPDATE, since the new key could not be known" if @sql_pk && !$returning;
Branch: 1 branch
BranchTrueFalseTotal
if @sql_pk and not $returning 1 128 129
Condition66%2/3
@sql_pk and not $returning
!ll&&!rl&&r
12801
MC/DC50%1/2
@sql_pk and not $returning
@sql_pk not $returning
Truth table66%2/3
A and not(B)
A= @sql_pkB= not $returning
ABresult
0X0
100
111
838  
839 # Fields the row already holds come back too, so an update keeps what the row read (its JSON, say). When the
840 # row holds and writes only default fields, that is the default list itself.
841 128 my $back = [];
842 128 ▶ if ($returning) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returning) 127 1 128
843 127 my $default = $self->_default_field_set($table);
844 127 ▶ $back = defined(first { !$default->{$_} } @set, keys %$data) ? $self->_read_back_fields($table, @set, sort grep { $t->{fields}->{$_} } keys %$data) : $self->_default_fields($table);
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
defined &first(sub { not $default->{$_}; } , @set, keys %$data) ? : 7 120 127
845 }
846  
847 128 my ($where_sql, $where_binds, $where_marked) = $self->_where_sql($where);
848 126 my ($places, $set_binds, $marked) = $self->_value_sql($changes, @set);
849 126 ▶ my $shape = $marked || $where_marked ? undef : join("\0" => 'update', $table, @set, $where_sql, 'returning', @$back);
Branch: 1 branch
BranchTrueFalseTotal
$marked || $where_marked ? : 6 120 126
Condition66%2/3
$marked or $where_marked
l!l&&r!l&&!r
60120
MC/DC50%1/2
$marked or $where_marked
$marked $where_marked
Truth table66%2/3
A or B
A= $markedB= $where_marked
ABresult
1X1
011
000
850 my $sql = $self->_statement(
851 $shape,
852 72 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
853 72 my $sql = 'UPDATE ' . $dialect->quote_identifier($table) . ' SET ' . join(', ' => map { $dialect->quote_identifier($set[$_]) . " = $places->[$_]" } 0 .. $#set) . " WHERE $where_sql";
854 72 ▶ $returning ? $sql . $self->_returning_sql($back) : $sql;
Branch: 1 branch
BranchTrueFalseTotal
$returning ? : 71 1 72
855 }
856 126 );
857 126 my $sth = $self->_run($t->{fields}, $sql, [@$set_binds, @$where_binds], undef, defined $shape);
858  
859 124 my $new;
860 124 ▶ if ($returning) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returning) { } 123 1 124
861 123 ▶ $new = $self->_fetch($t->{fields}, $sth)->[0] or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$new = $self->_fetch($t->{"fields"}, $sth)->[0] or return undef 106 17 123
862 }
863 else {
864 1 ▶ return undef unless $sth->rows > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth->rows > 0 0 1 1
865 1 ▶ $new = $self->_plain({map { $_ => exists($changes->{$_}) ? $changes->{$_} : $pk->{$_} } keys %$pk});
Branch: 1 branch
BranchTrueFalseTotal
exists $changes->{$_} ? : 1 0 1
866 }
867  
868 107 my $out = $self->lookup->update_entry($table, $self->_plain($pk), $data, $new);
869 107 $self->row_states->carry_inserted($data, $out);
870 107 return $out;
871 }
872  
873 =over 4
874  
875 =item $count = $conn->delete_row($table, \%data, enforce_canon => $bool, raw => $bool)
876  
877 Deletes one row, found by the primary key in the row data, and returns how
878 many rows were deleted (0 or 1). Its lookup table entry is removed, and the
879 row data and that entry are marked deleted (see L<DBIx::QuickORM::RowState>).
880 C<enforce_canon> is as for C<update_row>.
881  
882 my $ann = $conn->insert(users => {name => 'Ann'});
883 my $count = $conn->delete_row(users => $ann); # 1
884  
885 # by the key alone: a hashref that is not the canon row data
886 my $bo = $conn->insert(users => {name => 'Bo'});
887 my $gone = $conn->delete_row(
888 users => {id => $bo->{id}},
889 enforce_canon => 0,
890 );
891  
892 =back
893  
894 =cut
895  
896 260 my %DELETE_ARGS = map { $_ => 1 } qw/enforce_canon raw/;
897  
898 45 ▶sub delete_row {
Subroutine delete_row: called CC=2 SCAR=6.9
Pod documented
899 45 my $self = shift;
900 45 my ($table, $data, %params) = @_;
901  
902 45 $self->_check_params(delete_row => \%DELETE_ARGS, \%params);
903 44 my $t = $self->_table($table);
904 44 $data = $self->_row_data($data);
905 44 my $pk = $self->_pk_values($table, $data, $params{raw});
906 44 $self->_enforce_canon($table, $data, $params{enforce_canon});
907  
908 40 my ($where_sql, $where_binds, $marked) = $self->_where_sql($pk);
909 40 ▶ my $sql = $self->_statement($marked ? undef : join("\0" => 'delete', $table, $where_sql), sub { 'DELETE FROM ' . $self->{+DIALECT}->quote_identifier($table) . " WHERE $where_sql" });
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 1 39 40
910 40 my $sth = $self->_run($t->{fields}, $sql, $where_binds, undef, !$marked);
911  
912 39 $self->row_states->mark_deleted($data);
913 39 $self->lookup->gone($table, $self->_plain($pk));
914 39 return $sth->rows;
915 }
916  
917 =over 4
918  
919 =item $data = $conn->refresh_row($table, $pk, cache => $bool, db => $bool, fields => \@fields, raw => $bool)
920  
921 The canon row data for the primary key, or undef when there is no such row.
922 C<$pk> is the key in any form C<_pk_values> takes, so row data works and its
923 other fields are ignored. This is also C<find>.
924  
925 my $ann = $conn->insert(users => {name => 'Ann'});
926 my $id = $ann->{id};
927  
928 # by key: the canon hashref the lookup table holds, $ann itself
929 my $found = $conn->refresh_row(users => $id);
930  
931 # the key as a hashref, or row data: only id finds the row. Other values
932 # are ignored, but their field names join the fields read from the database
933 my $same = $conn->refresh_row(
934 users => {
935 id => $id,
936 name => 'whatever',
937 },
938 );
939  
940 # read from the database even when the lookup table holds the row
941 my $fresh = $conn->refresh_row(
942 users => $id,
943 cache => 0,
944 );
945  
946 # the lookup table only: undef when it holds no such row
947 my $cached = $conn->refresh_row(
948 users => 9999,
949 db => 0,
950 );
951  
952 # only these fields and the primary key: {id => $id, name => 'Ann'}. Read
953 # from the database, it is now the canon entry, and $ann is replaced
954 my $named = $conn->refresh_row(
955 users => $id,
956 cache => 0,
957 fields => ['name'],
958 );
959  
960 Without C<fields> it reads the default fields and the fields the given row
961 data holds, so a refreshed row keeps what it read.
962  
963 C<fields> must be fields of the table. C<cache>, C<db>, and C<fields> are as
964 L<DBIx::QuickORM/"CRUD operations"> describes for C<refresh_row>: the lookup
965 table's entry when it holds every field asked for, otherwise those fields read
966 from the database and ingested.
967  
968 A row the database no longer has is removed from the lookup table, and the
969 row data given and that entry are marked deleted.
970  
971 =back
972  
973 =cut
974  
975 260 my %REFRESH_ARGS = map { $_ => 1 } qw/cache db fields raw/;
976  
977 360 ▶sub refresh_row {
Subroutine refresh_row: called CC=27 SCAR=33.0
Pod documented
978 360 my $self = shift;
979 360 my ($table, $data, %params) = @_;
980  
981 360 my ($t, $pk, $given, @select);
982 360 my ($cache, $db) = (1, 1);
983 360 my $lookup = $self->lookup;
984  
985 # A plain value for a single untyped primary key, with no options: the lookup key is the value as given, so
986 # deflating the key, building the lookup key and building the SQL are skipped.
987 360 ▶ my $fast = !%params && defined($data) && !ref($data) ? $self->_find_key($table) : undef;
Branch: 1 branch
BranchTrueFalseTotal
!%params && defined $data && !ref($data) ? : 154 206 360
Condition100%6/6
not %params and defined $data and not ref $data
!ll&&!rl&&r
14066154
not %params and defined $data
!ll&&!rl&&r
1382220
MC/DC100%3/3
not %params and defined $data and not ref $data
not %params defined $data not ref $data
Truth table100%4/4
not(A) and B and not(C)
A= not %paramsB= defined $dataC= not ref $data
ABCresult
0XX0
10X0
1100
1111
988 360 ▶ if ($fast) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fast) { } 135 225 360
989 135 $t = $fast->{table};
990 135 $pk = {$fast->{field} => $data};
991 135 @select = @{$fast->{select}};
992 }
993 else {
994 225 $self->_check_params(refresh_row => \%REFRESH_ARGS, \%params);
995 225 $t = $self->_table($table);
996 225 $pk = $self->_pk_values($table, $data, $params{raw});
997 211 ▶ $cache = $params{cache} // 1;
Condition100%2/2
$params{"cache"} // 1
l!l
81130
MC/DC100%1/1
$params{"cache"} // 1
$params{"cache"}
Truth table100%2/2
A
A= $params{"cache"}
Aresult
11
00
998 211 ▶ $db = $params{db} // 1;
Condition100%2/2
$params{"db"} // 1
l!l
37174
MC/DC100%1/1
$params{"db"} // 1
$params{"db"}
Truth table100%2/2
A
A= $params{"db"}
Aresult
11
00
999 211 ▶ confess "refresh_row() needs 'cache' or 'db' to be true" unless $cache || $db;
Branch: 1 branch
BranchTrueFalseTotal
unless $cache or $db 1 210 211
Condition100%3/3
$cache or $db
l!l&&r!l&&!r
131791
MC/DC100%2/2
$cache or $db
$cache $db
Truth table100%3/3
A or B
A= $cacheB= $db
ABresult
1X1
011
000
1000  
1001 210 my $fields = $params{fields};
1002 210 ▶ confess "'fields' must be an arrayref of field names" if defined($fields) && ref($fields) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $fields and ref $fields ne "ARRAY" 1 209 210
Condition100%3/3
defined $fields and ref $fields ne "ARRAY"
!ll&&!rl&&r
184251
MC/DC100%2/2
defined $fields and ref $fields ne "ARRAY"
defined $fields ref $fields ne "ARRAY"
Truth table100%3/3
A and B
A= defined $fieldsB= ref $fields ne "ARRAY"
ABresult
0X0
100
111
1003 209 ▶ $self->_check_fields($table, @$fields) if $fields;
Branch: 1 branch
BranchTrueFalseTotal
if $fields 25 184 209
1004  
1005 # Without 'fields', the fields the given row data holds are read too, so a refresh keeps what the row read.
1006 208 ▶ $given = blessed($data) && $data->can('row_data') ? $data->row_data : ref($data) eq 'HASH' ? $data : undef;
Branch: 2 branches
BranchTrueFalseTotal
builtin::blessed($data) && $data->can('row_data') ? : 38 170 208
ref $data eq 'HASH' ? : 120 50 170
Condition100%3/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
162838
MC/DC100%2/2
builtin::blessed($data) and $data->can("row_data")
builtin::blessed($data) $data->can("row_data")
Truth table100%3/3
A and B
A= builtin::blessed($data)B= $data->can("row_data")
ABresult
0X0
100
111
1007 208 my %seen;
1008 208 ▶ @select = $fields ? grep { !$seen{$_}++ } sort(@$fields, @{$t->{pk}}) : @{$self->_read_back_fields($table, sort grep { $t->{fields}->{$_} } keys %{$given // {}})};
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 24 184 208
Condition100%2/2
$given // {}
l!l
13450
MC/DC100%1/1
$given // {}
$given
Truth table100%2/2
A
A= $given
Aresult
11
00
1009 }
1010  
1011 343 ▶ if ($cache) { # a lookup table that does not cache finds nothing
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 264 79 343
1012 264 ▶ my $canon = $fast ? $lookup->lookup_value($table, $fast->{field}, $data) : $lookup->lookup($table, $self->_plain($pk));
Branch: 1 branch
BranchTrueFalseTotal
$fast ? : 135 129 264
1013 264 ▶ return $canon if $canon && (!$db || !grep { !exists $canon->{$_} } @select);
Branch: 1 branch
BranchTrueFalseTotal
if $canon and not $db && grep({not exists $canon->{$_};} @select) 75 189 264
Condition100%6/6
$canon and not $db && grep({not exists $canon->{$_};} @select)
!ll&&!rl&&r
1721775
$db && grep({not exists $canon->{$_};} @select)
!ll&&!rl&&r
245117
MC/DC100%3/3
$canon and not $db && grep({not exists $canon->{$_};} @select)
$canon $db grep({not exists $canon->{$_};} @select)
Truth table100%4/4
A and not(B && C)
A= $canonB= $dbC= grep({not exists $canon->{$_};} @select)
ABCresult
0XX0
1110
10X1
1101
1014 }
1015 268 ▶ return undef unless $db;
Branch: 1 branch
BranchTrueFalseTotal
unless $db 12 256 268
1016  
1017 256 my ($sql, $binds, $marked);
1018 256 ▶ if ($fast) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fast) { } 111 145 256
1019 111 ($sql, $binds) = ($fast->{sql}, [[$fast->{field} => $data]]);
1020 }
1021 else {
1022 145 my $where_sql;
1023 145 ($where_sql, $binds, $marked) = $self->_where_sql($pk);
1024 145 $sql = $self->_select_sql($table, \@select, $where_sql, $marked);
1025 }
1026  
1027 256 my $row = $self->_fetch($t->{fields}, $self->_run($t->{fields}, $sql, $binds, undef, !$marked))->[0];
1028 255 ▶ if ($row) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row) 227 28 255
1029 227 my $canon = $lookup->ingest($table, $row);
1030 227 ▶ $self->row_states->carry_inserted($given, $canon) if $given;
Branch: 1 branch
BranchTrueFalseTotal
if $given 93 134 227
1031 227 return $canon;
1032 }
1033  
1034 28 ▶ $self->row_states->mark_deleted($given) if $given;
Branch: 1 branch
BranchTrueFalseTotal
if $given 9 19 28
1035 28 $lookup->gone($table, $self->_plain($pk));
1036 28 return undef;
1037 }
1038  
1039 =pod
1040  
1041 =over 4
1042  
1043 =item $info = $conn->_find_key($table)
1044  
1045 For a table whose primary key is one field with no type, what C<refresh_row>
1046 needs to read a row by a plain key value: C<table> (the map's record),
1047 C<field>, C<select> (the default fields) and C<sql>. Kept per table, since the
1048 map does not change. Undef for any other table.
1049  
1050 =item $sql = $conn->_select_sql($table, \@fields, $where_sql, $marked)
1051  
1052 The C<SELECT> of those fields from the table with that C<WHERE> body, built
1053 once per shape unless C<$marked>.
1054  
1055 =back
1056  
1057 =cut
1058  
1059 154 ▶sub _find_key {
Subroutine _find_key: called CC=12 SCAR=25.1
1060 154 my $self = shift;
1061 154 my ($table) = @_;
1062  
1063 154 ▶ return undef unless defined($table) && length($table); # refresh_row's own checks report it
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and length $table 0 154 154
Condition33%1/3
defined $table and length $table
!ll&&!rl&&r
00154
MC/DC0%0/2
defined $table and length $table
defined $table length $table
Truth table33%1/3
A and B
A= defined $tableB= length $table
ABresult
0X0
100
111
1064  
1065 154 ▶ my $keys = $self->{+FIND_KEYS} //= {};
Condition100%2/2
$self->{"find_keys"} //= {}
l!l
10351
MC/DC100%1/1
$self->{"find_keys"} //= {}
$self->{"find_keys"}
Truth table100%2/2
A
A= $self->{"find_keys"}
Aresult
11
00
1066 154 ▶ return $keys->{$table} if exists $keys->{$table};
Branch: 1 branch
BranchTrueFalseTotal
if exists $keys->{$table} 90 64 154
1067  
1068 64 ▶ my $t = $self->_map->table($table) or return undef; # so does an unknown table
Branch: 1 branch
BranchTrueFalseTotal
my $t = $self->_map->table($table) or return undef 64 0 64
1069  
1070 64 ▶ my $pk = $t->{pk} // [];
Condition100%2/2
$t->{"pk"} // []
l!l
622
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
1071 64 my $fields = $t->{fields};
1072 64 ▶ my $field = @$pk == 1 && ref($fields) eq 'HASH' ? $fields->{$pk->[0]} : undef;
Branch: 1 branch
BranchTrueFalseTotal
@$pk == 1 && ref $fields eq 'HASH' ? : 57 7 64
Condition100%3/3
@$pk == 1 and ref $fields eq "HASH"
!ll&&!rl&&r
5257
MC/DC100%2/2
@$pk == 1 and ref $fields eq "HASH"
@$pk == 1 ref $fields eq "HASH"
Truth table100%3/3
A and B
A= @$pk == 1B= ref $fields eq "HASH"
ABresult
0X0
100
111
1073 64 ▶ return $keys->{$table} = undef unless $field && !$t->{pk_types} && !$field->{orm_type};
Branch: 1 branch
BranchTrueFalseTotal
unless $field and not $t->{"pk_types"} and not $field->{"orm_type"} 18 46 64
Condition83%5/6
$field and not $t->{"pk_types"} and not $field->{"orm_type"}
!ll&&!rl&&r
18046
$field and not $t->{"pk_types"}
!ll&&!rl&&r
81046
MC/DC66%2/3
$field and not $t->{"pk_types"} and not $field->{"orm_type"}
$field not $t->{"pk_types"} not $field->{"orm_type"}
Truth table75%3/4
A and not(B) and not(C)
A= $fieldB= not $t->{"pk_types"}C= not $field->{"orm_type"}
ABCresult
0XX0
10X0
1100
1111
1074  
1075 46 my $select = $self->_default_fields($table);
1076 46 my ($where_sql) = $self->_where_sql({$pk->[0] => ''});
1077 46 return $keys->{$table} = {table => $t, field => $pk->[0], select => [@$select], sql => $self->_select_sql($table, $select, $where_sql)};
1078 }
1079  
1080 191 ▶sub _select_sql {
Subroutine _select_sql: called CC=2 SCAR=6.9
1081 191 my $self = shift;
1082 191 my ($table, $fields, $where_sql, $marked) = @_;
1083 191 my $dialect = $self->{+DIALECT};
1084 return $self->_statement(
1085 $marked ? undef : join("\0" => 'select', $table, @$fields, $where_sql),
1086 108 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1087 108 'SELECT ' . join(', ' => map { $dialect->quote_identifier($_) } @$fields) . ' FROM ' . $dialect->quote_identifier($table) . " WHERE $where_sql";
1088 }
1089 191 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 2 189 191
1090 }
1091  
1092 =over 4
1093  
1094 =item \@rows = $conn->select($source, $sql, \@binds)
1095  
1096 =item \%pending = $conn->select($source, $sql, \@binds, async => 1)
1097  
1098 Runs SQL built elsewhere for a source (a L<DBIx::QuickORM::Role::Source>) and
1099 returns every row as fetched.
1100  
1101 my $ann = $conn->insert(users => {name => 'Ann'});
1102 my $source = $orm->handle('users')->source;
1103  
1104 # binds are [field, value] pairs. The rows come back as fetched, and are
1105 # not added to the lookup table: [{id => $ann->{id}, name => 'Ann'}]
1106 my $rows = $conn->select(
1107 $source,
1108 'SELECT id, name FROM users WHERE id = ?',
1109 [[id => $ann->{id}]],
1110 );
1111  
1112 my $pending = $conn->select(
1113 $source,
1114 'SELECT 1 AS one',
1115 [],
1116 async => 1,
1117 );
1118 my $later = $pending->{collect}->(); # waits, then [{one => 1}]
1119  
1120 my $slow = $conn->select(
1121 $source,
1122 'SELECT 1 FROM pg_sleep(30)',
1123 [],
1124 async => 1,
1125 );
1126 my $ready = $slow->{ready}->(); # false while the query runs
1127 $slow->{cancel}->();
1128  
1129 Binds are C<[$name, $value]> pairs. The name (undef for none) is one of the
1130 source's C<field_records>, which also decide how fetched columns are read.
1131 Nothing is ingested here. The source's C<results> ingests the rows that
1132 belong to a table.
1133  
1134 With C<async>, on a dialect that C<supports_async>, the query is started
1135 without waiting for it and a hash of three code references is returned:
1136 C<ready> (true once the result has arrived), C<collect> (waits for the result
1137 and returns the rows), and C<cancel> (gives up on the query). Call C<collect>
1138 or C<cancel> once. A dialect without async queries croaks.
1139  
1140 While the query is pending the Connection is busy: every query, CRUD operation,
1141 and transaction statement that would send SQL croaks (a C<find> answered from
1142 the cache does not), including an explicit C<rollback>.
1143  
1144 A rollback forced by a block's exception, or by a L<DBIx::QuickORM::Txn>
1145 going out of scope, cancels the query first. After that C<collect> throws and
1146 C<cancel> does nothing.
1147  
1148 =back
1149  
1150 =cut
1151  
1152 260 my %SELECT_ARGS = (async => 1);
1153  
1154 334 ▶sub select {
Subroutine select: called CC=7 SCAR=32.5
Pod documented
1155 334 my $self = shift;
1156 334 my ($source, $sql, $binds, %params) = @_;
1157  
1158 334 $self->_check_params(select => \%SELECT_ARGS, \%params);
1159 333 ▶ confess "select() needs a source (a DBIx::QuickORM::Role::Source)" unless blessed($source) && $source->DOES('DBIx::QuickORM::Role::Source');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source") 1 332 333
Condition66%2/3
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
10332
MC/DC50%1/2
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
builtin::blessed($source) $source->DOES("DBIx::QuickORM::Role::Source")
Truth table66%2/3
A and B
A= builtin::blessed($source)B= $source->DOES("DBIx::QuickORM::Role::Source")
ABresult
0X0
100
111
1160 332 ▶ confess "'binds' must be an arrayref" if defined($binds) && ref($binds) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $binds and ref $binds ne "ARRAY" 1 331 332
Condition66%2/3
defined $binds and ref $binds ne "ARRAY"
!ll&&!rl&&r
03311
MC/DC50%1/2
defined $binds and ref $binds ne "ARRAY"
defined $binds ref $binds ne "ARRAY"
Truth table66%2/3
A and B
A= defined $bindsB= ref $binds ne "ARRAY"
ABresult
0X0
100
111
1161  
1162 331 my $fields = $source->field_records;
1163 331 $binds = $self->_resolve_binds($source, $binds);
1164 331 ▶ return $self->_fetch($fields, $self->_run($fields, $sql, $binds)) unless $params{async};
Branch: 1 branch
BranchTrueFalseTotal
unless $params{"async"} 331 0 331
1165  
1166 0 my ($dbh, $dialect) = @{$self}{+DBH, +DIALECT};
1167 0 ▶ confess "The " . $dialect->name . " dialect has no async queries" unless $dialect->supports_async;
Branch: 1 branch
BranchTrueFalseTotal
unless $dialect->supports_async 0 0 0
1168 0 my $sth = $self->_run($fields, $sql, $binds, $dialect->async_prepare_attrs);
1169 0 weaken($PENDING{refaddr($self)} = $self);
1170  
1171 # The statement is freed as soon as the query is over, before another can start beside it.
1172 0 ▶ my $done = sub { undef $sth; delete $self->{+BUSY}; delete $PENDING{refaddr($self)} };
Subroutine __ANON__: not called CC=1 SCAR=6.9
1173 my $pending = {
1174 0 ▶ ready => sub { $sth ? $dialect->async_ready($dbh, $sth) : 1 },
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
$sth ? : 0 0 0
1175 0 ▶ collect => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1176 0 ▶ die "This async query was cancelled when the transaction it ran in was rolled back\n" unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
1177 0 my $rows;
1178 0 my $ok = eval { $dialect->async_result($dbh, $sth); $rows = $self->_fetch($fields, $sth); 1 };
1179 0 my $err = $@;
1180 0 $done->();
1181 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
1182 0 return $rows;
1183 },
1184 0 ▶ cancel => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
1185 0 ▶ return unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
1186 0 my $ok = eval { $dialect->cancel_async($dbh, $sth); 1 };
1187 0 my $err = $@;
1188 0 $done->();
1189 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
1190 },
1191 0 };
1192 0 $self->{+BUSY} = {sth => $sth, cancel => $pending->{cancel}};
1193 0 return $pending;
1194 }
1195  
1196 =over 4
1197  
1198 =item $count = $conn->bulk_write($source, $sql, \@binds)
1199  
1200 =item $count = $conn->bulk_write($source, $sql, \@binds, mark_deleted => 1, keys => [$select_sql, \@select_binds])
1201  
1202 Runs an C<UPDATE> or C<DELETE> built elsewhere for a table source and returns
1203 the number of rows the database reports. Binds are as for C<select>.
1204  
1205 my $ann = $conn->insert(users => {name => 'Ann'});
1206 my $post = $conn->insert(
1207 posts => {
1208 user_id => $ann->{id},
1209 title => 'Hello',
1210 },
1211 );
1212  
1213 my $source = $orm->handle('posts')->source;
1214 my $binds = [[user_id => $ann->{id}]];
1215  
1216 my $bumped = $conn->bulk_write(
1217 $source,
1218 'UPDATE posts SET views = views + 1 WHERE user_id = ?',
1219 $binds,
1220 );
1221  
1222 # the update cleared posts from the lookup table: hold the row again
1223 $post = $conn->refresh_row(posts => $post->{id});
1224  
1225 # a row held for a deleted key is marked deleted
1226 my $deleted = $conn->bulk_write(
1227 $source,
1228 'DELETE FROM posts WHERE user_id = ?',
1229 $binds,
1230 mark_deleted => 1,
1231 keys => ['SELECT id FROM posts WHERE user_id = ?', $binds], # needed on MySQL only
1232 );
1233 my $status = $conn->canon_status(posts => $post); # {cause => 'deleted'}
1234  
1235 It cannot tell which rows changed, so it clears the table from the lookup
1236 table's top level and, inside a transaction, from its outside level. A source
1237 without a table croaks.
1238  
1239 With C<mark_deleted>, C<$sql> must be a C<DELETE>. The deleted rows' primary
1240 keys are also learned, and each is passed to the lookup table's C<gone>
1241 before the table is cleared: held rows for those keys are marked deleted (a
1242 rollback unmarks them).
1243  
1244 The count is still the rows the database reports deleted. With C<RETURNING>
1245 that equals the keys returned. On MySQL it can exceed them (see below).
1246  
1247 =over 4
1248  
1249 =item *
1250  
1251 Where the dialect C<supports_returning_delete>, C<$sql> gets C<RETURNING>
1252 and the key columns.
1253  
1254 =item *
1255  
1256 Otherwise (MySQL) C<keys> is required: a C<SELECT> of the key columns with
1257 the same C<where>. It runs with C<FOR UPDATE>, locking those rows, then
1258 C<$sql> runs. Both run in a transaction of their own when none is open.
1259 Nothing is marked unless the C<DELETE> succeeds. At C<READ COMMITTED> a row
1260 another session commits between the two is deleted and counted, but not
1261 marked.
1262  
1263 =back
1264  
1265 =back
1266  
1267 =cut
1268  
1269 260 my %BULK_ARGS = map { $_ => 1 } qw/mark_deleted keys/;
1270  
1271 26 ▶sub bulk_write {
Subroutine bulk_write: called CC=11 SCAR=29.8
Pod documented
1272 26 my $self = shift;
1273 26 my ($source, $sql, $binds, %params) = @_;
1274  
1275 26 $self->_check_params(bulk_write => \%BULK_ARGS, \%params);
1276 26 ▶ confess "bulk_write() needs a source (a DBIx::QuickORM::Role::Source)" unless blessed($source) && $source->DOES('DBIx::QuickORM::Role::Source');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source") 0 26 26
Condition33%1/3
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
0026
MC/DC0%0/2
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
builtin::blessed($source) $source->DOES("DBIx::QuickORM::Role::Source")
Truth table33%1/3
A and B
A= builtin::blessed($source)B= $source->DOES("DBIx::QuickORM::Role::Source")
ABresult
0X0
100
111
1277 26 my $table = $source->table;
1278 26 ▶ confess "bulk_write() needs a source with a table" unless defined $table;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table 0 26 26
1279 26 ▶ confess "'binds' must be an arrayref" if defined($binds) && ref($binds) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if defined $binds and ref $binds ne "ARRAY" 0 26 26
Condition33%1/3
defined $binds and ref $binds ne "ARRAY"
!ll&&!rl&&r
0260
MC/DC0%0/2
defined $binds and ref $binds ne "ARRAY"
defined $binds ref $binds ne "ARRAY"
Truth table33%1/3
A and B
A= defined $bindsB= ref $binds ne "ARRAY"
ABresult
0X0
100
111
1280  
1281 26 my $fields = $source->field_records;
1282 26 $binds = $self->_resolve_binds($source, $binds);
1283 26 my $lookup = $self->lookup;
1284  
1285 26 ▶ unless ($params{mark_deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params{"mark_deleted"}) 20 6 26
1286 20 my $sth = $self->_run($fields, $sql, $binds);
1287 20 $lookup->forget($table);
1288 20 return $sth->rows;
1289 }
1290  
1291 6 my $dialect = $self->{+DIALECT};
1292 6 ▶ if ($dialect->supports_returning_delete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dialect->supports_returning_delete) 6 0 6
1293 6 my $returning = join ', ' => map { $dialect->quote_identifier($_) } @{$self->_table($table)->{pk}};
1294 6 my $keys = $self->_fetch($fields, $self->_run($fields, "$sql RETURNING $returning", $binds));
1295 6 $lookup->gone($table, $_) for @$keys;
1296 6 $lookup->forget($table);
1297 6 return scalar @$keys;
1298 }
1299  
1300 0 my $select = $params{keys};
1301 0 ▶ confess "bulk_write() needs 'keys' to mark deleted rows: the " . $dialect->name . " dialect has no RETURNING on DELETE" unless ref($select) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $select eq "ARRAY" 0 0 0
1302 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1303 0 my $keys = $self->_fetch($fields, $self->_run($fields, "$select->[0] FOR UPDATE", $self->_resolve_binds($source, $select->[1])));
1304 0 my $sth = $self->_run($fields, $sql, $binds);
1305 0 $lookup->gone($table, $_) for @$keys;
1306 0 $lookup->forget($table);
1307 0 return $sth->rows;
1308 0 };
1309 0 ▶ return @{$self->{+TXNS}} ? $run->() : $self->txn($run);
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'txns'};} ? : 0 0 0
1310 }
1311  
1312 =pod
1313  
1314 =over 4
1315  
1316 =item $txn = $conn->txn(caller => \@frame)
1317  
1318 =item $txn = $conn->txn(isolation => $level, caller => \@frame)
1319  
1320 =item @result = $conn->txn(sub { my $txn = shift; ... }, retry => $n, isolation => $level, caller => \@frame)
1321  
1322 Opens a transaction, or a savepoint when one is already open, and returns its
1323 L<DBIx::QuickORM::Txn>. Given a block, runs it in the transaction and returns
1324 what the block returns.
1325  
1326 # object form: commit or roll back yourself
1327 # sends BEGIN ISOLATION LEVEL REPEATABLE READ
1328 my $txn = $conn->txn(isolation => 'repeatable read');
1329 $conn->insert(users => {name => 'Jo'});
1330 $txn->commit;
1331  
1332 # block form: commits when the block returns, rolls back on an exception
1333 my $kim = $conn->txn(sub {
1334 my $txn = shift;
1335 return $conn->insert(users => {name => 'Kim'});
1336 });
1337  
1338 # runs the block again, up to 3 more times, on a retriable error
1339 my $id = $conn->txn(
1340 sub { $conn->insert(users => {name => 'Lu'})->{id} },
1341 retry => 3,
1342 isolation => 'serializable',
1343 );
1344  
1345 # inside another transaction: a savepoint
1346 $conn->txn(sub {
1347 $conn->insert(users => {name => 'Max'});
1348 my $inner = $conn->txn;
1349 $conn->insert(users => {name => 'Ned'});
1350 $inner->rollback; # undoes Ned only
1351 });
1352  
1353 # a wrapper names its own caller, for warnings and errors
1354 sub in_txn {
1355 my ($conn, $code) = @_;
1356 return $conn->txn($code, caller => [caller]);
1357 }
1358  
1359 The transaction statements are sent as SQL, never through DBI's
1360 C<begin_work>. Nesting croaks on a dialect without savepoints (DuckDB).
1361 C<caller> is where it was opened, for warnings and errors. It is the caller of
1362 this method unless given.
1363  
1364 Opening one begins a lookup table level (see
1365 L<DBIx::QuickORM::Role::LookupTable>).
1366  
1367 The block is called in list context when C<txn> is, otherwise in scalar
1368 context. A normal return commits,
1369 unless the block already committed or rolled back itself. An exception rolls
1370 back and is rethrown.
1371  
1372 With C<retry>, the block of a root transaction runs again in a new
1373 transaction, up to C<$n> more times, while the exception is a
1374 L<DBIx::QuickORM::Exception::DB> whose C<retriable> is true. A
1375 C<retry> above 0 croaks inside another transaction or without a block. One
1376 that is not a count croaks.
1377  
1378 C<isolation> is the root transaction's level: C<read uncommitted>, C<read
1379 committed>, C<repeatable read>, or C<serializable>, in any case, or
1380 C<'server'> for the database's own default. Without it the Connection's
1381 C<isolation> applies. Every retry begins at the same level. It croaks inside
1382 another transaction and for any other value. A level on a database without
1383 settable levels (SQLite, DuckDB) croaks when the transaction opens.
1384  
1385 =back
1386  
1387 =cut
1388  
1389 260 my %TXN_ARGS = map { $_ => 1 } qw/retry isolation caller/;
1390 260 my @ISOLATION = ('read committed', 'read uncommitted', 'repeatable read', 'serializable', 'server');
1391 260 my %ISOLATION = map { $_ => 1 } @ISOLATION;
1392  
1393 179 ▶sub txn {
Subroutine txn: called CC=16 SCAR=27.7
Pod documented
1394 179 my $self = shift;
1395 179 ▶ my $code = ref($_[0]) eq 'CODE' ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'CODE' ? : 109 70 179
1396 179 my %params = @_;
1397  
1398 179 $self->_check_params(txn => \%TXN_ARGS, \%params);
1399 178 ▶ my $caller = $params{caller} // [caller];
Condition100%2/2
$params{"caller"} // [caller]
l!l
16810
MC/DC100%1/1
$params{"caller"} // [caller]
$params{"caller"}
Truth table100%2/2
A
A= $params{"caller"}
Aresult
11
00
1400 178 ▶ my $retry = $params{retry} // 0;
Condition100%2/2
$params{"retry"} // 0
l!l
10168
MC/DC100%1/1
$params{"retry"} // 0
$params{"retry"}
Truth table100%2/2
A
A= $params{"retry"}
Aresult
11
00
1401 178 ▶ confess "'retry' must be a count of retries" unless $retry =~ m/^\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $retry =~ /^\d+\z/ 1 177 178
1402 177 ▶ confess "'retry' needs a block: txn(sub { ... }, retry => \$n)" if $retry && !$code;
Branch: 1 branch
BranchTrueFalseTotal
if $retry and not $code 1 176 177
Condition100%3/3
$retry and not $code
!ll&&!rl&&r
16881
MC/DC100%2/2
$retry and not $code
$retry not $code
Truth table100%3/3
A and not(B)
A= $retryB= not $code
ABresult
0X0
100
111
1403 176 ▶ confess "'retry' is only for a root transaction, and a transaction is already open" if $retry && @{$self->{+TXNS}};
Branch: 1 branch
BranchTrueFalseTotal
if $retry and @{$self->{"txns"};} 1 175 176
Condition100%3/3
$retry and @{$self->{"txns"};}
!ll&&!rl&&r
16871
MC/DC100%2/2
$retry and @{$self->{"txns"};}
$retry @{$self->{"txns"};}
Truth table100%3/3
A and B
A= $retryB= @{$self->{"txns"};}
ABresult
0X0
100
111
1404  
1405 175 my $level = $params{isolation};
1406 175 ▶ if (defined $level) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $level) 5 170 175
1407 5 $level = $self->_isolation($level);
1408 4 ▶ confess "'isolation' is only for a root transaction, and a transaction is already open" if @{$self->{+TXNS}};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"txns"};} 1 3 4
1409 }
1410 173 ▶ return $self->_begin($caller, $level) unless $code;
Branch: 1 branch
BranchTrueFalseTotal
unless $code 67 106 173
1411  
1412 106 my $list = wantarray;
1413 106 for (my $tries = 0;; $tries++) {
1414 112 my ($ok, $err, @out) = $self->_run_block($code, $caller, $list, $level);
1415 112 ▶ return $list ? @out : $out[0] if $ok;
Branch: 2 branches
BranchTrueFalseTotal
if $ok 80 32 112
$list ? : 2 78 80
1416 32 ▶ die $err unless $tries < $retry && $self->_retriable($err);
Branch: 1 branch
BranchTrueFalseTotal
unless $tries < $retry and $self->_retriable($err) 26 6 32
Condition100%3/3
$tries < $retry and $self->_retriable($err)
!ll&&!rl&&r
2336
MC/DC100%2/2
$tries < $retry and $self->_retriable($err)
$tries < $retry $self->_retriable($err)
Truth table100%3/3
A and B
A= $tries < $retryB= $self->_retriable($err)
ABresult
0X0
100
111
1417 }
1418 }
1419  
1420 =pod
1421  
1422 =over 4
1423  
1424 =item $conn->commit_txn($txn)
1425  
1426 =item $conn->rollback_txn($txn)
1427  
1428 What C<< $txn->commit >> and C<< $txn->rollback >> do (see
1429 L<DBIx::QuickORM::Txn>).
1430  
1431 Either croaks unless the transaction is open and innermost, this is the
1432 process that opened it, and no async query is pending.
1433  
1434 Committing a transaction marked failed rolls it back instead, then croaks
1435 (see C<_run>).
1436  
1437 Ending a transaction ends its lookup table level (see
1438 L<DBIx::QuickORM::Role::LookupTable>). A failed commit or rollback is
1439 handled as L<DBIx::QuickORM::Txn> describes.
1440  
1441 =back
1442  
1443 =cut
1444  
1445 85 ▶sub commit_txn {
Subroutine commit_txn: called CC=6 SCAR=17.9
Pod documented
1446 85 my $self = shift;
1447 85 my ($txn) = @_;
1448  
1449 85 $self->_check_open($txn, 'commit');
1450 81 $self->_check_idle; # Before the commit, whose failure would roll back.
1451 81 ▶ if (defined(my $failed = $txn->failed)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $failed = $txn->failed)) 2 79 81
1452 2 $self->_unwind($txn);
1453 2 confess "The transaction opened at " . $txn->opened_at . " was rolled back instead of committed, since a statement in it failed.\nThe failure: $failed\n";
1454 }
1455 79 ▶ my $sql = $txn->depth == 1 ? 'COMMIT' : 'RELEASE SAVEPOINT ' . $txn->name;
Branch: 1 branch
BranchTrueFalseTotal
$txn->depth == 1 ? : 65 14 79
1456 79 ▶ unless (eval { $self->_do($sql); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->_do($sql); 1 } }) 3 76 79
1457 3 my $err = $@;
1458 3 ▶ die $err if eval { $self->_unwind($txn); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->_unwind($txn); 1 } } 1 2 3
1459 2 my $rollback_err = $@;
1460 2 $self->_abandon($txn);
1461 2 chomp($err, $rollback_err);
1462 2 die "The outcome of the transaction opened at " . $txn->opened_at . " is unknown: committing it failed, and so did rolling it back.\nCommit error: $err\nRollback error: $rollback_err\n";
1463 }
1464  
1465 76 pop @{$self->{+TXNS}};
1466 76 $self->lookup->commit_level;
1467 76 $self->row_states->commit_level;
1468 76 ▶ $self->_temps_committed($txn->depth) if $self->{+TEMPS};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"temps"} 8 68 76
1469 76 return 1;
1470 }
1471  
1472 62 ▶sub rollback_txn {
Subroutine rollback_txn: called CC=1 SCAR=0.0
Pod documented
1473 62 my $self = shift;
1474 62 my ($txn) = @_;
1475 62 $self->_check_open($txn, 'roll back');
1476 60 $self->_check_idle;
1477 60 $self->_unwind($txn);
1478 59 return 1;
1479 }
1480  
1481 # {{{ Temporary tables and views
1482  
1483 =pod
1484  
1485 =head2 Temporary tables and views
1486  
1487 The Connection tracks the temporary tables and views it created, by name, in
1488 its own map. Each remembers the transaction level that created it, and the
1489 level that dropped it while that level is still open. Their life follows the
1490 transactions:
1491  
1492 =over 4
1493  
1494 =item *
1495  
1496 Created in a transaction or savepoint that rolls back: gone. Where the
1497 dialect's C<temp_ddl_transactional> is false (the MySQL family) the
1498 Connection drops it after the rollback.
1499  
1500 =item *
1501  
1502 Dropped in a transaction: hidden from the map at once. A rollback of that
1503 level shows it again. The outermost commit makes the drop final. Where the
1504 dialect's C<temp_ddl_transactional> is false the C<DROP> is held back until
1505 then, so a rollback has nothing to undo.
1506  
1507 =item *
1508  
1509 A savepoint that commits hands both levels to the enclosing one.
1510  
1511 =item *
1512  
1513 A transaction whose outcome is unknown (see L<DBIx::QuickORM::Txn>) ends
1514 every temporary table or view it created or dropped, with a best-effort
1515 C<DROP>.
1516  
1517 =back
1518  
1519 When one ends, it leaves the map, its rows leave the lookup table, and the
1520 statements cached for it are forgotten. Its name is remembered with the
1521 reason (C<temp_gone>), for errors that name it.
1522  
1523 =over 4
1524  
1525 =item \%table = $conn->create_temp($name, $kind, \@create_sql, \@drop_sql, \&setup)
1526  
1527 Runs C<@create_sql>, where each item is a statement, or
1528 C<[$source, $sql, \@binds]> for one holding binds (bound for the source's
1529 fields as a query's are), reads the new table or view back (the dialect's
1530 C<scan_temp>), passes its map record to C<setup> to adjust in place, and adds
1531 it to the map. C<$kind> is C<table> or C<view>. C<@drop_sql> is what drops it
1532 later. Returns the record. C<setup> is required, even one that changes
1533 nothing: without it C<create_temp> croaks before creating anything.
1534  
1535 my $record = $conn->create_temp(
1536 'popular',
1537 'view',
1538 ['CREATE TEMPORARY VIEW popular AS SELECT id, title FROM posts WHERE views > 100'],
1539 ['DROP VIEW popular'],
1540 sub {
1541 my ($record) = @_;
1542 $record->{pk} = ['id']; # a view has no primary key of its own
1543 },
1544 );
1545  
1546 # a statement with binds, as [$source, $sql, \@binds]. Values are sent as
1547 # given, in database form: wrap one in inflated() to deflate it by its field
1548 my $source = $orm->handle('users')->source;
1549 $conn->create_temp(
1550 'recent',
1551 'table',
1552 [[$source, 'CREATE TEMPORARY TABLE recent AS SELECT * FROM users WHERE id > ?', [[id => 100]]]],
1553 ['DROP TABLE recent'],
1554 sub { },
1555 );
1556  
1557 my @names = $conn->temp_names; # ('popular', 'recent')
1558 my $kind = $conn->temp_kind('recent'); # 'table'
1559  
1560 Croaks when C<$name> is in the map already, or names one dropped in a
1561 transaction still open. When reading it back or C<setup> fails, it is dropped
1562 again and the error rethrown.
1563  
1564 =item $conn->drop_temp($name)
1565  
1566 Drops a temporary table or view this Connection created, as described above.
1567 Croaks for any other name.
1568  
1569 $conn->drop_temp('popular');
1570 my $why = $conn->temp_gone('popular'); # 'dropped'
1571  
1572 # in a transaction the drop is pending: a rollback brings it back
1573 my $txn = $conn->txn;
1574 $conn->drop_temp('recent');
1575 my $hidden = $conn->temp_kind('recent'); # undef
1576 $txn->rollback;
1577 my $back = $conn->temp_kind('recent'); # 'table'
1578  
1579 =item @names = $conn->temp_names
1580  
1581 The temporary tables and views in the map, sorted.
1582  
1583 =item $kind = $conn->temp_kind($name)
1584  
1585 C<table> or C<view> for one in the map, else undef.
1586  
1587 =item $reason = $conn->temp_gone($name)
1588  
1589 Why a temporary table or view of that name ended (C<dropped>,
1590 C<rolled back>, or C<outcome unknown>), or undef when none did, or one of that
1591 name exists again.
1592  
1593 =back
1594  
1595 =cut
1596  
1597 4 ▶sub temp_names {
Subroutine temp_names: called CC=2 SCAR=7.1
Pod documented
1598 4 ▶ sort grep { !defined $_[0]->{+TEMPS}->{$_}->{dropped} } keys %{$_[0]->{+TEMPS} // {}};
Condition50%1/2
$_[0]{"temps"} // {}
l!l
40
MC/DC0%0/1
$_[0]{"temps"} // {}
$_[0]{"temps"}
Truth table50%1/2
A
A= $_[0]{"temps"}
Aresult
11
00
1599 }
1600 7 ▶sub temp_gone { $_[0]->{+GONE_TEMPS}->{$_[1]} }
Subroutine temp_gone: called CC=1 SCAR=0.0
Pod documented
1601  
1602 2 ▶sub temp_kind {
Subroutine temp_kind: called CC=3 SCAR=11.0
Pod documented
1603 2 my $self = shift;
1604 2 my ($name) = @_;
1605 2 ▶ my $entry = $self->{+TEMPS}->{$name} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->{"temps"}{$name} or return undef 1 1 2
1606 1 ▶ return defined($entry->{dropped}) ? undef : $entry->{kind};
Branch: 1 branch
BranchTrueFalseTotal
defined $entry->{'dropped'} ? : 0 1 1
1607 }
1608  
1609 56 ▶sub create_temp {
Subroutine create_temp: called CC=9 SCAR=22.0
Pod documented
1610 56 my $self = shift;
1611 56 my ($name, $kind, $create, $drop, $setup) = @_;
1612 56 ▶ croak "create_temp() needs a setup code reference, even one that changes nothing" unless ref($setup) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $setup eq "CODE" 1 55 56
1613  
1614 55 my $map = $self->{+DB_MAP};
1615 55 ▶ croak "'$name' is already a table or view in the database map" if $map->table($name);
Branch: 1 branch
BranchTrueFalseTotal
if $map->table($name) 1 54 55
1616 54 ▶ croak "The temporary $self->{+TEMPS}->{$name}->{kind} '$name' was dropped in a transaction still open, so the name cannot be used again until it ends" if $self->{+TEMPS}->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"temps"}{$name} 1 53 54
1617  
1618 53 $self->_create_statement($_) for @$create;
1619  
1620 53 my $record;
1621 53 my $ok = eval {
1622 53 ▶ $record = $self->{+DIALECT}->scan_temp($self->{+DBH}, $name) or die "The temporary $kind '$name' was created but cannot be found\n";
Branch: 1 branch
BranchTrueFalseTotal
$record = $self->{"dialect"}->scan_temp($self->{"dbh"}, $name) or die "The temporary $kind '${name}' was created but cannot be found\n" 53 0 53
1623 53 $setup->($record);
1624 52 1;
1625 };
1626 53 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 52 53
1627 1 my $err = $@;
1628 1 ▶ eval { $self->_do($_) for @$drop; 1 } or warn "Dropping the temporary $kind '$name' after its setup failed also failed: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_do($_) foreach (@$drop); 1 } } or warn "Dropping the temporary $kind '${name}' after its setup failed also failed: $@" 1 0 1
1629 1 die $err;
1630 }
1631  
1632 52 $map->add_table($name, $record);
1633 52 $self->{+TEMPS}->{$name} = {kind => $kind, created => scalar(@{$self->{+TXNS}}), dropped => undef, drop => [@$drop]};
1634 52 delete $self->{+GONE_TEMPS}->{$name};
1635 52 return $record;
1636 }
1637  
1638 51 ▶sub drop_temp {
Subroutine drop_temp: called CC=7 SCAR=20.0
Pod documented
1639 51 my $self = shift;
1640 51 my ($name) = @_;
1641  
1642 51 my $entry = $self->{+TEMPS}->{$name};
1643 51 ▶ croak "'$name' is not a temporary table or view of this connection" unless $entry && !defined $entry->{dropped};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry and not defined $entry->{"dropped"} 0 51 51
Condition33%1/3
$entry and not defined $entry->{"dropped"}
!ll&&!rl&&r
0051
MC/DC0%0/2
$entry and not defined $entry->{"dropped"}
$entry not defined $entry->{"dropped"}
Truth table33%1/3
A and not(B)
A= $entryB= not defined $entry->{"dropped"}
ABresult
0X0
100
111
1644  
1645 51 my $depth = @{$self->{+TXNS}};
1646 51 ▶ $self->_do($_) for $depth && !$self->{+DIALECT}->temp_ddl_transactional ? () : @{$entry->{drop}};
Branch: 1 branch
BranchTrueFalseTotal
$depth && !$self->{'dialect'}->temp_ddl_transactional ? : 0 51 51
Condition66%2/3
$depth and not $self->{"dialect"}->temp_ddl_transactional
!ll&&!rl&&r
4290
MC/DC0%0/2
$depth and not $self->{"dialect"}->temp_ddl_transactional
$depth not $self->{"dialect"}->temp_ddl_transactional
Truth table66%2/3
A and not(B)
A= $depthB= not $self->{"dialect"}->temp_ddl_transactional
ABresult
0X0
100
111
1647 51 ▶ return $self->_end_temp($name, 'dropped') unless $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless $depth 42 9 51
1648  
1649 # Hidden, not ended: a rollback of this level brings it back.
1650 9 $entry->{dropped} = $depth;
1651 9 $entry->{record} = $self->{+DB_MAP}->table($name);
1652 9 $self->{+DB_MAP}->remove_table($name);
1653 9 return;
1654 }
1655  
1656 =pod
1657  
1658 =over 4
1659  
1660 =item $sql = $conn->inline_binds($source, $sql, \@binds)
1661  
1662 C<$sql> with each C<?> replaced by its bind as a literal, for a view, which
1663 cannot hold placeholders. The binds are C<[$name, $value]> pairs, as a SQL
1664 builder gives them, deflated for the source's fields as a query's would be. A
1665 binary value (a C<binary()> marker or a field of C<binary> affinity) goes
1666 through the dialect's C<quote_binary>, others through its C<quote_literal>.
1667  
1668 my $source = $orm->handle('users')->source;
1669  
1670 # SELECT id, name FROM users WHERE name = 'O''Neil' AND id > '10'
1671 my $sql = $conn->inline_binds(
1672 $source,
1673 'SELECT id, name FROM users WHERE name = ? AND id > ?',
1674 [[name => "O'Neil"], [id => 10]],
1675 );
1676  
1677 # [undef, $value] names no field, undef is written as NULL, and binary()
1678 # bytes as a bytea literal: SELECT 'x', NULL, '\x00ff'::bytea
1679 use DBIx::QuickORM::Value qw/binary/;
1680 my $more = $conn->inline_binds(
1681 $source,
1682 'SELECT ?, ?, ?',
1683 [[undef, 'x'], [email => undef], [undef, binary("\x00\xff")]],
1684 );
1685  
1686 Each C<?> in the SQL is taken for a placeholder, so literal SQL holding a
1687 question mark in a string cannot be inlined. Croaks when the counts differ.
1688  
1689 =back
1690  
1691 =cut
1692  
1693 24 ▶sub inline_binds {
Subroutine inline_binds: called CC=11 SCAR=24.3
Pod documented
1694 24 my $self = shift;
1695 24 my ($source, $sql, $binds) = @_;
1696 24 my ($dbh, $dialect) = @{$self}{+DBH, +DIALECT};
1697 24 my $fields = $source->field_records;
1698  
1699 24 my @literals;
1700 24 for my $bind (@{$self->_resolve_binds($source, $binds)}) {
1701 18 my ($name, $value) = @$bind;
1702 18 ▶ my $binary = defined($name) && $fields->{$name} && ($fields->{$name}->{affinity} // '') eq 'binary';
Condition75%6/8
defined $name && $fields->{$name} && ($fields->{$name}{'affinity'} // '') eq 'binary'
!ll&&!rl&&r
2106
defined $name and $fields->{$name}
!ll&&!rl&&r
2016
$fields->{$name}{"affinity"} // ""
l!l
160
MC/DC33%1/3
defined $name && $fields->{$name} && ($fields->{$name}{'affinity'} // '') eq 'binary'
defined $name $fields->{$name} $fields->{$name}{"affinity"}
Truth table50%2/4
A and B && C
A= defined $nameB= $fields->{$name}C= $fields->{$name}{"affinity"}
ABCresult
0XX0
10X0
1100
1111
1703 18 ▶ if (ref($value) && $self->_is_marker($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and $self->_is_marker($value)) 6 12 18
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
1206
MC/DC50%1/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table66%2/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
1704 6 ▶ confess "A " . $value->kind . "() marker cannot be written into a view" unless $value->kind eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $value->kind eq "binary" 0 6 6
1705 6 ($binary, $value) = (1, $value->value);
1706 }
1707 18 ▶ push @literals => !defined($value) ? 'NULL' : $binary ? $dialect->quote_binary($dbh, $value) : $dialect->quote_literal($value);
Branch: 2 branches
BranchTrueFalseTotal
!defined($value) ? : 0 18 18
$binary ? : 6 12 18
1708 }
1709  
1710 24 my $count = () = $sql =~ m/\?/g;
1711 24 ▶ croak "The query has $count placeholder(s) but " . @literals . " bind(s), so its binds cannot be written in" unless $count == @literals;
Branch: 1 branch
BranchTrueFalseTotal
unless $count == @literals 0 24 24
1712 24 $sql =~ s/\?/shift @literals/ge;
1713 24 return $sql;
1714 }
1715  
1716 # }}} Temporary tables and views
1717  
1718 =pod
1719  
1720 =over 4
1721  
1722 =item \%values = $conn->deflate($table, \%values, raw => $bool)
1723  
1724 The values in a new hashref (under C<raw> with no marker, the one given),
1725 deflated as L<DBIx::QuickORM/"CRUD operations"> describes. The CRUD operations
1726 use it on every value they send, except the plain key of a C<refresh_row> with
1727 no options on a single untyped key field, which deflating would not change. Row objects use it for the changes they send
1728 raw.
1729  
1730 use DBIx::QuickORM::Value qw/inflated/;
1731  
1732 # {prefs => '{"theme":"dark"}'}: through the JSON type
1733 my $db_form = $conn->deflate(users => {prefs => {theme => 'dark'}});
1734  
1735 # raw: not deflated, the same hashref back
1736 my $values = {prefs => '{"theme":"dark"}'};
1737 my $as_is = $conn->deflate(
1738 users => $values,
1739 raw => 1,
1740 );
1741  
1742 # raw, but inflated() still deflates its value through the type:
1743 # {name => 'Ann', prefs => '{"theme":"dark"}'}
1744 my $mixed = $conn->deflate(
1745 users => {
1746 name => 'Ann',
1747 prefs => inflated({theme => 'dark'}),
1748 },
1749 raw => 1,
1750 );
1751  
1752 Value markers (L<DBIx::QuickORM::Value>) are handled even under C<raw>: a
1753 C<raw> marker is unwrapped, an C<inflated> one is deflated through the type
1754 whatever C<is_inflated> says, and C<binary> and C<sql> markers are kept for
1755 the SQL. With C<raw> nothing else changes, and values holding no marker are
1756 returned as they are.
1757  
1758 Croaks for a table not in the map, or a field the table does not have, before
1759 deflating anything.
1760  
1761 =back
1762  
1763 =cut
1764  
1765 1561 ▶sub deflate {
Subroutine deflate: called CC=3 SCAR=11.0
Pod documented
1766 1561 my $self = shift;
1767 1561 my ($table, $values, %params) = @_;
1768 1561 my $fields = $self->_table($table)->{fields};
1769 1560 $self->_check_fields($table, sort keys %$values);
1770  
1771 1549 my $raw = $params{raw};
1772 1549 ▶ return $values if $raw && !grep { $self->_is_marker($_) } values %$values;
Branch: 1 branch
BranchTrueFalseTotal
if $raw and not grep({$self->_is_marker($_);} values %$values) 300 1249 1549
Condition100%3/3
$raw and not grep({$self->_is_marker($_);} values %$values)
!ll&&!rl&&r
12472300
MC/DC100%2/2
$raw and not grep({$self->_is_marker($_);} values %$values)
$raw not grep({$self->_is_marker($_);} values %$values)
Truth table100%3/3
A and not(B)
A= $rawB= not grep({$self->_is_marker($_);} values %$values)
ABresult
0X0
100
111
1773  
1774 1249 return {map { $_ => $self->_deflate_value($table, $_, $fields->{$_}, $values->{$_}, $raw) } keys %$values};
1775 }
1776  
1777 =over 4
1778  
1779 =item $conn->release_inherited
1780  
1781 In a forked child, lets go of the handle inherited from the parent without
1782 touching the parent's session. A Connection freed, or still held at exit, does
1783 this by itself, and so does C<< $orm->connection >>. Call it to let go sooner.
1784  
1785 my $pid = fork // die "Could not fork: $!";
1786 unless ($pid) {
1787 $conn->release_inherited; # the parent's session stays open
1788 exit 0;
1789 }
1790 waitpid($pid, 0);
1791  
1792 An async query the parent left pending is cleared too, so nothing the child
1793 does later, or at exit, waits on it. It does nothing in the process that
1794 opened the Connection, and calling it again is harmless.
1795  
1796 =back
1797  
1798 =cut
1799  
1800 10 ▶sub release_inherited {
Subroutine release_inherited: called CC=4 SCAR=21.3
Pod documented
1801 10 my $self = shift;
1802 10 ▶ return if $self->{+PID} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pid"} == $$ 1 9 10
1803 9 $self->{+DIALECT}->release_inherited($self->{+DBH});
1804  
1805 9 ▶ my $busy = delete $self->{+BUSY} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $busy = delete $self->{"busy"} or return 0 9 9
1806 0 my $sth = $busy->{sth};
1807 0 delete $PENDING{refaddr($self)};
1808 0 ▶ @{$sth}{qw/InactiveDestroy RaiseError PrintError PrintWarn HandleError/} = (1, 0, 0, 0, sub { 1 });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1809 0 local $@;
1810 0 ▶ eval { $sth->finish; 1 } or warn $@; # Against the released socket: it reads nothing of the parent's.
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $sth->finish; 1 } } or warn $@ 0 0 0
1811 0 return;
1812 }
1813  
1814 =head1 PRIVATE METHODS
1815  
1816 =pod
1817  
1818 =over 4
1819  
1820 =item $conn->_init_settings
1821  
1822 Checks the settings and fills in their defaults (C<time_zone>,
1823 C<datetime_parsers>, C<retain_cache>, C<lookup_class>, C<enforce_canon>,
1824 C<isolation>), for C<init>.
1825  
1826 =item DBIx::QuickORM::Connection->_forget_scans
1827  
1828 Empties the scan cache, for every database. Schema building calls it, so
1829 no later connection reuses a scan from before the build.
1830  
1831 =item $map = $conn->_scanned_map($dialect, $dbh, $namespace, $rescan)
1832  
1833 A new map of the database, from the scan cache (see L</"The scan cache">), or
1834 from a scan that refreshes it when C<$rescan> is true, nothing is cached for
1835 this database, or it cannot be shared (C<scan_cache_key> is undef).
1836  
1837 =back
1838  
1839 =cut
1840  
1841 449 ▶sub _init_settings {
Subroutine _init_settings: called CC=9 SCAR=22.0
1842 449 my $self = shift;
1843 449 ▶ $self->{+TIME_ZONE} //= 'UTC';
Condition100%2/2
$self->{"time_zone"} //= "UTC"
l!l
41408
MC/DC100%1/1
$self->{"time_zone"} //= "UTC"
$self->{"time_zone"}
Truth table100%2/2
A
A= $self->{"time_zone"}
Aresult
11
00
1844 449 ▶ $self->{+DATETIME_PARSERS} = exists($self->{+DATETIME_PARSERS}) ? $self->_check_datetime_parsers($self->{+DATETIME_PARSERS}) : [];
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'datetime_parsers'} ? : 13 436 449
1845 444 ▶ $self->{+RETAIN_CACHE} //= 0;
Condition100%2/2
$self->{"retain_cache"} //= 0
l!l
15429
MC/DC100%1/1
$self->{"retain_cache"} //= 0
$self->{"retain_cache"}
Truth table100%2/2
A
A= $self->{"retain_cache"}
Aresult
11
00
1846 444 ▶ $self->{+LOOKUP_CLASS} //= 'DBIx::QuickORM::LookupTable::Identity';
Condition100%2/2
$self->{"lookup_class"} //= "DBIx::QuickORM::LookupTable::Identity"
l!l
13431
MC/DC100%1/1
$self->{"lookup_class"} //= "DBIx::QuickORM::LookupTable::Identity"
$self->{"lookup_class"}
Truth table100%2/2
A
A= $self->{"lookup_class"}
Aresult
11
00
1847 444 $self->_check_lookup_class($self->{+LOOKUP_CLASS});
1848 441 ▶ croak "'retain_cache' needs a lookup table that caches, and $self->{+LOOKUP_CLASS} does not" if $self->{+RETAIN_CACHE} && !$self->{+LOOKUP_CLASS}->caches;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"retain_cache"} and not $self->{"lookup_class"}->caches 2 439 441
Condition100%3/3
$self->{"retain_cache"} and not $self->{"lookup_class"}->caches
!ll&&!rl&&r
43092
MC/DC100%2/2
$self->{"retain_cache"} and not $self->{"lookup_class"}->caches
$self->{"retain_cache"} not $self->{"lookup_class"}->caches
Truth table100%3/3
A and not(B)
A= $self->{"retain_cache"}B= not $self->{"lookup_class"}->caches
ABresult
0X0
100
111
1849 439 ▶ $self->{+ENFORCE_CANON} //= 1;
Condition100%2/2
$self->{"enforce_canon"} //= 1
l!l
6433
MC/DC100%1/1
$self->{"enforce_canon"} //= 1
$self->{"enforce_canon"}
Truth table100%2/2
A
A= $self->{"enforce_canon"}
Aresult
11
00
1850 439 ▶ $self->{+ISOLATION} = $self->_isolation($self->{+ISOLATION}) if defined $self->{+ISOLATION};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"isolation"} 4 435 439
1851 438 return;
1852 }
1853  
1854 5 ▶sub _forget_scans { %SCAN_CACHE = (); return }
Subroutine _forget_scans: called CC=1 SCAR=0.0
1855  
1856 383 ▶sub _scanned_map {
Subroutine _scanned_map: called CC=5 SCAR=16.1
1857 383 my $self = shift;
1858 383 my ($dialect, $dbh, $ns, $rescan) = @_;
1859  
1860 383 my $key = $dialect->scan_cache_key($dbh, $ns);
1861 383 ▶ return $SCAN_CACHE{$key}->clone if defined($key) && !$rescan && $SCAN_CACHE{$key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $key and not $rescan and $SCAN_CACHE{$key} 107 276 383
Condition100%6/6
defined $key and not $rescan and $SCAN_CACHE{$key}
!ll&&!rl&&r
23640107
defined $key and not $rescan
!ll&&!rl&&r
21917147
MC/DC100%3/3
defined $key and not $rescan and $SCAN_CACHE{$key}
defined $key not $rescan $SCAN_CACHE{$key}
Truth table100%4/4
A and not(B) and C
A= defined $keyB= not $rescanC= $SCAN_CACHE{$key}
ABCresult
0XX0
10X0
1100
1111
1862  
1863 276 my $map = DBIx::QuickORM::Map->new(tables => $dialect->scan($dbh));
1864 276 ▶ $SCAN_CACHE{$key} = $map->clone if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 57 219 276
1865 276 return $map;
1866 }
1867  
1868 =over 4
1869  
1870 =item $code = $conn->_error_handler($dialect, \@txns)
1871  
1872 The C<HandleError> callback: dies with a L<DBIx::QuickORM::Exception::DB>
1873 built from the failing handle. First it marks the innermost open transaction
1874 failed, with the error (see C<_run>). It holds the dialect and the
1875 transaction stack, not the Connection.
1876  
1877 =back
1878  
1879 =cut
1880  
1881 415 ▶sub _error_handler {
Subroutine _error_handler: called CC=1 SCAR=0.3
1882 415 my $self = shift;
1883 415 my ($dialect, $txns) = @_;
1884  
1885 49 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=20.5
1886 49 my ($msg, $h) = @_;
1887 49 my ($native, $state, $errstr) = ($h->err, $h->state, $h->errstr);
1888 49 ▶ $state = undef unless defined($state) && length($state);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $state and length $state 0 49 49
Condition33%1/3
defined $state and length $state
!ll&&!rl&&r
0049
MC/DC0%0/2
defined $state and length $state
defined $state length $state
Truth table33%1/3
A and B
A= defined $stateB= length $state
ABresult
0X0
100
111
1889  
1890 49 my $txn = $txns->[-1];
1891 49 ▶ $txn->{failed} //= $errstr // $msg if $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $txn 12 37 49
Condition33%2/6
$txn->{"failed"} //= $errstr // $msg
l!l&&r!l&&!r
0120
$errstr // $msg
l!l&&r!l&&!r
1200
MC/DC0%0/3
$txn->{"failed"} //= $errstr // $msg
$txn->{"failed"} $errstr $msg
Truth table0%0/4
A //= B // C
A= $txn->{"failed"}B= $errstrC= $msg
ABCresult
1XX1
01X1
0011
0000
1892  
1893 die DBIx::QuickORM::Exception::DB->new(
1894 kind => $dialect->error_kind($native, $state, $errstr),
1895 state => $state,
1896 native => $native,
1897 errstr => $errstr,
1898 statement => $h->{Statement},
1899 49 message => $msg,
1900 );
1901 415 };
1902 }
1903  
1904 =pod
1905  
1906 =over 4
1907  
1908 =item \%generated = $conn->_generate_keys(\%table, \%values)
1909  
1910 New values for the table's primary key fields missing from C<%values>, from
1911 each field's type's C<generate_key_value>. A field's C<generate> hint
1912 decides: C<none> never, C<prefer_orm> always, and C<prefer_db> (the default)
1913 unless the column has C<db_fills> and the dialect can return the inserted
1914 key (C<supports_returning_insert>). Fields without a type, or whose
1915 type cannot generate, are left out. The values are inflated. The caller
1916 deflates them, even for C<raw> inserts.
1917  
1918 =item @names = $conn->_key_generators(\%table, \%values)
1919  
1920 The primary key fields C<_generate_keys> would fill for C<%values>, decided
1921 from the field records and the dialect alone. Rows with the same fields get
1922 the same answer, so C<insert_many> asks once.
1923  
1924 =back
1925  
1926 =cut
1927  
1928 359 ▶sub _generate_keys {
Subroutine _generate_keys: called CC=2 SCAR=6.9
1929 359 my $self = shift;
1930 359 my ($t, $values) = @_;
1931  
1932 359 my $fields = $t->{fields};
1933 359 my %generated;
1934 359 for my $name ($self->_key_generators($t, $values)) { $generated{$name} = $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
1935 359 return \%generated;
1936 }
1937  
1938 415 ▶sub _key_generators {
Subroutine _key_generators: called CC=11 SCAR=24.0
1939 415 my $self = shift;
1940 415 my ($t, $values) = @_;
1941  
1942 415 my @names;
1943 415 ▶ for my $name (@{$t->{pk} // []}) {
Condition100%2/2
$t->{"pk"} // []
l!l
4078
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
1944 429 ▶ next if exists $values->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $values->{$name} 363 66 429
1945 66 my $field = $t->{fields}->{$name};
1946 66 my $type = $field->{orm_type};
1947 66 ▶ next unless $type && $type->can('generate_key_value');
Branch: 1 branch
BranchTrueFalseTotal
unless $type and $type->can("generate_key_value") 47 19 66
Condition100%3/3
$type and $type->can("generate_key_value")
!ll&&!rl&&r
46119
MC/DC100%2/2
$type and $type->can("generate_key_value")
$type $type->can("generate_key_value")
Truth table100%3/3
A and B
A= $typeB= $type->can("generate_key_value")
ABresult
0X0
100
111
1948  
1949 19 ▶ my $mode = $field->{generate} // 'prefer_db';
Condition100%2/2
$field->{"generate"} // "prefer_db"
l!l
316
MC/DC100%1/1
$field->{"generate"} // "prefer_db"
$field->{"generate"}
Truth table100%2/2
A
A= $field->{"generate"}
Aresult
11
00
1950 19 ▶ next if $mode eq 'none' || ($mode eq 'prefer_db' && $field->{db_fills} && $self->{+DIALECT}->supports_returning_insert);
Branch: 1 branch
BranchTrueFalseTotal
if $mode eq "none" or $mode eq "prefer_db" and $field->{"db_fills"} and $self->{"dialect"}->supports_returning_insert 3 16 19
Condition88%8/9
$mode eq "none" or $mode eq "prefer_db" and $field->{"db_fills"} and $self->{"dialect"}->supports_returning_insert
l!l&&r!l&&!r
2116
$mode eq "prefer_db" and $field->{"db_fills"} and $self->{"dialect"}->supports_returning_insert
!ll&&!rl&&r
1601
$mode eq "prefer_db" and $field->{"db_fills"}
!ll&&!rl&&r
1151
MC/DC75%3/4
$mode eq "none" or $mode eq "prefer_db" and $field->{"db_fills"} and $self->{"dialect"}->supports_returning_insert
$mode eq "none" $mode eq "prefer_db" $field->{"db_fills"} $self->{"dialect"}->supports_returning_insert
Truth table80%4/5
A or B and C and D
A= $mode eq "none"B= $mode eq "prefer_db"C= $field->{"db_fills"}D= $self->{"dialect"}->supports_returning_insert
ABCDresult
1XXX1
01111
00XX0
010X0
01100
1951 16 push @names => $name;
1952 }
1953  
1954 415 return @names;
1955 }
1956  
1957 =pod
1958  
1959 =over 4
1960  
1961 =item \%data = $conn->_row_data($row_or_data)
1962  
1963 The row data: a hashref as given, or a row object's C<row_data>. Croaks on
1964 anything else.
1965  
1966 =back
1967  
1968 =cut
1969  
1970 3593 ▶sub _row_data {
Subroutine _row_data: called CC=5 SCAR=16.2
1971 3593 my $self = shift;
1972 3593 my ($data) = @_;
1973 3593 ▶ $data = $data->row_data if blessed($data) && $data->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($data) and $data->can("row_data") 122 3471 3593
Condition66%2/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
34710122
MC/DC50%1/2
builtin::blessed($data) and $data->can("row_data")
builtin::blessed($data) $data->can("row_data")
Truth table66%2/3
A and B
A= builtin::blessed($data)B= $data->can("row_data")
ABresult
0X0
100
111
1974 3593 ▶ confess "Expected row data (a hashref) or a row object, got " . ($data // 'undef') unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 3591 3593
Condition50%1/2
$data // "undef"
l!l
20
MC/DC0%0/1
$data // "undef"
$data
Truth table50%1/2
A
A= $data
Aresult
11
00
1975 3591 return $data;
1976 }
1977  
1978 =pod
1979  
1980 =over 4
1981  
1982 =item $value = $conn->_deflate_value($table, $name, \%field, $value, $raw)
1983  
1984 One value deflated as C<deflate> describes. C<\%field> is undef for a name
1985 that is not a field.
1986  
1987 A value the type deflated to plain text then goes through the field's
1988 C<format>, if it has one and is not binary.
1989  
1990 =back
1991  
1992 =cut
1993  
1994 1671 ▶sub _deflate_value {
Subroutine _deflate_value: called CC=21 SCAR=30.5
1995 1671 my $self = shift;
1996 1671 my ($table, $name, $field, $value, $raw) = @_;
1997 1671 ▶ my $type = $field ? $field->{orm_type} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$field ? : 1642 29 1671
1998  
1999 1671 ▶ if (ref($value) && $self->_is_marker($value)) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $value and $self->_is_marker($value)) { } 88 1583 1671
elsif ($raw or not defined $value) { } 293 1290 1583
elsif ($type and not ref $value) { } 124 2246 2370
Condition100%3/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
14929188
MC/DC100%2/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table100%3/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
2000 88 my $kind = $value->kind;
2001 88 ▶ return $value if $kind eq 'binary' || $kind eq 'sql';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "binary" or $kind eq "sql" 44 44 88
Condition100%3/3
$kind eq "binary" or $kind eq "sql"
l!l&&r!l&&!r
212344
MC/DC100%2/2
$kind eq "binary" or $kind eq "sql"
$kind eq "binary" $kind eq "sql"
Truth table100%3/3
A or B
A= $kind eq "binary"B= $kind eq "sql"
ABresult
1X1
011
000
2002 44 $value = $value->value;
2003 44 ▶ return $value if $kind eq 'raw' || !defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "raw" or not defined $value 27 17 44
Condition66%2/3
$kind eq "raw" or not defined $value
l!l&&r!l&&!r
27017
MC/DC50%1/2
$kind eq "raw" or not defined $value
$kind eq "raw" not defined $value
Truth table66%2/3
A or not(B)
A= $kind eq "raw"B= not defined $value
ABresult
1X1
011
000
2004 }
2005 ▶ elsif ($raw || !defined($value)) {
Condition100%3/3
$raw or not defined $value
l!l&&r!l&&!r
276171290
MC/DC100%2/2
$raw or not defined $value
$raw not defined $value
Truth table100%3/3
A or not(B)
A= $rawB= not defined $value
ABresult
1X1
011
000
2006 293 return $value;
2007 }
2008 ▶ elsif ($type && !ref($value)) {
Condition100%3/3
$type and not ref $value
!ll&&!rl&&r
108086124
MC/DC100%2/2
$type and not ref $value
$type not ref $value
Truth table100%3/3
A and not(B)
A= $typeB= not ref $value
ABresult
0X0
100
111
2009 124 ▶ return $value unless $type->can('is_inflated') && $type->is_inflated($value);
Branch: 1 branch
BranchTrueFalseTotal
unless $type->can("is_inflated") and $type->is_inflated($value) 48 76 124
Condition100%3/3
$type->can("is_inflated") and $type->is_inflated($value)
!ll&&!rl&&r
14776
MC/DC100%2/2
$type->can("is_inflated") and $type->is_inflated($value)
$type->can("is_inflated") $type->is_inflated($value)
Truth table100%3/3
A and B
A= $type->can("is_inflated")B= $type->is_inflated($value)
ABresult
0X0
100
111
2010 }
2011  
2012 1259 ▶ unless ($type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 1083 176 1259
2013 1083 ▶ confess "The field '$name' of '$table' has no type to deflate a reference with; deflate it yourself and pass raw => 1" if ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if ref $value 6 1077 1083
2014 1077 return $value;
2015 }
2016  
2017 176 my $out = $type->deflate($value, $field, $self);
2018 176 my $format = $field->{format};
2019 176 ▶ return $out unless $format && defined($out) && !ref($out) && ($field->{affinity} // '') ne 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $format and defined $out and not ref $out and ($field->{"affinity"} // "") ne "binary" 163 13 176
Condition72%8/11
$format and defined $out and not ref $out and ($field->{"affinity"} // "") ne "binary"
!ll&&!rl&&r
162113
$format and defined $out and not ref $out
!ll&&!rl&&r
162014
$format and defined $out
!ll&&!rl&&r
162014
$field->{"affinity"} // ""
l!l
140
MC/DC25%1/4
$format and defined $out and not ref $out and ($field->{"affinity"} // "") ne "binary"
$format defined $out not ref $out $field->{"affinity"}
Truth table40%2/5
A and B and not(C) and D
A= $formatB= defined $outC= not ref $outD= $field->{"affinity"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2020 13 return $format->($out);
2021 }
2022  
2023 =pod
2024  
2025 =over 4
2026  
2027 =item $bool = $conn->_is_marker($value)
2028  
2029 =item $bool = $conn->_is_sql($value)
2030  
2031 True for a value marker, or an C<sql> marker.
2032  
2033 =back
2034  
2035 =cut
2036  
2037 2228 ▶sub _is_marker { blessed($_[1]) && $_[1]->isa('DBIx::QuickORM::Value') ? 1 : 0 }
Subroutine _is_marker: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($_[1]) && $_[1]->isa('DBIx::QuickORM::Value') ? : 186 2042 2228
Condition100%3/3
builtin::blessed($_[1]) and $_[1]->isa("DBIx::QuickORM::Value")
!ll&&!rl&&r
201329186
MC/DC100%2/2
builtin::blessed($_[1]) and $_[1]->isa("DBIx::QuickORM::Value")
builtin::blessed($_[1]) $_[1]->isa("DBIx::QuickORM::Value")
Truth table100%3/3
A and B
A= builtin::blessed($_[1])B= $_[1]->isa("DBIx::QuickORM::Value")
ABresult
0X0
100
111
2038 1355 ▶sub _is_sql { $_[0]->_is_marker($_[1]) && $_[1]->kind eq 'sql' ? 1 : 0 }
Subroutine _is_sql: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
$_[0]->_is_marker($_[1]) && $_[1]->kind eq 'sql' ? : 22 1333 1355
Condition100%3/3
$_[0]->_is_marker($_[1]) and $_[1]->kind eq "sql"
!ll&&!rl&&r
13181522
MC/DC100%2/2
$_[0]->_is_marker($_[1]) and $_[1]->kind eq "sql"
$_[0]->_is_marker($_[1]) $_[1]->kind eq "sql"
Truth table100%3/3
A and B
A= $_[0]->_is_marker($_[1])B= $_[1]->kind eq "sql"
ABresult
0X0
100
111
2039  
2040 =pod
2041  
2042 =over 4
2043  
2044 =item \%values = $conn->_plain(\%values)
2045  
2046 A copy with each C<binary> marker replaced by its value, for lookup keys and
2047 row data.
2048  
2049 =back
2050  
2051 =cut
2052  
2053 331 ▶sub _plain {
Subroutine _plain: called CC=2 SCAR=6.9
2054 331 my $self = shift;
2055 331 my ($values) = @_;
2056 331 ▶ return {map { my $v = $values->{$_}; ($_ => $self->_is_marker($v) ? $v->value : $v) } keys %$values};
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_marker($v) ? : 4 346 350
2057 }
2058  
2059 =pod
2060  
2061 =over 4
2062  
2063 =item (\@places, \@binds, $marked) = $conn->_value_sql(\%values, @names)
2064  
2065 The SQL for each named value, C<?> or an C<sql> marker's SQL, and the binds,
2066 in order. C<$marked> is true when any value was a marker: its SQL or bind
2067 attributes make the statement one of a kind, never cached.
2068  
2069 =back
2070  
2071 =cut
2072  
2073 1831 ▶sub _value_sql {
Subroutine _value_sql: called CC=6 SCAR=17.9
2074 1831 my $self = shift;
2075 1831 my ($values, @names) = @_;
2076  
2077 1831 my (@places, @binds, $marked);
2078 1831 for my $name (@names) {
2079 2988 my $value = $values->{$name};
2080 2988 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 24 2964 2988
Condition100%3/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
2962224
MC/DC100%2/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table100%3/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
2081 2988 ▶ if (ref($value) && $self->_is_sql($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and $self->_is_sql($value)) 16 2972 2988
Condition100%3/3
ref $value and $self->_is_sql($value)
!ll&&!rl&&r
29621016
MC/DC100%2/2
ref $value and $self->_is_sql($value)
ref $value $self->_is_sql($value)
Truth table100%3/3
A and B
A= ref $valueB= $self->_is_sql($value)
ABresult
0X0
100
111
2082 16 push @places => $value->value;
2083 16 push @binds => map { [undef, $_] } @{$value->binds};
2084 16 next;
2085 }
2086 2972 push @places => '?';
2087 2972 push @binds => [$name => $value];
2088 }
2089  
2090 1831 return (\@places, \@binds, $marked);
2091 }
2092  
2093 =pod
2094  
2095 =over 4
2096  
2097 =item @batches = $conn->_batches(\@values, \@names)
2098  
2099 The rows of a multi-row insert, as C<[\@places, \@binds, $marked]>: each
2100 place is one row's C<(...)>, each batch holds as many rows as fit in the
2101 dialect's C<bind_limit>, at least one, and C<$marked> is true when one of its
2102 rows held a marker.
2103  
2104 =back
2105  
2106 =cut
2107  
2108 11 ▶sub _batches {
Subroutine _batches: called CC=7 SCAR=19.5
2109 11 my $self = shift;
2110 11 my ($values, $names) = @_;
2111  
2112 11 my $limit = $self->{+DIALECT}->bind_limit;
2113 11 my $plain = '(' . join(', ' => ('?') x @$names) . ')';
2114 11 my @batches = ([[], [], 0]);
2115 11 for my $row (@$values) {
2116 1350 my ($places, $binds, $marked) = $self->_value_sql($row, @$names);
2117 1350 ▶ push @batches => [[], [], 0] if @{$batches[-1]->[0]} && @{$batches[-1]->[1]} + @$binds > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if @{$batches[-1][0];} and @{$batches[-1][1];} + @$binds > $limit 1 1349 1350
Condition100%3/3
@{$batches[-1][0];} and @{$batches[-1][1];} + @$binds > $limit
!ll&&!rl&&r
1113381
MC/DC100%2/2
@{$batches[-1][0];} and @{$batches[-1][1];} + @$binds > $limit
@{$batches[-1][0];} @{$batches[-1][1];} + @$binds > $limit
Truth table100%3/3
A and B
A= @{$batches[-1][0];}B= @{$batches[-1][1];} + @$binds > $limit
ABresult
0X0
100
111
2118 1350 ▶ push @{$batches[-1]->[0]} => $marked ? '(' . join(', ' => @$places) . ')' : $plain;
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 7 1343 1350
2119 1350 push @{$batches[-1]->[1]} => @$binds;
2120 1350 ▶ $batches[-1]->[2] ||= $marked ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 7 343 350
Condition100%3/3
$batches[-1][2] ||= $marked ? 1 : 0
l!l&&r!l&&!r
10007343
MC/DC100%2/2
$batches[-1][2] ||= $marked ? 1 : 0
$batches[-1][2] $marked ? 1 : 0
Truth table100%3/3
A ||= B
A= $batches[-1][2]B= $marked ? 1 : 0
ABresult
1X1
011
000
2121 }
2122  
2123 11 return @batches;
2124 }
2125  
2126 =pod
2127  
2128 =over 4
2129  
2130 =item \@binds = $conn->_resolve_binds($source, \@binds)
2131  
2132 Binds built elsewhere with their C<raw> and C<inflated> markers resolved, as
2133 C<deflate> with C<raw> resolves them, by the source's field each bind names.
2134  
2135 =back
2136  
2137 =cut
2138  
2139 395 ▶sub _resolve_binds {
Subroutine _resolve_binds: called CC=5 SCAR=16.1
2140 395 my $self = shift;
2141 395 my ($source, $binds) = @_;
2142  
2143 395 ▶ my $table = $source->table // '';
Condition100%2/2
$source->table // ""
l!l
34847
MC/DC100%1/1
$source->table // ""
$source->table
Truth table100%2/2
A
A= $source->table
Aresult
11
00
2144 395 my $fields = $source->field_records;
2145 395 ▶ return [map { my ($name, $value) = @$_; [$name, $self->_deflate_value($table, $name // '', defined($name) ? $fields->{$name} : undef, $value, 1)] } @{$binds // []}];
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 271 25 296
Condition75%3/4
$name // ""
l!l
27125
$binds // []
l!l
3950
MC/DC100%1/1
$name // ""
$name
MC/DC0%0/1
$binds // []
$binds
Truth table100%2/2
A
A= $name
Aresult
11
00
Truth table50%1/2
A
A= $binds
Aresult
11
00
2146 }
2147  
2148 =pod
2149  
2150 =over 4
2151  
2152 =item $conn->_check_params($name, \%known, \%params)
2153  
2154 Croaks naming every key of C<%params> not in C<%known>.
2155  
2156 =back
2157  
2158 =cut
2159  
2160 1409 ▶sub _check_params {
Subroutine _check_params: called CC=2 SCAR=6.9
2161 1409 my $self = shift;
2162 1409 my ($name, $known, $params) = @_;
2163 1409 my @unknown = sort grep { !$known->{$_} } keys %$params;
2164 1409 ▶ confess "Unknown argument(s) to $name(): " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 9 1400 1409
2165 }
2166  
2167 =pod
2168  
2169 =over 4
2170  
2171 =item \%table = $conn->_table($table)
2172  
2173 The map's record for the table. Croaks when there is none.
2174  
2175 =back
2176  
2177 =cut
2178  
2179 2437 ▶sub _table {
Subroutine _table: called CC=4 SCAR=13.9
2180 2437 my $self = shift;
2181 2437 my ($table) = @_;
2182 2437 ▶ confess "A table name is required" unless defined($table) && length($table);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and length $table 1 2436 2437
Condition66%2/3
defined $table and length $table
!ll&&!rl&&r
102436
MC/DC50%1/2
defined $table and length $table
defined $table length $table
Truth table66%2/3
A and B
A= defined $tableB= length $table
ABresult
0X0
100
111
2183 2436 ▶ return $self->_map->table($table) // confess "The table '$table' is not in the database map" . $self->_gone_note($table);
Condition100%2/2
$self->_map->table($table) // confess("The table '${table}' is not in the database map" . $self->_gone_note($table))
l!l
24342
MC/DC100%1/1
$self->_map->table($table) // confess("The table '${table}' is not in the database map" . $self->_gone_note($table))
$self->_map->table($table)
Truth table100%2/2
A
A= $self->_map->table($table)
Aresult
11
00
2184 }
2185  
2186 =pod
2187  
2188 =over 4
2189  
2190 =item $conn->_check_fields($table, @fields)
2191  
2192 Croaks for the first field not in the table.
2193  
2194 =back
2195  
2196 =cut
2197  
2198 1810 ▶sub _check_fields {
Subroutine _check_fields: called CC=3 SCAR=11.0
2199 1810 my $self = shift;
2200 1810 my ($table, @fields) = @_;
2201 1810 my $known = $self->_map->table($table)->{fields};
2202 1810 for my $field (@fields) {
2203 1973 ▶ confess "The table '$table' has no field '$field'" unless $known->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $known->{$field} 15 1958 1973
2204 }
2205 }
2206  
2207 =pod
2208  
2209 =over 4
2210  
2211 =item \%pk = $conn->_pk_values($table, $pk)
2212  
2213 =item \%pk = $conn->_pk_values($table, $pk, $raw)
2214  
2215 The key-field hash from a primary key in any form C<normalize_pk> in
2216 L<DBIx::QuickORM::Map> takes, each value put through C<deflate> (with C<raw>
2217 when C<$raw> is true). A C<binary> marker is kept for binding. C<_plain> of
2218 the hash is the raw key the lookup table takes. Croaks as C<normalize_pk> does, and on an C<sql> marker.
2219  
2220 =back
2221  
2222 =cut
2223  
2224 451 ▶sub _pk_values {
Subroutine _pk_values: called CC=3 SCAR=11.0
2225 451 my $self = shift;
2226 451 my ($table, $pk, $raw) = @_;
2227  
2228 451 my $map = $self->_map;
2229 451 my $values = $map->normalize_pk($table, $pk);
2230 436 my $fields = $map->pk($table);
2231 436 my $out = $self->deflate($table, {map { $fields->[$_] => $values->[$_] } 0 .. $#$fields}, raw => $raw);
2232 432 for my $field (@$fields) {
2233 446 ▶ confess "sql() cannot be used in a primary key (the field '$field')" if $self->_is_sql($out->{$field});
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_sql($out->{$field}) 1 445 446
2234 }
2235 431 return $out;
2236 }
2237  
2238 =pod
2239  
2240 =over 4
2241  
2242 =item \@copy = $conn->_check_datetime_parsers(\@parsers)
2243  
2244 A copy of C<@parsers> once each is a code reference, an object with
2245 C<parse_datetime>, or a class name. Loads each class not yet loaded. Croaks
2246 when the shape is wrong, or a class cannot be loaded or has no
2247 C<parse_datetime>.
2248  
2249 =back
2250  
2251 =cut
2252  
2253 19 ▶sub _check_datetime_parsers {
Subroutine _check_datetime_parsers: called CC=10 SCAR=23.1
2254 19 my $self = shift;
2255 19 my ($parsers) = @_;
2256  
2257 croak "'datetime_parsers' must be an arrayref of parsers: classes or objects with parse_datetime, or code references"
2258 19 ▶ unless ref($parsers) eq 'ARRAY' && !grep { ref($_) ne 'CODE' && !(blessed($_) ? $_->can('parse_datetime') : defined($_) && !ref($_) && m/^\w+(?:::\w+)*\z/) } @$parsers;
Branch: 2 branches
BranchTrueFalseTotal
unless ref $parsers eq "ARRAY" and not grep({ref $_ ne "CODE" and not builtin::blessed($_) ? $_->can("parse_datetime") : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/;} @$parsers) 4 15 19
builtin::blessed($_) ? : 1 9 10
Condition91%11/12
ref $parsers eq "ARRAY" and not grep({ref $_ ne "CODE" and not builtin::blessed($_) ? $_->can("parse_datetime") : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/;} @$parsers)
!ll&&!rl&&r
2215
ref $_ ne 'CODE' && !(builtin::blessed($_) ? $_->can('parse_datetime') : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/)
!ll&&!rl&&r
1182
defined $_ and not ref $_ and /^\w+(?:::\w+)*\z/
!ll&&!rl&&r
117
defined $_ and not ref $_
!ll&&!rl&&r
018
MC/DC100%2/2
ref $parsers eq "ARRAY" and not grep({ref $_ ne "CODE" and not builtin::blessed($_) ? $_->can("parse_datetime") : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/;} @$parsers)
ref $parsers eq "ARRAY" not grep({ref $_ ne "CODE" and not builtin::blessed($_) ? $_->can("parse_datetime") : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/;} @$parsers)
MC/DC100%2/2
ref $_ ne 'CODE' && !(builtin::blessed($_) ? $_->can('parse_datetime') : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/)
ref $_ ne 'CODE' !(builtin::blessed($_) ? $_->can('parse_datetime') : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/)
MC/DC66%2/3
defined $_ and not ref $_ and /^\w+(?:::\w+)*\z/
defined $_ not ref $_ /^\w+(?:::\w+)*\z/
Truth table100%3/3
A and not(B)
A= ref $parsers eq "ARRAY"B= not grep({ref $_ ne "CODE" and not builtin::blessed($_) ? $_->can("parse_datetime") : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/;} @$parsers)
ABresult
0X0
100
111
Truth table100%3/3
A && not(B)
A= ref $_ ne 'CODE'B= !(builtin::blessed($_) ? $_->can('parse_datetime') : defined $_ && !ref($_) && /^\w+(?:::\w+)*\z/)
ABresult
0X0
100
111
Truth table75%3/4
A and not(B) and C
A= defined $_B= not ref $_C= /^\w+(?:::\w+)*\z/
ABCresult
0XX0
10X0
1100
1111
2259  
2260 15 for my $parser (grep { !ref($_) } @$parsers) {
2261 7 ▶ next if $parser->can('parse_datetime');
Branch: 1 branch
BranchTrueFalseTotal
if $parser->can("parse_datetime") 0 7 7
2262 7 require DBIx::QuickORM;
2263 7 DBIx::QuickORM->load_class("'datetime_parsers' names the class '$parser', which", $parser);
2264 5 ▶ croak "'datetime_parsers' names the class '$parser', which has no parse_datetime" unless $parser->can('parse_datetime');
Branch: 1 branch
BranchTrueFalseTotal
unless $parser->can("parse_datetime") 2 3 5
2265 }
2266  
2267 11 return [@$parsers];
2268 }
2269  
2270 =pod
2271  
2272 =over 4
2273  
2274 =item $conn->_check_lookup_class($class)
2275  
2276 Loads the lookup table class unless it has a C<new>, and croaks when it cannot
2277 be loaded or does not compose L<DBIx::QuickORM::Role::LookupTable>.
2278  
2279 =back
2280  
2281 =cut
2282  
2283 444 ▶sub _check_lookup_class {
Subroutine _check_lookup_class: called CC=3 SCAR=11.0
2284 444 my $self = shift;
2285 444 my ($class) = @_;
2286  
2287 444 my $role = 'DBIx::QuickORM::Role::LookupTable';
2288 444 ▶ unless ($class->can('new')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class->can("new")) 4 440 444
2289 4 require DBIx::QuickORM;
2290 4 DBIx::QuickORM->load_class("The lookup table class '$class'", $class);
2291 }
2292 443 ▶ croak "The lookup table class '$class' does not compose $role" unless $class->DOES($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $class->DOES($role) 2 441 443
2293 441 return;
2294 }
2295  
2296 =pod
2297  
2298 =over 4
2299  
2300 =item $conn->_enforce_canon($table, \%data, $flag)
2301  
2302 Croaks unless the data is canon, when C<$flag> (or its default) says to check.
2303 The message gives the cause from C<canon_status>, the call behind it when
2304 known, and how to go on.
2305  
2306 =back
2307  
2308 =cut
2309  
2310 202 ▶sub _enforce_canon {
Subroutine _enforce_canon: called CC=5 SCAR=16.1
2311 202 my $self = shift;
2312 202 my ($table, $data, $flag) = @_;
2313  
2314 202 my $lookup = $self->lookup;
2315 202 ▶ $flag //= @{$self->{+TXNS}} ? 1 : $self->{+ENFORCE_CANON};
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'txns'};} ? : 28 100 128
Condition66%2/3
$flag //= @{$self->{"txns"};} ? 1 : $self->{"enforce_canon"}
l!l&&r!l&&!r
741280
MC/DC0%0/2
$flag //= @{$self->{"txns"};} ? 1 : $self->{"enforce_canon"}
$flag @{$self->{"txns"};} ? 1 : $self->{"enforce_canon"}
Truth table66%2/3
A //= B
A= $flagB= @{$self->{"txns"};} ? 1 : $self->{"enforce_canon"}
ABresult
1X1
011
000
2316 202 ▶ return unless $flag;
Branch: 1 branch
BranchTrueFalseTotal
unless $flag 77 125 202
2317 125 ▶ my $status = $lookup->canon_status($table, $data) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $status = $lookup->canon_status($table, $data) or return 27 98 125
2318 27 confess "The row data for '$table' is no longer canonical: " . $lookup->canon_reason($status) . " Refresh the row (\$row->refresh), update it with cas_update(), which writes only while the database still holds what the row read, or pass enforce_canon => 0";
2319 }
2320  
2321 =pod
2322  
2323 =over 4
2324  
2325 =item %cas = $conn->_cas_values($table, \%data, \%changes, \%params)
2326  
2327 The compare-and-swap fields and their values from the row data.
2328  
2329 =back
2330  
2331 =cut
2332  
2333 135 ▶sub _cas_values {
Subroutine _cas_values: called CC=6 SCAR=17.9
2334 135 my $self = shift;
2335 135 my ($table, $data, $changes, $params) = @_;
2336  
2337 135 ▶ my $cas = $params->{cas} // [];
Condition100%2/2
$params->{"cas"} // []
l!l
4194
MC/DC100%1/1
$params->{"cas"} // []
$params->{"cas"}
Truth table100%2/2
A
A= $params->{"cas"}
Aresult
11
00
2338 135 ▶ confess "'cas' must be an arrayref of field names" unless ref($cas) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cas eq "ARRAY" 1 134 135
2339 134 my @fields = @$cas;
2340 134 ▶ push @fields => grep { exists $data->{$_} } keys %$changes if $params->{auto_cas};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"auto_cas"} 6 128 134
2341 134 $self->_check_fields($table, @fields);
2342  
2343 134 for my $field (@fields) {
2344 46 ▶ confess "The 'cas' field '$field' is not in the row data: read it first (\$row->field('$field')), or select it with fields" unless exists $data->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $data->{$field} 4 42 46
2345 }
2346  
2347 130 return map { $_ => $data->{$_} } @fields;
2348 }
2349  
2350 =pod
2351  
2352 =over 4
2353  
2354 =item $map = $conn->_map
2355  
2356 The map.
2357  
2358 =back
2359  
2360 =cut
2361  
2362 4921 ▶sub _map { $_[0]->{+DB_MAP} }
Subroutine _map: called CC=1 SCAR=0.0
2363  
2364 =pod
2365  
2366 =over 4
2367  
2368 =item \@fields = $conn->_default_fields($table)
2369  
2370 The fields a table's queries select: C<default_fields>, or every field. The
2371 list is shared, so callers never change it.
2372  
2373 =item \%set = $conn->_default_field_set($table)
2374  
2375 The same fields as a hash of field name to true.
2376  
2377 =back
2378  
2379 Both are worked out once per table, when first asked for. The map does not
2380 change once the ORM is built, and a forked child's new Connection works them
2381 out again.
2382  
2383 =cut
2384  
2385 487 ▶sub _default_fields { ($_[0]->{+DEFAULTS}->{$_[1]} // $_[0]->_defaults($_[1]))->[0] }
Subroutine _default_fields: called CC=2 SCAR=7.2
Condition66%2/3
$_[0]{"defaults"}{$_[1]} // $_[0]->_defaults($_[1])
l!l&&r!l&&!r
3371500
MC/DC0%0/2
$_[0]{"defaults"}{$_[1]} // $_[0]->_defaults($_[1])
$_[0]{"defaults"}{$_[1]} $_[0]->_defaults($_[1])
Truth table66%2/3
A // B
A= $_[0]{"defaults"}{$_[1]}B= $_[0]->_defaults($_[1])
ABresult
1X1
011
000
2386 128 ▶sub _default_field_set { ($_[0]->{+DEFAULTS}->{$_[1]} // $_[0]->_defaults($_[1]))->[1] }
Subroutine _default_field_set: called CC=2 SCAR=7.2
Condition66%2/3
$_[0]{"defaults"}{$_[1]} // $_[0]->_defaults($_[1])
l!l&&r!l&&!r
118100
MC/DC0%0/2
$_[0]{"defaults"}{$_[1]} // $_[0]->_defaults($_[1])
$_[0]{"defaults"}{$_[1]} $_[0]->_defaults($_[1])
Truth table66%2/3
A // B
A= $_[0]{"defaults"}{$_[1]}B= $_[0]->_defaults($_[1])
ABresult
1X1
011
000
2387  
2388 160 ▶sub _defaults {
Subroutine _defaults: called CC=2 SCAR=6.9
2389 160 my $self = shift;
2390 160 my ($table) = @_;
2391 160 my $t = $self->_map->table($table);
2392 160 ▶ my $list = $t->{default_fields} // [sort keys %{$t->{fields}}];
Condition100%2/2
$t->{"default_fields"} // [sort(keys %{$$t{"fields"};})]
l!l
12148
MC/DC100%1/1
$t->{"default_fields"} // [sort(keys %{$$t{"fields"};})]
$t->{"default_fields"}
Truth table100%2/2
A
A= $t->{"default_fields"}
Aresult
11
00
2393 160 return $self->{+DEFAULTS}->{$table} = [$list, {map { $_ => 1 } @$list}];
2394 }
2395  
2396 =pod
2397  
2398 =over 4
2399  
2400 =item $sql = $conn->_returning_sql(\@fields)
2401  
2402 A C<RETURNING> clause, with a leading space, naming the fields, quoted.
2403  
2404 =back
2405  
2406 =cut
2407  
2408 202 ▶sub _returning_sql {
Subroutine _returning_sql: called CC=1 SCAR=0.0
2409 202 my $self = shift;
2410 202 my ($fields) = @_;
2411 202 my $dialect = $self->{+DIALECT};
2412 202 return ' RETURNING ' . join(', ' => map { $dialect->quote_identifier($_) } @$fields);
2413 }
2414  
2415 =pod
2416  
2417 =over 4
2418  
2419 =item \@fields = $conn->_read_back_fields($table, @names)
2420  
2421 What a write or refresh reads back: the table's default fields, then each of
2422 C<@names> they leave out. Writes pass the fields written, so a row holds what
2423 it just wrote (a JSON field, say). Updates and C<refresh_row> also pass the
2424 fields the row held.
2425  
2426 =back
2427  
2428 =cut
2429  
2430 315 ▶sub _read_back_fields {
Subroutine _read_back_fields: called CC=1 SCAR=0.0
2431 315 my $self = shift;
2432 315 my ($table, @names) = @_;
2433 315 my $default = $self->_default_fields($table);
2434 315 my %seen = map { $_ => 1 } @$default;
2435 315 return [@$default, grep { !$seen{$_}++ } @names];
2436 }
2437  
2438 =pod
2439  
2440 =over 4
2441  
2442 =item ($sql, \@binds, $marked) = $conn->_where_sql(\%pairs)
2443  
2444 A C<WHERE> body comparing each field to its value, in field order. An undef
2445 value becomes C<IS NULL>. Binds are C<[$field, $value]> pairs. An C<sql>
2446 marker croaks. C<$marked> is true when a value is another marker, as for
2447 C<_value_sql>. The SQL is built once per set of fields and null values (see
2448 C<_statement>).
2449  
2450 =back
2451  
2452 =cut
2453  
2454 360 ▶sub _where_sql {
Subroutine _where_sql: called CC=6 SCAR=17.9
2455 360 my $self = shift;
2456 360 my ($pairs) = @_;
2457  
2458 360 my (@shape, @binds, $marked);
2459 360 for my $field (sort keys %$pairs) {
2460 413 my $value = $pairs->{$field};
2461 413 ▶ confess "sql() cannot be used in a primary key or compare-and-swap value (the field '$field')" if $self->_is_sql($value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_sql($value) 2 411 413
2462 411 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 3 408 411
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
40803
MC/DC50%1/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table66%2/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
2463 411 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 408 3 411
2464 408 push @shape => $field;
2465 408 push @binds => [$field => $value];
2466 }
2467 else {
2468 3 push @shape => "\x01$field";
2469 }
2470 }
2471  
2472 358 my $dialect = $self->{+DIALECT};
2473 my $sql = $self->_statement(
2474 join("\0" => 'where', @shape),
2475 101 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2476 101 ▶ join ' AND ' => map { m/^\x01(.*)\z/s ? $dialect->quote_identifier($1) . ' IS NULL' : $dialect->quote_identifier($_) . ' = ?' } @shape;
Branch: 1 branch
BranchTrueFalseTotal
/^\x01(.*)\z/s ? : 2 120 122
2477 }
2478 358 );
2479  
2480 358 return ($sql, \@binds, $marked);
2481 }
2482  
2483 =pod
2484  
2485 =over 4
2486  
2487 =item $sql = $conn->_statement($shape, \&build)
2488  
2489 The SQL C<build> returns, kept by C<$shape> so it is built once per shape: a
2490 key naming the statement kind, the table, and its fields in order. An undef
2491 shape (a statement with a marker, see C<_value_sql>) builds it every time.
2492  
2493 =back
2494  
2495 =cut
2496  
2497 1070 ▶sub _statement {
Subroutine _statement: called CC=3 SCAR=11.0
2498 1070 my $self = shift;
2499 1070 my ($shape, $build) = @_;
2500 1070 ▶ return $build->() unless defined $shape;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $shape 19 1051 1070
2501 1051 ▶ return $self->{+STATEMENTS}->{$shape} //= $build->();
Condition66%2/3
$self->{"statements"}{$shape} //= &$build()
l!l&&r!l&&!r
5624890
MC/DC0%0/2
$self->{"statements"}{$shape} //= &$build()
$self->{"statements"}{$shape} &$build()
Truth table66%2/3
A //= B
A= $self->{"statements"}{$shape}B= &$build()
ABresult
1X1
011
000
2502 }
2503  
2504 =pod
2505  
2506 =over 4
2507  
2508 =item $sth = $conn->_run(\%fields, $sql, \@binds)
2509  
2510 =item $sth = $conn->_run(\%fields, $sql, \@binds, \%prepare_attrs, $cached)
2511  
2512 Prepares and executes the SQL, the one place the CRUD operations bind values.
2513 With C<$cached> the statement comes from C<prepare_cached>, for the
2514 single-row CRUD operations' fixed SQL only.
2515  
2516 Every statement the Connection sends comes through here or C<_run_plain>,
2517 so both croak while an async query is pending (see C<select>), and while the
2518 innermost transaction is marked failed, unless the statement rolls it back. Each bind is
2519 C<[$name, $value]>. The field record C<$fields{$name}> (none for an undef
2520 name) decides the bind attributes, except that a C<binary> marker is bound as
2521 binary. The SQL and every value not going to a binary field pass through the
2522 dialect's C<text_to_db>.
2523  
2524 =back
2525  
2526 =cut
2527  
2528 1628 ▶sub _run {
Subroutine _run: called CC=12 SCAR=24.9
2529 1628 my $self = shift;
2530 1628 my ($fields, $sql, $binds, $attrs, $cached) = @_;
2531  
2532 1628 $self->_run_guard($sql);
2533 1623 my $dialect = $self->{+DIALECT};
2534  
2535 1623 my (@values, @attrs, @text, %attrs_of);
2536 1623 for my $bind (@$binds) {
2537 2718 my ($name, $value) = @$bind;
2538 2718 ▶ my $field = defined($name) ? $fields->{$name} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 2686 32 2718
2539 2718 ▶ my $attrs = $field ? ($attrs_of{$field} //= [$dialect->bind_attrs($field)])->[0] : undef; # once per field record
Branch: 1 branch
BranchTrueFalseTotal
$field ? : 2682 36 2718
Condition100%2/2
$attrs_of{$field} //= [$dialect->bind_attrs($field)]
l!l
10531629
MC/DC100%1/1
$attrs_of{$field} //= [$dialect->bind_attrs($field)]
$attrs_of{$field}
Truth table100%2/2
A
A= $attrs_of{$field}
Aresult
11
00
2540 2718 ▶ if (ref($value) && $self->_is_marker($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and $self->_is_marker($value)) 14 2704 2718
Condition100%3/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
2702214
MC/DC100%2/2
ref $value and $self->_is_marker($value)
ref $value $self->_is_marker($value)
Truth table100%3/3
A and B
A= ref $valueB= $self->_is_marker($value)
ABresult
0X0
100
111
2541 14 ▶ confess "A " . $value->kind . "() marker cannot be bound here" unless $value->kind eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $value->kind eq "binary" 0 14 14
2542 14 ($field, $value) = ({affinity => 'binary'}, $value->value);
2543 14 $attrs = $dialect->bind_attrs($field);
2544 }
2545 2718 ▶ push @text => scalar(@values) unless $field && $field->{affinity} eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $field and $field->{"affinity"} eq "binary" 2663 55 2718
Condition100%3/3
$field and $field->{"affinity"} eq "binary"
!ll&&!rl&&r
35262855
MC/DC100%2/2
$field and $field->{"affinity"} eq "binary"
$field $field->{"affinity"} eq "binary"
Truth table100%3/3
A and B
A= $fieldB= $field->{"affinity"} eq "binary"
ABresult
0X0
100
111
2546 2718 push @values => $value;
2547 2718 push @attrs => $attrs;
2548 }
2549 1623 $dialect->text_to_db($sql, @values[@text]);
2550  
2551 # 3: a cached statement still active is left alone and a new one prepared.
2552 1623 ▶ my $sth = $cached ? $self->{+DBH}->prepare_cached($sql, $attrs, 3) : $self->{+DBH}->prepare($sql, $attrs);
Branch: 1 branch
BranchTrueFalseTotal
$cached ? : 755 868 1623
2553 1608 $sth->bind_param($_ + 1, $values[$_], $attrs[$_]) for 0 .. $#values;
2554 1606 $sth->execute;
2555  
2556 1584 return $sth;
2557 }
2558  
2559 =pod
2560  
2561 =over 4
2562  
2563 =item $sth = $conn->_run_plain($sql, \@values)
2564  
2565 C<_run> for values that need no bind attributes: no markers and no field
2566 whose C<bind_attrs> is defined. It runs the same checks, passes the SQL and
2567 every value through C<text_to_db>, and executes with the values in order.
2568 C<insert_many> uses it for batches of plain values.
2569  
2570 =item $conn->_run_guard($sql)
2571  
2572 The checks C<_run> and C<_run_plain> make before sending C<$sql>.
2573  
2574 =back
2575  
2576 =cut
2577  
2578 58 ▶sub _run_plain {
Subroutine _run_plain: called CC=1 SCAR=0.0
2579 58 my $self = shift;
2580 58 my ($sql, $values) = @_;
2581  
2582 58 $self->_run_guard($sql);
2583 58 $self->{+DIALECT}->text_to_db($sql, @$values);
2584 58 my $sth = $self->{+DBH}->prepare($sql);
2585 57 $sth->execute(@$values);
2586  
2587 55 return $sth;
2588 }
2589  
2590 1686 ▶sub _run_guard {
Subroutine _run_guard: called CC=4 SCAR=13.9
2591 1686 my $self = shift;
2592 1686 my ($sql) = @_;
2593  
2594 1686 $self->_check_idle;
2595 1686 ▶ my $txn = $self->{+TXNS}->[-1] or return;
Branch: 1 branch
BranchTrueFalseTotal
my $txn = $self->{"txns"}[-1] or return 424 1262 1686
2596  
2597 # RELEASE SAVEPOINT reaches a failed level only after ROLLBACK TO it: commit_txn rolls a failed level back first.
2598 424 ▶ confess "A statement in the transaction opened at " . $txn->opened_at . " failed, so the transaction can only be rolled back; to recover from a failure and go on, run the work that may fail in a nested transaction.\nThe failure: " . $txn->failed . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if defined $txn->failed and not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/ 5 419 424
Condition100%3/3
defined $txn->failed and not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/
!ll&&!rl&&r
403165
MC/DC100%2/2
defined $txn->failed and not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/
defined $txn->failed not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/
Truth table100%3/3
A and not(B)
A= defined $txn->failedB= not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/
ABresult
0X0
100
111
2599 if defined($txn->failed) && $sql !~ m/^(?:ROLLBACK|RELEASE SAVEPOINT)\b/;
2600 }
2601  
2602 =pod
2603  
2604 =over 4
2605  
2606 =item $conn->_check_idle
2607  
2608 Croaks while an async query is pending.
2609  
2610 =back
2611  
2612 =cut
2613  
2614 1827 ▶sub _check_idle {
Subroutine _check_idle: called CC=2 SCAR=7.2
2615 1827 my $self = shift;
2616 1827 ▶ confess "An async query is still pending on this connection; collect its iterator (ready, next, or all) first" if $self->{+BUSY};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"busy"} 0 1827 1827
2617 }
2618  
2619 =pod
2620  
2621 =over 4
2622  
2623 =item $conn->_do($sql)
2624  
2625 Runs a transaction statement through C<_run>.
2626  
2627 =back
2628  
2629 =cut
2630  
2631 471 ▶sub _do { $_[0]->_run({}, $_[1], []) }
Subroutine _do: called CC=1 SCAR=0.0
2632  
2633 =pod
2634  
2635 =over 4
2636  
2637 =item \@rows = $conn->_fetch(\%fields, $sth)
2638  
2639 Every remaining row of an executed statement, as hashes keyed by column name.
2640 It is the one place the CRUD operations fetch rows. The names and every value
2641 not from a binary field (by C<$fields{$name}>) pass through the dialect's
2642 C<text_from_db>.
2643  
2644 =back
2645  
2646 =cut
2647  
2648 917 ▶sub _fetch {
Subroutine _fetch: called CC=6 SCAR=17.9
2649 917 my $self = shift;
2650 917 my ($fields, $sth) = @_;
2651  
2652 917 my $dialect = $self->{+DIALECT};
2653  
2654 917 my @names = @{$sth->{NAME}};
2655 917 $dialect->text_from_db(@names);
2656  
2657 # Most dialects keep the base text_from_db, which does nothing, so their rows skip the call.
2658 917 my $decodes = $dialect->can('text_from_db') != \&DBIx::QuickORM::Dialect::text_from_db;
2659 917 ▶ my @text = $decodes ? grep { (($fields->{$names[$_]} // {})->{affinity} // '') ne 'binary' } 0 .. $#names : ();
Branch: 1 branch
BranchTrueFalseTotal
$decodes ? : 1 916 917
Condition100%4/4
+($$fields{$names[$_]} // {})->{"affinity"} // ""
l!l
12
$$fields{$names[$_]} // {}
l!l
21
MC/DC100%1/1
+($$fields{$names[$_]} // {})->{"affinity"} // ""
$$fields{$names[$_]}
Truth table100%2/2
A
A= $$fields{$names[$_]}
Aresult
11
00
2660  
2661 917 my @rows;
2662 917 ▶ while (my $row = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 1450 917 2367
2663 1450 my %row;
2664 1450 ▶ if (@text) {
Branch: 1 branch
BranchTrueFalseTotal
if (@text) { } 1 1449 1450
2665 1 my @values = @$row;
2666 1 $dialect->text_from_db(@values[@text]);
2667 1 @row{@names} = @values;
2668 }
2669 else {
2670 1449 @row{@names} = @$row;
2671 }
2672 1450 push @rows => \%row;
2673 }
2674  
2675 917 return \@rows;
2676 }
2677  
2678 =pod
2679  
2680 =over 4
2681  
2682 =item $level = $conn->_isolation($level)
2683  
2684 The level in lower case. Confesses unless it is one C<txn> takes or
2685 C<'server'>.
2686  
2687 =back
2688  
2689 =cut
2690  
2691 9 ▶sub _isolation {
Subroutine _isolation: called CC=4 SCAR=14.3
2692 9 my $self = shift;
2693 9 my ($level) = @_;
2694 9 ▶ return lc $level if defined($level) && !ref($level) && $ISOLATION{lc $level};
Branch: 1 branch
BranchTrueFalseTotal
if defined $level and not ref $level and $ISOLATION{lc $level} 7 2 9
Condition50%3/6
defined $level and not ref $level and $ISOLATION{lc $level}
!ll&&!rl&&r
027
defined $level and not ref $level
!ll&&!rl&&r
009
MC/DC33%1/3
defined $level and not ref $level and $ISOLATION{lc $level}
defined $level not ref $level $ISOLATION{lc $level}
Truth table50%2/4
A and not(B) and C
A= defined $levelB= not ref $levelC= $ISOLATION{lc $level}
ABCresult
0XX0
10X0
1100
1111
2695 2 confess "'isolation' must be one of: " . join(', ' => map { "'$_'" } @ISOLATION);
2696 }
2697  
2698 =pod
2699  
2700 =over 4
2701  
2702 =item $txn = $conn->_begin(\@caller, $level)
2703  
2704 Opens a transaction or savepoint and pushes it onto the stack. C<$level> is
2705 the root transaction's isolation level from C<txn>, or undef.
2706  
2707 A root transaction always states its level: C<$level>, else the Connection's
2708 C<isolation>, else C<'read committed'> where the dialect
2709 C<supports_isolation>. C<'server'> sends the dialect's plain C<begin_sql>.
2710  
2711 =back
2712  
2713 =cut
2714  
2715 179 ▶sub _begin {
Subroutine _begin: called CC=8 SCAR=20.8
2716 179 my $self = shift;
2717 179 my ($caller, $level) = @_;
2718  
2719 179 my $txns = $self->{+TXNS};
2720 179 my $dialect = $self->{+DIALECT};
2721 179 my $name = 'qorm_txn_' . ++$self->{+TXN_COUNT};
2722 179 ▶ if (@$txns) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$txns) { } 35 144 179
2723 35 ▶ confess "The " . $dialect->name . " dialect has no savepoints, so transactions cannot be nested" unless $dialect->supports_savepoints;
Branch: 1 branch
BranchTrueFalseTotal
unless $dialect->supports_savepoints 0 35 35
2724 35 $self->_do("SAVEPOINT $name");
2725 34 $self->lookup->push_level;
2726 34 $self->row_states->push_level;
2727 }
2728 else {
2729 144 ▶ $level //= $self->{+ISOLATION} // ($dialect->supports_isolation ? 'read committed' : 'server');
Branch: 1 branch
BranchTrueFalseTotal
$dialect->supports_isolation ? : 0 140 140
Condition100%4/4
$level //= $self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
l!l
3141
$self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
l!l
1140
MC/DC100%1/1
$level //= $self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
$level
Truth table100%2/2
A
A= $level
Aresult
11
00
2730 144 ▶ $self->_do($_) for $dialect->begin_sql($level eq 'server' ? undef : uc $level);
Branch: 1 branch
BranchTrueFalseTotal
$level eq 'server' ? : 142 2 144
2731 141 $self->lookup->begin_root;
2732 141 $self->row_states->push_level;
2733 }
2734  
2735 175 my $txn = DBIx::QuickORM::Txn->new(connection => $self, name => $name, depth => @$txns + 1, caller => $caller);
2736 175 weaken($txns->[@$txns] = $txn);
2737 175 return $txn;
2738 }
2739  
2740 =pod
2741  
2742 =over 4
2743  
2744 =item ($ok, $err, @out) = $conn->_run_block($code, \@caller, $list, $level)
2745  
2746 Runs one attempt of a transaction block, as C<txn> describes, and reports how
2747 it ended, including a failure to open the transaction. A failed rollback after
2748 the block threw is a warning, so the block's exception is what propagates. The
2749 transaction is then abandoned (C<_abandon>).
2750  
2751 =back
2752  
2753 =cut
2754  
2755 112 ▶sub _run_block {
Subroutine _run_block: called CC=7 SCAR=19.5
2756 112 my $self = shift;
2757 112 my ($code, $caller, $list, $level) = @_;
2758  
2759 112 ▶ my $txn = eval { $self->_begin($caller, $level) } or return (0, $@);
Branch: 1 branch
BranchTrueFalseTotal
my $txn = eval { do { $self->_begin($caller, $level) } } or return 0, $@ 109 3 112
2760 109 my @out;
2761 109 my $ok = eval {
2762 109 ▶ if ($list) { @out = $code->($txn) }
Branch: 1 branch
BranchTrueFalseTotal
if ($list) { } 4 105 109
2763 105 else { $out[0] = $code->($txn) }
2764 82 ▶ $self->commit_txn($txn) if $self->_is_open($txn);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_open($txn) 58 24 82
2765 80 1;
2766 };
2767 109 ▶ return (1, undef, @out) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 80 29 109
2768  
2769 29 my $err = $@;
2770 29 ▶ if ($self->_is_open($txn) && !eval { $self->_unwind($txn); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_open($txn) and not eval { do { $self->_unwind($txn); 1 } }) 2 27 29
Condition100%3/3
$self->_is_open($txn) and not eval { do { $self->_unwind($txn); 1 } }
!ll&&!rl&&r
1262
MC/DC100%2/2
$self->_is_open($txn) and not eval { do { $self->_unwind($txn); 1 } }
$self->_is_open($txn) not eval { do { $self->_unwind($txn); 1 } }
Truth table100%3/3
A and not(B)
A= $self->_is_open($txn)B= not eval { do { $self->_unwind($txn); 1 } }
ABresult
0X0
100
111
2771 2 warn "Rolling back the transaction opened at " . $txn->opened_at . " after its block threw an exception failed: $@";
2772 2 $self->_abandon($txn);
2773 }
2774 29 return (0, $err);
2775 }
2776  
2777 =pod
2778  
2779 =over 4
2780  
2781 =item $bool = $conn->_retriable($err)
2782  
2783 True for a L<DBIx::QuickORM::Exception::DB> whose C<retriable> is true.
2784  
2785 =back
2786  
2787 =cut
2788  
2789 9 ▶sub _retriable {
Subroutine _retriable: called CC=4 SCAR=13.9
2790 9 my $self = shift;
2791 9 my ($err) = @_;
2792 9 ▶ return 0 unless blessed($err) && $err->isa('DBIx::QuickORM::Exception::DB');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($err) and $err->isa("DBIx::QuickORM::Exception::DB") 1 8 9
Condition66%2/3
builtin::blessed($err) and $err->isa("DBIx::QuickORM::Exception::DB")
!ll&&!rl&&r
108
MC/DC50%1/2
builtin::blessed($err) and $err->isa("DBIx::QuickORM::Exception::DB")
builtin::blessed($err) $err->isa("DBIx::QuickORM::Exception::DB")
Truth table66%2/3
A and B
A= builtin::blessed($err)B= $err->isa("DBIx::QuickORM::Exception::DB")
ABresult
0X0
100
111
2793 8 ▶ return $err->retriable ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$err->retriable ? : 6 2 8
2794 }
2795  
2796 =pod
2797  
2798 =over 4
2799  
2800 =item $bool = $conn->_is_open($txn)
2801  
2802 True while the transaction is on the stack.
2803  
2804 =back
2805  
2806 =cut
2807  
2808 433 ▶sub _is_open {
Subroutine _is_open: called CC=3 SCAR=11.0
2809 433 my $self = shift;
2810 433 my ($txn) = @_;
2811 433 my $open = $self->{+TXNS}->[$txn->depth - 1];
2812 433 ▶ return $open && $open == $txn ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$open && $open == $txn ? : 235 198 433
Condition100%3/3
$open and $open == $txn
!ll&&!rl&&r
18612235
MC/DC100%2/2
$open and $open == $txn
$open $open == $txn
Truth table100%3/3
A and B
A= $openB= $open == $txn
ABresult
0X0
100
111
2813 }
2814  
2815 =pod
2816  
2817 =over 4
2818  
2819 =item $conn->_check_open($txn, $action)
2820  
2821 Croaks unless the transaction is open and innermost, and this is the process
2822 that opened it.
2823  
2824 =back
2825  
2826 =cut
2827  
2828 147 ▶sub _check_open {
Subroutine _check_open: called CC=4 SCAR=13.9
2829 147 my $self = shift;
2830 147 my ($txn, $action) = @_;
2831  
2832 147 my $where = $txn->opened_at;
2833 147 ▶ confess "Cannot $action the transaction opened at $where from process $$; process $self->{+PID} opened it" unless $self->{+PID} == $$;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"pid"} == $$ 0 147 147
2834 147 ▶ confess "Cannot $action the transaction opened at $where: it is already finished" unless $self->_is_open($txn);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_is_open($txn) 3 144 147
2835 144 ▶ confess "Cannot $action the transaction opened at $where: a transaction opened inside it is still open" unless $txn->depth == @{$self->{+TXNS}};
Branch: 1 branch
BranchTrueFalseTotal
unless $txn->depth == @{$self->{"txns"};} 3 141 144
2836 }
2837  
2838 =pod
2839  
2840 =over 4
2841  
2842 =item $conn->_unwind($txn)
2843  
2844 Rolls the transaction back, with every transaction open inside it, then drops
2845 them from the stack and the lookup table. An async query still pending is
2846 cancelled first, warning if that fails. Nothing is dropped when the database
2847 refuses the rollback.
2848  
2849 =back
2850  
2851 =cut
2852  
2853 98 ▶sub _unwind {
Subroutine _unwind: called CC=4 SCAR=16.0
2854 98 my $self = shift;
2855 98 my ($txn) = @_;
2856  
2857 # A query left pending inside it cannot be collected any more. On PostgreSQL the cancel aborts the transaction.
2858 98 ▶ if (my $busy = $self->{+BUSY}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $busy = $self->{"busy"}) 0 98 98
2859 0 local $@;
2860 0 ▶ eval { $busy->{cancel}->(); 1 } or warn "Cancelling the async query pending in the transaction opened at " . $txn->opened_at . " failed: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $busy->{"cancel"}->(); 1 } } or warn 'Cancelling the async query pending in the transaction opened at ' . $txn->opened_at . " failed: $@" 0 0 0
2861 }
2862  
2863 98 ▶ if ($txn->depth == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($txn->depth == 1) { } 79 19 98
2864 79 $self->_do('ROLLBACK');
2865 }
2866 else {
2867 19 $self->_do('ROLLBACK TO SAVEPOINT ' . $txn->name);
2868 16 $self->_do('RELEASE SAVEPOINT ' . $txn->name);
2869 }
2870  
2871 91 $self->_drop_levels($txn);
2872 }
2873  
2874 =pod
2875  
2876 =over 4
2877  
2878 =item $conn->_drop_levels($txn)
2879  
2880 =item $conn->_drop_levels($txn, $unknown)
2881  
2882 Drops the transaction, and every transaction open inside it, from the stack
2883 and the lookup table, and ends or restores their temporary tables and views
2884 (C<_temps_rolled_back>). Sends no SQL but that of the MySQL family's
2885 temporary table drops.
2886  
2887 =back
2888  
2889 =cut
2890  
2891 97 ▶sub _drop_levels {
Subroutine _drop_levels: called CC=3 SCAR=11.0
2892 97 my $self = shift;
2893 97 my ($txn, $unknown) = @_;
2894  
2895 97 my $txns = $self->{+TXNS};
2896 97 my $lookup = $self->lookup;
2897 97 ▶ while (@$txns >= $txn->depth) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$txns >= $txn->depth) 99 97 196
2898 99 my $level = @$txns;
2899 99 pop @$txns;
2900 99 $lookup->rollback_level;
2901 99 $self->row_states->rollback_level;
2902 99 ▶ $self->_temps_rolled_back($level, $unknown) if $self->{+TEMPS};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"temps"} 8 91 99
2903 }
2904 }
2905  
2906 =pod
2907  
2908 =over 4
2909  
2910 =item $conn->_abandon($txn)
2911  
2912 For a transaction whose outcome is unknown: drops it as C<_drop_levels> does
2913 (ending the temporary tables and views it touched), then empties every remaining transaction lookup level, so no row held from
2914 inside the transaction is canon. The outside level is kept.
2915  
2916 =back
2917  
2918 =cut
2919  
2920 6 ▶sub _abandon {
Subroutine _abandon: called CC=1 SCAR=0.0
2921 6 my $self = shift;
2922 6 my ($txn) = @_;
2923 6 $self->_drop_levels($txn, 1);
2924 6 $self->lookup->clear_txn_levels;
2925 6 $self->row_states->clear_levels;
2926 }
2927  
2928 =pod
2929  
2930 =over 4
2931  
2932 =item $conn->_temps_committed($depth)
2933  
2934 =item $conn->_temps_rolled_back($level, $unknown)
2935  
2936 The temporary table and view transitions when the transaction at C<$depth>
2937 commits, or the one at C<$level> rolls back (C<$unknown> when its outcome is
2938 unknown), as L</"Temporary tables and views"> describes.
2939  
2940 =item $conn->_end_temp($name, $reason)
2941  
2942 Forgets a temporary table or view that no longer exists: its map entry, its
2943 rows in the lookup table, and the statements cached for it.
2944  
2945 =item $conn->_create_statement($statement)
2946  
2947 One item of C<create_temp>'s C<@create_sql>.
2948  
2949 =item $note = $conn->_gone_note($name)
2950  
2951 For a "not in the database map" error: why a temporary table or view of that
2952 name ended, as a parenthesized note, or an empty string.
2953  
2954 =item $conn->_drop_quietly($name)
2955  
2956 Sends a temporary table's or view's C<DROP> statements, warning instead of
2957 dying when they fail, for drops nothing can undo or report.
2958  
2959 =back
2960  
2961 =cut
2962  
2963 8 ▶sub _temps_committed {
Subroutine _temps_committed: called CC=7 SCAR=19.5
2964 8 my $self = shift;
2965 8 my ($depth) = @_;
2966 8 my $temps = $self->{+TEMPS};
2967 8 for my $name (sort keys %$temps) {
2968 8 my $entry = $temps->{$name};
2969 8 ▶ $entry->{created} = $depth - 1 if $entry->{created} == $depth;
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"created"} == $depth 1 7 8
2970 8 ▶ next unless defined($entry->{dropped}) && $entry->{dropped} == $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry->{"dropped"} and $entry->{"dropped"} == $depth 2 6 8
Condition66%2/3
defined $entry->{"dropped"} and $entry->{"dropped"} == $depth
!ll&&!rl&&r
206
MC/DC50%1/2
defined $entry->{"dropped"} and $entry->{"dropped"} == $depth
defined $entry->{"dropped"} $entry->{"dropped"} == $depth
Truth table66%2/3
A and B
A= defined $entry->{"dropped"}B= $entry->{"dropped"} == $depth
ABresult
0X0
100
111
2971 6 ▶ if ($depth > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth > 1) 2 4 6
2972 2 $entry->{dropped} = $depth - 1;
2973 2 next;
2974 }
2975 4 ▶ $self->_drop_quietly($name) unless $self->{+DIALECT}->temp_ddl_transactional;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"dialect"}->temp_ddl_transactional 0 4 4
2976 4 $self->_end_temp($name, 'dropped');
2977 }
2978 }
2979  
2980 8 ▶sub _temps_rolled_back {
Subroutine _temps_rolled_back: called CC=10 SCAR=24.7
2981 8 my $self = shift;
2982 8 my ($level, $unknown) = @_;
2983 8 my $temps = $self->{+TEMPS};
2984 8 my $dbs = $self->{+DIALECT}->temp_ddl_transactional;
2985 8 for my $name (sort keys %$temps) {
2986 9 my $entry = $temps->{$name};
2987 9 my $created = $entry->{created} >= $level;
2988 9 ▶ next unless $created || (defined($entry->{dropped}) && $entry->{dropped} >= $level);
Branch: 1 branch
BranchTrueFalseTotal
unless $created or defined $entry->{"dropped"} and $entry->{"dropped"} >= $level 0 9 9
Condition50%3/6
$created or defined $entry->{"dropped"} and $entry->{"dropped"} >= $level
l!l&&r!l&&!r
540
defined $entry->{"dropped"} and $entry->{"dropped"} >= $level
!ll&&!rl&&r
004
MC/DC0%0/3
$created or defined $entry->{"dropped"} and $entry->{"dropped"} >= $level
$created defined $entry->{"dropped"} $entry->{"dropped"} >= $level
Truth table50%2/4
A or B and C
A= $createdB= defined $entry->{"dropped"}C= $entry->{"dropped"} >= $level
ABCresult
1XX1
0111
00X0
0100
2989 9 ▶ if ($unknown || $created) {
Branch: 1 branch
BranchTrueFalseTotal
if ($unknown or $created) 5 4 9
Condition66%2/3
$unknown or $created
l!l&&r!l&&!r
054
MC/DC50%1/2
$unknown or $created
$unknown $created
Truth table66%2/3
A or B
A= $unknownB= $created
ABresult
1X1
011
000
2990 5 ▶ $self->_drop_quietly($name) if $unknown || !$dbs;
Branch: 1 branch
BranchTrueFalseTotal
if $unknown or not $dbs 0 5 5
Condition33%1/3
$unknown or not $dbs
l!l&&r!l&&!r
005
MC/DC0%0/2
$unknown or not $dbs
$unknown not $dbs
Truth table33%1/3
A or not(B)
A= $unknownB= not $dbs
ABresult
1X1
011
000
2991 5 ▶ $self->_end_temp($name, $unknown ? 'outcome unknown' : 'rolled back');
Branch: 1 branch
BranchTrueFalseTotal
$unknown ? : 0 5 5
2992 5 next;
2993 }
2994 4 $self->{+DB_MAP}->add_table($name, delete $entry->{record});
2995 4 $entry->{dropped} = undef;
2996 }
2997 }
2998  
2999 64 ▶sub _create_statement {
Subroutine _create_statement: called CC=2 SCAR=6.9
3000 64 my $self = shift;
3001 64 my ($statement) = @_;
3002 64 ▶ return $self->_do($statement) unless ref($statement);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $statement 50 14 64
3003 14 my ($source, $sql, $binds) = @$statement;
3004 14 $self->_run($source->field_records, $sql, $self->_resolve_binds($source, $binds));
3005 14 return;
3006 }
3007  
3008 51 ▶sub _end_temp {
Subroutine _end_temp: called CC=5 SCAR=16.1
3009 51 my $self = shift;
3010 51 my ($name, $reason) = @_;
3011 51 delete $self->{+TEMPS}->{$name};
3012 51 $self->{+DB_MAP}->remove_table($name);
3013 51 $self->{+GONE_TEMPS}->{$name} = $reason;
3014 51 ▶ $self->{+LOOKUP}->remove_table($name) if $self->{+LOOKUP};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"lookup"} 45 6 51
3015 51 ▶ delete $self->{+FIND_KEYS}->{$name} if $self->{+FIND_KEYS};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"find_keys"} 40 11 51
3016 51 ▶ delete $self->{+DEFAULTS}->{$name} if $self->{+DEFAULTS};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"defaults"} 45 6 51
3017 51 ▶ my $statements = $self->{+STATEMENTS} // {};
Condition100%2/2
$self->{"statements"} // {}
l!l
501
MC/DC100%1/1
$self->{"statements"} // {}
$self->{"statements"}
Truth table100%2/2
A
A= $self->{"statements"}
Aresult
11
00
3018 51 delete @{$statements}{grep { (split /\0/ => $_, 3)[1] eq $name } keys %$statements};
3019 51 return;
3020 }
3021  
3022 11 ▶sub _gone_note {
Subroutine _gone_note: called CC=3 SCAR=11.0
3023 11 my $self = shift;
3024 11 my ($name) = @_;
3025 11 ▶ my $reason = $self->{+GONE_TEMPS} && $self->{+GONE_TEMPS}->{$name} or return '';
Branch: 1 branch
BranchTrueFalseTotal
my $reason = $self->{"gone_temps"} && $self->{"gone_temps"}{$name} or return "" 1 10 11
Condition100%3/3
$self->{'gone_temps'} && $self->{'gone_temps'}{$name}
!ll&&!rl&&r
911
MC/DC100%2/2
$self->{'gone_temps'} && $self->{'gone_temps'}{$name}
$self->{'gone_temps'} $self->{'gone_temps'}{$name}
Truth table100%3/3
A && B
A= $self->{'gone_temps'}B= $self->{'gone_temps'}{$name}
ABresult
0X0
100
111
3026 1 return " (it was a temporary table or view, which ended: $reason)";
3027 }
3028  
3029 0 ▶sub _drop_quietly {
Subroutine _drop_quietly: not called CC=4 SCAR=30.0
3030 0 my $self = shift;
3031 0 my ($name) = @_;
3032 0 ▶ my $entry = $self->{+TEMPS}->{$name} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $entry = $self->{"temps"}{$name} or return 0 0 0
3033 0 local $@;
3034 0 ▶ eval { $self->_do($_) for @{$entry->{drop}}; 1 } or warn "Dropping the temporary $entry->{kind} '$name' failed: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->_do($_) foreach (@{$$entry{"drop"};}); 1 } } or warn qq[Dropping the temporary $entry->{"kind"} '${name}' failed: $@] 0 0 0
3035 }
3036  
3037 471 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=13.9
3038 471 my $self = shift;
3039 471 ▶ return if !$self->{+PID} || $self->{+PID} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"pid"} or $self->{"pid"} == $$ 465 6 471
Condition100%3/3
not $self->{"pid"} or $self->{"pid"} == $$
l!l&&r!l&&!r
554106
MC/DC100%2/2
not $self->{"pid"} or $self->{"pid"} == $$
not $self->{"pid"} $self->{"pid"} == $$
Truth table100%3/3
not(A) or B
A= not $self->{"pid"}B= $self->{"pid"} == $$
ABresult
1X1
011
000
3040  
3041 # By now DBI has torn its handles down. Any still alive at exit were released before that.
3042 6 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 6 6
3043  
3044 6 $self->release_inherited;
3045 }
3046  
3047 # A child that exits with the parent's async query still pending would otherwise free the handle and the
3048 # statement in any order during global destruction. DBD::Pg 3.21.2, freeing the statement after its handle,
3049 # reads freed memory (https://github.com/bucardo/dbdpg/issues/218) and can wait on the query, taking the
3050 # parent's result off the shared socket.
3051 260 ▶END {
Subroutine END: called CC=2 SCAR=11.6
3052 0 ▶ local ($?, $@, $!);
Subroutine END: not called CC=2 SCAR=11.6
3053 0 $_->release_inherited for grep { $_ } values %PENDING;
3054 }
3055  
3056 260 1;
3057  
3058 __END__
« blib/lib/DBIx/QuickORM/Map.pm ↑ Summary blib/lib/DBIx/QuickORM/AggregateRow.pm »