blib/lib/DBIx/QuickORM/Connection.pm

filter: Statementstmt 89.7% 815 / 908 Branchbran 84.7% 351 / 414 Conditioncond 78.5% 297 / 378 MC/DCmcdc 62.7% 138 / 220 Subroutinesub 91.5% 87 / 95 Podpod 89.4% 17 / 19 totaltotal 83.8% 1705 / 2034 CC 706 SCAR 26.9
CC
706
Cov
86%
insert_many
38.8
insert_many
38.8
init
36.9
CRAP 14.7
« blib/lib/DBIx/QuickORM/Map.pm ↑ Summary blib/lib/DBIx/QuickORM/AggregateRow.pm »
1 package DBIx::QuickORM::Connection;
2 304 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 304 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 304 our $VERSION = '0.000032';
6  
7 304 ▶use Carp qw/croak confess/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 304 ▶use Scalar::Util qw/blessed refaddr weaken/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 304 ▶use List::Util qw/first/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 304 ▶use DBIx::QuickORM::Dialect();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 304 ▶use DBIx::QuickORM::Exception::DB();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 304 ▶use DBIx::QuickORM::LookupTable();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 304 ▶use DBIx::QuickORM::Map();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 304 ▶use DBIx::QuickORM::Txn();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 304 ▶use Object::HashBase qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
18 <dbh
19 <db_map
20 <time_zone
21 <datetime_parsers
22 <retain_cache
23 <enforce_canon
24 <debug
25 <isolation
26 <dialect
27 <namespace
28 <pid
29 +lookup
30 <txns
31 +txn_count
32 +busy
33 +statements
34 +find_keys
35 +defaults
36 +rescan
37 304 };
38  
39 # Scans by scan_cache_key, as maps that are only ever cloned (see "The scan cache").
40 304 my %SCAN_CACHE;
41  
42 # Connections with an async query pending, so a forked child can release them at exit (see END).
43 my %PENDING;
44  
45 =pod
46  
47 =encoding UTF-8
48  
49 =head1 NAME
50  
51 DBIx::QuickORM::Connection - One database handle and the state tied to it.
52  
53 =head1 DESCRIPTION
54  
55 A Connection holds one database handle and everything that must be reset when
56 that handle is replaced: its dialect, its namespace, the pid that opened it,
57 the open transactions (L<DBIx::QuickORM::Txn>), and the lookup table of canon
58 rows (L<DBIx::QuickORM::LookupTable>). The ORM replaces the whole Connection
59 at once, as it does in a forked child. The new one starts with no transaction
60 and an empty lookup table.
61  
62 It implements the ORM's CRUD operations on plain row data and knows nothing of
63 the ORM: it returns hashrefs, which L<DBIx::QuickORM> wraps. A row object
64 given is read through its C<row_data>. The rules shared by every CRUD
65 operation (row data, C<raw>, value markers, what comes back with and without
66 C<RETURNING>) are in L<DBIx::QuickORM/"CRUD operations">. The entries here add
67 what the Connection itself does.
68  
69 Construction prepares the handle:
70  
71 =over 4
72  
73 =item *
74  
75 C<RaiseError> must be on. C<PrintError> is turned off and
76 C<AutoInactiveDestroy> on.
77  
78 =item *
79  
80 C<AutoCommit> must be on, with no transaction open: the ORM manages
81 transactions.
82  
83 =item *
84  
85 Every database error on the handle is thrown as a
86 L<DBIx::QuickORM::Exception::DB>, classified by the dialect.
87  
88 =item *
89  
90 The dialect sets up the session.
91  
92 =item *
93  
94 The connection must have a current schema or database, or construction
95 croaks.
96  
97 =back
98  
99 Rows read go through the lookup table's C<ingest>. Rows written replace its
100 entry.
101  
102 The single-row CRUD operations build their SQL once per table and set of fields
103 and run it through C<prepare_cached>. SQL holding an C<sql()> or C<binary()>
104 marker, C<insert_many>, and queries built elsewhere are prepared each time.
105  
106 In a forked child, a Connection that is freed, or still held at exit, lets go
107 of its inherited handle (C<release_inherited>), so the parent's session
108 survives.
109  
110 =head2 The scan cache
111  
112 Scanning the database is the slowest part of building a Connection. The first
113 scan of a database in a process is kept, and later Connections built without a
114 C<db_map> start from a copy of it, so the database is scanned once per
115 process. The cache holds plain map data, never a handle, so a forked child
116 uses it too.
117  
118 It is keyed by which database the handle reaches and what the session sees
119 of it, as the dialect's C<scan_cache_key> says. By default that is the
120 driver, the DSN, the user name, and the namespace. PostgreSQL adds the
121 resolved host, port, database, and user, the server address, the current
122 user, the search path, and C<quote_all_identifiers>, and caches nothing for a
123 session that already has temporary tables. MySQL and MariaDB add the server, the resolved
124 account, the active roles, and on MySQL 8.0.30 and later whether the catalog
125 shows generated invisible primary keys. SQLite uses the
126 database file's path, and DuckDB its path and namespace. An in-memory SQLite
127 or DuckDB database is never cached.
128  
129 A table changed after the scan is not seen. Pass C<rescan> after changing
130 tables in a running process, or restart it.
131  
132 =head1 SYNOPSIS
133  
134 my $conn = $orm->connection; # the ORM's current Connection (a forked child gets a new one)
135  
136 my $dialect = $conn->dialect;
137 my $schema = $conn->namespace;
138 my $lookup = $conn->lookup;
139  
140 =head1 ATTRIBUTES
141  
142 =over 4
143  
144 =item $dbh = $conn->dbh
145  
146 The database handle. Required.
147  
148 =item $map = $conn->db_map
149  
150 The L<DBIx::QuickORM::Map>. When none is given, a copy of the cached scan of
151 the database is used, or the database is scanned (see L</"The scan cache">).
152 The ORM then adjusts it in place.
153  
154 =item rescan => $bool
155  
156 A construction argument, not kept: when true and no C<db_map> is given, the
157 database is scanned again and the cache refreshed.
158  
159 =item $tz = $conn->time_zone
160  
161 The session time zone, C<UTC> unless given.
162  
163 =item \@parsers = $conn->datetime_parsers
164  
165 The ORM's C<datetime_parsers>, for the DateTime type. Empty unless given.
166 Checked as the ORM's C<new> describes. C<set_datetime_parsers> changes it.
167  
168 =item $bool = $conn->retain_cache
169  
170 Passed to the lookup table as C<retain>. 0 unless given.
171  
172 =item $bool = $conn->enforce_canon
173  
174 The default C<enforce_canon> for C<update_row> and C<delete_row> outside a
175 transaction. 1 unless given. C<set_enforce_canon> changes it.
176  
177 =item $bool = $conn->debug
178  
179 Passed to the lookup table: whether it records which call made a hash stop
180 being canon. 0 unless given.
181  
182 =item $level = $conn->isolation
183  
184 The isolation level a root transaction opens at when C<txn> names none, in
185 lower case: a level C<txn> takes, or C<'server'>. Undef unless given: then
186 C<'read committed'> where the dialect C<supports_isolation>, otherwise
187 C<'server'>. An unknown level croaks.
188  
189 =item $dialect = $conn->dialect
190  
191 The L<DBIx::QuickORM::Dialect> object for the handle, holding the server
192 version.
193  
194 =item $ns = $conn->namespace
195  
196 The current schema or database, from the dialect.
197  
198 =item $pid = $conn->pid
199  
200 The process that opened the connection.
201  
202 =item \@txns = $conn->txns
203  
204 The open transactions, outermost first, as L<DBIx::QuickORM::Txn> objects
205 (held weakly). Empty outside a transaction.
206  
207 =back
208  
209 =cut
210  
211 409 ▶sub init {
Subroutine init: called CC=13 SCAR=36.1
Pod undocumented
212 0 ▶ my $self = shift;
Subroutine init: not called CC=13 SCAR=36.1
Pod undocumented
213  
214 0 my $dbh = $self->{+DBH};
215 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 407 409
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
20407
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
216 0 ▶ croak "The database handle must have RaiseError on" unless $dbh->{RaiseError};
Branch: 2 branches
BranchTrueFalseTotal
unless $dbh->{"RaiseError"} 16 391 407
unless $dbh->{"RaiseError"} 0 0 0
217 croak "The database handle must have AutoCommit on and no transaction open; the ORM manages transactions"
218 0 ▶ unless $dbh->{AutoCommit};
Branch: 2 branches
BranchTrueFalseTotal
unless $dbh->{"AutoCommit"} 20 371 391
unless $dbh->{"AutoCommit"} 0 0 0
219  
220 0 ▶ $self->{+TIME_ZONE} //= 'UTC';
Condition50%2/4
$self->{"time_zone"} //= "UTC"
l!l
37334
$self->{"time_zone"} //= "UTC"
l!l
00
MC/DC100%1/1
$self->{"time_zone"} //= "UTC"
$self->{"time_zone"}
MC/DC0%0/1
$self->{"time_zone"} //= "UTC"
$self->{"time_zone"}
Truth table100%2/2
A
A= $self->{"time_zone"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"time_zone"}
Aresult
11
00
221 0 ▶ $self->{+DATETIME_PARSERS} = exists($self->{+DATETIME_PARSERS}) ? $self->_check_datetime_parsers($self->{+DATETIME_PARSERS}) : [];
Branch: 2 branches
BranchTrueFalseTotal
exists $self->{'datetime_parsers'} ? : 13 358 371
exists $self->{'datetime_parsers'} ? : 0 0 0
222 0 ▶ $self->{+RETAIN_CACHE} //= 0;
Condition50%2/4
$self->{"retain_cache"} //= 0
l!l
13353
$self->{"retain_cache"} //= 0
l!l
00
MC/DC100%1/1
$self->{"retain_cache"} //= 0
$self->{"retain_cache"}
MC/DC0%0/1
$self->{"retain_cache"} //= 0
$self->{"retain_cache"}
Truth table100%2/2
A
A= $self->{"retain_cache"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"retain_cache"}
Aresult
11
00
223 0 ▶ $self->{+DEBUG} //= 0;
Condition50%2/4
$self->{"debug"} //= 0
l!l
35016
$self->{"debug"} //= 0
l!l
00
MC/DC100%1/1
$self->{"debug"} //= 0
$self->{"debug"}
MC/DC0%0/1
$self->{"debug"} //= 0
$self->{"debug"}
Truth table100%2/2
A
A= $self->{"debug"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"debug"}
Aresult
11
00
224 0 ▶ $self->{+ENFORCE_CANON} //= 1;
Condition50%2/4
$self->{"enforce_canon"} //= 1
l!l
6360
$self->{"enforce_canon"} //= 1
l!l
00
MC/DC100%1/1
$self->{"enforce_canon"} //= 1
$self->{"enforce_canon"}
MC/DC0%0/1
$self->{"enforce_canon"} //= 1
$self->{"enforce_canon"}
Truth table100%2/2
A
A= $self->{"enforce_canon"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"enforce_canon"}
Aresult
11
00
225 0 ▶ $self->{+ISOLATION} = $self->_isolation($self->{+ISOLATION}) if defined $self->{+ISOLATION};
Branch: 2 branches
BranchTrueFalseTotal
if defined $self->{"isolation"} 4 362 366
if defined $self->{"isolation"} 0 0 0
226  
227 0 $dbh->{PrintError} = 0;
228 0 $dbh->{AutoInactiveDestroy} = 1;
229  
230 0 my $dialect = $self->{+DIALECT} = DBIx::QuickORM::Dialect->for_dbh($dbh);
231 0 $dbh->{HandleError} = $self->_error_handler($dialect, $self->{+TXNS} = []);
232 0 $dialect->init_session($dbh, $self->{+TIME_ZONE});
233  
234 0 my $ns = $self->{+NAMESPACE} = $dialect->namespace($dbh);
235 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 363 364
unless defined $ns 0 0 0
236  
237 0 my $rescan = delete $self->{+RESCAN};
238 0 ▶ $self->{+DB_MAP} //= $self->_scanned_map($dialect, $dbh, $ns, $rescan);
Condition33%2/6
$self->{"db_map"} //= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
l!l&&r!l&&!r
303330
$self->{"db_map"} //= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"db_map"} //= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
$self->{"db_map"} $self->_scanned_map($dialect, $dbh, $ns, $rescan)
MC/DC0%0/2
$self->{"db_map"} //= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
$self->{"db_map"} $self->_scanned_map($dialect, $dbh, $ns, $rescan)
Truth table66%2/3
A //= B
A= $self->{"db_map"}B= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
ABresult
1X1
011
000
Truth table0%0/3
A //= B
A= $self->{"db_map"}B= $self->_scanned_map($dialect, $dbh, $ns, $rescan)
ABresult
1X1
011
000
239 0 $self->{+PID} = $$;
240 }
241  
242 =head1 PUBLIC METHODS
243  
244 =over 4
245  
246 =item $conn->set_enforce_canon($bool)
247  
248 Changes C<enforce_canon>. Each C<update_row> and C<delete_row> reads it when
249 it runs.
250  
251 =item $conn->set_datetime_parsers(\@parsers)
252  
253 Replaces C<datetime_parsers> with a copy of C<@parsers>, checked as the ORM's
254 C<new> checks them: it loads each class, and croaks on a bad parser.
255  
256 Values read after the call use the new parsers. A DateTime field read before
257 the call keeps the parsers it was read with, even while still unparsed.
258  
259 =back
260  
261 =cut
262  
263 2 ▶sub set_enforce_canon { $_[0]->{+ENFORCE_CANON} = $_[1] }
Subroutine set_enforce_canon: called CC=1 SCAR=0.0
Pod documented
264  
265 6 ▶sub set_datetime_parsers {
Subroutine set_datetime_parsers: called CC=1 SCAR=0.0
Pod documented
266 6 my $self = shift;
267 6 my ($parsers) = @_;
268 6 $self->{+DATETIME_PARSERS} = $self->_check_datetime_parsers($parsers);
269 }
270  
271 =over 4
272  
273 =item $lookup = $conn->lookup
274  
275 The Connection's L<DBIx::QuickORM::LookupTable>, built on first use.
276  
277 =back
278  
279 =cut
280  
281 1598 ▶sub lookup {
Subroutine lookup: called CC=2 SCAR=7.1
Pod documented
282 1598 my $self = shift;
283 1598 ▶ return $self->{+LOOKUP} //= DBIx::QuickORM::LookupTable->new(db_map => $self->{+DB_MAP}, connection => $self, retain => $self->{+RETAIN_CACHE}, debug => $self->{+DEBUG});
Condition66%2/3
$self->{"lookup"} //= "DBIx::QuickORM::LookupTable"->new("db_map", $self->{"db_map"}, "connection", $self, "retain", $self->{"retain_cache"}, "debug", $self->{"debug"})
l!l&&r!l&&!r
14851130
MC/DC0%0/2
$self->{"lookup"} //= "DBIx::QuickORM::LookupTable"->new("db_map", $self->{"db_map"}, "connection", $self, "retain", $self->{"retain_cache"}, "debug", $self->{"debug"})
$self->{"lookup"} "DBIx::QuickORM::LookupTable"->new("db_map", $self->{"db_map"}, "connection", $self, "retain", $self->{"retain_cache"}, "debug", $self->{"debug"})
Truth table66%2/3
A //= B
A= $self->{"lookup"}B= "DBIx::QuickORM::LookupTable"->new("db_map", $self->{"db_map"}, "connection", $self, "retain", $self->{"retain_cache"}, "debug", $self->{"debug"})
ABresult
1X1
011
000
284 }
285  
286 =over 4
287  
288 =item $bool = $conn->is_canon($table, $row_or_data)
289  
290 True when the row data (or a row object's C<row_data>) is the lookup table's
291 entry for its primary key. Croaks when the primary key cannot be determined.
292  
293 =back
294  
295 =cut
296  
297 151 ▶sub is_canon {
Subroutine is_canon: called CC=1 SCAR=0.0
Pod documented
298 151 my $self = shift;
299 151 my ($table, $data) = @_;
300 151 return $self->lookup->is_canon($table, $self->_row_data($data));
301 }
302  
303 =over 4
304  
305 =item $status = $conn->canon_status($table, $row_or_data)
306  
307 The lookup table's C<canon_status> for the row data (or a row object's
308 C<row_data>): undef while canonical, otherwise why not.
309  
310 =back
311  
312 =cut
313  
314 25 ▶sub canon_status {
Subroutine canon_status: called CC=1 SCAR=0.0
Pod documented
315 25 my $self = shift;
316 25 my ($table, $data) = @_;
317 25 return $self->lookup->canon_status($table, $self->_row_data($data));
318 }
319  
320 =over 4
321  
322 =item $data = $conn->insert($table, \%fields, raw => $bool, as_given => $bool, void => $bool)
323  
324 Inserts one row and returns its new row data, now the lookup table's entry.
325 Where the primary key comes from, C<as_given>, and the croaks, are as
326 L<DBIx::QuickORM/"CRUD operations"> describes for C<insert>.
327  
328 Primary key fields left out may get generated values first (see
329 C<_generate_keys>). C<as_given> includes them.
330  
331 A table without a primary key returns the C<RETURNING> row without storing it
332 in the lookup table.
333  
334 With C<as_given>, C<RETURNING> names only the primary key fields, and the
335 result is never stored.
336  
337 C<< void => 1 >> is what the ORM passes in void context: the row is inserted
338 without C<RETURNING>, nothing is stored or returned, and none of the primary
339 key croaks apply.
340  
341 =back
342  
343 =cut
344  
345 304 my %INSERT_ARGS = map { $_ => 1 } qw/raw void as_given/;
346  
347 317 ▶sub insert {
Subroutine insert: called CC=30 SCAR=34.2
Pod documented
348 317 my $self = shift;
349 317 my ($table, $fields, %params) = @_;
350  
351 317 $self->_check_params(insert => \%INSERT_ARGS, \%params);
352 316 my $t = $self->_table($table);
353 315 my $values = $self->_row_data($fields);
354 315 ▶ confess "insert() into '$table' needs at least one field" unless %$values;
Branch: 1 branch
BranchTrueFalseTotal
unless %$values 2 313 315
355 313 my $generated = $self->_generate_keys($t, $values);
356 313 $values = {%{$self->deflate($table, $values, raw => $params{raw})}, %{$self->deflate($table, $generated)}};
357 309 my @names = sort keys %$values;
358  
359 309 my $void = $params{void};
360 309 my $as_given = $params{as_given};
361 309 my $dialect = $self->{+DIALECT};
362 309 ▶ my $pk = $t->{pk} && @{$t->{pk}} ? $t->{pk} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$t->{'pk'} && @{$t->{'pk'};} ? : 305 4 309
Condition66%2/3
$t->{"pk"} and @{$t->{"pk"};}
!ll&&!rl&&r
40305
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
363 309 ▶ my $returning = !$void && ($pk || !$as_given) && $dialect->supports_returning_insert;
Condition100%9/9
!$void && ($pk || !$as_given) && $dialect->supports_returning_insert
!ll&&!rl&&r
1481160
not $void and $pk || !$as_given
!ll&&!rl&&r
1471161
$pk or not $as_given
l!l&&r!l&&!r
16011
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
364 309 ▶ 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
440265
!defined($values->{$_}) || $self->_is_sql($values->{$_})
l!l&&r!l&&!r
391279
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
365 309 ▶ unless ($void || $returning) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($void or $returning) 2 307 309
Condition100%3/3
$void or $returning
l!l&&r!l&&!r
1471602
MC/DC100%2/2
$void or $returning
$void $returning
Truth table100%3/3
A or B
A= $voidB= $returning
ABresult
1X1
011
000
366 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
367 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
368 }
369  
370 309 my ($places, $binds, $marked) = $self->_value_sql($values, @names);
371 309 ▶ my $shape = $marked ? undef : join("\0" => 'insert', $table, ($returning ? ($as_given ? 'pk' : 'all') : ''), @names);
Branch: 3 branches
BranchTrueFalseTotal
$marked ? : 7 302 309
$returning ? : 158 144 302
$as_given ? : 6 152 158
372 my $sql = $self->_statement(
373 $shape,
374 163 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
375 163 my $sql = 'INSERT INTO ' . $dialect->quote_identifier($table) . ' (' . join(', ' => map { $dialect->quote_identifier($_) } @names) . ') VALUES (' . join(', ' => @$places) . ')';
376 163 ▶ $returning ? $sql . $self->_returning_sql($as_given ? $pk : $self->_read_back_fields($table, @names)) : $sql;
Branch: 2 branches
BranchTrueFalseTotal
$returning ? : 91 72 163
$as_given ? : 6 85 91
377 }
378 309 );
379 309 my $sth = $self->_run($t->{fields}, $sql, $binds, undef, defined $shape);
380 294 ▶ return if $void;
Branch: 1 branch
BranchTrueFalseTotal
if $void 136 158 294
381  
382 158 ▶ my $data = $returning ? $self->_fetch($t->{fields}, $sth)->[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
$returning ? : 156 2 158
383 158 ▶ if ($pk && !$data && $given_pk) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pk and not $data and $given_pk) { } 0 158 158
elsif ($pk and not $data) { } 1 159 160
Condition83%5/6
$pk and not $data and $given_pk
!ll&&!rl&&r
15710
$pk and not $data
!ll&&!rl&&r
21551
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
384 0 $data = $self->_plain({map { $_ => $values->{$_} } @$pk});
385 }
386 ▶ elsif ($pk && !$data) {
Condition100%3/3
$pk and not $data
!ll&&!rl&&r
21551
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
387 # Only MySQL gets here (no RETURNING). DBD::MariaDB gives 0 when the insert
388 # generated no key, and AUTO_INCREMENT never generates 0, so 0 is "none".
389 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
390 1 $data = {$pk->[0] => $id};
391 }
392  
393 158 my $lookup = $self->lookup;
394 158 my $out;
395 158 ▶ if ($as_given) {
Branch: 1 branch
BranchTrueFalseTotal
if ($as_given) { } 8 150 158
396 8 my %copy = map { $_ => $values->{$_} } grep { !$self->_is_sql($values->{$_}) } @names;
397 8 ▶ $out = {%{$self->_plain(\%copy)}, %{$data // {}}};
Condition100%2/2
$data // {}
l!l
71
MC/DC100%1/1
$data // {}
$data
Truth table100%2/2
A
A= $data
Aresult
11
00
398 }
399 else {
400 150 ▶ $out = $pk ? $lookup->store($table, $data) : $data;
Branch: 1 branch
BranchTrueFalseTotal
$pk ? : 149 1 150
401 }
402  
403 158 $lookup->mark_inserted($out);
404 158 return $out;
405 }
406  
407 =over 4
408  
409 =item \@data = $conn->insert_many($table, \@rows, raw => $bool)
410  
411 =item $count = $conn->insert_many($table, \@rows, count => 1, raw => $bool)
412  
413 =item $conn->insert_many($table, \@rows, void => 1, raw => $bool)
414  
415 Generates missing primary key values for each row as C<insert> does, then
416 inserts the rows in multi-row C<INSERT> statements, each holding as many rows
417 as the dialect's C<bind_limit> allows. The batching, the transaction around
418 it, and the croaks are as L<DBIx::QuickORM/"CRUD operations"> describes for
419 C<insert_many>.
420  
421 It returns an arrayref of the new rows' row data, now the lookup table's
422 entries (a table without a primary key bypasses it). Without C<RETURNING> each
423 holds the primary key taken from the given values.
424  
425 C<< count => 1 >> returns how many rows the database reports inserted
426 instead, and C<< void => 1 >> (what the ORM passes in void context) returns
427 nothing useful. Neither sends C<RETURNING> or stores anything.
428  
429 An empty C<\@rows> sends nothing and returns an empty arrayref, or 0 with
430 C<count>.
431  
432 The field list and the keys to generate are decided once per call. Each
433 value is deflated as C<deflate> would (C<_insert_many_chunks>, or
434 C<_insert_many_hashes> for a column with a format hint). Plain rows go out in
435 statements of as many rows as the bind limit allows, through C<_run_plain>.
436 When a value is a marker or a column has bind attributes (a binary field),
437 every row is batched by its actual binds through C<_batches>, and each
438 statement goes through C<_run_plain> when it holds neither a C<sql()> marker
439 nor a value needing bind attributes, else through C<_run>.
440  
441 =back
442  
443 =cut
444  
445 304 my %INSERT_MANY_ARGS = map { $_ => 1 } qw/raw count void/;
446  
447 71 ▶sub insert_many {
Subroutine insert_many: called CC=32 SCAR=36.6
Pod documented
448 71 my $self = shift;
449 71 my ($table, $rows, %params) = @_;
450  
451 71 $self->_check_params(insert_many => \%INSERT_MANY_ARGS, \%params);
452 67 my $t = $self->_table($table);
453 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
454 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
455 66 ▶ return $returning ? [] : 0 unless @$rows;
Branch: 2 branches
BranchTrueFalseTotal
unless @$rows 6 60 66
$returning ? : 3 3 6
456 60 my @values = map { $self->_row_data($_) } @$rows;
457 60 my @names = sort keys %{$values[0]};
458 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
459  
460 59 for my $i (1 .. $#values) {
461 2769 my $v = $values[$i];
462 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
463 }
464  
465 57 $self->_check_fields($table, @names);
466 56 my $fields = $t->{fields};
467 56 my $dialect = $self->{+DIALECT};
468  
469 # The keys to generate and the column list are decided once, since every row has the first row's fields. A
470 # format hint's result is used as it comes, so formatted columns keep the per-row deflate exactly as it was.
471 56 my @gen = $self->_key_generators($t, $values[0]);
472 56 my @cols = sort(@names, @gen);
473 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
474 56 my ($chunks, $hashes, $marked);
475 56 ▶ if (grep { $fields->{$_}->{format} } @cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$fields->{$_}{'format'};} @cols) { } 2 54 56
476 2 $hashes = $self->_insert_many_hashes($table, $t, \@values, \@names, \@gen, $params{raw});
477 2 @cols = sort keys %{$hashes->[0]};
478 }
479 54 else { ($chunks, $marked) = $self->_insert_many_chunks($table, $t, \@values, \@names, \@gen, \@cols, $per, $params{raw}) }
480  
481 # A marker or a column with bind attributes (a binary field) batches every row by its actual binds, through
482 # _batches as before. Each statement then goes through _run_plain when it holds only plain values.
483 55 my $binary = grep { defined $dialect->bind_attrs($fields->{$_}) } @cols;
484 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
485  
486 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
487 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
488 55 my @keys;
489 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
490 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
491 @keys = map {
492 0 my $row = $_;
493 0 +{map { ($_ => $row->{$_}) } @$pk}
494 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
495 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"
496 if grep {
497 0 ▶ my $key = $_;
Branch: 1 branch
BranchTrueFalseTotal
if grep {my $key = $_; grep {not defined $_ or $self->_is_sql($_);} values %$key;} @keys 0 0 0
498 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
499 } @keys;
500 }
501  
502 55 my $into = 'INSERT INTO ' . $dialect->quote_identifier($table) . ' (' . join(', ' => map { $dialect->quote_identifier($_) } @cols) . ') VALUES ';
503 55 ▶ my $ret = $sql_ret ? $self->_returning_sql($self->_read_back_fields($table, @cols)) : '';
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 34 55
504 55 my $place = '(' . join(', ' => ('?') x @cols) . ')';
505 my @batches = $hashes
506 ? map {
507 12 my ($places, $binds, $marked) = @$_;
508 # A marker may leave a placeholder for _run's binding to treat as NULL, or need a bind attribute, so only
509 # statements without one go through _run_plain.
510 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
511 12 ▶ [$plain, $into . join(', ' => @$places) . $ret, $plain ? [map { $_->[1] } @$binds] : $binds]
Branch: 1 branch
BranchTrueFalseTotal
$plain ? : 3 9 12
512 } $self->_batches($hashes, \@cols)
513 55 ▶ : map { [1, $into . join(', ' => ($place) x (@$_ / @cols)) . $ret, $_] } @$chunks;
Branch: 1 branch
BranchTrueFalseTotal
$hashes ? : 11 44 55
514  
515 55 ▶ my $send = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
516 55 my ($count, @got) = (0);
517 55 for my $batch (@batches) {
518 67 my ($plain, $sql, $binds) = @$batch;
519 67 ▶ my $sth = $plain ? $self->_run_plain($sql, $binds) : $self->_run($fields, $sql, $binds);
Branch: 1 branch
BranchTrueFalseTotal
$plain ? : 58 9 67
520 64 ▶ if ($sql_ret) { push @got => @{$self->_fetch($fields, $sth)} }
Branch: 1 branch
BranchTrueFalseTotal
if ($sql_ret) { } 24 40 64
521 40 else { $count += $sth->rows }
522 }
523 52 ▶ return $sql_ret ? \@got : $count;
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 31 52
524 55 };
525  
526 55 ▶ my $own_txn = @{$self->{+TXNS}} ? $dialect->supports_savepoints : @batches > 1;
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'txns'};} ? : 3 52 55
527 55 ▶ my $out = $own_txn ? $self->txn($send) : $send->();
Branch: 1 branch
BranchTrueFalseTotal
$own_txn ? : 9 46 55
528 52 ▶ return $out unless $returning;
Branch: 1 branch
BranchTrueFalseTotal
unless $returning 31 21 52
529  
530 # Without RETURNING each row is its primary key, taken from the given values.
531 0 ▶ my @got = $sql_ret ? @$out : map { $self->_plain($_) } @keys;
Branch: 1 branch
BranchTrueFalseTotal
$sql_ret ? : 21 0 21
532  
533 21 my $lookup = $self->lookup;
534 21 ▶ @got = map { $lookup->store($table, $_) } @got if $pk;
Branch: 1 branch
BranchTrueFalseTotal
if $pk 20 1 21
535 21 $lookup->mark_inserted(@got);
536 21 return \@got;
537 }
538  
539 =pod
540  
541 =over 4
542  
543 =item (\@chunks, $marked) = $conn->_insert_many_chunks($table, \%table, \@values, \@names, \@generate, \@columns, $per, $raw)
544  
545 The rows' deflated values, packed in column order into flat arrays of up to
546 C<$per> rows each, one per statement. Each row's keys in C<@generate> are made
547 first, in primary key order. Then its given fields deflate in name order, then
548 its generated keys (without C<raw>). A plain value of an untyped column (with
549 C<$raw>, any plain value, and undef always) is used as is, and every other
550 value goes through C<_deflate_value>. C<$marked> is true when a deflated value
551 is a marker.
552  
553 =item \@rows = $conn->_insert_many_hashes($table, \%table, \@values, \@names, \@generate, $raw)
554  
555 The rows deflated one hash at a time, each value through C<_deflate_value> in
556 list context, for calls with a column that has a format hint, whose result is
557 used as it comes. Each row's keys in C<@generate> are made first and deflated
558 after its given fields.
559  
560 =item \@rows = $conn->_insert_many_rows(\@chunks, \@columns)
561  
562 The chunks' rows as hashes, for C<_batches> and for keys read back without
563 C<RETURNING>.
564  
565 =back
566  
567 =cut
568  
569 54 ▶sub _insert_many_chunks {
Subroutine _insert_many_chunks: called CC=18 SCAR=29.0
570 54 my $self = shift;
571 54 my ($table, $t, $values, $names, $gen, $cols, $per, $raw) = @_;
572  
573 54 my $fields = $t->{fields};
574 54 my $width = @$cols;
575 54 my %slot = map { ($cols->[$_] => $_) } 0 .. $#$cols;
576 54 ▶ my @given = map { [$_, $fields->{$_}, $fields->{$_}->{orm_type} ? 1 : 0, $slot{$_}] } @$names;
Branch: 1 branch
BranchTrueFalseTotal
$fields->{$_}{'orm_type'} ? : 8 171 179
577 54 my @generated = map { [$_, $fields->{$_}, $slot{$_}] } @$gen;
578  
579 54 my ($marked, $in, @chunks) = (0, $per);
580 54 for (@$values) { # $_ is this call's copy of the row while user code runs, as it was under the old map
581 2820 my $v = $_;
582 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
583 2820 my $buf = $chunks[-1];
584 2820 my $at = @$buf;
585 2820 my @made;
586 2820 for my $name (@$gen) { push @made => scalar $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
587 2820 $#$buf = $at + $width - 1;
588  
589 # While a type deflates, $_ is the field's name, as it was under the old map over the names.
590 2820 for my $p (@given) {
591 13106 my ($name, $field, $typed, $slot) = @$p;
592 13106 my $value = $v->{$name};
593 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
594 30 local $_ = $name;
595 30 $value = $self->_deflate_value($table, $name, $field, $value, $raw);
596 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
597 }
598 13105 $buf->[$at + $slot] = $value;
599 }
600  
601 # Generated keys deflate in the order of a hash built as _generate_keys builds one, as they always did.
602 2819 my @order = 0 .. $#generated;
603 2819 ▶ if (@order > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@order > 1) 2 2817 2819
604 2 my %made;
605 2 $made{$gen->[$_]} = $_ for @order;
606 2 @order = map { $made{$_} } keys %made;
607 }
608 2819 for my $i (@order) {
609 14 my ($name, $field, $slot) = @{$generated[$i]};
610 14 local $_ = $name;
611 14 my $value = $self->_deflate_value($table, $name, $field, $made[$i]);
612 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
613 14 $buf->[$at + $slot] = $value;
614 }
615 2819 $in++;
616 }
617  
618 53 return (\@chunks, $marked);
619 }
620  
621 2 ▶sub _insert_many_hashes {
Subroutine _insert_many_hashes: called CC=3 SCAR=11.0
622 2 my $self = shift;
623 2 my ($table, $t, $values, $names, $gen, $raw) = @_;
624  
625 2 my $fields = $t->{fields};
626 return [
627 map {
628 2 my $v = $_;
629 3 my %generated;
630 0 for my $name (@$gen) { $generated{$name} = $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
631 3 my %out = map { ($_ => $self->_deflate_value($table, $_, $fields->{$_}, $v->{$_}, $raw)) } @$names;
632 3 $out{$_} = $self->_deflate_value($table, $_, $fields->{$_}, $generated{$_}) for keys %generated;
633 3 \%out;
634 } @$values
635 ];
636 }
637  
638 9 ▶sub _insert_many_rows {
Subroutine _insert_many_rows: called CC=3 SCAR=11.0
639 9 my $self = shift;
640 9 my ($chunks, $cols) = @_;
641  
642 9 my @rows;
643 9 for my $chunk (@$chunks) {
644 11 ▶ for (my $at = 0; $at < @$chunk; $at += @$cols) {
Branch: 1 branch
BranchTrueFalseTotal
if ($at < @$chunk) 1347 11 1358
645 1347 push @rows => {map { ($cols->[$_] => $chunk->[$at + $_]) } 0 .. $#$cols};
646 }
647 }
648  
649 9 return \@rows;
650 }
651  
652 =over 4
653  
654 =item $data = $conn->update_row($table, \%data, \%changes, %opts)
655  
656 Updates one row, found by the primary key in the row data, and returns its new
657 row data, or undef when no row matched.
658  
659 The new row data replaces the old in the lookup table, re-keyed when the
660 primary key changed. Undef leaves the lookup table alone. At least one change
661 is required. Setting a primary key field with C<sql()> croaks on a database
662 without C<RETURNING> for C<UPDATE>, since the new key could not be known.
663  
664 With C<RETURNING>, the new row data holds the default fields, the fields
665 changed, and the fields the old row data held, as the database returns them.
666  
667 The options C<enforce_canon>, C<cas>, and C<auto_cas> are as
668 L<DBIx::QuickORM/"CRUD operations"> describes for C<update_row>. Each C<cas>
669 field must be in the row data.
670  
671 =back
672  
673 =cut
674  
675 304 my %UPDATE_ARGS = map { $_ => 1 } qw/enforce_canon cas auto_cas raw/;
676  
677 145 ▶sub update_row {
Subroutine update_row: called CC=13 SCAR=25.7
Pod documented
678 145 my $self = shift;
679 145 my ($table, $data, $changes, %params) = @_;
680  
681 145 $self->_check_params(update_row => \%UPDATE_ARGS, \%params);
682 144 my $t = $self->_table($table);
683 143 $data = $self->_row_data($data);
684 142 ▶ 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 140 142
Condition66%2/3
ref $changes eq "HASH" and %$changes
!ll&&!rl&&r
02140
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
685 140 my @set = sort keys %$changes;
686  
687 140 my $pk = $self->_pk_values($table, $data, $params{raw});
688 137 $self->_enforce_canon($table, $data, $params{enforce_canon});
689 116 my $where = {%{$self->deflate($table, {$self->_cas_values($table, $data, $changes, \%params)}, raw => $params{raw})}, %$pk};
690 111 $changes = $self->deflate($table, $changes, raw => $params{raw});
691  
692 110 my $dialect = $self->{+DIALECT};
693 110 my $returning = $dialect->supports_returning_update;
694 110 my @sql_pk = grep { $self->_is_sql($changes->{$_}) } keys %$pk;
695 110 ▶ 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 109 110
Condition66%2/3
@sql_pk and not $returning
!ll&&!rl&&r
10901
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
696  
697 # Fields the row already holds come back too, so an update keeps what the row read (its JSON, say). When the
698 # row holds and writes only default fields, that is the default list itself.
699 109 my $back = [];
700 109 ▶ if ($returning) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returning) 108 1 109
701 108 my $default = $self->_default_field_set($table);
702 108 ▶ $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 101 108
703 }
704  
705 109 my ($where_sql, $where_binds, $where_marked) = $self->_where_sql($where);
706 107 my ($places, $set_binds, $marked) = $self->_value_sql($changes, @set);
707 107 ▶ my $shape = $marked || $where_marked ? undef : join("\0" => 'update', $table, @set, $where_sql, 'returning', @$back);
Branch: 1 branch
BranchTrueFalseTotal
$marked || $where_marked ? : 5 102 107
Condition66%2/3
$marked or $where_marked
l!l&&r!l&&!r
50102
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
708 my $sql = $self->_statement(
709 $shape,
710 62 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
711 62 my $sql = 'UPDATE ' . $dialect->quote_identifier($table) . ' SET ' . join(', ' => map { $dialect->quote_identifier($set[$_]) . " = $places->[$_]" } 0 .. $#set) . " WHERE $where_sql";
712 62 ▶ $returning ? $sql . $self->_returning_sql($back) : $sql;
Branch: 1 branch
BranchTrueFalseTotal
$returning ? : 61 1 62
713 }
714 107 );
715 107 my $sth = $self->_run($t->{fields}, $sql, [@$set_binds, @$where_binds], undef, defined $shape);
716  
717 105 my $new;
718 105 ▶ if ($returning) {
Branch: 1 branch
BranchTrueFalseTotal
if ($returning) { } 104 1 105
719 104 ▶ $new = $self->_fetch($t->{fields}, $sth)->[0] or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$new = $self->_fetch($t->{"fields"}, $sth)->[0] or return undef 91 13 104
720 }
721 else {
722 1 ▶ return undef unless $sth->rows > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth->rows > 0 0 1 1
723 1 ▶ $new = $self->_plain({map { $_ => exists($changes->{$_}) ? $changes->{$_} : $pk->{$_} } keys %$pk});
Branch: 1 branch
BranchTrueFalseTotal
exists $changes->{$_} ? : 1 0 1
724 }
725  
726 92 return $self->lookup->_update_entry($table, $self->_plain($pk), $data, $new);
727 }
728  
729 =over 4
730  
731 =item $count = $conn->delete_row($table, \%data, enforce_canon => $bool, raw => $bool)
732  
733 Deletes one row, found by the primary key in the row data, and returns how
734 many rows were deleted (0 or 1). Its lookup table entry is removed, and the
735 row data and that entry are marked deleted (see L<DBIx::QuickORM::LookupTable/Row state>).
736 C<enforce_canon> is as for C<update_row>.
737  
738 =back
739  
740 =cut
741  
742 304 my %DELETE_ARGS = map { $_ => 1 } qw/enforce_canon raw/;
743  
744 42 ▶sub delete_row {
Subroutine delete_row: called CC=2 SCAR=6.9
Pod documented
745 42 my $self = shift;
746 42 my ($table, $data, %params) = @_;
747  
748 42 $self->_check_params(delete_row => \%DELETE_ARGS, \%params);
749 41 my $t = $self->_table($table);
750 41 $data = $self->_row_data($data);
751 41 my $pk = $self->_pk_values($table, $data, $params{raw});
752 41 $self->_enforce_canon($table, $data, $params{enforce_canon});
753  
754 37 my ($where_sql, $where_binds, $marked) = $self->_where_sql($pk);
755 37 ▶ 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 36 37
756 37 my $sth = $self->_run($t->{fields}, $sql, $where_binds, undef, !$marked);
757  
758 36 $self->lookup->gone($table, $self->_plain($pk), $data);
759 36 return $sth->rows;
760 }
761  
762 =over 4
763  
764 =item $data = $conn->refresh_row($table, $pk, cache => $bool, db => $bool, fields => \@fields, raw => $bool)
765  
766 The canon row data for the primary key, or undef when there is no such row.
767 C<$pk> is the key in any form C<_pk_values> takes, so row data works and its
768 other fields are ignored. This is also C<find>.
769  
770 Without C<fields> it reads the default fields and the fields the given row
771 data holds, so a refreshed row keeps what it read.
772  
773 C<fields> must be fields of the table. C<cache>, C<db>, and C<fields> are as
774 L<DBIx::QuickORM/"CRUD operations"> describes for C<refresh_row>: the lookup
775 table's entry when it holds every field asked for, otherwise those fields read
776 from the database and ingested.
777  
778 A row the database no longer has is removed from the lookup table, and the
779 row data given and that entry are marked deleted.
780  
781 =back
782  
783 =cut
784  
785 304 my %REFRESH_ARGS = map { $_ => 1 } qw/cache db fields raw/;
786  
787 313 ▶sub refresh_row {
Subroutine refresh_row: called CC=26 SCAR=32.6
Pod documented
788 313 my $self = shift;
789 313 my ($table, $data, %params) = @_;
790  
791 313 my ($t, $pk, $given, @select);
792 313 my ($cache, $db) = (1, 1);
793 313 my $lookup = $self->lookup;
794  
795 # A plain value for a single untyped primary key, with no options: the lookup key is the value as given, so
796 # deflating the key, building the lookup key and building the SQL are skipped.
797 313 ▶ my $fast = !%params && defined($data) && !ref($data) ? $self->_find_key($table) : undef;
Branch: 1 branch
BranchTrueFalseTotal
!%params && defined $data && !ref($data) ? : 129 184 313
Condition100%6/6
not %params and defined $data and not ref $data
!ll&&!rl&&r
11866129
not %params and defined $data
!ll&&!rl&&r
1162195
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
798 313 ▶ if ($fast) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fast) { } 112 201 313
799 112 $t = $fast->{table};
800 112 $pk = {$fast->{field} => $data};
801 112 @select = @{$fast->{select}};
802 }
803 else {
804 201 $self->_check_params(refresh_row => \%REFRESH_ARGS, \%params);
805 201 $t = $self->_table($table);
806 201 $pk = $self->_pk_values($table, $data, $params{raw});
807 188 ▶ $cache = $params{cache} // 1;
Condition100%2/2
$params{"cache"} // 1
l!l
61127
MC/DC100%1/1
$params{"cache"} // 1
$params{"cache"}
Truth table100%2/2
A
A= $params{"cache"}
Aresult
11
00
808 188 ▶ $db = $params{db} // 1;
Condition100%2/2
$params{"db"} // 1
l!l
36152
MC/DC100%1/1
$params{"db"} // 1
$params{"db"}
Truth table100%2/2
A
A= $params{"db"}
Aresult
11
00
809 188 ▶ confess "refresh_row() needs 'cache' or 'db' to be true" unless $cache || $db;
Branch: 1 branch
BranchTrueFalseTotal
unless $cache or $db 1 187 188
Condition100%3/3
$cache or $db
l!l&&r!l&&!r
127601
MC/DC100%2/2
$cache or $db
$cache $db
Truth table100%3/3
A or B
A= $cacheB= $db
ABresult
1X1
011
000
810  
811 187 my $fields = $params{fields};
812 187 ▶ 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 186 187
Condition100%3/3
defined $fields and ref $fields ne "ARRAY"
!ll&&!rl&&r
163231
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
813 186 ▶ $self->_check_fields($table, @$fields) if $fields;
Branch: 1 branch
BranchTrueFalseTotal
if $fields 23 163 186
814  
815 # Without 'fields', the fields the given row data holds are read too, so a refresh keeps what the row read.
816 185 ▶ $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') ? : 31 154 185
ref $data eq 'HASH' ? : 118 36 154
Condition100%3/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
146831
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
817 185 my %seen;
818 185 ▶ @select = $fields ? grep { !$seen{$_}++ } sort(@$fields, @{$t->{pk}}) : @{$self->_read_back_fields($table, sort grep { $t->{fields}->{$_} } keys %{$given // {}})};
Branch: 1 branch
BranchTrueFalseTotal
$fields ? : 22 163 185
Condition100%2/2
$given // {}
l!l
12736
MC/DC100%1/1
$given // {}
$given
Truth table100%2/2
A
A= $given
Aresult
11
00
819 }
820  
821 297 ▶ if ($cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cache) 237 60 297
822 237 ▶ my $canon = $fast ? $lookup->_find($table, "$data") : $lookup->lookup($table, $self->_plain($pk));
Branch: 1 branch
BranchTrueFalseTotal
$fast ? : 112 125 237
823 237 ▶ return $canon if $canon && (!$db || !grep { !exists $canon->{$_} } @select);
Branch: 1 branch
BranchTrueFalseTotal
if $canon and not $db && grep({not exists $canon->{$_};} @select) 74 163 237
Condition100%6/6
$canon and not $db && grep({not exists $canon->{$_};} @select)
!ll&&!rl&&r
1481574
$db && grep({not exists $canon->{$_};} @select)
!ll&&!rl&&r
245015
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
824 }
825 223 ▶ return undef unless $db;
Branch: 1 branch
BranchTrueFalseTotal
unless $db 11 212 223
826  
827 212 my ($sql, $binds, $marked);
828 212 ▶ if ($fast) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fast) { } 89 123 212
829 89 ($sql, $binds) = ($fast->{sql}, [[$fast->{field} => $data]]);
830 }
831 else {
832 123 my $where_sql;
833 123 ($where_sql, $binds, $marked) = $self->_where_sql($pk);
834 123 $sql = $self->_select_sql($table, \@select, $where_sql, $marked);
835 }
836  
837 212 my $row = $self->_fetch($t->{fields}, $self->_run($t->{fields}, $sql, $binds, undef, !$marked))->[0];
838 211 ▶ if ($row) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row) 186 25 211
839 186 my $canon = $lookup->ingest($table, $row);
840 186 ▶ $lookup->carry_inserted($given, $canon) if $given;
Branch: 1 branch
BranchTrueFalseTotal
if $given 84 102 186
841 186 return $canon;
842 }
843  
844 25 $lookup->gone($table, $self->_plain($pk), $given);
845 25 return undef;
846 }
847  
848 =pod
849  
850 =over 4
851  
852 =item $info = $conn->_find_key($table)
853  
854 For a table whose primary key is one field with no type, what C<refresh_row>
855 needs to read a row by a plain key value: C<table> (the map's record),
856 C<field>, C<select> (the default fields) and C<sql>. Kept per table, since the
857 map does not change. Undef for any other table.
858  
859 =item $sql = $conn->_select_sql($table, \@fields, $where_sql, $marked)
860  
861 The C<SELECT> of those fields from the table with that C<WHERE> body, built
862 once per shape unless C<$marked>.
863  
864 =back
865  
866 =cut
867  
868 129 ▶sub _find_key {
Subroutine _find_key: called CC=12 SCAR=25.1
869 129 my $self = shift;
870 129 my ($table) = @_;
871  
872 129 ▶ 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 129 129
Condition33%1/3
defined $table and length $table
!ll&&!rl&&r
00129
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
873  
874 129 ▶ my $keys = $self->{+FIND_KEYS} //= {};
Condition100%2/2
$self->{"find_keys"} //= {}
l!l
8940
MC/DC100%1/1
$self->{"find_keys"} //= {}
$self->{"find_keys"}
Truth table100%2/2
A
A= $self->{"find_keys"}
Aresult
11
00
875 129 ▶ return $keys->{$table} if exists $keys->{$table};
Branch: 1 branch
BranchTrueFalseTotal
if exists $keys->{$table} 79 50 129
876  
877 50 ▶ 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 50 0 50
878  
879 50 ▶ my $pk = $t->{pk} // [];
Condition100%2/2
$t->{"pk"} // []
l!l
491
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
880 50 my $fields = $t->{fields};
881 50 ▶ my $field = @$pk == 1 && ref($fields) eq 'HASH' ? $fields->{$pk->[0]} : undef;
Branch: 1 branch
BranchTrueFalseTotal
@$pk == 1 && ref $fields eq 'HASH' ? : 44 6 50
Condition100%3/3
@$pk == 1 and ref $fields eq "HASH"
!ll&&!rl&&r
4244
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
882 50 ▶ 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"} 16 34 50
Condition83%5/6
$field and not $t->{"pk_types"} and not $field->{"orm_type"}
!ll&&!rl&&r
16034
$field and not $t->{"pk_types"}
!ll&&!rl&&r
7934
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
883  
884 34 my $select = $self->_default_fields($table);
885 34 my ($where_sql) = $self->_where_sql({$pk->[0] => ''});
886 34 return $keys->{$table} = {table => $t, field => $pk->[0], select => [@$select], sql => $self->_select_sql($table, $select, $where_sql)};
887 }
888  
889 157 ▶sub _select_sql {
Subroutine _select_sql: called CC=2 SCAR=6.9
890 157 my $self = shift;
891 157 my ($table, $fields, $where_sql, $marked) = @_;
892 157 my $dialect = $self->{+DIALECT};
893 return $self->_statement(
894 $marked ? undef : join("\0" => 'select', $table, @$fields, $where_sql),
895 84 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
896 84 'SELECT ' . join(', ' => map { $dialect->quote_identifier($_) } @$fields) . ' FROM ' . $dialect->quote_identifier($table) . " WHERE $where_sql";
897 }
898 157 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 2 155 157
899 }
900  
901 =over 4
902  
903 =item \@rows = $conn->select($source, $sql, \@binds)
904  
905 =item \%pending = $conn->select($source, $sql, \@binds, async => 1)
906  
907 Runs SQL built elsewhere for a source (a L<DBIx::QuickORM::Role::Source>) and
908 returns every row as fetched.
909  
910 Binds are C<[$name, $value]> pairs. The name (undef for none) is one of the
911 source's C<field_records>, which also decide how fetched columns are read.
912 Nothing is ingested here. The source's C<results> ingests the rows that
913 belong to a table.
914  
915 With C<async>, on a dialect that C<supports_async>, the query is started
916 without waiting for it and a hash of three code references is returned:
917 C<ready> (true once the result has arrived), C<collect> (waits for the result
918 and returns the rows), and C<cancel> (gives up on the query). Call C<collect>
919 or C<cancel> once. A dialect without async queries croaks.
920  
921 While the query is pending the Connection is busy: every query, CRUD operation,
922 and transaction statement that would send SQL croaks (a C<find> answered from
923 the cache does not), including an explicit C<rollback>.
924  
925 A rollback forced by a block's exception, or by a L<DBIx::QuickORM::Txn>
926 going out of scope, cancels the query first. After that C<collect> throws and
927 C<cancel> does nothing.
928  
929 =back
930  
931 =cut
932  
933 304 my %SELECT_ARGS = (async => 1);
934  
935 277 ▶sub select {
Subroutine select: called CC=7 SCAR=32.5
Pod documented
936 277 my $self = shift;
937 277 my ($source, $sql, $binds, %params) = @_;
938  
939 277 $self->_check_params(select => \%SELECT_ARGS, \%params);
940 276 ▶ 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 275 276
Condition66%2/3
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
10275
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
941 275 ▶ 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 274 275
Condition66%2/3
defined $binds and ref $binds ne "ARRAY"
!ll&&!rl&&r
02741
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
942  
943 274 my $fields = $source->field_records;
944 274 $binds = $self->_resolve_binds($source, $binds);
945 274 ▶ return $self->_fetch($fields, $self->_run($fields, $sql, $binds)) unless $params{async};
Branch: 1 branch
BranchTrueFalseTotal
unless $params{"async"} 274 0 274
946  
947 0 my ($dbh, $dialect) = @{$self}{+DBH, +DIALECT};
948 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
949 0 my $sth = $self->_run($fields, $sql, $binds, $dialect->async_prepare_attrs);
950 0 weaken($PENDING{refaddr($self)} = $self);
951  
952 # The statement is freed as soon as the query is over, before another can start beside it.
953 0 ▶ my $done = sub { undef $sth; delete $self->{+BUSY}; delete $PENDING{refaddr($self)} };
Subroutine __ANON__: not called CC=1 SCAR=6.9
954 my $pending = {
955 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
956 0 ▶ collect => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
957 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
958 0 my $rows;
959 0 my $ok = eval { $dialect->async_result($dbh, $sth); $rows = $self->_fetch($fields, $sth); 1 };
960 0 my $err = $@;
961 0 $done->();
962 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
963 0 return $rows;
964 },
965 0 ▶ cancel => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
966 0 ▶ return unless $sth;
Branch: 1 branch
BranchTrueFalseTotal
unless $sth 0 0 0
967 0 my $ok = eval { $dialect->cancel_async($dbh, $sth); 1 };
968 0 my $err = $@;
969 0 $done->();
970 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
971 },
972 0 };
973 0 $self->{+BUSY} = {sth => $sth, cancel => $pending->{cancel}};
974 0 return $pending;
975 }
976  
977 =over 4
978  
979 =item $count = $conn->bulk_write($source, $sql, \@binds)
980  
981 =item $count = $conn->bulk_write($source, $sql, \@binds, mark_deleted => 1, keys => [$select_sql, \@select_binds])
982  
983 Runs an C<UPDATE> or C<DELETE> built elsewhere for a table source and returns
984 the number of rows the database reports. Binds are as for C<select>.
985  
986 It cannot tell which rows changed, so it clears the table from the lookup
987 table's top level and, inside a transaction, from its outside level. A source
988 without a table croaks.
989  
990 With C<mark_deleted>, C<$sql> must be a C<DELETE>. The deleted rows' primary
991 keys are also learned, and each is passed to the lookup table's C<gone>
992 before the table is cleared: held rows for those keys are marked deleted (a
993 rollback unmarks them).
994  
995 The count is still the rows the database reports deleted. With C<RETURNING>
996 that equals the keys returned. On MySQL it can exceed them (see below).
997  
998 =over 4
999  
1000 =item *
1001  
1002 Where the dialect C<supports_returning_delete>, C<$sql> gets C<RETURNING>
1003 and the key columns.
1004  
1005 =item *
1006  
1007 Otherwise (MySQL) C<keys> is required: a C<SELECT> of the key columns with
1008 the same C<where>. It runs with C<FOR UPDATE>, locking those rows, then
1009 C<$sql> runs. Both run in a transaction of their own when none is open.
1010 Nothing is marked unless the C<DELETE> succeeds. At C<READ COMMITTED> a row
1011 another session commits between the two is deleted and counted, but not
1012 marked.
1013  
1014 =back
1015  
1016 =back
1017  
1018 =cut
1019  
1020 304 my %BULK_ARGS = map { $_ => 1 } qw/mark_deleted keys/;
1021  
1022 16 ▶sub bulk_write {
Subroutine bulk_write: called CC=11 SCAR=29.8
Pod documented
1023 16 my $self = shift;
1024 16 my ($source, $sql, $binds, %params) = @_;
1025  
1026 16 $self->_check_params(bulk_write => \%BULK_ARGS, \%params);
1027 16 ▶ 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 16 16
Condition33%1/3
builtin::blessed($source) and $source->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
0016
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
1028 16 my $table = $source->table;
1029 16 ▶ confess "bulk_write() needs a source with a table" unless defined $table;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table 0 16 16
1030 16 ▶ 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 16 16
Condition33%1/3
defined $binds and ref $binds ne "ARRAY"
!ll&&!rl&&r
0160
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
1031  
1032 16 my $fields = $source->field_records;
1033 16 $binds = $self->_resolve_binds($source, $binds);
1034 16 my $lookup = $self->lookup;
1035  
1036 16 ▶ unless ($params{mark_deleted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params{"mark_deleted"}) 10 6 16
1037 10 my $sth = $self->_run($fields, $sql, $binds);
1038 10 $lookup->forget($table);
1039 10 return $sth->rows;
1040 }
1041  
1042 6 my $dialect = $self->{+DIALECT};
1043 6 ▶ if ($dialect->supports_returning_delete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dialect->supports_returning_delete) 6 0 6
1044 6 my $returning = join ', ' => map { $dialect->quote_identifier($_) } @{$self->_table($table)->{pk}};
1045 6 my $keys = $self->_fetch($fields, $self->_run($fields, "$sql RETURNING $returning", $binds));
1046 6 $lookup->gone($table, $_) for @$keys;
1047 6 $lookup->forget($table);
1048 6 return scalar @$keys;
1049 }
1050  
1051 0 my $select = $params{keys};
1052 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
1053 0 ▶ my $run = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
1054 0 my $keys = $self->_fetch($fields, $self->_run($fields, "$select->[0] FOR UPDATE", $self->_resolve_binds($source, $select->[1])));
1055 0 my $sth = $self->_run($fields, $sql, $binds);
1056 0 $lookup->gone($table, $_) for @$keys;
1057 0 $lookup->forget($table);
1058 0 return $sth->rows;
1059 0 };
1060 0 ▶ return @{$self->{+TXNS}} ? $run->() : $self->txn($run);
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'txns'};} ? : 0 0 0
1061 }
1062  
1063 =pod
1064  
1065 =over 4
1066  
1067 =item $txn = $conn->txn(caller => \@frame)
1068  
1069 =item $txn = $conn->txn(isolation => $level, caller => \@frame)
1070  
1071 =item @result = $conn->txn(sub { my $txn = shift; ... }, retry => $n, isolation => $level, caller => \@frame)
1072  
1073 Opens a transaction, or a savepoint when one is already open, and returns its
1074 L<DBIx::QuickORM::Txn>. Given a block, runs it in the transaction and returns
1075 what the block returns.
1076  
1077 The transaction statements are sent as SQL, never through DBI's
1078 C<begin_work>. Nesting croaks on a dialect without savepoints (DuckDB).
1079 C<caller> is where it was opened, for warnings and errors. It is the caller of
1080 this method unless given.
1081  
1082 Opening one begins a lookup table level (see L<DBIx::QuickORM::LookupTable>).
1083  
1084 The block is called in list context when C<txn> is, otherwise in scalar
1085 context. A normal return commits,
1086 unless the block already committed or rolled back itself. An exception rolls
1087 back and is rethrown.
1088  
1089 With C<retry>, the block of a root transaction runs again in a new
1090 transaction, up to C<$n> more times, while the exception is a
1091 L<DBIx::QuickORM::Exception::DB> whose C<retriable> is true. A
1092 C<retry> above 0 croaks inside another transaction or without a block. One
1093 that is not a count croaks.
1094  
1095 C<isolation> is the root transaction's level: C<read uncommitted>, C<read
1096 committed>, C<repeatable read>, or C<serializable>, in any case, or
1097 C<'server'> for the database's own default. Without it the Connection's
1098 C<isolation> applies. Every retry begins at the same level. It croaks inside
1099 another transaction and for any other value. A level on a database without
1100 settable levels (SQLite, DuckDB) croaks when the transaction opens.
1101  
1102 =back
1103  
1104 =cut
1105  
1106 304 my %TXN_ARGS = map { $_ => 1 } qw/retry isolation caller/;
1107 304 my @ISOLATION = ('read committed', 'read uncommitted', 'repeatable read', 'serializable', 'server');
1108 304 my %ISOLATION = map { $_ => 1 } @ISOLATION;
1109  
1110 152 ▶sub txn {
Subroutine txn: called CC=16 SCAR=27.7
Pod documented
1111 152 my $self = shift;
1112 152 ▶ my $code = ref($_[0]) eq 'CODE' ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'CODE' ? : 94 58 152
1113 152 my %params = @_;
1114  
1115 152 $self->_check_params(txn => \%TXN_ARGS, \%params);
1116 151 ▶ my $caller = $params{caller} // [caller];
Condition100%2/2
$params{"caller"} // [caller]
l!l
1429
MC/DC100%1/1
$params{"caller"} // [caller]
$params{"caller"}
Truth table100%2/2
A
A= $params{"caller"}
Aresult
11
00
1117 151 ▶ my $retry = $params{retry} // 0;
Condition100%2/2
$params{"retry"} // 0
l!l
10141
MC/DC100%1/1
$params{"retry"} // 0
$params{"retry"}
Truth table100%2/2
A
A= $params{"retry"}
Aresult
11
00
1118 151 ▶ confess "'retry' must be a count of retries" unless $retry =~ m/^\d+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $retry =~ /^\d+\z/ 1 150 151
1119 150 ▶ confess "'retry' needs a block: txn(sub { ... }, retry => \$n)" if $retry && !$code;
Branch: 1 branch
BranchTrueFalseTotal
if $retry and not $code 1 149 150
Condition100%3/3
$retry and not $code
!ll&&!rl&&r
14181
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
1120 149 ▶ 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 148 149
Condition100%3/3
$retry and @{$self->{"txns"};}
!ll&&!rl&&r
14171
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
1121  
1122 148 my $level = $params{isolation};
1123 148 ▶ if (defined $level) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $level) 6 142 148
1124 6 $level = $self->_isolation($level);
1125 5 ▶ 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 4 5
1126 }
1127 146 ▶ return $self->_begin($caller, $level) unless $code;
Branch: 1 branch
BranchTrueFalseTotal
unless $code 55 91 146
1128  
1129 91 my $list = wantarray;
1130 91 for (my $tries = 0;; $tries++) {
1131 97 my ($ok, $err, @out) = $self->_run_block($code, $caller, $list, $level);
1132 97 ▶ return $list ? @out : $out[0] if $ok;
Branch: 2 branches
BranchTrueFalseTotal
if $ok 69 28 97
$list ? : 2 67 69
1133 28 ▶ die $err unless $tries < $retry && $self->_retriable($err);
Branch: 1 branch
BranchTrueFalseTotal
unless $tries < $retry and $self->_retriable($err) 22 6 28
Condition100%3/3
$tries < $retry and $self->_retriable($err)
!ll&&!rl&&r
1936
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
1134 }
1135 }
1136  
1137 =pod
1138  
1139 =over 4
1140  
1141 =item $conn->commit_txn($txn)
1142  
1143 =item $conn->rollback_txn($txn)
1144  
1145 What C<< $txn->commit >> and C<< $txn->rollback >> do (see
1146 L<DBIx::QuickORM::Txn>).
1147  
1148 Either croaks unless the transaction is open and innermost, this is the
1149 process that opened it, and no async query is pending.
1150  
1151 Committing a transaction marked failed rolls it back instead, then croaks
1152 (see C<_run>).
1153  
1154 Ending a transaction ends its lookup table level, as
1155 L<DBIx::QuickORM::LookupTable> describes. A failed commit or rollback is
1156 handled as L<DBIx::QuickORM::Txn> describes.
1157  
1158 =back
1159  
1160 =cut
1161  
1162 73 ▶sub commit_txn {
Subroutine commit_txn: called CC=5 SCAR=16.1
Pod documented
1163 73 my $self = shift;
1164 73 my ($txn) = @_;
1165  
1166 73 $self->_check_open($txn, 'commit');
1167 69 $self->_check_idle; # Before the commit, whose failure would roll back.
1168 69 ▶ if (defined(my $failed = $txn->failed)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $failed = $txn->failed)) 2 67 69
1169 2 $self->_unwind($txn);
1170 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";
1171 }
1172 67 ▶ my $sql = $txn->depth == 1 ? 'COMMIT' : 'RELEASE SAVEPOINT ' . $txn->name;
Branch: 1 branch
BranchTrueFalseTotal
$txn->depth == 1 ? : 54 13 67
1173 67 ▶ unless (eval { $self->_do($sql); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $self->_do($sql); 1 } }) 3 64 67
1174 3 my $err = $@;
1175 3 ▶ die $err if eval { $self->_unwind($txn); 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { $self->_unwind($txn); 1 } } 1 2 3
1176 2 my $rollback_err = $@;
1177 2 $self->_abandon($txn);
1178 2 chomp($err, $rollback_err);
1179 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";
1180 }
1181  
1182 64 pop @{$self->{+TXNS}};
1183 64 $self->lookup->commit_level;
1184 64 return 1;
1185 }
1186  
1187 51 ▶sub rollback_txn {
Subroutine rollback_txn: called CC=1 SCAR=0.0
Pod documented
1188 51 my $self = shift;
1189 51 my ($txn) = @_;
1190 51 $self->_check_open($txn, 'roll back');
1191 49 $self->_check_idle;
1192 49 $self->_unwind($txn);
1193 48 return 1;
1194 }
1195  
1196 =pod
1197  
1198 =over 4
1199  
1200 =item \%values = $conn->deflate($table, \%values, raw => $bool)
1201  
1202 The values in a new hashref (under C<raw> with no marker, the one given),
1203 deflated as L<DBIx::QuickORM/"CRUD operations"> describes. The CRUD operations
1204 use it on every value they send, except the plain key of a C<refresh_row> with
1205 no options on a single untyped key field, which deflating would not change. Row objects use it for the changes they send
1206 raw.
1207  
1208 Value markers (L<DBIx::QuickORM::Value>) are handled even under C<raw>: a
1209 C<raw> marker is unwrapped, an C<inflated> one is deflated through the type
1210 whatever C<is_inflated> says, and C<binary> and C<sql> markers are kept for
1211 the SQL. With C<raw> nothing else changes, and values holding no marker are
1212 returned as they are.
1213  
1214 Croaks for a table not in the map, or a field the table does not have, before
1215 deflating anything.
1216  
1217 =back
1218  
1219 =cut
1220  
1221 1350 ▶sub deflate {
Subroutine deflate: called CC=3 SCAR=11.0
Pod documented
1222 1350 my $self = shift;
1223 1350 my ($table, $values, %params) = @_;
1224 1350 my $fields = $self->_table($table)->{fields};
1225 1349 $self->_check_fields($table, sort keys %$values);
1226  
1227 1338 my $raw = $params{raw};
1228 1338 ▶ return $values if $raw && !grep { $self->_is_marker($_) } values %$values;
Branch: 1 branch
BranchTrueFalseTotal
if $raw and not grep({$self->_is_marker($_);} values %$values) 228 1110 1338
Condition100%3/3
$raw and not grep({$self->_is_marker($_);} values %$values)
!ll&&!rl&&r
11091228
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
1229  
1230 1110 return {map { $_ => $self->_deflate_value($table, $_, $fields->{$_}, $values->{$_}, $raw) } keys %$values};
1231 }
1232  
1233 =over 4
1234  
1235 =item $conn->release_inherited
1236  
1237 In a forked child, lets go of the handle inherited from the parent without
1238 touching the parent's session.
1239  
1240 An async query the parent left pending is cleared too, so nothing the child
1241 does later, or at exit, waits on it. It does nothing in the process that
1242 opened the Connection, and calling it again is harmless.
1243  
1244 =back
1245  
1246 =cut
1247  
1248 9 ▶sub release_inherited {
Subroutine release_inherited: called CC=4 SCAR=22.5
Pod documented
1249 9 my $self = shift;
1250 9 ▶ return if $self->{+PID} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pid"} == $$ 0 9 9
1251 9 $self->{+DIALECT}->release_inherited($self->{+DBH});
1252  
1253 9 ▶ my $busy = delete $self->{+BUSY} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $busy = delete $self->{"busy"} or return 0 9 9
1254 0 my $sth = $busy->{sth};
1255 0 delete $PENDING{refaddr($self)};
1256 0 ▶ @{$sth}{qw/InactiveDestroy RaiseError PrintError PrintWarn HandleError/} = (1, 0, 0, 0, sub { 1 });
Subroutine __ANON__: not called CC=1 SCAR=6.9
1257 0 local $@;
1258 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
1259 0 return;
1260 }
1261  
1262 =head1 PRIVATE METHODS
1263  
1264 =pod
1265  
1266 =over 4
1267  
1268 =item $map = $conn->_scanned_map($dialect, $dbh, $namespace, $rescan)
1269  
1270 A new map of the database, from the scan cache (see L</"The scan cache">), or
1271 from a scan that refreshes it when C<$rescan> is true, nothing is cached for
1272 this database, or it cannot be shared (C<scan_cache_key> is undef).
1273  
1274 =back
1275  
1276 =cut
1277  
1278 333 ▶sub _scanned_map {
Subroutine _scanned_map: called CC=5 SCAR=16.1
1279 333 my $self = shift;
1280 333 my ($dialect, $dbh, $ns, $rescan) = @_;
1281  
1282 333 my $key = $dialect->scan_cache_key($dbh, $ns);
1283 333 ▶ 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} 97 236 333
Condition100%6/6
defined $key and not $rescan and $SCAN_CACHE{$key}
!ll&&!rl&&r
1983897
defined $key and not $rescan
!ll&&!rl&&r
18711135
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
1284  
1285 236 my $map = DBIx::QuickORM::Map->new(tables => $dialect->scan($dbh));
1286 236 ▶ $SCAN_CACHE{$key} = $map->clone if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 49 187 236
1287 236 return $map;
1288 }
1289  
1290 =over 4
1291  
1292 =item $code = $conn->_error_handler($dialect, \@txns)
1293  
1294 The C<HandleError> callback: dies with a L<DBIx::QuickORM::Exception::DB>
1295 built from the failing handle. First it marks the innermost open transaction
1296 failed, with the error (see C<_run>). It holds the dialect and the
1297 transaction stack, not the Connection.
1298  
1299 =back
1300  
1301 =cut
1302  
1303 364 ▶sub _error_handler {
Subroutine _error_handler: called CC=1 SCAR=0.3
1304 364 my $self = shift;
1305 364 my ($dialect, $txns) = @_;
1306  
1307 31 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=20.5
1308 31 my ($msg, $h) = @_;
1309 31 my ($native, $state, $errstr) = ($h->err, $h->state, $h->errstr);
1310 31 ▶ $state = undef unless defined($state) && length($state);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $state and length $state 0 31 31
Condition33%1/3
defined $state and length $state
!ll&&!rl&&r
0031
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
1311  
1312 31 my $txn = $txns->[-1];
1313 31 ▶ $txn->{failed} //= $errstr // $msg if $txn;
Branch: 1 branch
BranchTrueFalseTotal
if $txn 12 19 31
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
1314  
1315 die DBIx::QuickORM::Exception::DB->new(
1316 kind => $dialect->error_kind($native, $state, $errstr),
1317 state => $state,
1318 native => $native,
1319 errstr => $errstr,
1320 statement => $h->{Statement},
1321 31 message => $msg,
1322 );
1323 364 };
1324 }
1325  
1326 =pod
1327  
1328 =over 4
1329  
1330 =item \%generated = $conn->_generate_keys(\%table, \%values)
1331  
1332 New values for the table's primary key fields missing from C<%values>, from
1333 each field's type's C<generate_key_value>. A field's C<generate> hint
1334 decides: C<none> never, C<prefer_orm> always, and C<prefer_db> (the default)
1335 unless the column has C<db_fills> and the dialect can return the inserted
1336 key (C<supports_returning_insert>). Fields without a type, or whose
1337 type cannot generate, are left out. The values are inflated. The caller
1338 deflates them, even for C<raw> inserts.
1339  
1340 =item @names = $conn->_key_generators(\%table, \%values)
1341  
1342 The primary key fields C<_generate_keys> would fill for C<%values>, decided
1343 from the field records and the dialect alone. Rows with the same fields get
1344 the same answer, so C<insert_many> asks once.
1345  
1346 =back
1347  
1348 =cut
1349  
1350 313 ▶sub _generate_keys {
Subroutine _generate_keys: called CC=2 SCAR=6.9
1351 313 my $self = shift;
1352 313 my ($t, $values) = @_;
1353  
1354 313 my $fields = $t->{fields};
1355 313 my %generated;
1356 313 for my $name ($self->_key_generators($t, $values)) { $generated{$name} = $fields->{$name}->{orm_type}->generate_key_value($fields->{$name}, $self) }
1357 313 return \%generated;
1358 }
1359  
1360 369 ▶sub _key_generators {
Subroutine _key_generators: called CC=11 SCAR=24.0
1361 369 my $self = shift;
1362 369 my ($t, $values) = @_;
1363  
1364 369 my @names;
1365 369 ▶ for my $name (@{$t->{pk} // []}) {
Condition100%2/2
$t->{"pk"} // []
l!l
3618
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
1366 382 ▶ next if exists $values->{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $values->{$name} 316 66 382
1367 66 my $field = $t->{fields}->{$name};
1368 66 my $type = $field->{orm_type};
1369 66 ▶ next unless $type && $type->can('generate_key_value');
Branch: 1 branch
BranchTrueFalseTotal
unless $type and $type->can("generate_key_value") 47 19 66
Condition66%2/3
$type and $type->can("generate_key_value")
!ll&&!rl&&r
47019
MC/DC50%1/2
$type and $type->can("generate_key_value")
$type $type->can("generate_key_value")
Truth table66%2/3
A and B
A= $typeB= $type->can("generate_key_value")
ABresult
0X0
100
111
1370  
1371 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
1372 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
1373 16 push @names => $name;
1374 }
1375  
1376 369 return @names;
1377 }
1378  
1379 =pod
1380  
1381 =over 4
1382  
1383 =item \%data = $conn->_row_data($row_or_data)
1384  
1385 The row data: a hashref as given, or a row object's C<row_data>. Croaks on
1386 anything else.
1387  
1388 =back
1389  
1390 =cut
1391  
1392 3504 ▶sub _row_data {
Subroutine _row_data: called CC=5 SCAR=16.2
1393 3504 my $self = shift;
1394 3504 my ($data) = @_;
1395 3504 ▶ $data = $data->row_data if blessed($data) && $data->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($data) and $data->can("row_data") 99 3405 3504
Condition66%2/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
3405099
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
1396 3504 ▶ 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 3502 3504
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
1397 3502 return $data;
1398 }
1399  
1400 =pod
1401  
1402 =over 4
1403  
1404 =item $value = $conn->_deflate_value($table, $name, \%field, $value, $raw)
1405  
1406 One value deflated as C<deflate> describes. C<\%field> is undef for a name
1407 that is not a field.
1408  
1409 A value the type deflated to plain text then goes through the field's
1410 C<format>, if it has one and is not binary.
1411  
1412 =back
1413  
1414 =cut
1415  
1416 1436 ▶sub _deflate_value {
Subroutine _deflate_value: called CC=21 SCAR=30.5
1417 1436 my $self = shift;
1418 1436 my ($table, $name, $field, $value, $raw) = @_;
1419 1436 ▶ my $type = $field ? $field->{orm_type} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$field ? : 1414 22 1436
1420  
1421 1436 ▶ if (ref($value) && $self->_is_marker($value)) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $value and $self->_is_marker($value)) { } 71 1365 1436
elsif ($raw or not defined $value) { } 223 1142 1365
elsif ($type and not ref $value) { } 118 1971 2089
Condition100%3/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
12848171
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
1422 71 my $kind = $value->kind;
1423 71 ▶ return $value if $kind eq 'binary' || $kind eq 'sql';
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "binary" or $kind eq "sql" 30 41 71
Condition100%3/3
$kind eq "binary" or $kind eq "sql"
l!l&&r!l&&!r
102041
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
1424 41 $value = $value->value;
1425 41 ▶ return $value if $kind eq 'raw' || !defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq "raw" or not defined $value 26 15 41
Condition66%2/3
$kind eq "raw" or not defined $value
l!l&&r!l&&!r
26015
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
1426 }
1427 ▶ elsif ($raw || !defined($value)) {
Condition100%3/3
$raw or not defined $value
l!l&&r!l&&!r
206171142
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
1428 223 return $value;
1429 }
1430 ▶ elsif ($type && !ref($value)) {
Condition100%3/3
$type and not ref $value
!ll&&!rl&&r
94777118
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
1431 118 ▶ 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 70 118
Condition100%3/3
$type->can("is_inflated") and $type->is_inflated($value)
!ll&&!rl&&r
14770
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
1432 }
1433  
1434 1109 ▶ unless ($type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type) 950 159 1109
1435 950 ▶ 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 5 945 950
1436 945 return $value;
1437 }
1438  
1439 159 my $out = $type->deflate($value, $field, $self);
1440 159 my $format = $field->{format};
1441 159 ▶ 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" 149 10 159
Condition72%8/11
$format and defined $out and not ref $out and ($field->{"affinity"} // "") ne "binary"
!ll&&!rl&&r
148110
$format and defined $out and not ref $out
!ll&&!rl&&r
148011
$format and defined $out
!ll&&!rl&&r
148011
$field->{"affinity"} // ""
l!l
110
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
1442 10 return $format->($out);
1443 }
1444  
1445 =pod
1446  
1447 =over 4
1448  
1449 =item $bool = $conn->_is_marker($value)
1450  
1451 =item $bool = $conn->_is_sql($value)
1452  
1453 True for a value marker, or an C<sql> marker.
1454  
1455 =back
1456  
1457 =cut
1458  
1459 1903 ▶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') ? : 150 1753 1903
Condition100%3/3
builtin::blessed($_[1]) and $_[1]->isa("DBIx::QuickORM::Value")
!ll&&!rl&&r
172528150
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
1460 1171 ▶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' ? : 21 1150 1171
Condition100%3/3
$_[0]->_is_marker($_[1]) and $_[1]->kind eq "sql"
!ll&&!rl&&r
11381221
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
1461  
1462 =pod
1463  
1464 =over 4
1465  
1466 =item \%values = $conn->_plain(\%values)
1467  
1468 A copy with each C<binary> marker replaced by its value, for lookup keys and
1469 row data.
1470  
1471 =back
1472  
1473 =cut
1474  
1475 305 ▶sub _plain {
Subroutine _plain: called CC=2 SCAR=6.9
1476 305 my $self = shift;
1477 305 my ($values) = @_;
1478 305 ▶ return {map { my $v = $values->{$_}; ($_ => $self->_is_marker($v) ? $v->value : $v) } keys %$values};
Branch: 1 branch
BranchTrueFalseTotal
$self->_is_marker($v) ? : 4 320 324
1479 }
1480  
1481 =pod
1482  
1483 =over 4
1484  
1485 =item (\@places, \@binds, $marked) = $conn->_value_sql(\%values, @names)
1486  
1487 The SQL for each named value, C<?> or an C<sql> marker's SQL, and the binds,
1488 in order. C<$marked> is true when any value was a marker: its SQL or bind
1489 attributes make the statement one of a kind, never cached.
1490  
1491 =back
1492  
1493 =cut
1494  
1495 1766 ▶sub _value_sql {
Subroutine _value_sql: called CC=6 SCAR=17.9
1496 1766 my $self = shift;
1497 1766 my ($values, @names) = @_;
1498  
1499 1766 my (@places, @binds, $marked);
1500 1766 for my $name (@names) {
1501 2859 my $value = $values->{$name};
1502 2859 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 20 2839 2859
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
2839020
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
1503 2859 ▶ if (ref($value) && $self->_is_sql($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and $self->_is_sql($value)) 15 2844 2859
Condition100%3/3
ref $value and $self->_is_sql($value)
!ll&&!rl&&r
2839515
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
1504 15 push @places => $value->value;
1505 15 push @binds => map { [undef, $_] } @{$value->binds};
1506 15 next;
1507 }
1508 2844 push @places => '?';
1509 2844 push @binds => [$name => $value];
1510 }
1511  
1512 1766 return (\@places, \@binds, $marked);
1513 }
1514  
1515 =pod
1516  
1517 =over 4
1518  
1519 =item @batches = $conn->_batches(\@values, \@names)
1520  
1521 The rows of a multi-row insert, as C<[\@places, \@binds, $marked]>: each
1522 place is one row's C<(...)>, each batch holds as many rows as fit in the
1523 dialect's C<bind_limit>, at least one, and C<$marked> is true when one of its
1524 rows held a marker.
1525  
1526 =back
1527  
1528 =cut
1529  
1530 11 ▶sub _batches {
Subroutine _batches: called CC=7 SCAR=19.5
1531 11 my $self = shift;
1532 11 my ($values, $names) = @_;
1533  
1534 11 my $limit = $self->{+DIALECT}->bind_limit;
1535 11 my $plain = '(' . join(', ' => ('?') x @$names) . ')';
1536 11 my @batches = ([[], [], 0]);
1537 11 for my $row (@$values) {
1538 1350 my ($places, $binds, $marked) = $self->_value_sql($row, @$names);
1539 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
1540 1350 ▶ push @{$batches[-1]->[0]} => $marked ? '(' . join(', ' => @$places) . ')' : $plain;
Branch: 1 branch
BranchTrueFalseTotal
$marked ? : 7 1343 1350
1541 1350 push @{$batches[-1]->[1]} => @$binds;
1542 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
1543 }
1544  
1545 11 return @batches;
1546 }
1547  
1548 =pod
1549  
1550 =over 4
1551  
1552 =item \@binds = $conn->_resolve_binds($source, \@binds)
1553  
1554 Binds built elsewhere with their C<raw> and C<inflated> markers resolved, as
1555 C<deflate> with C<raw> resolves them, by the source's field each bind names.
1556  
1557 =back
1558  
1559 =cut
1560  
1561 290 ▶sub _resolve_binds {
Subroutine _resolve_binds: called CC=5 SCAR=16.1
1562 290 my $self = shift;
1563 290 my ($source, $binds) = @_;
1564  
1565 290 ▶ my $table = $source->table // '';
Condition100%2/2
$source->table // ""
l!l
25733
MC/DC100%1/1
$source->table // ""
$source->table
Truth table100%2/2
A
A= $source->table
Aresult
11
00
1566 290 my $fields = $source->field_records;
1567 290 ▶ 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 ? : 199 19 218
Condition75%3/4
$name // ""
l!l
19919
$binds // []
l!l
2900
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
1568 }
1569  
1570 =pod
1571  
1572 =over 4
1573  
1574 =item $conn->_check_params($name, \%known, \%params)
1575  
1576 Croaks naming every key of C<%params> not in C<%known>.
1577  
1578 =back
1579  
1580 =cut
1581  
1582 1221 ▶sub _check_params {
Subroutine _check_params: called CC=2 SCAR=6.9
1583 1221 my $self = shift;
1584 1221 my ($name, $known, $params) = @_;
1585 1221 my @unknown = sort grep { !$known->{$_} } keys %$params;
1586 1221 ▶ confess "Unknown argument(s) to $name(): " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 9 1212 1221
1587 }
1588  
1589 =pod
1590  
1591 =over 4
1592  
1593 =item \%table = $conn->_table($table)
1594  
1595 The map's record for the table. Croaks when there is none.
1596  
1597 =back
1598  
1599 =cut
1600  
1601 2132 ▶sub _table {
Subroutine _table: called CC=4 SCAR=13.9
1602 2132 my $self = shift;
1603 2132 my ($table) = @_;
1604 2132 ▶ confess "A table name is required" unless defined($table) && length($table);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and length $table 1 2131 2132
Condition66%2/3
defined $table and length $table
!ll&&!rl&&r
102131
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
1605 2131 ▶ return $self->_map->table($table) // confess "The table '$table' is not in the database map";
Condition100%2/2
$self->_map->table($table) // confess("The table '${table}' is not in the database map")
l!l
21292
MC/DC100%1/1
$self->_map->table($table) // confess("The table '${table}' is not in the database map")
$self->_map->table($table)
Truth table100%2/2
A
A= $self->_map->table($table)
Aresult
11
00
1606 }
1607  
1608 =pod
1609  
1610 =over 4
1611  
1612 =item $conn->_check_fields($table, @fields)
1613  
1614 Croaks for the first field not in the table.
1615  
1616 =back
1617  
1618 =cut
1619  
1620 1569 ▶sub _check_fields {
Subroutine _check_fields: called CC=3 SCAR=11.0
1621 1569 my $self = shift;
1622 1569 my ($table, @fields) = @_;
1623 1569 my $known = $self->_map->table($table)->{fields};
1624 1569 for my $field (@fields) {
1625 1715 ▶ confess "The table '$table' has no field '$field'" unless $known->{$field};
Branch: 1 branch
BranchTrueFalseTotal
unless $known->{$field} 15 1700 1715
1626 }
1627 }
1628  
1629 =pod
1630  
1631 =over 4
1632  
1633 =item \%pk = $conn->_pk_values($table, $pk)
1634  
1635 =item \%pk = $conn->_pk_values($table, $pk, $raw)
1636  
1637 The key-field hash from a primary key in any form C<normalize_pk> in
1638 L<DBIx::QuickORM::Map> takes, each value put through C<deflate> (with C<raw>
1639 when C<$raw> is true). A C<binary> marker is kept for binding. C<_plain> of
1640 the hash is the raw key the lookup table takes. Croaks as C<normalize_pk> does, and on an C<sql> marker.
1641  
1642 =back
1643  
1644 =cut
1645  
1646 403 ▶sub _pk_values {
Subroutine _pk_values: called CC=3 SCAR=11.0
1647 403 my $self = shift;
1648 403 my ($table, $pk, $raw) = @_;
1649  
1650 403 my $map = $self->_map;
1651 403 my $values = $map->normalize_pk($table, $pk);
1652 389 my $fields = $map->pk($table);
1653 389 my $out = $self->deflate($table, {map { $fields->[$_] => $values->[$_] } 0 .. $#$fields}, raw => $raw);
1654 385 for my $field (@$fields) {
1655 399 ▶ 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 398 399
1656 }
1657 384 return $out;
1658 }
1659  
1660 =pod
1661  
1662 =over 4
1663  
1664 =item \@copy = $conn->_check_datetime_parsers(\@parsers)
1665  
1666 A copy of C<@parsers> once each is a code reference, an object with
1667 C<parse_datetime>, or a class name. Loads each class not yet loaded. Croaks
1668 when the shape is wrong, or a class cannot be loaded or has no
1669 C<parse_datetime>.
1670  
1671 =back
1672  
1673 =cut
1674  
1675 19 ▶sub _check_datetime_parsers {
Subroutine _check_datetime_parsers: called CC=10 SCAR=23.1
1676 19 my $self = shift;
1677 19 my ($parsers) = @_;
1678  
1679 croak "'datetime_parsers' must be an arrayref of parsers: classes or objects with parse_datetime, or code references"
1680 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
1681  
1682 15 for my $parser (grep { !ref($_) } @$parsers) {
1683 7 ▶ next if $parser->can('parse_datetime');
Branch: 1 branch
BranchTrueFalseTotal
if $parser->can("parse_datetime") 0 7 7
1684 7 require DBIx::QuickORM;
1685 7 DBIx::QuickORM->load_class("'datetime_parsers' names the class '$parser', which", $parser);
1686 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
1687 }
1688  
1689 11 return [@$parsers];
1690 }
1691  
1692 =pod
1693  
1694 =over 4
1695  
1696 =item $conn->_enforce_canon($table, \%data, $flag)
1697  
1698 Croaks unless the data is canon, when C<$flag> (or its default) says to check.
1699 The message gives the cause from C<canon_status>, the call behind it when
1700 known, and how to go on.
1701  
1702 =back
1703  
1704 =cut
1705  
1706 178 ▶sub _enforce_canon {
Subroutine _enforce_canon: called CC=5 SCAR=16.1
1707 178 my $self = shift;
1708 178 my ($table, $data, $flag) = @_;
1709  
1710 178 my $lookup = $self->lookup;
1711 178 ▶ $flag //= $lookup->in_txn ? 1 : $self->{+ENFORCE_CANON};
Branch: 1 branch
BranchTrueFalseTotal
$lookup->in_txn ? : 23 83 106
Condition66%2/3
$flag //= $lookup->in_txn ? 1 : $self->{"enforce_canon"}
l!l&&r!l&&!r
721060
MC/DC0%0/2
$flag //= $lookup->in_txn ? 1 : $self->{"enforce_canon"}
$flag $lookup->in_txn ? 1 : $self->{"enforce_canon"}
Truth table66%2/3
A //= B
A= $flagB= $lookup->in_txn ? 1 : $self->{"enforce_canon"}
ABresult
1X1
011
000
1712 178 ▶ return unless $flag;
Branch: 1 branch
BranchTrueFalseTotal
unless $flag 75 103 178
1713 103 ▶ my $status = $lookup->canon_status($table, $data) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $status = $lookup->canon_status($table, $data) or return 25 78 103
1714 25 confess "The row data for '$table' is no longer canonical: " . $self->_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";
1715 }
1716  
1717 =pod
1718  
1719 =over 4
1720  
1721 =item $text = $conn->_canon_reason(\%status)
1722  
1723 The cause in a C<canon_status> result as sentences for an error message, with
1724 the call behind it when known. Without C<debug>, no call is recorded, so it
1725 says how to record one instead.
1726  
1727 =back
1728  
1729 =cut
1730  
1731 304 my %CANON_REASON = (
1732 replaced => ['the row was fetched or written again elsewhere in the code, leaving this copy stale.', 'Last replaced by'],
1733 cache_cleared => ['its cached copy was cleared.', 'Last cleared by'],
1734 deleted => ['the row was deleted.', 'Deleted by'],
1735 not_in_db => ['the row is not in the database.'],
1736 txn => ['it was read before the open transaction began, and rows from before a transaction are not canonical in it.'],
1737 not_cached => ['the row cache holds no copy of it (it was read around the cache, its transaction rolled back, or the cache was cleared).', 'Last cache clear:'],
1738 );
1739  
1740 25 ▶sub _canon_reason {
Subroutine _canon_reason: called CC=7 SCAR=19.5
1741 25 my $self = shift;
1742 25 my ($status) = @_;
1743 25 ▶ my ($text, $lead) = @{$CANON_REASON{$status->{cause}} // ["the cause is '$status->{cause}'."]};
Condition50%1/2
$CANON_REASON{$status->{"cause"}} // [qq[the cause is '$status->{"cause"}'.]]
l!l
250
MC/DC0%0/1
$CANON_REASON{$status->{"cause"}} // [qq[the cause is '$status->{"cause"}'.]]
$CANON_REASON{$status->{"cause"}}
Truth table50%1/2
A
A= $CANON_REASON{$status->{"cause"}}
Aresult
11
00
1744 25 ▶ my $frame = $status->{by} // $status->{last_clear};
Condition100%3/3
$status->{"by"} // $status->{"last_clear"}
l!l&&r!l&&!r
2122
MC/DC100%2/2
$status->{"by"} // $status->{"last_clear"}
$status->{"by"} $status->{"last_clear"}
Truth table100%3/3
A // B
A= $status->{"by"}B= $status->{"last_clear"}
ABresult
1X1
011
000
1745 25 ▶ return "$text $lead $frame->[3] call in $frame->[1] at line $frame->[2]." if $lead && $frame;
Branch: 1 branch
BranchTrueFalseTotal
if $lead and $frame 3 22 25
Condition100%3/3
$lead and $frame
!ll&&!rl&&r
3193
MC/DC100%2/2
$lead and $frame
$lead $frame
Truth table100%3/3
A and B
A= $leadB= $frame
ABresult
0X0
100
111
1746 22 ▶ return "$text Construct the ORM with debug => 1 to record which call did it." if $lead && !$self->{+DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $lead and not $self->{"debug"} 18 4 22
Condition100%3/3
$lead and not $self->{"debug"}
!ll&&!rl&&r
3118
MC/DC100%2/2
$lead and not $self->{"debug"}
$lead not $self->{"debug"}
Truth table100%3/3
A and not(B)
A= $leadB= not $self->{"debug"}
ABresult
0X0
100
111
1747 4 return $text;
1748 }
1749  
1750 =pod
1751  
1752 =over 4
1753  
1754 =item %cas = $conn->_cas_values($table, \%data, \%changes, \%params)
1755  
1756 The compare-and-swap fields and their values from the row data.
1757  
1758 =back
1759  
1760 =cut
1761  
1762 116 ▶sub _cas_values {
Subroutine _cas_values: called CC=6 SCAR=17.9
1763 116 my $self = shift;
1764 116 my ($table, $data, $changes, $params) = @_;
1765  
1766 116 ▶ my $cas = $params->{cas} // [];
Condition100%2/2
$params->{"cas"} // []
l!l
3779
MC/DC100%1/1
$params->{"cas"} // []
$params->{"cas"}
Truth table100%2/2
A
A= $params->{"cas"}
Aresult
11
00
1767 116 ▶ confess "'cas' must be an arrayref of field names" unless ref($cas) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cas eq "ARRAY" 1 115 116
1768 115 my @fields = @$cas;
1769 115 ▶ push @fields => grep { exists $data->{$_} } keys %$changes if $params->{auto_cas};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"auto_cas"} 2 113 115
1770 115 $self->_check_fields($table, @fields);
1771  
1772 115 for my $field (@fields) {
1773 38 ▶ 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 34 38
1774 }
1775  
1776 111 return map { $_ => $data->{$_} } @fields;
1777 }
1778  
1779 =pod
1780  
1781 =over 4
1782  
1783 =item $map = $conn->_map
1784  
1785 The map.
1786  
1787 =back
1788  
1789 =cut
1790  
1791 4277 ▶sub _map { $_[0]->{+DB_MAP} }
Subroutine _map: called CC=1 SCAR=0.0
1792  
1793 =pod
1794  
1795 =over 4
1796  
1797 =item \@fields = $conn->_default_fields($table)
1798  
1799 The fields a table's queries select: C<default_fields>, or every field. The
1800 list is shared, so callers never change it.
1801  
1802 =item \%set = $conn->_default_field_set($table)
1803  
1804 The same fields as a hash of field name to true.
1805  
1806 =back
1807  
1808 Both are worked out once per table, when first asked for. The map does not
1809 change once the ORM is built, and a forked child's new Connection works them
1810 out again.
1811  
1812 =cut
1813  
1814 417 ▶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
3021150
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
1815 109 ▶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
10090
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
1816  
1817 124 ▶sub _defaults {
Subroutine _defaults: called CC=2 SCAR=6.9
1818 124 my $self = shift;
1819 124 my ($table) = @_;
1820 124 my $t = $self->_map->table($table);
1821 124 ▶ my $list = $t->{default_fields} // [sort keys %{$t->{fields}}];
Condition100%2/2
$t->{"default_fields"} // [sort(keys %{$$t{"fields"};})]
l!l
12112
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
1822 124 return $self->{+DEFAULTS}->{$table} = [$list, {map { $_ => 1 } @$list}];
1823 }
1824  
1825 =pod
1826  
1827 =over 4
1828  
1829 =item $sql = $conn->_returning_sql(\@fields)
1830  
1831 A C<RETURNING> clause, with a leading space, naming the fields, quoted.
1832  
1833 =back
1834  
1835 =cut
1836  
1837 173 ▶sub _returning_sql {
Subroutine _returning_sql: called CC=1 SCAR=0.0
1838 173 my $self = shift;
1839 173 my ($fields) = @_;
1840 173 my $dialect = $self->{+DIALECT};
1841 173 return ' RETURNING ' . join(', ' => map { $dialect->quote_identifier($_) } @$fields);
1842 }
1843  
1844 =pod
1845  
1846 =over 4
1847  
1848 =item \@fields = $conn->_read_back_fields($table, @names)
1849  
1850 What a write or refresh reads back: the table's default fields, then each of
1851 C<@names> they leave out. Writes pass the fields written, so a row holds what
1852 it just wrote (a JSON field, say). Updates and C<refresh_row> also pass the
1853 fields the row held.
1854  
1855 =back
1856  
1857 =cut
1858  
1859 276 ▶sub _read_back_fields {
Subroutine _read_back_fields: called CC=1 SCAR=0.0
1860 276 my $self = shift;
1861 276 my ($table, @names) = @_;
1862 276 my $default = $self->_default_fields($table);
1863 276 my %seen = map { $_ => 1 } @$default;
1864 276 return [@$default, grep { !$seen{$_}++ } @names];
1865 }
1866  
1867 =pod
1868  
1869 =over 4
1870  
1871 =item ($sql, \@binds, $marked) = $conn->_where_sql(\%pairs)
1872  
1873 A C<WHERE> body comparing each field to its value, in field order. An undef
1874 value becomes C<IS NULL>. Binds are C<[$field, $value]> pairs. An C<sql>
1875 marker croaks. C<$marked> is true when a value is another marker, as for
1876 C<_value_sql>. The SQL is built once per set of fields and null values (see
1877 C<_statement>).
1878  
1879 =back
1880  
1881 =cut
1882  
1883 304 ▶sub _where_sql {
Subroutine _where_sql: called CC=6 SCAR=17.9
1884 304 my $self = shift;
1885 304 my ($pairs) = @_;
1886  
1887 304 my (@shape, @binds, $marked);
1888 304 for my $field (sort keys %$pairs) {
1889 349 my $value = $pairs->{$field};
1890 349 ▶ 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 347 349
1891 347 ▶ $marked = 1 if ref($value) && $self->_is_marker($value);
Branch: 1 branch
BranchTrueFalseTotal
if ref $value and $self->_is_marker($value) 3 344 347
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
34403
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
1892 347 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) { } 344 3 347
1893 344 push @shape => $field;
1894 344 push @binds => [$field => $value];
1895 }
1896 else {
1897 3 push @shape => "\x01$field";
1898 }
1899 }
1900  
1901 302 my $dialect = $self->{+DIALECT};
1902 my $sql = $self->_statement(
1903 join("\0" => 'where', @shape),
1904 81 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1905 81 ▶ 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 98 100
1906 }
1907 302 );
1908  
1909 302 return ($sql, \@binds, $marked);
1910 }
1911  
1912 =pod
1913  
1914 =over 4
1915  
1916 =item $sql = $conn->_statement($shape, \&build)
1917  
1918 The SQL C<build> returns, kept by C<$shape> so it is built once per shape: a
1919 key naming the statement kind, the table, and its fields in order. An undef
1920 shape (a statement with a marker, see C<_value_sql>) builds it every time.
1921  
1922 =back
1923  
1924 =cut
1925  
1926 912 ▶sub _statement {
Subroutine _statement: called CC=3 SCAR=11.0
1927 912 my $self = shift;
1928 912 my ($shape, $build) = @_;
1929 912 ▶ return $build->() unless defined $shape;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $shape 15 897 912
1930 897 ▶ return $self->{+STATEMENTS}->{$shape} //= $build->();
Condition66%2/3
$self->{"statements"}{$shape} //= &$build()
l!l&&r!l&&!r
5023950
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
1931 }
1932  
1933 =pod
1934  
1935 =over 4
1936  
1937 =item $sth = $conn->_run(\%fields, $sql, \@binds)
1938  
1939 =item $sth = $conn->_run(\%fields, $sql, \@binds, \%prepare_attrs, $cached)
1940  
1941 Prepares and executes the SQL, the one place the CRUD operations bind values.
1942 With C<$cached> the statement comes from C<prepare_cached>, for the
1943 single-row CRUD operations' fixed SQL only.
1944  
1945 Every statement the Connection sends comes through here or C<_run_plain>,
1946 so both croak while an async query is pending (see C<select>), and while the
1947 innermost transaction is marked failed, unless the statement rolls it back. Each bind is
1948 C<[$name, $value]>. The field record C<$fields{$name}> (none for an undef
1949 name) decides the bind attributes, except that a C<binary> marker is bound as
1950 binary. The SQL and every value not going to a binary field pass through the
1951 dialect's C<text_to_db>.
1952  
1953 =back
1954  
1955 =cut
1956  
1957 1275 ▶sub _run {
Subroutine _run: called CC=12 SCAR=24.9
1958 1275 my $self = shift;
1959 1275 my ($fields, $sql, $binds, $attrs, $cached) = @_;
1960  
1961 1275 $self->_run_guard($sql);
1962 1270 my $dialect = $self->{+DIALECT};
1963  
1964 1270 my (@values, @attrs, @text, %attrs_of);
1965 1270 for my $bind (@$binds) {
1966 2455 my ($name, $value) = @$bind;
1967 2455 ▶ my $field = defined($name) ? $fields->{$name} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 2428 27 2455
1968 2455 ▶ my $attrs = $field ? ($attrs_of{$field} //= [$dialect->bind_attrs($field)])->[0] : undef; # once per field record
Branch: 1 branch
BranchTrueFalseTotal
$field ? : 2425 30 2455
Condition100%2/2
$attrs_of{$field} //= [$dialect->bind_attrs($field)]
l!l
10431382
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
1969 2455 ▶ if (ref($value) && $self->_is_marker($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and $self->_is_marker($value)) 10 2445 2455
Condition66%2/3
ref $value and $self->_is_marker($value)
!ll&&!rl&&r
2445010
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
1970 10 ▶ confess "A " . $value->kind . "() marker cannot be bound here" unless $value->kind eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $value->kind eq "binary" 0 10 10
1971 10 ($field, $value) = ({affinity => 'binary'}, $value->value);
1972 10 $attrs = $dialect->bind_attrs($field);
1973 }
1974 2455 ▶ push @text => scalar(@values) unless $field && $field->{affinity} eq 'binary';
Branch: 1 branch
BranchTrueFalseTotal
unless $field and $field->{"affinity"} eq "binary" 2404 51 2455
Condition100%3/3
$field and $field->{"affinity"} eq "binary"
!ll&&!rl&&r
29237551
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
1975 2455 push @values => $value;
1976 2455 push @attrs => $attrs;
1977 }
1978 1270 $dialect->text_to_db($sql, @values[@text]);
1979  
1980 # 3: a cached statement still active is left alone and a new one prepared.
1981 1270 ▶ my $sth = $cached ? $self->{+DBH}->prepare_cached($sql, $attrs, 3) : $self->{+DBH}->prepare($sql, $attrs);
Branch: 1 branch
BranchTrueFalseTotal
$cached ? : 647 623 1270
1982 1257 $sth->bind_param($_ + 1, $values[$_], $attrs[$_]) for 0 .. $#values;
1983 1257 $sth->execute;
1984  
1985 1243 return $sth;
1986 }
1987  
1988 =pod
1989  
1990 =over 4
1991  
1992 =item $sth = $conn->_run_plain($sql, \@values)
1993  
1994 C<_run> for values that need no bind attributes: no markers and no field
1995 whose C<bind_attrs> is defined. It runs the same checks, passes the SQL and
1996 every value through C<text_to_db>, and executes with the values in order.
1997 C<insert_many> uses it for batches of plain values.
1998  
1999 =item $conn->_run_guard($sql)
2000  
2001 The checks C<_run> and C<_run_plain> make before sending C<$sql>.
2002  
2003 =back
2004  
2005 =cut
2006  
2007 58 ▶sub _run_plain {
Subroutine _run_plain: called CC=1 SCAR=0.0
2008 58 my $self = shift;
2009 58 my ($sql, $values) = @_;
2010  
2011 58 $self->_run_guard($sql);
2012 58 $self->{+DIALECT}->text_to_db($sql, @$values);
2013 58 my $sth = $self->{+DBH}->prepare($sql);
2014 57 $sth->execute(@$values);
2015  
2016 55 return $sth;
2017 }
2018  
2019 1333 ▶sub _run_guard {
Subroutine _run_guard: called CC=4 SCAR=13.9
2020 1333 my $self = shift;
2021 1333 my ($sql) = @_;
2022  
2023 1333 $self->_check_idle;
2024 1333 ▶ my $txn = $self->{+TXNS}->[-1] or return;
Branch: 1 branch
BranchTrueFalseTotal
my $txn = $self->{"txns"}[-1] or return 356 977 1333
2025  
2026 # RELEASE SAVEPOINT reaches a failed level only after ROLLBACK TO it: commit_txn rolls a failed level back first.
2027 356 ▶ 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 351 356
Condition100%3/3
defined $txn->failed and not $sql =~ /^(?:ROLLBACK|RELEASE SAVEPOINT)\b/
!ll&&!rl&&r
335165
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
2028 if defined($txn->failed) && $sql !~ m/^(?:ROLLBACK|RELEASE SAVEPOINT)\b/;
2029 }
2030  
2031 =pod
2032  
2033 =over 4
2034  
2035 =item $conn->_check_idle
2036  
2037 Croaks while an async query is pending.
2038  
2039 =back
2040  
2041 =cut
2042  
2043 1451 ▶sub _check_idle {
Subroutine _check_idle: called CC=2 SCAR=7.2
2044 1451 my $self = shift;
2045 1451 ▶ 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 1451 1451
2046 }
2047  
2048 =pod
2049  
2050 =over 4
2051  
2052 =item $conn->_do($sql)
2053  
2054 Runs a transaction statement through C<_run>.
2055  
2056 =back
2057  
2058 =cut
2059  
2060 311 ▶sub _do { $_[0]->_run({}, $_[1], []) }
Subroutine _do: called CC=1 SCAR=0.0
2061  
2062 =pod
2063  
2064 =over 4
2065  
2066 =item \@rows = $conn->_fetch(\%fields, $sth)
2067  
2068 Every remaining row of an executed statement, as hashes keyed by column name.
2069 It is the one place the CRUD operations fetch rows. The names and every value
2070 not from a binary field (by C<$fields{$name}>) pass through the dialect's
2071 C<text_from_db>.
2072  
2073 =back
2074  
2075 =cut
2076  
2077 780 ▶sub _fetch {
Subroutine _fetch: called CC=6 SCAR=17.9
2078 780 my $self = shift;
2079 780 my ($fields, $sth) = @_;
2080  
2081 780 my $dialect = $self->{+DIALECT};
2082  
2083 780 my @names = @{$sth->{NAME}};
2084 780 $dialect->text_from_db(@names);
2085  
2086 # Most dialects keep the base text_from_db, which does nothing, so their rows skip the call.
2087 780 my $decodes = $dialect->can('text_from_db') != \&DBIx::QuickORM::Dialect::text_from_db;
2088 780 ▶ my @text = $decodes ? grep { (($fields->{$names[$_]} // {})->{affinity} // '') ne 'binary' } 0 .. $#names : ();
Branch: 1 branch
BranchTrueFalseTotal
$decodes ? : 1 779 780
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
2089  
2090 780 my @rows;
2091 780 ▶ while (my $row = $sth->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $sth->fetchrow_arrayref) 1319 780 2099
2092 1319 my %row;
2093 1319 ▶ if (@text) {
Branch: 1 branch
BranchTrueFalseTotal
if (@text) { } 1 1318 1319
2094 1 my @values = @$row;
2095 1 $dialect->text_from_db(@values[@text]);
2096 1 @row{@names} = @values;
2097 }
2098 else {
2099 1318 @row{@names} = @$row;
2100 }
2101 1319 push @rows => \%row;
2102 }
2103  
2104 780 return \@rows;
2105 }
2106  
2107 =pod
2108  
2109 =over 4
2110  
2111 =item $level = $conn->_isolation($level)
2112  
2113 The level in lower case. Confesses unless it is one C<txn> takes or
2114 C<'server'>.
2115  
2116 =back
2117  
2118 =cut
2119  
2120 10 ▶sub _isolation {
Subroutine _isolation: called CC=4 SCAR=14.3
2121 10 my $self = shift;
2122 10 my ($level) = @_;
2123 10 ▶ 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} 8 2 10
Condition50%3/6
defined $level and not ref $level and $ISOLATION{lc $level}
!ll&&!rl&&r
028
defined $level and not ref $level
!ll&&!rl&&r
0010
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
2124 2 confess "'isolation' must be one of: " . join(', ' => map { "'$_'" } @ISOLATION);
2125 }
2126  
2127 =pod
2128  
2129 =over 4
2130  
2131 =item $txn = $conn->_begin(\@caller, $level)
2132  
2133 Opens a transaction or savepoint and pushes it onto the stack. C<$level> is
2134 the root transaction's isolation level from C<txn>, or undef.
2135  
2136 A root transaction always states its level: C<$level>, else the Connection's
2137 C<isolation>, else C<'read committed'> where the dialect
2138 C<supports_isolation>. C<'server'> sends the dialect's plain C<begin_sql>.
2139  
2140 =back
2141  
2142 =cut
2143  
2144 152 ▶sub _begin {
Subroutine _begin: called CC=8 SCAR=20.8
2145 152 my $self = shift;
2146 152 my ($caller, $level) = @_;
2147  
2148 152 my $txns = $self->{+TXNS};
2149 152 my $dialect = $self->{+DIALECT};
2150 152 my $name = 'qorm_txn_' . ++$self->{+TXN_COUNT};
2151 152 ▶ if (@$txns) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$txns) { } 32 120 152
2152 32 ▶ 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 32 32
2153 32 $self->_do("SAVEPOINT $name");
2154 31 $self->lookup->push_level;
2155 }
2156 else {
2157 120 ▶ $level //= $self->{+ISOLATION} // ($dialect->supports_isolation ? 'read committed' : 'server');
Branch: 1 branch
BranchTrueFalseTotal
$dialect->supports_isolation ? : 0 115 115
Condition100%4/4
$level //= $self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
l!l
4116
$self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
l!l
1115
MC/DC100%1/1
$level //= $self->{"isolation"} // ($dialect->supports_isolation ? "read committed" : "server")
$level
Truth table100%2/2
A
A= $level
Aresult
11
00
2158 120 ▶ $self->_do($_) for $dialect->begin_sql($level eq 'server' ? undef : uc $level);
Branch: 1 branch
BranchTrueFalseTotal
$level eq 'server' ? : 117 3 120
2159 116 $self->lookup->begin_root;
2160 }
2161  
2162 147 my $txn = DBIx::QuickORM::Txn->new(connection => $self, name => $name, depth => @$txns + 1, caller => $caller);
2163 147 weaken($txns->[@$txns] = $txn);
2164 147 return $txn;
2165 }
2166  
2167 =pod
2168  
2169 =over 4
2170  
2171 =item ($ok, $err, @out) = $conn->_run_block($code, \@caller, $list, $level)
2172  
2173 Runs one attempt of a transaction block, as C<txn> describes, and reports how
2174 it ended, including a failure to open the transaction. A failed rollback after
2175 the block threw is a warning, so the block's exception is what propagates. The
2176 transaction is then abandoned (C<_abandon>).
2177  
2178 =back
2179  
2180 =cut
2181  
2182 97 ▶sub _run_block {
Subroutine _run_block: called CC=7 SCAR=19.5
2183 97 my $self = shift;
2184 97 my ($code, $caller, $list, $level) = @_;
2185  
2186 97 ▶ 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, $@ 93 4 97
2187 93 my @out;
2188 93 my $ok = eval {
2189 93 ▶ if ($list) { @out = $code->($txn) }
Branch: 1 branch
BranchTrueFalseTotal
if ($list) { } 4 89 93
2190 89 else { $out[0] = $code->($txn) }
2191 71 ▶ $self->commit_txn($txn) if $self->_is_open($txn);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_is_open($txn) 51 20 71
2192 69 1;
2193 };
2194 93 ▶ return (1, undef, @out) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 69 24 93
2195  
2196 24 my $err = $@;
2197 24 ▶ 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 22 24
Condition100%3/3
$self->_is_open($txn) and not eval { do { $self->_unwind($txn); 1 } }
!ll&&!rl&&r
1212
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
2198 2 warn "Rolling back the transaction opened at " . $txn->opened_at . " after its block threw an exception failed: $@";
2199 2 $self->_abandon($txn);
2200 }
2201 24 return (0, $err);
2202 }
2203  
2204 =pod
2205  
2206 =over 4
2207  
2208 =item $bool = $conn->_retriable($err)
2209  
2210 True for a L<DBIx::QuickORM::Exception::DB> whose C<retriable> is true.
2211  
2212 =back
2213  
2214 =cut
2215  
2216 9 ▶sub _retriable {
Subroutine _retriable: called CC=4 SCAR=13.9
2217 9 my $self = shift;
2218 9 my ($err) = @_;
2219 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
2220 8 ▶ return $err->retriable ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$err->retriable ? : 6 2 8
2221 }
2222  
2223 =pod
2224  
2225 =over 4
2226  
2227 =item $bool = $conn->_is_open($txn)
2228  
2229 True while the transaction is on the stack.
2230  
2231 =back
2232  
2233 =cut
2234  
2235 366 ▶sub _is_open {
Subroutine _is_open: called CC=3 SCAR=11.0
2236 366 my $self = shift;
2237 366 my ($txn) = @_;
2238 366 my $open = $self->{+TXNS}->[$txn->depth - 1];
2239 366 ▶ return $open && $open == $txn ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$open && $open == $txn ? : 200 166 366
Condition100%3/3
$open and $open == $txn
!ll&&!rl&&r
1588200
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
2240 }
2241  
2242 =pod
2243  
2244 =over 4
2245  
2246 =item $conn->_check_open($txn, $action)
2247  
2248 Croaks unless the transaction is open and innermost, and this is the process
2249 that opened it.
2250  
2251 =back
2252  
2253 =cut
2254  
2255 124 ▶sub _check_open {
Subroutine _check_open: called CC=4 SCAR=13.9
2256 124 my $self = shift;
2257 124 my ($txn, $action) = @_;
2258  
2259 124 my $where = $txn->opened_at;
2260 124 ▶ 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 124 124
2261 124 ▶ 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 121 124
2262 121 ▶ 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 118 121
2263 }
2264  
2265 =pod
2266  
2267 =over 4
2268  
2269 =item $conn->_unwind($txn)
2270  
2271 Rolls the transaction back, with every transaction open inside it, then drops
2272 them from the stack and the lookup table. An async query still pending is
2273 cancelled first, warning if that fails. Nothing is dropped when the database
2274 refuses the rollback.
2275  
2276 =back
2277  
2278 =cut
2279  
2280 82 ▶sub _unwind {
Subroutine _unwind: called CC=4 SCAR=16.0
2281 82 my $self = shift;
2282 82 my ($txn) = @_;
2283  
2284 # A query left pending inside it cannot be collected any more. On PostgreSQL the cancel aborts the transaction.
2285 82 ▶ if (my $busy = $self->{+BUSY}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $busy = $self->{"busy"}) 0 82 82
2286 0 local $@;
2287 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
2288 }
2289  
2290 82 ▶ if ($txn->depth == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($txn->depth == 1) { } 65 17 82
2291 65 $self->_do('ROLLBACK');
2292 }
2293 else {
2294 17 $self->_do('ROLLBACK TO SAVEPOINT ' . $txn->name);
2295 14 $self->_do('RELEASE SAVEPOINT ' . $txn->name);
2296 }
2297  
2298 75 $self->_drop_levels($txn);
2299 }
2300  
2301 =pod
2302  
2303 =over 4
2304  
2305 =item $conn->_drop_levels($txn)
2306  
2307 Drops the transaction, and every transaction open inside it, from the stack
2308 and the lookup table, without SQL.
2309  
2310 =back
2311  
2312 =cut
2313  
2314 81 ▶sub _drop_levels {
Subroutine _drop_levels: called CC=2 SCAR=6.9
2315 81 my $self = shift;
2316 81 my ($txn) = @_;
2317  
2318 81 my $txns = $self->{+TXNS};
2319 81 my $lookup = $self->lookup;
2320 81 ▶ while (@$txns >= $txn->depth) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$txns >= $txn->depth) 83 81 164
2321 83 pop @$txns;
2322 83 $lookup->rollback_level;
2323 }
2324 }
2325  
2326 =pod
2327  
2328 =over 4
2329  
2330 =item $conn->_abandon($txn)
2331  
2332 For a transaction whose outcome is unknown: drops it as C<_drop_levels> does,
2333 then empties every remaining transaction lookup level, so no row held from
2334 inside the transaction is canon. The outside level is kept.
2335  
2336 =back
2337  
2338 =cut
2339  
2340 6 ▶sub _abandon {
Subroutine _abandon: called CC=1 SCAR=0.0
2341 6 my $self = shift;
2342 6 my ($txn) = @_;
2343 6 $self->_drop_levels($txn);
2344 6 $self->lookup->clear_txn_levels;
2345 }
2346  
2347 392 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=13.9
2348 392 my $self = shift;
2349 392 ▶ return if !$self->{+PID} || $self->{+PID} == $$;
Branch: 1 branch
BranchTrueFalseTotal
if not $self->{"pid"} or $self->{"pid"} == $$ 386 6 392
Condition100%3/3
not $self->{"pid"} or $self->{"pid"} == $$
l!l&&r!l&&!r
463406
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
2350  
2351 # By now DBI has torn its handles down. Any still alive at exit were released before that.
2352 6 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 6 6
2353  
2354 6 $self->release_inherited;
2355 }
2356  
2357 # A child that exits with the parent's async query still pending would otherwise free the handle and the
2358 # statement in any order during global destruction. DBD::Pg 3.21.2, freeing the statement after its handle,
2359 # reads freed memory (https://github.com/bucardo/dbdpg/issues/218) and can wait on the query, taking the
2360 # parent's result off the shared socket.
2361 304 ▶END {
Subroutine END: called CC=2 SCAR=11.6
2362 0 ▶ local ($?, $@, $!);
Subroutine END: not called CC=2 SCAR=11.6
2363 0 $_->release_inherited for grep { $_ } values %PENDING;
2364 }
2365  
2366 304 1;
2367  
2368 __END__
« blib/lib/DBIx/QuickORM/Map.pm ↑ Summary blib/lib/DBIx/QuickORM/AggregateRow.pm »