blib/lib/DBIx/QuickORM.pm

filter: Statementstmt 96.3% 818 / 849 Branchbran 90.5% 411 / 454 Conditioncond 76.3% 304 / 398 MC/DCmcdc 57.5% 133 / 231 Subroutinesub 97.5% 120 / 123 Podpod 94.1% 32 / 34 totaltotal 87.0% 1818 / 2089 CC 759 SCAR 25.2
CC
759
Cov
90%
_insert_fk
30.5
_insert_fk
30.5
_apply_default_fields
24.0
CRAP 12.5
« blib/lib/DBIx/QuickORM/AggregateRow.pm ↑ Summary blib/lib/DBIx/QuickORM/Source/Join.pm »
1 package DBIx::QuickORM;
2 303 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 303 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 303 our $VERSION = '0.000032';
6  
7 303 ▶use Carp qw/carp croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 303 ▶use List::Util qw/first/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 303 ▶use Scalar::Util qw/blessed/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 303 ▶use DBI();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 303 ▶use DBIx::QuickORM::Connection();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 303 ▶use DBIx::QuickORM::Handle();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 303 ▶use DBIx::QuickORM::LookupTable();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 303 ▶use DBIx::QuickORM::Map();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 303 ▶use DBIx::QuickORM::Row();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 303 ▶use DBIx::QuickORM::Source::Query();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 303 ▶use DBIx::QuickORM::Source::Table();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 303 ▶use DBIx::QuickORM::SQLBuilder::SQLAbstract();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 303 ▶use DBIx::QuickORM::WhereBuilder::RawSQL();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 303 ▶use DBIx::QuickORM::WhereBuilder::Simple();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 303 ▶use DBIx::QuickORM::WhereBuilder::SQLAbstract();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 303 ▶use DBIx::QuickORM::Value qw/raw sql/;
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 # Our own new() wraps init(). Predeclared so Object::HashBase does not add one.
26 sub new;
27  
28 303 ▶use Object::HashBase qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
29 <row_class
30 <row_classes
31 <row_namespace
32 <row_class_name
33 <omit
34 <default_fields
35 <auto_omit
36 <debug
37 <types
38 <autotype
39 <append_autotype
40 <fks
41 <sql_builder
42 <connector
43 +connection
44 <_can_connect
45 <like_aggregates
46 <type_options
47 +table_sources
48 +table_fields
49 <where_builders
50 +fast_bless
51 303 };
52  
53 =pod
54  
55 =encoding UTF-8
56  
57 =head1 NAME
58  
59 DBIx::QuickORM - An ORM that quickly gives you what you need with minimal boilerplate, and easily extends to more complex use cases.
60  
61 =head1 EXPERIMENTAL STATUS
62  
63 This distribution is still considered experimental and may change
64 significantly without warning.
65  
66 Once we release version 1.x, we will have a settled final shape and will be
67 careful about breaking public APIs. Until then there is no guarantee of
68 compatibility between releases.
69  
70 =head1 WHERE TO START
71  
72 New to the ORM? Read L<DBIx::QuickORM::Manual::Quickstart>: short examples of
73 everything most applications need. See L<DBIx::QuickORM::Manual> for
74 additional resources.
75  
76 =head1 AI/LLM POLICY AND INFORMATION
77  
78 This project does allow the use of AI/LLM in contributions. However, it is not a
79 low-effort "slop" project. The project was originally entirely hand-coded
80 without AI/LLM, and its intended audience is humans writing code, not bots. It
81 has since been reworked several times and AI/LLM tools have been used to
82 shuffle around and restructure much of the code. It was never unreviewed or
83 low-effort.
84  
85 I cannot promise some hard to read AI documentation will not slip through, and
86 I cannot promise the AI/LLM portions of the code are bug free. But I can say
87 they have been held to the same standard as any human contribution, including
88 my own. Humans can also write bugs and bad documentation. I do review what
89 agents produce, and I have caught many cases of terrible documentation wording,
90 terrible code, and bugs where the agent was a moron. I am sure plenty of others
91 have slipped through despite my thorough review.
92  
93 If you want to avoid AI/LLM code completely, use another distribution. If you
94 want to send me slop or unreviewed and terrible low-effort PRs then use
95 another distribution. Responsible and vetted AI use is perfectly acceptable.
96  
97 Discussions, PRs and bug reports should remain civil, and must not become a
98 place to debate if or when AI/LLM should be used. That said, we absolutely can
99 call out low-effort slop, and reject it for that reason. But AI/LLM being
100 involved is not in itself enough to reject submissions, so long as the quality
101 is good, and the person submitting it understands it, reviews it, and stands by
102 it.
103  
104 The full AI/LLM policy is covered in the AI_AND_LLM_POLICY.md file included with
105 this distribution.
106  
107 =head1 DESCRIPTION
108  
109 Connect and start working. DBIx::QuickORM scans the live database and uses
110 what it finds as the schema. There is no schema, table, or column metadata
111 to declare. Most of it is automatic. Insert, find, update, delete, and query
112 rows right away.
113  
114 Rows come back as L<DBIx::QuickORM::Row> objects, but custom row classes can be
115 defined, or you can request plain hashrefs be returned if you do not want the
116 overhead of a full row object.
117  
118 When the scan gets something wrong, or you need custom behavior, it is easy to
119 adjust: omit fields by default, give a field a data type for inflation, add
120 foreign keys the database does not declare, and so on. See C<new> (under
121 L</Constructor>), or the easy to use DSL (L<DBIx::QuickORM::DSL>), for details.
122  
123 Larger applications can declare the ORM and its row classes in their own
124 modules. See L<DBIx::QuickORM::ORM>.
125  
126 Supported databases: PostgreSQL, MySQL, MariaDB, SQLite, and DuckDB.
127  
128 =head1 SYNOPSIS
129  
130 use DBIx::QuickORM;
131  
132 my $orm = DBIx::QuickORM->new(
133 credentials => {
134 dsn => $dsn,
135 user => $user,
136 pass => $pass,
137 },
138 );
139  
140 my $bob = $orm->insert(users => {name => 'Bob'});
141 my $row = $orm->find(users => $bob->field('id'));
142  
143 $bob->update({name => 'Robert'});
144  
145 my @roberts = $orm->handle('users')
146 ->where({name => 'Robert'})
147 ->all;
148  
149 $orm->txn(sub {
150 $orm->insert(users => {name => 'Ann'});
151 $orm->insert(users => {name => 'Cy'});
152 });
153  
154 $bob->delete;
155  
156 =head1 PUBLIC METHODS
157  
158 =head2 Constructor
159  
160 =over 4
161  
162 =item $orm = DBIx::QuickORM->new(%args)
163  
164 =item $orm = DBIx::QuickORM->new(\%args)
165  
166 Connects, scans the database into a map of its tables and fields
167 (L<DBIx::QuickORM::Map>), and returns the ORM. Pass exactly one of C<dbh>,
168 C<connect>, or C<credentials>. An unknown argument croaks.
169  
170 my $orm = DBIx::QuickORM->new(
171 credentials => {
172 dsn => $dsn,
173 user => $user,
174 pass => $pass,
175 },
176 omit => {users => ['prefs']}, # selected only when asked for
177 row_classes => {posts => undef}, # posts come back as plain hashrefs
178 retain_cache => 1, # keep rows cached until clear_cache()
179 );
180  
181 The connection argument, one of:
182  
183 =over 4
184  
185 =item dbh => $dbh
186  
187 A connected L<DBI> handle with C<RaiseError> and C<AutoCommit> on. The ORM
188 takes it over and may change its attributes. Using it elsewhere is
189 unsupported.
190  
191 With this form the ORM cannot open a second connection: using the ORM from a
192 forked child croaks, and so do C<aside> and C<forked> on its handles (see
193 L<DBIx::QuickORM::Handle/Running elsewhere>).
194  
195 =item connect => sub { ... }
196  
197 A code reference that returns a new, uncached handle with C<RaiseError> and
198 C<AutoCommit> on each time it is called.
199  
200 =item credentials => {dsn => $dsn, user => $user, pass => $pass, attrs => \%attrs}
201  
202 Arguments for C<< DBI->connect >>. C<dsn> is required. C<user>, C<pass>, and
203 C<attrs> are optional. Other keys croak. C<RaiseError> and C<AutoCommit> are
204 always turned on, and C<AutoCommit> given false in C<attrs> croaks.
205  
206 =back
207  
208 The ORM manages transactions, so every form needs C<AutoCommit> on. A handle
209 with C<AutoCommit> off, or with a transaction already open, croaks.
210  
211 The remaining arguments adjust the map. The database is scanned into a
212 L<DBIx::QuickORM::Map> unless C<db_map> is given, once per process (see
213 C<rescan>). These arguments then change it, in this order. Each type or row class they name is loaded during C<new>.
214  
215 Naming a table or field not in the map croaks, as does an argument of the
216 wrong type.
217  
218 =over 4
219  
220 =item db_map => $map
221  
222 A L<DBIx::QuickORM::Map>, or a hashref of map data, used instead of a scan.
223 It is deep-copied, so the original is never changed. The arguments below
224 adjust the copy.
225  
226 =item rescan => 1
227  
228 Scans the database even when this process scanned it before.
229  
230 The first scan of a database in a process is kept, and every later C<new>
231 without a C<db_map> starts from a copy of it, so building an ORM again (after
232 a lost connection, say) does not scan again. Each ORM still applies its own
233 arguments to its copy. The cache is keyed by which database the connection
234 reaches and what the session sees of it: the server, database, user, and
235 schema (or search path, or active roles), or the database file. In-memory
236 SQLite and DuckDB databases are never cached.
237  
238 Tables changed after the first scan are not seen. Pass C<rescan> after
239 changing tables in a running process, as a migration script does, or restart
240 the process. L<DBIx::QuickORM::Connection/"The scan cache"> has the details.
241  
242 =item autotype => \@types
243  
244 =item autotype => undef
245  
246 =item append_autotype => \@types
247  
248 The types tried, in order, on each field when the map is built. The first
249 that matches becomes the field's C<orm_type>. Default: C<UUID>, C<JSON>, then
250 C<DateTime> (L<DBIx::QuickORM::Type::UUID>, L<DBIx::QuickORM::Type::JSON>,
251 L<DBIx::QuickORM::Type::DateTime>).
252  
253 C<< autotype => undef >> or C<[]> turns this off. C<append_autotype> adds to
254 the C<autotype> list, or to the default. With a C<db_map>, the map keeps its
255 types unless either is given. Then every field is typed again.
256  
257 A type matches through its C<base_types> or C<matches> (see
258 L<DBIx::QuickORM::Role::Type>).
259  
260 Type names work the same everywhere: a bare name such as C<JSON> means
261 C<DBIx::QuickORM::Type::JSON>, and a leading C<+> marks a full class name,
262 such as C<+My::Type>. The map holds the full name.
263  
264 Array fields are never typed automatically: those whose C<db_type> ends in
265 C<[]> or C<[N]> (PostgreSQL arrays, DuckDB lists and fixed-size arrays). Use
266 C<types> to give one a type.
267  
268 =item types => {table => {field => $type_or_undef}}
269  
270 =item types => {table => {field => {class => $type_or_undef, format => \&code, generate => $mode}}}
271  
272 Sets a field's type. Undef removes it.
273  
274 The hashref form also sets field hints: C<format> and C<generate> (see
275 L<DBIx::QuickORM::Role::Type/Field hints>). Without C<class> it keeps the
276 field's type.
277  
278 Either form replaces the field's hints with the ones given (none for the plain
279 form). C<type_options> then fills in the rest. Other keys croak, and so does a
280 hint on a field left without a type.
281  
282 =item type_options => {$type => {format => \&code, generate => $mode}}
283  
284 Field hints for every field of a type, such as C<< {UUID => {format => sub { uc $_[0] }}} >>.
285 A field's own hints in C<types> win, each hint separately.
286  
287 =item fks => {table => {other_table => [{field => other_field}, ...]}}
288  
289 Foreign keys to add to the scanned ones. A key identical to one the table
290 already has is ignored. A key over the same fields that maps them differently
291 croaks.
292  
293 =item omit => {table => \@fields}
294  
295 =item default_fields => {table => \@fields}
296  
297 Set which fields a table's queries select by default (the table's
298 C<default_fields>).
299  
300 C<omit> selects every field but the ones listed. C<default_fields> selects the
301 ones listed plus the primary key. A table named in neither selects every
302 field, unless a given C<db_map> sets its default fields.
303  
304 Croaks when both name the same table, when C<omit> names a primary key field,
305 or when no field is left.
306  
307 =item auto_omit => {types => \@types, db_types => \@db_types}
308  
309 Leaves fields of these types out of default selects, on every table C<omit>
310 and C<default_fields> do not name. Nothing is left out unless asked. For
311 example, C<< auto_omit => {types => ['JSON'], db_types => ['bytea']} >>.
312  
313 C<types> names ORM types as C<types> does (C<JSON>, C<+My::Type>), matching a
314 field whose C<orm_type> is that class or a subclass. Each is loaded, and one
315 that cannot be croaks. C<db_types> names database types, matched against the
316 field's base type (C<type> in L<DBIx::QuickORM::Map>): lowercased, without
317 sizes or array markers, so C<bytea> also matches C<bytea[]>.
318  
319 A field left out is fetched the first time a row reads it (see
320 L<DBIx::QuickORM::Manual::Caching/"FIELDS LEFT OUT OF A SELECT">).
321  
322 Primary, unique, and foreign key fields are never left out, and neither is any
323 field of a table without a primary key, which a row could not fetch later. A
324 given C<db_map> keeps the default fields it carries, including ones an
325 earlier C<auto_omit> set. Name a table in C<omit> or C<default_fields> to
326 change it. In a table class, a bare C<omit;> selects every field again.
327  
328 =item row_classes => {table => $class_or_undef}
329  
330 The row class for one table's rows. Undef means hashrefs.
331  
332 Every row class named anywhere is loaded unless it already has a C<new>
333 method. One that cannot be loaded croaks.
334  
335 =item row_namespace => $namespace
336  
337 Gives each table a row class under C<$namespace>, named from the table:
338 C<user_posts> gets C<${namespace}::UserPosts>.
339  
340 A table with an entry in C<row_classes> (or in a given C<db_map>) keeps it.
341  
342 A table whose class is not loaded and has no module keeps the default row
343 class. A module that
344 fails to load croaks with its error.
345  
346 A class found this way must do L<DBIx::QuickORM::Role::Row>. One that does
347 not croaks, naming the table and the class.
348  
349 A table name that gives no valid class name (it must start with a letter or
350 C<_> and hold only word characters) warns and keeps the default row class.
351  
352 =item row_class_name => sub { my ($table) = @_; return $name }
353  
354 Replaces how C<row_namespace> names a table's class. It gets the table name
355 and returns the part after the namespace, such as C<'Person'> for C<people>.
356  
357 Returning undef keeps the default row class for that table, without a
358 warning. Returning an invalid name (one holding C<::>, say) warns and keeps
359 the default.
360  
361 =back
362  
363 C<row_class>, C<sql_builder>, C<where_builders>, and C<like_aggregates> are
364 described under L</ATTRIBUTES>. C<retain_cache>, C<enforce_canon>, C<debug>,
365 C<isolation>, C<time_zone> (or C<tz>), and C<datetime_parsers> are described
366 under L</Settings>. A setting of the wrong type croaks.
367  
368 A subclass constructor can pass C<< caller => [caller] >> so errors from
369 C<new> name its own caller's line. It is not kept on the object.
370  
371 =back
372  
373 =cut
374  
375 303 my %ARGS;
376 303 my @DEFAULT_WHERE_BUILDERS = map { "DBIx::QuickORM::WhereBuilder::$_" } qw/RawSQL Simple SQLAbstract/;
377  
378 431 ▶sub new {
Subroutine new: called CC=5 SCAR=21.6
Pod documented
379 0 ▶ my $class = shift;
Subroutine new: not called CC=5 SCAR=21.6
Pod documented
380 0 ▶ my $self = bless(@_ == 1 && ref($_[0]) eq 'HASH' ? {%{$_[0]}} : {@_}, $class);
Branch: 2 branches
BranchTrueFalseTotal
@_ == 1 && ref $_[0] eq 'HASH' ? : 1 430 431
@_ == 1 && ref $_[0] eq 'HASH' ? : 0 0 0
Condition33%2/6
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
43001
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
000
MC/DC50%1/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
MC/DC0%0/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
381 0 ▶ my $frame = delete($self->{caller}) // [caller];
Condition50%2/4
delete $self->{"caller"} // [caller]
l!l
26405
delete $self->{"caller"} // [caller]
l!l
00
MC/DC100%1/1
delete $self->{"caller"} // [caller]
delete $self->{"caller"}
MC/DC0%0/1
delete $self->{"caller"} // [caller]
delete $self->{"caller"}
Truth table100%2/2
A
A= delete $self->{"caller"}
Aresult
11
00
Truth table0%0/2
A
A= delete $self->{"caller"}
Aresult
11
00
382  
383 0 ▶ eval { $self->init; 1 } or _rethrow_at($frame, "$class->new()", $@);
Branch: 2 branches
BranchTrueFalseTotal
eval { do { $self->init; 1 } } or _rethrow_at($frame, "$class->new()", $@) 294 137 431
eval { do { $self->init; 1 } } or _rethrow_at($frame, "$class->new()", $@) 0 0 0
384  
385 0 return $self;
386 }
387  
388 431 ▶sub init {
Subroutine init: called CC=6 SCAR=23.5
Pod undocumented
389 0 ▶ my $self = shift;
Subroutine init: not called CC=6 SCAR=23.5
Pod undocumented
390  
391 0 my @unknown = sort grep { !$ARGS{$_} } keys %$self;
392 0 ▶ croak "Unknown argument(s) to new(): " . join(', ' => @unknown) if @unknown;
Branch: 2 branches
BranchTrueFalseTotal
if @unknown 4 427 431
if @unknown 0 0 0
393  
394 0 $self->_check_args;
395  
396 0 $self->{+CONNECTOR} = $self->_build_connector;
397 0 $self->{+SQL_BUILDER} = $self->_build_sql_builder;
398  
399 0 ▶ $self->{+WHERE_BUILDERS} = $self->_where_builders("'where_builders'", $self->{+WHERE_BUILDERS} // [@DEFAULT_WHERE_BUILDERS]);
Condition50%2/4
$self->{"where_builders"} // [@DEFAULT_WHERE_BUILDERS]
l!l
5388
$self->{"where_builders"} // [@DEFAULT_WHERE_BUILDERS]
l!l
00
MC/DC100%1/1
$self->{"where_builders"} // [@DEFAULT_WHERE_BUILDERS]
$self->{"where_builders"}
MC/DC0%0/1
$self->{"where_builders"} // [@DEFAULT_WHERE_BUILDERS]
$self->{"where_builders"}
Truth table100%2/2
A
A= $self->{"where_builders"}
Aresult
11
00
Truth table0%0/2
A
A= $self->{"where_builders"}
Aresult
11
00
400  
401 0 ▶ $self->{+ROW_CLASS} = 'DBIx::QuickORM::Row' unless exists $self->{+ROW_CLASS};
Branch: 2 branches
BranchTrueFalseTotal
unless exists $self->{"row_class"} 291 100 391
unless exists $self->{"row_class"} 0 0 0
402  
403 0 ▶ my %settings = map { exists($self->{$_}) ? ($_ => delete $self->{$_}) : () } qw/retain_cache enforce_canon isolation time_zone datetime_parsers/;
Branch: 2 branches
BranchTrueFalseTotal
exists $self->{$_} ? : 56 1899 1955
exists $self->{$_} ? : 0 0 0
404 0 my $given = delete $self->{db_map};
405 0 ▶ $self->{+DEBUG} = $self->{+DEBUG} ? 1 : 0; # kept here too, so a call checks it without reaching the Connection
Branch: 2 branches
BranchTrueFalseTotal
$self->{'debug'} ? : 2 389 391
$self->{'debug'} ? : 0 0 0
406 0 my $rescan = delete $self->{rescan};
407 0 my $conn = $self->{+CONNECTION} = $self->_connect(%settings, debug => $self->{+DEBUG}, db_map => $self->_copy_map($given), rescan => $rescan);
408 0 $self->_setup_map($conn->db_map, defined $given);
409 }
410  
411 =pod
412  
413 =head2 Settings
414  
415 =over 4
416  
417 =item $conn = $orm->connection
418  
419 The current L<DBIx::QuickORM::Connection>.
420  
421 In a forked child, the ORM drops the inherited handle without closing the
422 parent's session. It then opens a new Connection from the connector, keeping
423 the map and settings.
424  
425 That croaks when the ORM was given a C<dbh>, and when a second connection
426 cannot reach the same data (an in-memory SQLite database, or DuckDB).
427  
428 =back
429  
430 =cut
431  
432 3768 ▶sub connection {
Subroutine connection: called CC=3 SCAR=15.0
Pod documented
433 0 ▶ my $self = shift;
Subroutine connection: not called CC=3 SCAR=15.0
Pod documented
434  
435 0 my $conn = $self->{+CONNECTION};
436 0 ▶ return $conn if $conn->pid == $$;
Branch: 2 branches
BranchTrueFalseTotal
if $conn->pid == $$ 3765 3 3768
if $conn->pid == $$ 0 0 0
437  
438 0 my $shared = $conn->dialect->supports_second_connection($conn->dbh);
439 0 $conn->release_inherited;
440 0 ▶ croak "This ORM's database cannot be opened by a second connection (an in-memory SQLite database, or DuckDB), so a forked child cannot reconnect" unless $shared;
Branch: 2 branches
BranchTrueFalseTotal
unless $shared 0 3 3
unless $shared 0 0 0
441 0 return $self->{+CONNECTION} = $self->_connect_like($conn);
442 }
443  
444 =pod
445  
446 =over 4
447  
448 =item $map = $orm->db_map
449  
450 The L<DBIx::QuickORM::Map> built when the ORM was constructed.
451  
452 =item $bool = $orm->retain_cache
453  
454 Whether canonical copies stay in the row cache outside a transaction.
455 Default 0.
456  
457 With 0 they are held weakly and freed once nothing else uses them. With 1 they
458 stay until C<clear_cache>.
459  
460 =item $bool = $orm->enforce_canon
461  
462 Whether C<update_row> and C<delete_row> refuse row data that is not
463 canonical. Default 1.
464  
465 Outside a transaction, they croak when given row data that is not the
466 canonical copy. Inside one, the check is on by default whatever this says. Each
467 call can override it.
468  
469 =item $orm->set_enforce_canon($bool)
470  
471 Change C<enforce_canon> on the current Connection, for every write after the
472 call.
473  
474 =item $bool = $orm->debug
475  
476 Whether the ORM records which call made row data stop being canonical, for
477 C<canon_status> and the non-canonical croak. Default 0. Pass
478 C<< debug => 1 >> to C<new> to turn it on.
479  
480 my $orm = DBIx::QuickORM->new(credentials => \%credentials, debug => 1);
481  
482 It adds about 1 to 5 µs to each single-row write and about 1 µs to each
483 C<find>, and nothing per row to a fetch of many rows unless a row it reads
484 replaces a copy already held: 3% to 12% on a loop of small writes, and about
485 1% of a web request's query time.
486 L<DBIx::QuickORM::Manual::Caching/"WHY A ROW IS NOT CANONICAL"> says what it
487 records, and gives the numbers.
488  
489 =item $level = $orm->isolation
490  
491 The default isolation level for outermost transactions. Undef means
492 C<'read committed'>. Takes the levels C<txn> takes (see C<txn> under
493 L</Transactions>).
494  
495 =item $tz = $orm->time_zone
496  
497 The session time zone, C<UTC> unless given. MySQL and MariaDB get C<UTC> as
498 C<+00:00>. SQLite has no session time zone.
499 C<new> also accepts it as C<tz>. Giving both croaks.
500  
501 =item \@parsers = $orm->datetime_parsers
502  
503 Parsers for date and time text that neither the database's own parser nor
504 L<DateTime::Format::ISO8601> reads, tried in order. Empty unless given.
505  
506 use DateTime::Format::Strptime;
507  
508 my $orm = DBIx::QuickORM->new(
509 credentials => {
510 dsn => $dsn,
511 user => $user,
512 pass => $pass,
513 },
514 datetime_parsers => [
515 DateTime::Format::Strptime->new(pattern => '%d/%m/%Y %H:%M'),
516 # epoch seconds
517 sub { $_[0] =~ m/^\d+\z/ ? DateTime->from_epoch(epoch => $_[0]) : undef },
518 ],
519 );
520  
521 Each is a class or object with C<parse_datetime>, or a code reference taking
522 the text. C<new> loads each class, and croaks when one cannot be loaded or has
523 no C<parse_datetime>.
524  
525 A parser says no by returning undef or dying. The first DateTime returned
526 wins. Returning anything else croaks.
527  
528 =item $orm->set_datetime_parsers(\@parsers)
529  
530 Replace C<datetime_parsers> on the current Connection, checked as C<new>
531 checks it, for values read after the call.
532  
533 A DateTime field read before the call keeps the parsers it was read with, even
534 while still unparsed.
535  
536 =back
537  
538 Only C<enforce_canon> and C<datetime_parsers> have setters. The other settings
539 are fixed when the ORM is built. Build a new ORM to change them. A forked
540 child's new Connection keeps the changed values.
541  
542 =cut
543  
544 1473 ▶sub db_map { $_[0]->connection->db_map }
Subroutine db_map: called CC=1 SCAR=0.0
Pod documented
545 4 ▶sub retain_cache { $_[0]->connection->retain_cache }
Subroutine retain_cache: called CC=1 SCAR=0.0
Pod documented
546 3 ▶sub enforce_canon { $_[0]->connection->enforce_canon }
Subroutine enforce_canon: called CC=1 SCAR=0.0
Pod documented
547 2 ▶sub set_enforce_canon { $_[0]->connection->set_enforce_canon($_[1]) }
Subroutine set_enforce_canon: called CC=1 SCAR=0.0
Pod documented
548 4 ▶sub isolation { $_[0]->connection->isolation }
Subroutine isolation: called CC=1 SCAR=0.0
Pod documented
549 7 ▶sub time_zone { $_[0]->connection->time_zone }
Subroutine time_zone: called CC=1 SCAR=0.0
Pod documented
550 3 ▶sub datetime_parsers { $_[0]->connection->datetime_parsers }
Subroutine datetime_parsers: called CC=1 SCAR=0.0
Pod documented
551  
552 5 ▶sub set_datetime_parsers {
Subroutine set_datetime_parsers: called CC=2 SCAR=6.9
Pod documented
553 5 my $self = shift;
554 5 my $frame = [caller];
555 5 ▶ eval { $self->connection->set_datetime_parsers(@_); 1 } or _rethrow_at($frame, 'set_datetime_parsers()', $@);
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->connection->set_datetime_parsers(@_); 1 } } or _rethrow_at($frame, "set_datetime_parsers()", $@) 2 3 5
556 }
557  
558 =pod
559  
560 =head2 The row cache
561  
562 The ORM caches one canonical copy of each row's data, by primary key. A row
563 is canonical when its data is that copy. That does not mean it matches the
564 database right now.
565  
566 =over 4
567  
568 =item $bool = $orm->is_canon($table, $row_or_data)
569  
570 True when the row data (or a row object's C<row_data>) is the canonical copy
571 for its primary key.
572  
573 False when it is not, or when the row cache has no copy for that key. Croaks
574 when the primary key cannot be determined.
575  
576 So a row missing part of its key (a new row from C<vivify>, say) croaks here,
577 while the row's own C<is_canon> answers false.
578  
579 =item $status = $orm->canon_status($table, $row_or_data)
580  
581 Why the row data (or a row object's C<row_data>) is not the canonical copy:
582 undef while it is, otherwise a hashref with its C<cause>. A row's own
583 C<canon_status> calls this.
584  
585 =over 4
586  
587 =item C<replaced>
588  
589 Another copy took its place: a read of changed data or of fewer fields, a
590 write, or a primary key change.
591  
592 =item C<cache_cleared>
593  
594 Its copy was cleared on its own (C<< clear_cache($table => $pk) >>).
595  
596 =item C<txn>
597  
598 It was read before the open transaction began.
599  
600 =item C<deleted>
601  
602 The row was deleted, or found gone.
603  
604 =item C<not_in_db>
605  
606 The row is not in the database: built by C<vivify>, or its insert was rolled
607 back.
608  
609 =item C<not_cached>
610  
611 The row cache holds no copy of it: it was read around the cache (C<no_cache>,
612 C<bare>), its transaction rolled back, or its table or the whole cache was
613 cleared.
614  
615 =back
616  
617 C<by> is the call behind a C<replaced>, C<cache_cleared>, or C<deleted>, and
618 C<last_clear> the call that last cleared the table or the whole cache for a
619 C<not_cached>, each when known, as a C<caller> frame: package, file, line, and
620 the public method called. When a public method calls another, the outer one is
621 recorded. They are recorded only with C<< debug => 1 >> (see C<debug>).
622  
623 Without C<debug> the cause is what can be worked out when asked: row data
624 whose key another hash holds is C<replaced> (a copy that was never canonical
625 looks the same), and a cleared key is C<not_cached>.
626  
627 # with debug => 1
628 my $one = $orm->find(users => $id);
629 my $two = $orm->handle('users')->fields(['name'])->where({id => $id})->only;
630  
631 my $why = $orm->canon_status(users => $one);
632 # {cause => 'replaced', by => ['main', 'app.pl', 3, 'DBIx::QuickORM::Handle::only']}
633  
634 Writing non-canonical row data croaks naming the same cause and call. A row
635 object that is deleted or not in the database is refused earlier by the row
636 method, with its own error.
637  
638 A deleted or C<not_in_db> row needs no primary key here. Any other croaks as
639 C<is_canon> does when the key cannot be determined.
640  
641 =item $orm->clear_cache
642  
643 =item $orm->clear_cache($table)
644  
645 =item $orm->clear_cache($table => $pk)
646  
647 Forgets canonical copies: all of them, one table's, or one row's.
648 They are read from the database again when next looked up.
649  
650 my $user = $orm->find(users => $id);
651 my $held = $orm->is_canon(users => $user); # true: $user's data is the canonical copy
652  
653 $orm->clear_cache(users => $id); # or clear_cache('users'), or clear_cache()
654 my $still = $orm->is_canon(users => $user); # false
655 $user->refresh; # canonical again
656  
657 C<$pk> takes the forms C<find> takes (see L<DBIx::QuickORM::Handle>), and its
658 values are deflated (turned into database form) the same way.
659  
660 A typed key matches in any form: a C<DateTime> or the database's text, a
661 UUID in upper case or as 16 bytes.
662  
663 Inside a transaction, it clears the current transaction or savepoint level,
664 and the cache from before the outermost transaction. A savepoint rollback
665 restores what the enclosing level held. L</Transactions> says what ending the
666 outermost transaction does.
667  
668 A handle that already ran keeps its rows. Call its C<clear> to query again.
669  
670 =back
671  
672 =cut
673  
674 105 ▶sub is_canon { my $self = shift; $self->connection->is_canon(@_) }
Subroutine is_canon: called CC=1 SCAR=0.0
Pod documented
675 25 ▶sub canon_status { my $self = shift; $self->connection->canon_status(@_) }
Subroutine canon_status: called CC=1 SCAR=0.0
Pod documented
676  
677 61 ▶sub clear_cache {
Subroutine clear_cache: called CC=4 SCAR=13.9
Pod documented
678 61 my $self = shift;
679 61 my ($table, @pk) = @_;
680 61 my $conn = $self->connection;
681 61 my $lookup = $conn->lookup;
682 61 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $self->{+DEBUG} && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} and not $lookup->{"caller"} 2 59 61
Condition66%2/3
$self->{"debug"} and not $lookup->{"caller"}
!ll&&!rl&&r
5902
MC/DC50%1/2
$self->{"debug"} and not $lookup->{"caller"}
$self->{"debug"} not $lookup->{"caller"}
Truth table66%2/3
A and not(B)
A= $self->{"debug"}B= not $lookup->{"caller"}
ABresult
0X0
100
111
683 61 ▶ return $lookup->forget(@_) unless @pk;
Branch: 1 branch
BranchTrueFalseTotal
unless @pk 40 21 61
684 21 return $lookup->forget($table, $conn->_plain($conn->_pk_values($table, $pk[0])));
685 }
686  
687 =head2 CRUD operations
688  
689 # a row object
690 my $ann = $orm->insert(
691 users => {
692 name => 'Ann',
693 prefs => {theme => 'dark'},
694 },
695 );
696  
697 # row data: a hashref
698 my $ben = $orm->insert(
699 users => {name => 'Ben'},
700 data => 1,
701 );
702  
703 $orm->insert(users => {name => 'Cy'}); # void: nothing read back
704  
705 # compare-and-swap on any hashref, a bare one included: undef if the name
706 # changed since it was read
707 my ($cy) = $orm->handle('users')->where({name => 'Cy'})->bare->all;
708 my $renamed = $orm->cas_update(users => $cy, {name => 'Cyrus'});
709  
710 # an arrayref of rows, or with count => 1, how many went in
711 my $rows = $orm->insert_many(users => [{name => 'Di'}, {name => 'Ed'}]);
712 my $n = $orm->insert_many(
713 users => [{name => 'Flo'}],
714 count => 1,
715 );
716  
717 $orm->update_row(users => $ann, {name => 'Anne'}); # updates the row object given
718  
719 my $fresh = $orm->update_row(
720 users => $ben,
721 {email => 'ben@example.com'},
722 cas => ['email'],
723 );
724  
725  
726 my $again = $orm->refresh_row(users => {id => $ben->{id}}); # a row object, from the cache
727 my $gone = $orm->delete_row(users => $fresh); # 1
728  
729 # rows have the same operations as methods
730 $ann->update({email => 'ann@example.com'}); # $orm->update_row(users => $ann, {...})
731 $ann->refresh; # $orm->refresh_row(users => $ann, cache => 0)
732 $ann->delete; # $orm->delete_row(users => $ann)
733  
734 The CRUD operations work on row data: plain hashrefs where a missing key means
735 the field was not fetched and an undef value means NULL. Wherever row data is
736 expected, a row object works too, and its C<row_data> is used.
737  
738 A row object given to C<update_row> or C<refresh_row> must also have
739 C<set_row_data>, which takes the new row data. One without it, or an aggregate
740 row, croaks before anything is sent.
741  
742 Each CRUD operation croaks on an argument it does not know.
743  
744 The CRUD operations that return rows (C<insert>, C<insert_many>,
745 C<update_row>, and C<refresh_row>) share one rule. C<find>,
746 C<find_or_insert>, C<insert_fk>, and C<insert_many_fk> follow it too, and
747 C<vivify> takes C<row_class>:
748  
749 =over 4
750  
751 =item *
752  
753 In void context they do the work and return nothing.
754  
755 =item *
756  
757 Given a row object, C<update_row> and C<refresh_row> return that same object,
758 now holding the new row data (it takes the new data in void context too).
759  
760 =item *
761  
762 C<< data => 1 >> returns the row data instead of a row. A given row object
763 still takes the new data. A handle's C<data_only> does the same for the
764 rows it returns.
765  
766 =item *
767  
768 C<< row_class => $class >> builds the rows with that class for this call,
769 loading it when needed. C<< row_class => undef >> returns the row data. With
770 C<< data => 1 >> too, C<data> wins. A given row object still takes the new
771 data. A handle passes its own C<row_class> this
772 way.
773  
774 =item *
775  
776 Otherwise they return a new row object. The class is the table's
777 C<row_class> in the map when set (even to undef), else the ORM's
778 C<row_class>. When that class is undef (as with C<< row_class => undef >>
779 to C<new>), they return the row data.
780  
781 =item *
782  
783 C<insert_many> returns an arrayref of these, never a list.
784  
785 =item *
786  
787 When no row matched, C<update_row> and C<refresh_row> return undef. A row
788 object given keeps its row data, but a C<refresh_row> that finds no row marks
789 it deleted (see C<was_deleted> in L<DBIx::QuickORM::Role::Row>).
790  
791 =back
792  
793 For row class authors: the object is built with
794 C<< $class->new(row_data => \%data, orm => $orm, table => $table) >>, or
795 blessed from those directly when the class's C<fast_bless> is true.
796  
797 Writes replace the canonical copy for that primary key. A read keeps the
798 canonical copy when every fetched value matches it and it fetched every field
799 the copy holds, adding any new fields. Otherwise the read replaces it, and
800 row objects holding the old copy are no longer canonical
801 (L<DBIx::QuickORM::Manual::Caching/"FIELDS LEFT OUT OF A SELECT">).
802  
803 A row written through C<RETURNING> comes back with the table's default
804 fields, the fields written, and for an update the fields the row held.
805 Without C<RETURNING> (MySQL always, MariaDB for updates) it holds only the
806 primary key.
807  
808 Values sent are never copied into the returned row data (except with
809 C<insert>'s C<as_given>): defaults, triggers, and generated columns can change
810 them.
811  
812 Every CRUD operation takes C<raw>. Without it, every value sent (inserted
813 values, changes, compare-and-swap values, and primary key values) is deflated,
814 turned from a Perl value into database form, by its field's type:
815  
816 =over 4
817  
818 =item *
819  
820 A reference on a typed field is deflated.
821  
822 =item *
823  
824 A reference on a field without a type croaks.
825  
826 =item *
827  
828 A plain value on a typed field is deflated when the type's C<is_inflated> says
829 it is inflated. A plain value can be ambiguous (is C<123> JSON, or already
830 encoded?). Wrap it in C<raw()> or C<inflated()> to say which.
831  
832 =item *
833  
834 Anything else is sent as given.
835  
836 =back
837  
838 C<< raw => 1 >> says every value is already in database form and skips
839 deflation. It is also how to send a reference to a field without a type (a
840 PostgreSQL array, say).
841  
842 C<raw> covers only the values you gave. Values the ORM generates, such as a
843 primary key from its type, are deflated as above whatever C<raw> says.
844  
845 To mark one value instead of all, wrap it in a marker from
846 L<DBIx::QuickORM::Value>. A marker overrides both the default and C<raw>:
847  
848 use DBIx::QuickORM::Value qw/raw inflated sql/;
849  
850 my $dee = $orm->insert(
851 users => {
852 name => 'Dee',
853 prefs => raw('{"theme":"dark"}'), # already JSON text: sent as is
854 created => sql('now()'), # literal SQL
855 },
856 );
857  
858 # raw => 1 for every value, but deflate this one
859 my $eli = $orm->insert(
860 users => {
861 name => 'Eli',
862 prefs => inflated({theme => 'light'}),
863 },
864 raw => 1,
865 );
866  
867 C<raw()> sends one value as given, and C<inflated()> deflates one even under
868 C<< raw => 1 >>. C<binary()> binds bytes, and C<sql()> is literal SQL.
869 L<DBIx::QuickORM::Manual::Values> covers each marker, deflation, and
870 inflation on read.
871  
872 The single-row CRUD operations reuse prepared statements (DBI's
873 C<prepare_cached>). Behind a pooler in transaction mode, such as PgBouncer,
874 turn off server-side prepares (DBD::Pg's C<pg_server_prepare>).
875  
876 =over 4
877  
878 =item $row = $orm->insert($table => \%fields, raw => $bool)
879  
880 =item \%data = $orm->insert($table => \%fields, data => 1, raw => $bool)
881  
882 =item $row = $orm->insert($table => \%fields, as_given => 1, raw => $bool)
883  
884 Inserts one row and returns it. At least one field is required.
885  
886 The new primary key comes from C<RETURNING>, from the given values, or from
887 the database's last insert id for a single-field key.
888  
889 A typed primary key field left out can get its value from its type (a version
890 7 UUID for a UUID field). The ORM skips this when the database fills the
891 column and can return it with C<RETURNING>. On MySQL it always generates. The
892 field's C<generate> hint changes this (see
893 L<DBIx::QuickORM::Role::Type/Field hints>).
894  
895 A field passed as undef is sent as NULL and is not generated.
896  
897 Generated values are sent like your own, and C<as_given> includes them.
898 C<insert_many> generates them the same way for each row.
899  
900 In void context it only inserts. It sends no C<RETURNING>, caches no canonical
901 copy, builds no row, and skips the checks below.
902  
903 Without C<RETURNING> (MySQL), unless in void context:
904  
905 =over 4
906  
907 =item *
908  
909 A table without a primary key croaks.
910  
911 =item *
912  
913 A compound key not given in full croaks before anything is sent.
914  
915 =item *
916  
917 A single-field key not given (or given as C<sql()>) is read from the last
918 insert id after the insert. When the database generated none (a key that is
919 not auto-increment gives 0), the insert croaks with the row already in the
920 table.
921  
922 =back
923  
924 C<< as_given => 1 >> returns a copy of the fields as sent, in database form,
925 plus the new primary key, instead of reading the row back. Fields sent as
926 C<sql()> are left out.
927  
928 The copy is not canonical, so C<update> and C<delete> on it croak while
929 C<enforce_canon> is on. Refresh it first. A row object fetches a field the
930 copy lacks when it is read.
931  
932 On a table without a primary key it returns the copy even without
933 C<RETURNING>, but nothing can be written or fetched through it.
934  
935 =back
936  
937 =cut
938  
939 276 ▶sub insert {
Subroutine insert: called CC=4 SCAR=16.4
Pod documented
940 276 my $self = shift;
941 276 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition33%1/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
27600
MC/DC0%0/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
942 276 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller}; # see LookupTable, "Who made a hash stop being canon"
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 276 276
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
27600
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
943 276 $self->_primitive(insert => @_);
944 }
945  
946 =pod
947  
948 =over 4
949  
950 =item \@rows = $orm->insert_many($table => \@rows, raw => $bool)
951  
952 =item \@data = $orm->insert_many($table => \@rows, data => 1, raw => $bool)
953  
954 =item $count = $orm->insert_many($table => \@rows, count => 1, raw => $bool)
955  
956 Inserts many rows and returns an arrayref of the new rows. Every row must
957 have the same fields, at least one.
958  
959 On a table with a primary key, the new rows become canonical. Copies already
960 in the row cache stay.
961  
962 C<< count => 1 >> returns how many rows were inserted instead. It works on
963 every database, never reads rows back, and cannot be combined with
964 C<< data => 1 >>.
965  
966 In void context it only inserts: nothing is read back or made canonical.
967  
968 An empty C<\@rows> sends nothing and returns an empty arrayref (0 with
969 C<count>).
970  
971 The rows go in multi-row C<INSERT> statements, each holding as many rows as
972 the database's bind limit allows. When it takes more than one statement, they
973 run in one transaction, so either every row is inserted or none is.
974  
975 Inside an open transaction it always takes a savepoint, even for one
976 statement: a failure rolls back only these rows and leaves the open
977 transaction usable. On DuckDB, which has no savepoints, the open transaction
978 is used as it is.
979  
980 The returned rows come in the order the database gives them, with the table's
981 default fields.
982  
983 Without C<RETURNING> (MySQL) each row holds only its primary key, so every
984 row must carry its whole primary key. A row without it, or a table without a
985 primary key, croaks before anything is sent. Use C<count> or void context.
986  
987 =back
988  
989 =cut
990  
991 61 ▶sub insert_many {
Subroutine insert_many: called CC=4 SCAR=16.4
Pod documented
992 61 my $self = shift;
993 61 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition33%1/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
6100
MC/DC0%0/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
994 61 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 61 61
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
6100
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
995 61 $self->_primitive(insert_many => @_);
996 }
997  
998 =pod
999  
1000 =over 4
1001  
1002 =item $row = $orm->update_row($table, $row_or_data, \%changes, %opts)
1003  
1004 =item \%data = $orm->update_row($table, $row_or_data, \%changes, data => 1, %opts)
1005  
1006 Updates the row with the row data's primary key and returns it, or undef when
1007 no row matched. At least one change is required. A row object given follows
1008 the rule in L</"CRUD operations">.
1009  
1010 Options:
1011  
1012 =over 4
1013  
1014 =item enforce_canon => $bool
1015  
1016 When true, croaks unless the row data is canonical (see C<is_canon>). Undef or
1017 absent means true inside a transaction, otherwise the ORM's C<enforce_canon>.
1018  
1019 0 skips that check, but C<cas> and C<auto_cas> still apply. It also skips the
1020 row state checks: a row not in the database (vivified, or deleted) is still
1021 updated by its key, where the row's own C<update> croaks. Not recommended.
1022  
1023 =item cas => \@fields
1024  
1025 Compare-and-swap: update only while these fields still hold the row data's
1026 values (undef matches NULL). Otherwise return undef and change nothing. Each
1027 field must be in the row data, or it croaks.
1028  
1029 It compares with C<=>, so it does not suit floats, PostgreSQL C<json>, or
1030 MySQL C<JSON>.
1031  
1032 =item auto_cas => $bool
1033  
1034 Compare-and-swap on every field present in both the row data and the changes.
1035  
1036 =back
1037  
1038 =back
1039  
1040 =cut
1041  
1042 118 ▶sub update_row {
Subroutine update_row: called CC=4 SCAR=13.9
Pod documented
1043 118 my $self = shift;
1044 118 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition66%2/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
10909
MC/DC50%1/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table66%2/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1045 118 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 2 116 118
Condition100%3/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
10972
MC/DC100%2/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table100%3/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1046 118 $self->_primitive(update_row => @_);
1047 }
1048  
1049 =pod
1050  
1051 =over 4
1052  
1053 =item \%data = $orm->cas_update($table, \%data, \%changes)
1054  
1055 =item $row = $orm->cas_update($table, $row, \%changes, cas => \@fields)
1056  
1057 C<update_row> as a compare-and-swap: writes the changes only while the
1058 database still holds the row data's values for the changed fields (or the
1059 C<cas> fields), and returns undef otherwise, changing nothing.
1060  
1061 The row data need not be canonical, so it takes any hashref holding the
1062 primary key and the compared fields, a C<bare> one included, and returns the
1063 new row data, or a row of C<row_class> when that option is given. Given a row
1064 object it returns that object, holding the new data (L</"CRUD operations">). A
1065 row's own C<cas_update> calls this.
1066  
1067 The row data's values, its primary key included, are used as the database
1068 returned them, as a fetch gives them, not deflated as C<update_row> deflates
1069 them. A hand-built hashref must hold stored values, or wrap an inflated one in
1070 C<inflated()> (L<DBIx::QuickORM::Value>). The changes are deflated as for
1071 C<update_row>, unless C<raw> is true.
1072  
1073 It croaks on any option but C<cas>, C<raw>, and C<row_class>, on an empty
1074 C<cas> list (an unconditional write), on row data not in the database
1075 (vivified, or deleted), and when the row data lacks a field it compares.
1076  
1077 Inside a transaction, the returned row data keeps the row's
1078 inserted-in-this-transaction mark when the given hashref or the row's cached
1079 copy carries it. When neither does (say a hashref fetched again with C<bare>
1080 after C<clear_cache>), it cannot. If a rollback then undoes the insert, it may
1081 still report being in the database. Find the row again before relying on it.
1082  
1083 =back
1084  
1085 =cut
1086  
1087 303 my %CAS_UPDATE_ARGS = map { $_ => 1 } qw/cas raw row_class/;
1088  
1089 28 ▶sub cas_update {
Subroutine cas_update: called CC=17 SCAR=28.8
Pod documented
1090 28 my $self = shift;
1091 28 my ($table, $row, $changes, @args) = @_;
1092 28 ▶ croak "cas_update() needs a hashref of changes" unless ref($changes) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $changes eq "HASH" 1 27 28
1093 27 ▶ croak "Odd number of options to cas_update()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 26 27
1094 26 my %params = @args;
1095 26 my @unknown = sort grep { !$CAS_UPDATE_ARGS{$_} } keys %params;
1096 26 ▶ croak "Unknown argument(s) to cas_update(): " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 25 26
1097 25 ▶ croak "cas_update() needs a field to compare (an empty list would write unconditionally)" if ref($params{cas}) eq 'ARRAY' && !@{$params{cas}};
Branch: 1 branch
BranchTrueFalseTotal
if ref $params{"cas"} eq "ARRAY" and not @{$params{"cas"};} 2 23 25
Condition100%3/3
ref $params{"cas"} eq "ARRAY" and not @{$params{"cas"};}
!ll&&!rl&&r
1582
MC/DC100%2/2
ref $params{"cas"} eq "ARRAY" and not @{$params{"cas"};}
ref $params{"cas"} eq "ARRAY" not @{$params{"cas"};}
Truth table100%3/3
A and not(B)
A= ref $params{"cas"} eq "ARRAY"B= not @{$params{"cas"};}
ABresult
0X0
100
111
1098  
1099 23 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition33%1/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
2300
MC/DC0%0/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1100 23 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 23 23
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
2300
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1101  
1102 23 ▶ my $data = blessed($row) && $row->can('row_data') ? $row->row_data : $row;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($row) && $row->can('row_data') ? : 11 12 23
Condition66%2/3
builtin::blessed($row) and $row->can("row_data")
!ll&&!rl&&r
12011
MC/DC50%1/2
builtin::blessed($row) and $row->can("row_data")
builtin::blessed($row) $row->can("row_data")
Truth table66%2/3
A and B
A= builtin::blessed($row)B= $row->can("row_data")
ABresult
0X0
100
111
1103 23 ▶ croak "Cannot cas_update a row that is not in the database; insert it first" if ref($data) eq 'HASH' && DBIx::QuickORM::LookupTable->row_state($data);
Branch: 1 branch
BranchTrueFalseTotal
if ref $data eq "HASH" and "DBIx::QuickORM::LookupTable"->row_state($data) 1 22 23
Condition66%2/3
ref $data eq "HASH" and "DBIx::QuickORM::LookupTable"->row_state($data)
!ll&&!rl&&r
0221
MC/DC50%1/2
ref $data eq "HASH" and "DBIx::QuickORM::LookupTable"->row_state($data)
ref $data eq "HASH" "DBIx::QuickORM::LookupTable"->row_state($data)
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= "DBIx::QuickORM::LookupTable"->row_state($data)
ABresult
0X0
100
111
1104  
1105 # The row data is compared as fetched, so only the changes are deflated.
1106 22 ▶ $changes = $self->connection->deflate($table, $changes) unless delete $params{raw};
Branch: 1 branch
BranchTrueFalseTotal
unless delete $params{"raw"} 22 0 22
1107  
1108 22 ▶ my $cas = $params{cas} // [keys %$changes];
Condition100%2/2
$params{"cas"} // [keys %$changes]
l!l
814
MC/DC100%1/1
$params{"cas"} // [keys %$changes]
$params{"cas"}
Truth table100%2/2
A
A= $params{"cas"}
Aresult
11
00
1109 22 ▶ my @back = blessed($row) || exists $params{row_class} ? () : (data => 1);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($row) || exists $params{'row_class'} ? : 12 10 22
Condition100%3/3
builtin::blessed($row) or exists $params{"row_class"}
l!l&&r!l&&!r
11110
MC/DC100%2/2
builtin::blessed($row) or exists $params{"row_class"}
builtin::blessed($row) exists $params{"row_class"}
Truth table100%3/3
A or B
A= builtin::blessed($row)B= exists $params{"row_class"}
ABresult
1X1
011
000
1110 22 return $self->_primitive(update_row => $table, $row, $changes, %params, @back, cas => $cas, enforce_canon => 0, raw => 1);
1111 }
1112  
1113 =pod
1114  
1115 =over 4
1116  
1117 =item $count = $orm->delete_row($table, $row_or_data, enforce_canon => $bool, raw => $bool)
1118  
1119 Deletes the row with the row data's primary key and returns how many rows were
1120 deleted (0 or 1). The ORM stops holding it and marks the row data deleted (see
1121 C<was_deleted> in L<DBIx::QuickORM::Role::Row>).
1122  
1123 A delete that matches no row also marks it deleted (it is not in the
1124 database) and returns 0.
1125  
1126 C<enforce_canon> is as for C<update_row>, including what 0 bypasses.
1127  
1128 =back
1129  
1130 =cut
1131  
1132 18 ▶sub delete_row {
Subroutine delete_row: called CC=4 SCAR=16.4
Pod documented
1133 18 my $self = shift;
1134 18 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition33%1/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
1800
MC/DC0%0/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1135 18 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 18 18
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
1800
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1136 18 return $self->connection->delete_row(@_);
1137 }
1138  
1139 =pod
1140  
1141 =over 4
1142  
1143 =item $row = $orm->refresh_row($table, $row_or_data, cache => $bool, db => $bool, fields => \@fields, raw => $bool)
1144  
1145 =item \%data = $orm->refresh_row($table, $row_or_data, data => 1, %opts)
1146  
1147 The canonical row for a primary key, or undef when there is none. It takes row
1148 data, a row, or a primary key in any form (a value, an arrayref, or a
1149 hashref).
1150  
1151 A row object given follows the rule in L</"CRUD operations">.
1152  
1153 It reads C<fields> plus the primary key, or the table's default fields plus
1154 the fields the given row data holds.
1155  
1156 By default it returns the canonical copy when that has every field asked for,
1157 and reads the database otherwise. C<< cache => 0 >> always reads the database.
1158 C<< db => 0 >> only looks in the cache, returning the canonical copy as it is,
1159 or undef. Both 0 croaks.
1160  
1161 =back
1162  
1163 =cut
1164  
1165 129 ▶sub refresh_row {
Subroutine refresh_row: called CC=4 SCAR=13.9
Pod documented
1166 129 my $self = shift;
1167 129 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition66%2/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
12702
MC/DC50%1/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table66%2/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1168 129 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 1 128 129
Condition100%3/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
12711
MC/DC100%2/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table100%3/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1169 129 $self->_primitive(refresh_row => @_);
1170 }
1171  
1172 =head2 Finding by primary key
1173  
1174 my $user = $orm->find(users => $id);
1175 my $data = $orm->find(users => $id, data => 1); # row data
1176 my $none = $orm->find(users => -1); # undef
1177  
1178 Reads one row by primary key, like C<refresh_row>. It never writes to the
1179 database.
1180  
1181 =over 4
1182  
1183 =item $row = $orm->find($table, $pk, %opts)
1184  
1185 =item \%data = $orm->find($table, $pk, data => 1, %opts)
1186  
1187 The row with primary key C<$pk>, or undef. C<$pk> takes any key form (see
1188 C<find> in L<DBIx::QuickORM::Handle>). The options are C<refresh_row>'s.
1189  
1190 A row object passed in gives its key. It may also show the state the read
1191 found, such as new values or that the row is gone.
1192  
1193 =back
1194  
1195 =cut
1196  
1197 168 ▶sub find {
Subroutine find: called CC=12 SCAR=24.9
Pod documented
1198 168 my $self = shift;
1199 168 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition66%2/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
152016
MC/DC50%1/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table66%2/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1200 168 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 16 152 168
Condition66%2/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
152016
MC/DC50%1/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table66%2/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1201 168 my ($table, $pk, @args) = @_;
1202 168 ▶ $pk = $pk->row_data if blessed($pk) && $pk->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($pk) and $pk->can("row_data") 3 165 168
Condition100%3/3
builtin::blessed($pk) and $pk->can("row_data")
!ll&&!rl&&r
15783
MC/DC100%2/2
builtin::blessed($pk) and $pk->can("row_data")
builtin::blessed($pk) $pk->can("row_data")
Truth table100%3/3
A and B
A= builtin::blessed($pk)B= $pk->can("row_data")
ABresult
0X0
100
111
1203 168 ▶ return $self->_primitive(refresh_row => $table, $pk, @args) if ref($pk) || (@args && !(@args == 2 && $args[0] eq 'row_class'));
Branch: 1 branch
BranchTrueFalseTotal
if ref $pk or @args and not @args == 2 && $args[0] eq "row_class" 44 124 168
Condition100%9/9
ref $pk or @args and not @args == 2 && $args[0] eq "row_class"
l!l&&r!l&&!r
2915124
@args and not @args == 2 && $args[0] eq "row_class"
!ll&&!rl&&r
116815
@args == 2 && $args[0] eq 'row_class'
!ll&&!rl&&r
3128
MC/DC100%4/4
ref $pk or @args and not @args == 2 && $args[0] eq "row_class"
ref $pk @args @args == 2 $args[0] eq 'row_class'
Truth table100%5/5
A or B and not(C && D)
A= ref $pkB= @argsC= @args == 2D= $args[0] eq 'row_class'
ABCDresult
1XXX1
010X1
01101
00XX0
01110
1204  
1205 # A plain key and no options but row_class: what _primitive does, without its argument handling.
1206 124 ▶ my @build = @args ? $self->_row_class_opt({@args}) : ();
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 8 116 124
1207 122 my $out = $self->connection->refresh_row($table, $pk);
1208 116 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 1 115 116
1209 115 return $self->_row($table, $out, @build);
1210 }
1211  
1212 =head2 Finding or inserting
1213  
1214 my $gil = $orm->find_or_insert(
1215 users => {
1216 name => 'Gil',
1217 email => 'gil@example.com',
1218 },
1219 by => ['email'],
1220 );
1221 my $same = $orm->find_or_insert(
1222 users => {email => 'gil@example.com'},
1223 by => ['email'],
1224 );
1225  
1226 =over 4
1227  
1228 =item $row = $orm->find_or_insert($table => \%fields, by => \@fields, raw => $bool)
1229  
1230 =item \%data = $orm->find_or_insert($table => \%fields, data => 1, %opts)
1231  
1232 Returns the row whose C<by> fields hold the given values, inserting it from
1233 C<\%fields> when there is none. It follows the CRUD operations' return rule.
1234  
1235 C<by> defaults to the primary key. A table without one needs C<by>. Every
1236 C<by> field must be in C<\%fields>. Croaks when more than one row matches, or
1237 for a field the table does not have, whether or not the row exists.
1238  
1239 An undef C<by> value croaks: NULL does not identify a row, since a unique key
1240 allows many.
1241  
1242 The insert runs in a savepoint, or in a transaction when none is open, so a
1243 failed insert leaves an open transaction usable. When the insert fails (say
1244 another process inserted the row first), it looks the row up again and returns
1245 it. If it still finds none, it rethrows the insert's error.
1246  
1247 This recovery needs a unique key on the C<by> fields. Without one, two
1248 racing calls can both insert.
1249  
1250 Recovery works at the default C<'read committed'>. Inside a transaction at
1251 C<'repeatable read'> or C<'serializable'> (when chosen, or the MySQL family's
1252 server default under C<'server'>), the second lookup reads the transaction's
1253 snapshot. A row another session committed after this transaction started
1254 stays invisible, so the insert's error is rethrown.
1255  
1256 C<< raw => 1 >> also covers the C<by> values used to look the row up. They
1257 must then be in exact database form, or the lookup misses and the insert fails
1258 on a duplicate key.
1259  
1260 On DuckDB, which has no savepoints, an insert inside an open transaction runs
1261 without one, and a failed insert leaves that transaction unusable.
1262  
1263 A table handle has it too: C<< $h->find_or_insert(\%fields, %opts) >> (see
1264 L<DBIx::QuickORM::Handle>).
1265  
1266 =back
1267  
1268 =cut
1269  
1270 23 ▶sub find_or_insert { my $self = shift; $self->_find_or_insert($self->{+DEBUG} ? [(caller(0))[0 .. 3]] : [caller], @_) }
Subroutine find_or_insert: called CC=2 SCAR=7.2
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->{'debug'} ? : 0 23 23
1271  
1272 =head2 Rows not in the database
1273  
1274 A row can exist in memory before it is inserted. Change it with C<modify>,
1275 then write it with its C<insert>.
1276  
1277 =over 4
1278  
1279 =item $row = $orm->vivify($table => \%fields)
1280  
1281 =item $row = $orm->vivify($table => \%fields, row_class => $class_or_undef)
1282  
1283 A new row that is not in the database yet. Nothing is written until you call
1284 its C<insert>. Until then, C<modify> changes it (see
1285 L<DBIx::QuickORM::Role::Row>).
1286  
1287 The fields are checked and deflated as C<insert> does, into a new hashref. An
1288 empty hashref is fine. Fill it in with C<modify>. The row is built as the
1289 CRUD operations build rows, so with no row class it is the row data.
1290 C<row_class> picks the class for this row, as for the CRUD operations.
1291  
1292 =back
1293  
1294 =cut
1295  
1296 13 ▶sub vivify {
Subroutine vivify: called CC=5 SCAR=16.3
Pod documented
1297 13 my $self = shift;
1298 13 my ($table, $fields, @args) = @_;
1299 13 ▶ croak "vivify() needs a table and a hashref of fields" unless defined($table) && ref($fields) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and ref $fields eq "HASH" 0 13 13
Condition33%1/3
defined $table and ref $fields eq "HASH"
!ll&&!rl&&r
0013
MC/DC0%0/2
defined $table and ref $fields eq "HASH"
defined $table ref $fields eq "HASH"
Truth table33%1/3
A and B
A= defined $tableB= ref $fields eq "HASH"
ABresult
0X0
100
111
1300 13 ▶ croak "Odd number of options to vivify()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 12 13
1301 12 my %opts = @args;
1302 12 my @build = $self->_row_class_opt(\%opts);
1303 12 ▶ croak "Unknown argument(s) to vivify(): " . join(', ' => sort keys %opts) if %opts;
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 11 12
1304  
1305 11 my $data = $self->connection->deflate($table, $fields);
1306 10 DBIx::QuickORM::LookupTable->mark_vivified($data);
1307 10 return $self->_row($table, $data, @build);
1308 }
1309  
1310 =head2 Following foreign keys
1311  
1312 my $post = $orm->insert(
1313 posts => {
1314 user_id => $id,
1315 title => 'Hi',
1316 },
1317 );
1318  
1319 my $author = $orm->follow_fk(posts => $post, 'users')->only;
1320 my @posts = $orm->follow_fk(users => $author, 'posts')->order_by('id')->all;
1321  
1322 # the same, as a row method: no table needed
1323 my $writer = $post->follow_fk('users')->only;
1324  
1325 =over 4
1326  
1327 =item $h = $orm->follow_fk($table, $row_or_data, $other_table, link => \%link)
1328  
1329 =item $h = $orm->follow_fk($table, $row_or_data, $other_table, via => \%via)
1330  
1331 A table handle (L<DBIx::QuickORM::Handle>) on C<$other_table> for the rows
1332 linked to this row by a foreign key: the row it points to, or the rows that
1333 point to it.
1334  
1335 The handle's C<where> holds the linked fields' values from the row, qualified
1336 as C<other_table.field>, so the handle can be joined to other tables. Narrow
1337 the handle with C<and>, since C<where> would replace the link.
1338  
1339 C<link> is C<< {our_field => their_field, ...} >>, as foreign keys are written
1340 in the map, and gives the direction. On a self-referencing C<employees> table,
1341 C<< {manager_id => 'id'} >> follows to an employee's manager and
1342 C<< {id => 'manager_id'} >> to their reports. It must match a foreign key of
1343 C<$table> to C<$other_table>, or one of C<$other_table> to C<$table> reversed.
1344 Without it there must be exactly one such key.
1345  
1346 C<via> takes the same mapping for a key the map does not know, such as one
1347 the database never declared: C<< via => {editor_id => 'id'} >>. No foreign key
1348 need exist, but both tables must be in the map and every field it names must
1349 exist. To declare the key for every call instead, give C<fks> to C<new>.
1350  
1351 Croaks on a link that matches no key, on more than one key without a C<link>,
1352 on a key to a table not in the map, on a C<via> field that does not exist, and
1353 when given both C<link> and C<via>.
1354  
1355 The handle expects one row (C<single>, see L<DBIx::QuickORM::Iterator>) when
1356 the fields it looks up are the other table's primary key or a unique key.
1357 Otherwise it expects many (C<multi>), whatever the data.
1358  
1359 Linked fields missing from the row data are fetched first, with one
1360 C<refresh_row>. It croaks if the row is gone. A NULL linked value refers to
1361 nothing, so the handle matches no rows.
1362  
1363 =back
1364  
1365 =cut
1366  
1367 16 ▶sub follow_fk { my $self = shift; $self->_follow_fk($self->{+DEBUG} ? [(caller(0))[0 .. 3]] : [caller], @_) }
Subroutine follow_fk: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->{'debug'} ? : 1 15 16
1368  
1369 =head2 Inserting linked rows
1370  
1371 my $post = $orm->insert_fk(users => $alice, 'posts', {title => 'One'});
1372 my $posts = $orm->insert_many_fk(users => $alice, 'posts', {title => 'A'}, {title => 'B'});
1373  
1374 # the same, as row methods
1375 my $draft = $alice->insert_fk('posts', {title => 'Draft'});
1376  
1377 Inserts rows into C<$other_table> that point at this row, filling their
1378 foreign key fields from it. Only that direction: a key of C<$table> to
1379 C<$other_table> cannot be followed this way, since the new row would have to
1380 be written back into this one.
1381  
1382 =over 4
1383  
1384 =item $row = $orm->insert_fk($table, $row_or_data, $other_table, %opts, \%fields)
1385  
1386 =item \@rows = $orm->insert_many_fk($table, $row_or_data, $other_table, %opts, @fields)
1387  
1388 C<insert_fk> inserts exactly one row and returns it, as C<insert> does.
1389 C<insert_many_fk> inserts any number, as C<insert_many> does: an arrayref of
1390 rows, the count with C<< count => 1 >>, nothing in void context.
1391  
1392 After C<$other_table>, a string is an option name taking the next argument as
1393 its value, and every other hashref is a row's fields:
1394  
1395 $alice->insert_fk('posts', link => {id => 'user_id'}, {title => 'Linked'});
1396  
1397 C<link> chooses the key when more than one of C<$other_table> points at
1398 C<$table>, written C<< {our_field => their_field} >> as C<follow_fk> takes it.
1399 C<via> gives a mapping with no key behind it, as for C<follow_fk>. The new
1400 rows' right-hand fields are filled from this row's left-hand fields.
1401 The other options are those of C<insert> (C<raw>, C<data>, C<as_given>,
1402 C<row_class>) or C<insert_many> (C<raw>, C<data>, C<count>, C<row_class>).
1403  
1404 Croaks, before anything is inserted, when the fields set a link field, when
1405 the row's linked value is NULL, when the row is not in the database, and on a
1406 C<link> that points from C<$table>. A linked field missing from the row data
1407 is fetched first, with one C<refresh_row>. The linked values are sent as they
1408 are in the row data, so a hashref must hold them in database form, as row
1409 data does.
1410  
1411 =back
1412  
1413 =cut
1414  
1415 2 ▶sub insert_fk { my $self = shift; $self->_insert_fk($self->{+DEBUG} ? [(caller(0))[0 .. 3]] : [caller], insert => @_) }
Subroutine insert_fk: called CC=2 SCAR=7.2
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->{'debug'} ? : 0 2 2
1416 1 ▶sub insert_many_fk { my $self = shift; $self->_insert_fk($self->{+DEBUG} ? [(caller(0))[0 .. 3]] : [caller], insert_many => @_) }
Subroutine insert_many_fk: called CC=2 SCAR=7.2
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$self->{'debug'} ? : 0 1 1
1417  
1418 =head2 Handles
1419  
1420 my @bobs = $orm->handle('users')
1421 ->where({name => 'Bob'})
1422 ->order_by('id')
1423 ->all;
1424 my @rows = $orm->handle(\['SELECT id, name FROM users WHERE id > ?', 10])->all;
1425  
1426 =over 4
1427  
1428 =item $h = $orm->handle($table)
1429  
1430 =item $h = $orm->handle(\$sql)
1431  
1432 =item $h = $orm->handle(\[$sql, @binds])
1433  
1434 =item $h = $orm->handle($source)
1435  
1436 A L<DBIx::QuickORM::Handle> over a table, an SQL query, or a source object
1437 (L<DBIx::QuickORM::Role::Source>).
1438  
1439 An SQL query runs as written, and its binds are not deflated. Its rows belong
1440 to no table: they are never canonical and cannot be written through the ORM.
1441  
1442 =back
1443  
1444 =cut
1445  
1446 218 ▶sub handle {
Subroutine handle: called CC=9 SCAR=22.1
Pod documented
1447 218 my $self = shift;
1448 218 my ($what) = @_;
1449  
1450 218 my $type = ref($what);
1451 my $source =
1452 blessed($what) && $what->DOES('DBIx::QuickORM::Role::Source') ? $what
1453 : $type eq 'SCALAR' ? DBIx::QuickORM::Source::Query->new(sql => $$what)
1454 218 ▶ : $type eq 'REF' && ref($$what) eq 'ARRAY' ? DBIx::QuickORM::Source::Query->new(sql => $$what->[0], binds => [@{$$what}[1 .. $#$$what]])
Branch: 5 branches
BranchTrueFalseTotal
builtin::blessed($what) && $what->DOES('DBIx::QuickORM::Role::Source') ? : 1 217 218
$type eq 'SCALAR' ? : 11 206 217
$type eq 'REF' && ref $$what eq 'ARRAY' ? : 2 204 206
$type || !defined($what) ? : 1 203 204
$self->db_map->table($what) ? : 200 3 203
Condition66%6/9
builtin::blessed($what) and $what->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
21701
$type eq "REF" and ref $$what eq "ARRAY"
!ll&&!rl&&r
20402
$type or not defined $what
l!l&&r!l&&!r
10203
MC/DC50%1/2
builtin::blessed($what) and $what->DOES("DBIx::QuickORM::Role::Source")
builtin::blessed($what) $what->DOES("DBIx::QuickORM::Role::Source")
MC/DC50%1/2
$type eq "REF" and ref $$what eq "ARRAY"
$type eq "REF" ref $$what eq "ARRAY"
MC/DC50%1/2
$type or not defined $what
$type not defined $what
Truth table66%2/3
A and B
A= builtin::blessed($what)B= $what->DOES("DBIx::QuickORM::Role::Source")
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= $type eq "REF"B= ref $$what eq "ARRAY"
ABresult
0X0
100
111
Truth table66%2/3
A or not(B)
A= $typeB= not defined $what
ABresult
1X1
011
000
1455 : $type || !defined($what) ? croak "handle() takes a table name, \\\$sql, \\[\$sql, \@binds], or a source"
1456 : $self->db_map->table($what) ? $self->_table_source($what)
1457 : croak "The table '$what' is not in the database map";
1458  
1459 214 return DBIx::QuickORM::Handle->new(orm => $self, source => $source);
1460 }
1461  
1462 =head2 Transactions
1463  
1464 L<DBIx::QuickORM::Txn> shows the block and object forms. Nesting gives
1465 savepoints. C<isolation> sets the level and C<retry> replays a block:
1466  
1467 $orm->txn(sub {
1468 $orm->insert(users => {name => 'Outer'});
1469 eval {
1470 $orm->txn(sub {
1471 $orm->insert(users => {name => 'Inner'});
1472 die "undo only the inner work\n";
1473 });
1474 };
1475 }); # Outer is committed, Inner was rolled back with its savepoint
1476  
1477 my $count = $orm->txn(
1478 sub { $orm->handle('users')->count }, # the block's return value
1479 isolation => 'serializable',
1480 retry => 3,
1481 );
1482  
1483 =over 4
1484  
1485 =item $txn = $orm->txn
1486  
1487 =item $txn = $orm->txn(isolation => $level)
1488  
1489 =item @result = $orm->txn(sub { my $txn = shift; ... })
1490  
1491 =item @result = $orm->txn(sub { ... }, retry => $n, isolation => $level)
1492  
1493 Opens a transaction, or a savepoint inside the open one, as a
1494 L<DBIx::QuickORM::Txn>. Given a block, runs it with the transaction and
1495 returns what the block returns.
1496  
1497 Without a block, commit or roll back through the returned object. Only the
1498 innermost open transaction can be committed or rolled back. One that goes out
1499 of scope unfinished is rolled back with a warning.
1500  
1501 With a block, a normal return commits, unless the block already committed or
1502 rolled back the transaction. An exception rolls back and is rethrown.
1503  
1504 C<< retry => $n >> runs the block of an outermost transaction again, up to
1505 C<$n> more times, while the exception is a database error whose C<retriable>
1506 is true (a deadlock, a serialization failure, or a lock timeout). See
1507 L<DBIx::QuickORM::Exception::DB>. The block must be safe to run again.
1508 C<retry> croaks without a block, and on a nested transaction, which cannot be
1509 replayed alone.
1510  
1511 An outermost transaction opens at the ORM's C<isolation>, or C<'read
1512 committed'> by default. It states that level when it opens, so a changed
1513 server or session default cannot alter it.
1514  
1515 C<'server'> is the exception: it sends a plain C<BEGIN> and uses the
1516 database's own default.
1517  
1518 C<< isolation => $level >> opens an outermost transaction at another level:
1519 C<'read committed'>, C<'repeatable read'>, C<'serializable'>, C<'read
1520 uncommitted'>, or C<'server'>, in any case. Each C<retry> begins at the same
1521 level.
1522  
1523 C<isolation> croaks on a nested transaction and for any other value.
1524  
1525 The ORM's C<isolation> setting takes the same levels, and C<new> croaks for
1526 any other. It is undef unless given, and is stored in lower case.
1527  
1528 SQLite and DuckDB cannot set a level. There the default is C<'server'>, and
1529 any other level croaks when the transaction opens. PostgreSQL runs C<'read
1530 uncommitted'> as C<'read committed'>.
1531 L<DBIx::QuickORM::Manual::Transactions/ISOLATION> has the details.
1532  
1533 Savepoints need a database that has them, so nesting croaks on DuckDB.
1534  
1535 Inside a transaction, C<update_row> and C<delete_row> check that row data is
1536 canonical by default, whatever C<enforce_canon> says. Canonical copies are
1537 held strongly.
1538  
1539 Inside a transaction, rows read before it are not canonical until read again.
1540 A rollback restores the row cache and row state from before. A commit keeps
1541 what the transaction read. After a rollback, refresh a row object you still
1542 hold. See L<DBIx::QuickORM::Manual::Transactions> for the details.
1543  
1544 =back
1545  
1546 =cut
1547  
1548 142 ▶sub txn {
Subroutine txn: called CC=4 SCAR=14.0
Pod documented
1549 142 my $self = shift;
1550 142 ▶ my $lookup = $self->{+DEBUG} && $self->connection->lookup;
Condition66%2/3
$self->{'debug'} && $self->connection->lookup
!ll&&!rl&&r
14002
MC/DC50%1/2
$self->{'debug'} && $self->connection->lookup
$self->{'debug'} $self->connection->lookup
Truth table66%2/3
A && B
A= $self->{'debug'}B= $self->connection->lookup
ABresult
0X0
100
111
1551 142 ▶ local $lookup->{caller} = [(caller(0))[0 .. 3]] if $lookup && !$lookup->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 2 140 142
Condition66%2/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
14002
MC/DC50%1/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table66%2/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1552 142 return $self->connection->txn(@_, caller => [caller]);
1553 }
1554  
1555 =head2 Loading classes
1556  
1557 =over 4
1558  
1559 =item $bool = DBIx::QuickORM->load_class($what, $class)
1560  
1561 =item $bool = DBIx::QuickORM->load_class($what, $class, $missing_ok)
1562  
1563 Loads a class from its module file and returns true. Croaks "$what could not
1564 be loaded" with the error when it cannot.
1565  
1566 With C<$missing_ok>, a missing module file returns false instead. An error
1567 inside the file still croaks.
1568  
1569 =back
1570  
1571 =cut
1572  
1573 272 ▶sub load_class {
Subroutine load_class: called CC=4 SCAR=13.9
Pod documented
1574 272 my $self = shift;
1575 272 my ($what, $class, $missing_ok) = @_;
1576  
1577 272 (my $file = "$class.pm") =~ s{::}{/}g;
1578 272 ▶ return 1 if eval { require $file; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require $file; 1 } } 231 41 272
1579 41 ▶ return 0 if $missing_ok && $@ =~ m/^Can't locate \Q$file\E in \@INC/;
Branch: 1 branch
BranchTrueFalseTotal
if $missing_ok and $@ =~ /^Can't locate \Q$file\E in \@INC/ 20 21 41
Condition100%3/3
$missing_ok and $@ =~ /^Can't locate \Q$file\E in \@INC/
!ll&&!rl&&r
19220
MC/DC100%2/2
$missing_ok and $@ =~ /^Can't locate \Q$file\E in \@INC/
$missing_ok $@ =~ /^Can't locate \Q$file\E in \@INC/
Truth table100%3/3
A and B
A= $missing_okB= $@ =~ /^Can't locate \Q$file\E in \@INC/
ABresult
0X0
100
111
1580 21 croak "$what could not be loaded: $@";
1581 }
1582  
1583 =pod
1584  
1585 =over 4
1586  
1587 =item $class = $orm->require_type($type)
1588  
1589 =item $class = $orm->require_type($type, $context)
1590  
1591 Returns the full class name for a type name (C<JSON>, or C<+My::Type> for a
1592 class outside C<DBIx::QuickORM::Type>), loading it unless it already has
1593 C<deflate>.
1594  
1595 Croaks when it cannot be loaded. C<$context>, when given, says in that error
1596 what asked for the type.
1597  
1598 =back
1599  
1600 =cut
1601  
1602 1103 ▶sub require_type {
Subroutine require_type: called CC=3 SCAR=11.0
Pod documented
1603 1103 my $self = shift;
1604 1103 my ($type, $context) = @_;
1605  
1606 1103 my $class = $self->_type_class($type);
1607 1101 ▶ return $class if $class->can('deflate');
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("deflate") 903 198 1101
1608  
1609 198 ▶ $self->load_class(defined($context) ? "'$context' names the type '$type', which" : "The type '$type'", $class);
Branch: 1 branch
BranchTrueFalseTotal
defined $context ? : 196 2 198
1610 190 return $class;
1611 }
1612  
1613 =pod
1614  
1615 =over 4
1616  
1617 =item $orm->load_row_class($class)
1618  
1619 Loads a row class unless it already has a C<new>. Croaks when the name is not
1620 a valid package name or the class cannot be loaded.
1621  
1622 =back
1623  
1624 =cut
1625  
1626 292 ▶sub load_row_class {
Subroutine load_row_class: called CC=3 SCAR=11.0
Pod documented
1627 292 my $self = shift;
1628 292 my ($class) = @_;
1629  
1630 292 ▶ croak "The row class '$class' is not a valid package name" unless $class =~ m/^\w+(?:::\w+)*\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $class =~ /^\w+(?:::\w+)*\z/ 4 288 292
1631 288 ▶ $self->load_class("The row class '$class'", $class) unless $class->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("new") 9 279 288
1632 }
1633  
1634 =head1 ATTRIBUTES
1635  
1636 Read-only accessors. Each returns the constructor argument of the same name,
1637 or its default. C<connector>, C<sql_builder>, and C<where_builders> hold what
1638 C<new> built from it.
1639  
1640 =over 4
1641  
1642 =item $class = $orm->row_class
1643  
1644 The default row class, C<DBIx::QuickORM::Row> unless given. Undef means plain
1645 hashrefs.
1646  
1647 =item \%classes = $orm->row_classes
1648  
1649 =item $namespace = $orm->row_namespace
1650  
1651 =item $code = $orm->row_class_name
1652  
1653 =item \%omit = $orm->omit
1654  
1655 =item \%fields = $orm->default_fields
1656  
1657 =item \%types = $orm->types
1658  
1659 =item \%options = $orm->type_options
1660  
1661 =item \@types = $orm->autotype
1662  
1663 =item \@types = $orm->append_autotype
1664  
1665 =item \%auto_omit = $orm->auto_omit
1666  
1667 =item \%fks = $orm->fks
1668  
1669 The arguments as given to C<new>, or undef. See C<new> for what each does.
1670 C<db_map> holds the result. C<autotype> is undef unless given, even though a
1671 default list applies.
1672  
1673 =item $builder = $orm->sql_builder
1674  
1675 The SQL builder that handles use. Default:
1676 L<DBIx::QuickORM::SQLBuilder::SQLAbstract>.
1677  
1678 C<new> takes an object composing L<DBIx::QuickORM::Role::SQLBuilder>, or the
1679 name of a class that does. A class is loaded unless it has C<new>, then built
1680 with no arguments. Anything else croaks.
1681  
1682 =item \@builders = $orm->where_builders
1683  
1684 The where builders that render a handle's C<where>. The first that can build
1685 it wins (see L<DBIx::QuickORM::Role::WhereBuilder>).
1686  
1687 Default: L<DBIx::QuickORM::WhereBuilder::RawSQL>,
1688 L<DBIx::QuickORM::WhereBuilder::Simple>, then
1689 L<DBIx::QuickORM::WhereBuilder::SQLAbstract>.
1690  
1691 C<new> takes a non-empty arrayref of classes or objects composing the role. A
1692 class is loaded unless it has C<build_where>. Anything else croaks. A handle
1693 can use its own list through its C<where_builders>.
1694  
1695 =item $code = $orm->connector
1696  
1697 The code reference the ORM calls to open a database handle, built from the
1698 connection argument.
1699  
1700 =item \@names = $orm->like_aggregates
1701  
1702 Extra aggregate functions whose result keeps the field's type and foreign
1703 keys, like the built-in C<min> and C<max>. Undef unless given.
1704  
1705 A computed column C<[$func, $field]> using one of them gets the field's type
1706 and foreign keys (see L<DBIx::QuickORM::Handle/Computed columns>). Names are
1707 matched case-insensitively.
1708  
1709 =back
1710  
1711 =head1 PRIVATE METHODS
1712  
1713 =over 4
1714  
1715 =item $out = $orm->_primitive($method, $table, $row_or_data, @args)
1716  
1717 Runs the Connection's CRUD operation and returns its result by the rule the
1718 CRUD operations share. In void context it returns nothing. Given a row object
1719 for C<update_row> or C<refresh_row>, it returns that row after C<set_row_data>
1720 (which runs in void context too). With C<< data => 1 >> it returns the row
1721 data. Otherwise it returns a new row built by C<_row>, with the C<row_class>
1722 option when given (see C<_row_class_opt>). Handles pass their C<row_class>
1723 that way, before the caller's options.
1724  
1725 An undef result is undef, and the row is left alone.
1726  
1727 An arrayref result (C<insert_many>) comes back as an arrayref, of rows or of
1728 row data. A plain result (C<insert_many>'s C<count>) comes back as it is.
1729  
1730 Croaks before running the CRUD operation when a row object given to
1731 C<update_row> or C<refresh_row> cannot take new data: it has no
1732 C<set_row_data>, or it is an aggregate row.
1733  
1734 =back
1735  
1736 =cut
1737  
1738 303 my %TAKES_ROW = (update_row => 1, refresh_row => 1);
1739  
1740 713 ▶sub _primitive {
Subroutine _primitive: called CC=22 SCAR=30.9
1741 713 my $self = shift;
1742 713 my ($method, $table, $arg, @args) = @_;
1743  
1744 713 ▶ my @changes = $method eq 'update_row' ? (shift @args) : ();
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'update_row' ? : 149 564 713
1745 713 ▶ croak "Odd number of options to $method()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 712 713
1746 712 my %opts = @args;
1747 712 ▶ my $data = $opts{count} ? undef : delete $opts{data}; # with count, data is left for the Connection to refuse
Branch: 1 branch
BranchTrueFalseTotal
$opts{'count'} ? : 11 701 712
1748 712 ▶ delete $opts{row_class} if $data; # data wins
Branch: 1 branch
BranchTrueFalseTotal
if $data 47 665 712
1749 712 my @build = $self->_row_class_opt(\%opts);
1750 712 my $void = !defined wantarray;
1751 712 ▶ $opts{void} = 1 if $void && !$TAKES_ROW{$method};
Branch: 1 branch
BranchTrueFalseTotal
if $void and not $TAKES_ROW{$method} 193 519 712
Condition100%3/3
$void and not $TAKES_ROW{$method}
!ll&&!rl&&r
43287193
MC/DC100%2/2
$void and not $TAKES_ROW{$method}
$void not $TAKES_ROW{$method}
Truth table100%3/3
A and not(B)
A= $voidB= not $TAKES_ROW{$method}
ABresult
0X0
100
111
1752  
1753 712 ▶ my $row = $TAKES_ROW{$method} && blessed($arg) && $arg->can('row_data') ? $arg : undef;
Branch: 1 branch
BranchTrueFalseTotal
$TAKES_ROW{$method} && builtin::blessed($arg) && $arg->can('row_data') ? : 98 614 712
Condition100%6/6
$TAKES_ROW{$method} and builtin::blessed($arg) and $arg->can("row_data")
!ll&&!rl&&r
606898
$TAKES_ROW{$method} and builtin::blessed($arg)
!ll&&!rl&&r
388218106
MC/DC100%3/3
$TAKES_ROW{$method} and builtin::blessed($arg) and $arg->can("row_data")
$TAKES_ROW{$method} builtin::blessed($arg) $arg->can("row_data")
Truth table100%4/4
A and B and C
A= $TAKES_ROW{$method}B= builtin::blessed($arg)C= $arg->can("row_data")
ABCresult
0XX0
10X0
1100
1111
1754 712 ▶ croak "A row object passed to $method() must take new data with set_row_data; pass its row_data instead"
Branch: 1 branch
BranchTrueFalseTotal
if $row and !$row->can("set_row_data") || $row->isa("DBIx::QuickORM::AggregateRow") 6 706 712
Condition100%6/6
$row and !$row->can("set_row_data") || $row->isa("DBIx::QuickORM::AggregateRow")
!ll&&!rl&&r
614926
not $row->can("set_row_data") or $row->isa("DBIx::QuickORM::AggregateRow")
l!l&&r!l&&!r
3392
MC/DC100%3/3
$row and !$row->can("set_row_data") || $row->isa("DBIx::QuickORM::AggregateRow")
$row not $row->can("set_row_data") $row->isa("DBIx::QuickORM::AggregateRow")
Truth table100%4/4
A and not(B) or C
A= $rowB= not $row->can("set_row_data")C= $row->isa("DBIx::QuickORM::AggregateRow")
ABCresult
0XX0
1000
11X1
1011
1755 if $row && (!$row->can('set_row_data') || $row->isa('DBIx::QuickORM::AggregateRow'));
1756  
1757 706 my $out = $self->connection->$method($table, $arg, @changes, %opts);
1758 622 ▶ $row->set_row_data($out) if $row && $out;
Branch: 1 branch
BranchTrueFalseTotal
if $row and $out 68 554 622
Condition100%3/3
$row and $out
!ll&&!rl&&r
545968
MC/DC100%2/2
$row and $out
$row $out
Truth table100%3/3
A and B
A= $rowB= $out
ABresult
0X0
100
111
1759  
1760 622 ▶ return if $void;
Branch: 1 branch
BranchTrueFalseTotal
if $void 199 423 622
1761 423 ▶ return $out unless ref $out;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $out 43 380 423
1762  
1763 380 ▶ if (ref($out) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $out eq "ARRAY") 24 356 380
1764 24 ▶ return $out if $data;
Branch: 1 branch
BranchTrueFalseTotal
if $data 1 23 24
1765 23 ▶ my $build = $self->_row_builder($table, @build) or return $out;
Branch: 1 branch
BranchTrueFalseTotal
my $build = $self->_row_builder($table, @build) or return $out 12 11 23
1766 12 return [map { $build->($_) } @$out];
1767 }
1768  
1769 356 ▶ return $data ? $out : $row || $self->_row($table, $out, @build);
Branch: 1 branch
BranchTrueFalseTotal
$data ? : 39 317 356
Condition66%2/3
$row or $self->_row($table, $out, @build)
l!l&&r!l&&!r
492680
MC/DC0%0/2
$row or $self->_row($table, $out, @build)
$row $self->_row($table, $out, @build)
Truth table66%2/3
A or B
A= $rowB= $self->_row($table, $out, @build)
ABresult
1X1
011
000
1770 }
1771  
1772 =pod
1773  
1774 =over 4
1775  
1776 =item $out = $orm->_find_or_insert(\@frame, $table, \%fields, %opts)
1777  
1778 C<find_or_insert>, reporting its errors at C<@frame>, the public method's
1779 C<caller(0)> frame, which its reads and insert also run under in the lookup
1780 table's C<caller> slot. Handles pass their C<row_class> as the option of that
1781 name, before the caller's options.
1782  
1783 =back
1784  
1785 =cut
1786  
1787 303 my %FIND_OR_INSERT_ARGS = map { $_ => 1 } qw/by data raw row_class/;
1788  
1789 31 ▶sub _find_or_insert {
Subroutine _find_or_insert: called CC=21 SCAR=30.7
1790 31 my $self = shift;
1791 31 my ($frame, $table, $fields, @args) = @_;
1792 31 ▶ _croak_at($frame, "Odd number of options to find_or_insert()") if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 30 31
1793 30 my %opts = @args;
1794  
1795 30 my @unknown = sort grep { !$FIND_OR_INSERT_ARGS{$_} } keys %opts;
1796 30 ▶ _croak_at($frame, "Unknown argument(s) to find_or_insert(): " . join(', ' => @unknown)) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 29 30
1797 29 ▶ _croak_at($frame, "find_or_insert() needs the fields as a hashref") unless ref($fields) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fields eq "HASH" 0 29 29
1798 29 ▶ delete $opts{row_class} if $opts{data}; # data wins
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"data"} 2 27 29
1799 29 my @build = $self->_row_class_opt(\%opts);
1800  
1801 29 ▶ my $by = $opts{by} // $self->db_map->pk($table) // _croak_at($frame, "find_or_insert() needs 'by': the table '$table' has no primary key");
Condition83%5/6
($opts{"by"} // $self->db_map->pk($table)) // _croak_at($frame, "find_or_insert() needs 'by': the table '${table}' has no primary key")
l!l&&r!l&&!r
2810
$opts{"by"} // $self->db_map->pk($table)
l!l&&r!l&&!r
15131
MC/DC0%0/3
($opts{"by"} // $self->db_map->pk($table)) // _croak_at($frame, "find_or_insert() needs 'by': the table '${table}' has no primary key")
$opts{"by"} $self->db_map->pk($table) _croak_at($frame, "find_or_insert() needs 'by': the table '${table}' has no primary key")
Truth table50%2/4
A // B // C
A= $opts{"by"}B= $self->db_map->pk($table)C= _croak_at($frame, "find_or_insert() needs 'by': the table '${table}' has no primary key")
ABCresult
1XX1
01X1
0011
0000
1802 28 ▶ _croak_at($frame, "'by' must be a non-empty arrayref of field names") unless ref($by) eq 'ARRAY' && @$by;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $by eq "ARRAY" and @$by 2 26 28
Condition100%3/3
ref $by eq "ARRAY" and @$by
!ll&&!rl&&r
1126
MC/DC100%2/2
ref $by eq "ARRAY" and @$by
ref $by eq "ARRAY" @$by
Truth table100%3/3
A and B
A= ref $by eq "ARRAY"B= @$by
ABresult
0X0
100
111
1803 26 my @missing = grep { !exists $fields->{$_} } @$by;
1804 26 ▶ _croak_at($frame, "find_or_insert() finds by (" . join(', ' => @missing) . "), which the fields do not give") if @missing;
Branch: 1 branch
BranchTrueFalseTotal
if @missing 1 25 26
1805  
1806 25 my $conn = $self->connection;
1807 25 ▶ my $lookup = $self->{+DEBUG} && $conn->lookup;
Condition33%1/3
$self->{'debug'} && $conn->lookup
!ll&&!rl&&r
2500
MC/DC0%0/2
$self->{'debug'} && $conn->lookup
$self->{'debug'} $conn->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $conn->lookup
ABresult
0X0
100
111
1808 25 ▶ local $lookup->{caller} = $frame if $lookup && !$lookup->{caller}; # the reads and the insert below can replace row data
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 25 25
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
2500
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
1809 25 $conn->_check_fields($table, sort keys %$fields);
1810 23 my $where = $conn->deflate($table, {map { $_ => $fields->{$_} } @$by}, raw => $opts{raw});
1811 23 my @undef = grep { !defined $where->{$_} } @$by;
1812 23 ▶ _croak_at($frame, "find_or_insert() cannot find by an undef value: (" . join(', ' => @undef) . ")") if @undef;
Branch: 1 branch
BranchTrueFalseTotal
if @undef 2 21 23
1813  
1814 21 my $h = $self->handle($table)->data_only->where($where)->limit(2);
1815 24 ▶ my $find = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1816 24 $h->clear; # a retry after a failed insert must query again
1817 24 my @found = $h->all;
1818 24 ▶ _croak_at($frame, "find_or_insert() found more than one row in '$table' by (" . join(', ' => @$by) . ")") if @found > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @found > 1 1 23 24
1819 23 return $found[0];
1820 21 };
1821  
1822 21 my $data = $find->();
1823 20 ▶ unless ($data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($data) 11 9 20
1824 11 ▶ my $insert = sub { $self->insert($table => $fields, data => 1, raw => $opts{raw}) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1825 11 ▶ my $bare = @{$conn->txns} && !$conn->dialect->supports_savepoints;
Condition66%2/3
@{$conn->txns;} && !$conn->dialect->supports_savepoints
!ll&&!rl&&r
740
MC/DC0%0/2
@{$conn->txns;} && !$conn->dialect->supports_savepoints
@{$conn->txns;} !$conn->dialect->supports_savepoints
Truth table66%2/3
A && not(B)
A= @{$conn->txns;}B= !$conn->dialect->supports_savepoints
ABresult
0X0
100
111
1826 11 ▶ unless (eval { $data = $bare ? $insert->() : $self->txn($insert); 1 }) {
Branch: 2 branches
BranchTrueFalseTotal
unless (eval { do { $data = $bare ? &$insert() : $self->txn($insert); 1 } }) 3 8 11
$bare ? : 0 11 11
1827 3 my $err = $@;
1828 3 ▶ $data = eval { $find->() } or die $err;
Branch: 1 branch
BranchTrueFalseTotal
$data = eval { do { &$find() } } or die $err 2 1 3
1829 }
1830 }
1831  
1832 19 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 19 19
1833 19 ▶ return $opts{data} ? $data : $self->_row($table, $data, @build);
Branch: 1 branch
BranchTrueFalseTotal
$opts{'data'} ? : 2 17 19
1834 }
1835  
1836 =pod
1837  
1838 =over 4
1839  
1840 =item $row = $orm->_row($table, \%data, %opts)
1841  
1842 The row data, or a row object over it when the table has a row class. Undef
1843 for undef. A C<row_class> option, when present (even undef), replaces the
1844 table's class. Handles and the C<row_class> CRUD option pass it this way.
1845 Built by C<_row_builder>.
1846  
1847 =back
1848  
1849 =cut
1850  
1851 411 ▶sub _row {
Subroutine _row: called CC=3 SCAR=11.0
1852 411 my $self = shift;
1853 411 my ($table, $data, %opts) = @_;
1854 411 ▶ return undef unless $data;
Branch: 1 branch
BranchTrueFalseTotal
unless $data 12 399 411
1855  
1856 399 ▶ my $build = $self->_row_builder($table, %opts) or return $data;
Branch: 1 branch
BranchTrueFalseTotal
my $build = $self->_row_builder($table, %opts) or return $data 184 215 399
1857 184 return $build->($data);
1858 }
1859  
1860 =pod
1861  
1862 =over 4
1863  
1864 =item $build = $orm->_row_builder($table, %opts)
1865  
1866 What turns row data into rows of the table, resolved once for a whole result
1867 set: a code reference taking the row data and returning the row object, or
1868 undef when rows are hashrefs (no row class). The C<row_class> option is as for
1869 C<_row>.
1870  
1871 Every place that builds table rows uses it. When the class's C<fast_bless> is
1872 true the row is blessed directly, otherwise built with C<new>. The ORM asks
1873 each class for C<fast_bless> once and remembers the answer.
1874  
1875 =back
1876  
1877 =cut
1878  
1879 672 ▶sub _row_builder {
Subroutine _row_builder: called CC=7 SCAR=19.5
1880 672 my $self = shift;
1881 672 my ($table, %opts) = @_;
1882  
1883 672 ▶ my $class = exists $opts{row_class} ? $opts{row_class} : $self->_row_class($table);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'row_class'} ? : 83 589 672
1884 672 ▶ return undef unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 350 322 672
1885  
1886 322 ▶ my $fast = $self->{+FAST_BLESS}->{$class} //= $class->can('fast_bless') && $class->fast_bless ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('fast_bless') && $class->fast_bless ? : 57 12 69
Condition100%5/5
$self->{"fast_bless"}{$class} //= $class->can("fast_bless") && $class->fast_bless ? 1 : 0
l!l
25369
$class->can("fast_bless") and $class->fast_bless
!ll&&!rl&&r
4857
MC/DC100%1/1
$self->{"fast_bless"}{$class} //= $class->can("fast_bless") && $class->fast_bless ? 1 : 0
$self->{"fast_bless"}{$class}
Truth table100%2/2
A
A= $self->{"fast_bless"}{$class}
Aresult
11
00
1887 377 ▶ return sub { bless({orm => $self, table => $table, row_data => $_[0]}, $class) }
Subroutine __ANON__: called CC=1 SCAR=0.0
1888 322 ▶ if $fast;
Branch: 1 branch
BranchTrueFalseTotal
if $fast 308 14 322
1889 14 ▶ return sub { $class->new(row_data => $_[0], orm => $self, table => $table) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1890 }
1891  
1892 =pod
1893  
1894 =over 4
1895  
1896 =item @args = $orm->_row_class_opt(\%opts)
1897  
1898 Takes the C<row_class> option out of a CRUD call's options and returns it as
1899 named arguments for C<_row> and C<_row_builder>: C<< (row_class => $class) >>
1900 when present (undef for row data), or an empty list when absent. Loads a class
1901 that is not loaded yet. Croaks for a reference.
1902  
1903 =back
1904  
1905 =cut
1906  
1907 761 ▶sub _row_class_opt {
Subroutine _row_class_opt: called CC=4 SCAR=13.9
1908 761 my $self = shift;
1909 761 my ($opts) = @_;
1910 761 ▶ return () unless exists $opts->{row_class};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"row_class"} 737 24 761
1911  
1912 24 my $class = delete $opts->{row_class};
1913 24 ▶ croak "'row_class' must be a class name or undef" if ref $class;
Branch: 1 branch
BranchTrueFalseTotal
if ref $class 1 23 24
1914 23 ▶ $self->load_row_class($class) if defined $class;
Branch: 1 branch
BranchTrueFalseTotal
if defined $class 15 8 23
1915 22 return (row_class => $class);
1916 }
1917  
1918 =pod
1919  
1920 =over 4
1921  
1922 =item $class = $orm->_row_class($table)
1923  
1924 The table's row class: its C<row_class> in the map when set (even to undef),
1925 otherwise the ORM's, which is also the class for an undef table.
1926  
1927 =back
1928  
1929 =cut
1930  
1931 633 ▶sub _row_class {
Subroutine _row_class: called CC=4 SCAR=13.9
1932 633 my $self = shift;
1933 633 my ($table) = @_;
1934 633 ▶ my $t = defined($table) ? $self->db_map->table($table) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $table ? : 621 12 633
1935 633 ▶ return $t->{row_class} if $t && exists $t->{row_class};
Branch: 1 branch
BranchTrueFalseTotal
if $t and exists $t->{"row_class"} 15 618 633
Condition100%3/3
$t and exists $t->{"row_class"}
!ll&&!rl&&r
1260615
MC/DC100%2/2
$t and exists $t->{"row_class"}
$t exists $t->{"row_class"}
Truth table100%3/3
A and B
A= $tB= exists $t->{"row_class"}
ABresult
0X0
100
111
1936 618 return $self->{+ROW_CLASS};
1937 }
1938  
1939 1909 ▶my $STR = sub { defined($_[0]) && !ref($_[0]) && length($_[0]) };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and not ref $_[0] and length $_[0] 1887 22 1909
Condition100%3/3
defined $_[0] and not ref $_[0]
!ll&&!rl&&r
2201887
MC/DC100%2/2
defined $_[0] and not ref $_[0]
defined $_[0] not ref $_[0]
Truth table100%3/3
A and not(B)
A= defined $_[0]B= not ref $_[0]
ABresult
0X0
100
111
1940 256 ▶my $OPT_STR = sub { !defined($_[0]) || $STR->($_[0]) };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
not defined $_[0] or &$STR($_[0]) 94 162 256
1941 79 ▶my $STR_LIST = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1942 79 ▶ ref($_[0]) eq 'ARRAY' && !grep { !$STR->($_) } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and not grep({not &$STR($_);} @{$_[0];}) 76 3 79
1943 303 };
1944 1161 ▶my $HASH_OF = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1945 1161 my ($check) = @_;
1946 618 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1947 618 ▶ ref($_[0]) eq 'HASH' && !grep { !$check->($_) } values %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "HASH" and not grep({not &$check($_);} values %{$_[0];}) 616 2 618
1948 1161 };
1949 303 };
1950 26 ▶my $LINK = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1951 26 ▶ ref($_[0]) eq 'HASH' && %{$_[0]} && !grep { !$STR->($_) } values %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "HASH" and %{$_[0];} and not grep({not &$STR($_);} values %{$_[0];}) 25 1 26
Condition66%2/3
ref $_[0] eq "HASH" and %{$_[0];}
!ll&&!rl&&r
0125
MC/DC50%1/2
ref $_[0] eq "HASH" and %{$_[0];}
ref $_[0] eq "HASH" %{$_[0];}
Truth table66%2/3
A and B
A= ref $_[0] eq "HASH"B= %{$_[0];}
ABresult
0X0
100
111
1952 303 };
1953  
1954 my %SHAPES = (
1955 row_class => ['a class name or undef', $OPT_STR],
1956 10 ▶ row_namespace => ['a package name', sub { $STR->($_[0]) && $_[0] =~ m/^\w+(?:::\w+)*\z/ }],
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
&$STR($_[0]) and $_[0] =~ /^\w+(?:::\w+)*\z/ 10 0 10
1957 3 ▶ row_class_name => ['a code reference', sub { ref($_[0]) eq 'CODE' }],
Subroutine __ANON__: called CC=1 SCAR=0.0
1958 12 ▶ retain_cache => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
1959 5 ▶ enforce_canon => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
1960 2 ▶ debug => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
1961 time_zone => ['a time zone name', $STR],
1962  
1963 auto_omit => [
1964 'undef, or a hashref of types => [type names] and db_types => [type names]',
1965 11 ▶ sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
1966 11 ▶ !defined($_[0]) || (ref($_[0]) eq 'HASH' && !grep { !m/^(?:types|db_types)\z/ } keys %{$_[0]}) && !grep { !$STR_LIST->($_) } values %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
not defined $_[0] or ref $_[0] eq "HASH" and not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];}) and not grep({not &$STR_LIST($_);} values %{$_[0];}) 0 11 11
Condition77%7/9
!defined($_[0]) || ref $_[0] eq 'HASH' && !grep({not /^(?:types|db_types)\z/;} keys %{$_[0];}) && !grep({not &$STR_LIST($_);} values %{$_[0];})
l!l&&r!l&&!r
092
ref $_[0] eq "HASH" and not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];}) and not grep({not &$STR_LIST($_);} values %{$_[0];})
!ll&&!rl&&r
209
ref $_[0] eq "HASH" and not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];})
!ll&&!rl&&r
119
MC/DC50%2/4
!defined($_[0]) || ref $_[0] eq 'HASH' && !grep({not /^(?:types|db_types)\z/;} keys %{$_[0];}) && !grep({not &$STR_LIST($_);} values %{$_[0];})
!defined($_[0]) ref $_[0] eq "HASH" not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];}) not grep({not &$STR_LIST($_);} values %{$_[0];})
Truth table60%3/5
not(A) || B and not(C) and not(D)
A= !defined($_[0])B= ref $_[0] eq "HASH"C= not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];})D= not grep({not &$STR_LIST($_);} values %{$_[0];})
ABCDresult
1XXX1
01111
00XX0
010X0
01100
1967 }
1968 ],
1969  
1970 like_aggregates => [
1971 'an arrayref of function names',
1972 3 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
1973 3 ▶ ref($_[0]) eq 'ARRAY' && !grep { !$STR->($_) || !m/^\w+\z/ } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and not grep({not &$STR($_) && /^\w+\z/;} @{$_[0];}) 3 0 3
Condition66%2/3
&$STR($_) && /^\w+\z/
!ll&&!rl&&r
012
MC/DC50%1/2
&$STR($_) && /^\w+\z/
&$STR($_) /^\w+\z/
Truth table66%2/3
A && B
A= &$STR($_)B= /^\w+\z/
ABresult
0X0
100
111
1974 }
1975 ],
1976  
1977 where_builders => [
1978 'a non-empty arrayref of where builders: classes or objects',
1979 405 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
1980 405 ▶ ref($_[0]) eq 'ARRAY' && @{$_[0]} && !grep { !blessed($_) && !($STR->($_) && m/^\w+(?:::\w+)*\z/) } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and @{$_[0];} and not grep({not builtin::blessed($_) || &$STR($_) && /^\w+(?:::\w+)*\z/;} @{$_[0];}) 402 3 405
Condition88%8/9
ref $_[0] eq "ARRAY" and @{$_[0];}
!ll&&!rl&&r
12402
builtin::blessed($_) || &$STR($_) && /^\w+(?:::\w+)*\z/
l!l&&r!l&&!r
211751
&$STR($_) and /^\w+(?:::\w+)*\z/
!ll&&!rl&&r
101175
MC/DC100%2/2
ref $_[0] eq "ARRAY" and @{$_[0];}
ref $_[0] eq "ARRAY" @{$_[0];}
MC/DC66%2/3
builtin::blessed($_) || &$STR($_) && /^\w+(?:::\w+)*\z/
builtin::blessed($_) &$STR($_) /^\w+(?:::\w+)*\z/
Truth table100%3/3
A and B
A= ref $_[0] eq "ARRAY"B= @{$_[0];}
ABresult
0X0
100
111
Truth table75%3/4
A || B and C
A= builtin::blessed($_)B= &$STR($_)C= /^\w+(?:::\w+)*\z/
ABCresult
1XX1
0111
00X0
0100
1981 }
1982 303 ],
1983 );
1984  
1985 303 %ARGS = map { $_ => 1 } keys(%SHAPES), qw/datetime_parsers isolation tz dbh connect credentials db_map rescan row_classes omit default_fields types type_options autotype append_autotype fks sql_builder/;
1986  
1987 =pod
1988  
1989 =over 4
1990  
1991 =item $orm->_check_args
1992  
1993 Turns C<tz> into C<time_zone>, then croaks naming the first argument in
1994 C<%SHAPES> whose shape is wrong. The Connection checks C<datetime_parsers>.
1995  
1996 =back
1997  
1998 =cut
1999  
2000 427 ▶sub _check_args {
Subroutine _check_args: called CC=6 SCAR=17.9
2001 427 my $self = shift;
2002  
2003 427 ▶ if (exists $self->{tz}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"tz"}) 7 420 427
2004 7 ▶ croak "Give 'time_zone' or its alias 'tz', not both" if exists $self->{time_zone};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"time_zone"} 2 5 7
2005 5 $self->{time_zone} = delete $self->{tz};
2006 }
2007  
2008 425 for my $arg (sort keys %SHAPES) {
2009 4199 ▶ next unless exists $self->{$arg};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{$arg} 4015 184 4199
2010 184 my ($want, $check) = @{$SHAPES{$arg}};
2011 184 ▶ croak "'$arg' must be $want" unless $check->($self->{$arg});
Branch: 1 branch
BranchTrueFalseTotal
unless &$check($self->{$arg}) 14 170 184
2012 }
2013 }
2014  
2015 =pod
2016  
2017 =over 4
2018  
2019 =item _croak_at(\@frame, $message)
2020  
2021 Dies with the message at the frame's file and line, worded as C<croak> words
2022 it. C<@frame> is a C<caller> frame that a public method captured, so an error
2023 found deeper, reached through a handle or a row, reports the user's line.
2024  
2025 =item _rethrow_at(\@frame, $what, $error)
2026  
2027 Rethrows an error caught at a public entry, with the frame's file and line
2028 appended: C<< (from $what at FILE line N) >>. The error keeps its own location,
2029 so a bug report still shows where it was thrown. Exception objects are
2030 rethrown unchanged, and so is a message that already ends at the frame's line.
2031  
2032 Use it where one public call reaches many errors in other modules, such as
2033 C<new>. C<_croak_at> suits a chain with a few known errors.
2034  
2035 =back
2036  
2037 =cut
2038  
2039 44 ▶sub _croak_at {
Subroutine _croak_at: called CC=1 SCAR=0.0
2040 44 my ($frame, $msg) = @_;
2041 44 die "$msg at $frame->[1] line $frame->[2].\n";
2042 }
2043  
2044 140 ▶sub _rethrow_at {
Subroutine _rethrow_at: called CC=3 SCAR=11.0
2045 140 my ($frame, $what, $err) = @_;
2046  
2047 140 ▶ die $err if ref $err;
Branch: 1 branch
BranchTrueFalseTotal
if ref $err 1 139 140
2048  
2049 139 my $at = " at $frame->[1] line $frame->[2].\n";
2050 139 ▶ die $err if substr($err, -length($at)) eq $at;
Branch: 1 branch
BranchTrueFalseTotal
if substr($err, -length($at)) eq $at 94 45 139
2051  
2052 45 chomp($err);
2053 45 die "$err\n (from $what at $frame->[1] line $frame->[2])\n";
2054 }
2055  
2056 =pod
2057  
2058 =over 4
2059  
2060 =item $h = $orm->_follow_fk(\@frame, $table, $row_or_data, $other_table, %params)
2061  
2062 C<follow_fk>, reporting its errors at C<@frame>: the C<caller(0)> frame of the
2063 public C<follow_fk> (the ORM's or a row's). When the row lacks link fields,
2064 the read of them runs under C<@frame> in the lookup table's C<caller> slot.
2065  
2066 =back
2067  
2068 =cut
2069  
2070 303 my %FOLLOW_ARGS = (link => 1, via => 1);
2071  
2072 42 ▶sub _follow_fk {
Subroutine _follow_fk: called CC=14 SCAR=27.2
2073 42 my $self = shift;
2074 42 my ($frame, $table, $data, $other, %params) = @_;
2075  
2076 42 my @unknown = sort grep { !$FOLLOW_ARGS{$_} } keys %params;
2077 42 ▶ _croak_at($frame, "Unknown argument(s) to follow_fk(): " . join(', ' => @unknown)) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 41 42
2078  
2079 41 my $conn = $self->connection;
2080 41 my $map = $conn->db_map;
2081 41 ▶ _croak_at($frame, "The table '$table' is not in the database map") unless defined($table) && $map->table($table);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and $map->table($table) 0 41 41
Condition33%1/3
defined $table and $map->table($table)
!ll&&!rl&&r
0041
MC/DC0%0/2
defined $table and $map->table($table)
defined $table $map->table($table)
Truth table33%1/3
A and B
A= defined $tableB= $map->table($table)
ABresult
0X0
100
111
2082 41 ▶ _croak_at($frame, "follow_fk() needs the table to follow to") unless defined($other) && length($other);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $other and length $other 0 41 41
Condition33%1/3
defined $other and length $other
!ll&&!rl&&r
0041
MC/DC0%0/2
defined $other and length $other
defined $other length $other
Truth table33%1/3
A and B
A= defined $otherB= length $other
ABresult
0X0
100
111
2083  
2084 41 my $link = $self->_link_for($frame, $map, $table, $other, \%params);
2085 27 ▶ $data = $data->row_data if blessed($data) && $data->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($data) and $data->can("row_data") 18 9 27
Condition66%2/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
9018
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
2086 27 ▶ _croak_at($frame, "follow_fk() needs row data (a hashref) or a row object") unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 1 26 27
2087 26 ▶ if (my @missing = grep { !exists $data->{$_} } sort keys %$link) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@missing) = grep({not exists $data->{$_};} sort(keys %$link))) 5 21 26
2088 5 ▶ my $lookup = $self->{+DEBUG} && $conn->lookup;
Condition66%2/3
$self->{'debug'} && $conn->lookup
!ll&&!rl&&r
401
MC/DC50%1/2
$self->{'debug'} && $conn->lookup
$self->{'debug'} $conn->lookup
Truth table66%2/3
A && B
A= $self->{'debug'}B= $conn->lookup
ABresult
0X0
100
111
2089 5 ▶ local $lookup->{caller} = $frame if $lookup && !$lookup->{caller}; # the read can replace the row's canonical copy
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 1 4 5
Condition66%2/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
401
MC/DC50%1/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table66%2/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
2090 5 ▶ $data = $conn->refresh_row($table, $data, fields => $self->_with_held($table, $data, @missing)) or _croak_at($frame, "Cannot follow the foreign key: the row is no longer in the table '$table'");
Branch: 1 branch
BranchTrueFalseTotal
$data = $conn->refresh_row($table, $data, "fields", $self->_with_held($table, $data, @missing)) or _croak_at($frame, "Cannot follow the foreign key: the row is no longer in the table '${table}'") 4 1 5
2091 }
2092  
2093 25 return $self->_fk_handle($other, {map { ($link->{$_} => $data->{$_}) } keys %$link});
2094 }
2095  
2096 =pod
2097  
2098 =over 4
2099  
2100 =item $out = $orm->_insert_fk(\@frame, $method, $table, $row_or_data, $other_table, @args)
2101  
2102 C<insert_fk> (C<$method> C<insert>) or C<insert_many_fk> (C<insert_many>),
2103 reporting its errors at C<@frame>: the C<caller(0)> frame of the public method
2104 (the ORM's or a row's), which its reads and inserts also run under in the
2105 lookup table's C<caller> slot.
2106  
2107 =back
2108  
2109 =cut
2110  
2111 my %INSERT_FK_ARGS = (
2112 1818 insert => {map { $_ => 1 } qw/link via raw data as_given row_class/},
2113 303 insert_many => {map { $_ => 1 } qw/link via raw data count row_class/},
2114 );
2115  
2116 32 ▶sub _insert_fk {
Subroutine _insert_fk: called CC=27 SCAR=34.2
2117 32 my $self = shift;
2118 32 my ($frame, $method, $table, $data, $other, @args) = @_;
2119 32 my $name = "${method}_fk";
2120  
2121 32 my (%opts, @rows);
2122 32 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 49 27 76
2123 49 my $arg = shift @args;
2124 49 ▶ if (ref($arg) eq 'HASH') { push @rows => $arg; next }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg eq "HASH") 31 18 49
2125 18 ▶ _croak_at($frame, "$name() takes option => value pairs and hashrefs of fields, not " . ($arg // 'undef')) if ref($arg) || !defined($arg);
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg or not defined $arg 1 17 18
Condition50%3/6
ref $arg or not defined $arg
l!l&&r!l&&!r
1017
$arg // "undef"
l!l
100
MC/DC50%1/2
ref $arg or not defined $arg
ref $arg not defined $arg
MC/DC0%0/1
$arg // "undef"
$arg
Truth table66%2/3
A or not(B)
A= ref $argB= not defined $arg
ABresult
1X1
011
000
Truth table50%1/2
A
A= $arg
Aresult
11
00
2126 17 ▶ _croak_at($frame, "Unknown argument to $name(): $arg") unless $INSERT_FK_ARGS{$method}->{$arg};
Branch: 1 branch
BranchTrueFalseTotal
unless $INSERT_FK_ARGS{$method}{$arg} 3 14 17
2127 14 ▶ _croak_at($frame, "The option '$arg' to $name() has no value") unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 13 14
2128 13 $opts{$arg} = shift @args;
2129 }
2130 27 ▶ _croak_at($frame, "insert_fk() inserts one row; use insert_many_fk() for more") if $method eq 'insert' && @rows != 1;
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "insert" and @rows != 1 2 25 27
Condition100%3/3
$method eq "insert" and @rows != 1
!ll&&!rl&&r
8172
MC/DC100%2/2
$method eq "insert" and @rows != 1
$method eq "insert" @rows != 1
Truth table100%3/3
A and B
A= $method eq "insert"B= @rows != 1
ABresult
0X0
100
111
2131  
2132 25 my $conn = $self->connection;
2133 25 my $map = $conn->db_map;
2134 25 ▶ my $lookup = $self->{+DEBUG} && $conn->lookup;
Condition33%1/3
$self->{'debug'} && $conn->lookup
!ll&&!rl&&r
2500
MC/DC0%0/2
$self->{'debug'} && $conn->lookup
$self->{'debug'} $conn->lookup
Truth table33%1/3
A && B
A= $self->{'debug'}B= $conn->lookup
ABresult
0X0
100
111
2135 25 ▶ local $lookup->{caller} = $frame if $lookup && !$lookup->{caller}; # the reads and the inserts below can replace row data
Branch: 1 branch
BranchTrueFalseTotal
if $lookup and not $lookup->{"caller"} 0 25 25
Condition33%1/3
$lookup and not $lookup->{"caller"}
!ll&&!rl&&r
2500
MC/DC0%0/2
$lookup and not $lookup->{"caller"}
$lookup not $lookup->{"caller"}
Truth table33%1/3
A and not(B)
A= $lookupB= not $lookup->{"caller"}
ABresult
0X0
100
111
2136 25 ▶ _croak_at($frame, "The table '$table' is not in the database map") unless defined($table) && $map->table($table);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table and $map->table($table) 0 25 25
Condition33%1/3
defined $table and $map->table($table)
!ll&&!rl&&r
0025
MC/DC0%0/2
defined $table and $map->table($table)
defined $table $map->table($table)
Truth table33%1/3
A and B
A= defined $tableB= $map->table($table)
ABresult
0X0
100
111
2137 25 ▶ _croak_at($frame, "$name() needs the table to insert into") unless defined($other) && length($other);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $other and length $other 0 25 25
Condition33%1/3
defined $other and length $other
!ll&&!rl&&r
0025
MC/DC0%0/2
defined $other and length $other
defined $other length $other
Truth table33%1/3
A and B
A= defined $otherB= length $other
ABresult
0X0
100
111
2138 25 my $link = $self->_link_for($frame, $map, $table, $other, {map { ($_ => delete $opts{$_}) } grep { exists $opts{$_} } qw/link via/}, $name);
2139  
2140 21 ▶ $data = $data->row_data if blessed($data) && $data->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($data) and $data->can("row_data") 18 3 21
Condition66%2/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
3018
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
2141 21 ▶ _croak_at($frame, "$name() needs row data (a hashref) or a row object") unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 21 21
2142 21 ▶ _croak_at($frame, "Cannot insert rows linked to a '$table' row that is not in the database") if DBIx::QuickORM::LookupTable->row_state($data);
Branch: 1 branch
BranchTrueFalseTotal
if "DBIx::QuickORM::LookupTable"->row_state($data) 2 19 21
2143 19 ▶ if (my @missing = grep { !exists $data->{$_} } sort keys %$link) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@missing) = grep({not exists $data->{$_};} sort(keys %$link))) 2 17 19
2144 2 ▶ $data = $conn->refresh_row($table, $data, fields => $self->_with_held($table, $data, @missing)) or _croak_at($frame, "Cannot insert linked rows: the row is no longer in the table '$table'");
Branch: 1 branch
BranchTrueFalseTotal
$data = $conn->refresh_row($table, $data, "fields", $self->_with_held($table, $data, @missing)) or _croak_at($frame, "Cannot insert linked rows: the row is no longer in the table '${table}'") 2 0 2
2145 }
2146 19 my %values = map { ($link->{$_} => $data->{$_}) } keys %$link;
2147 19 ▶ if (my @null = sort grep { !defined $values{$_} } keys %values) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@null) = sort(grep({not defined $values{$_};} keys %values))) 1 18 19
2148 1 _croak_at($frame, "Cannot insert rows linked to a '$table' row whose linked value is NULL (" . join(', ' => @null) . ")");
2149 }
2150 18 for my $row (@rows) {
2151 21 my @set = sort grep { exists $row->{$_} } keys %values;
2152 21 ▶ _croak_at($frame, "$name() sets the link field(s) itself; remove " . join(', ' => @set) . " from the row") if @set;
Branch: 1 branch
BranchTrueFalseTotal
if @set 2 19 21
2153 }
2154  
2155 16 my %link_values = map { ($_ => raw($values{$_})) } keys %values; # row data is in database form already
2156 16 my @filled = map { +{%$_, %link_values} } @rows;
2157 16 ▶ return $self->_primitive($method, $other, $method eq 'insert' ? $filled[0] : \@filled, %opts);
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'insert' ? : 8 8 16
2158 }
2159  
2160 =pod
2161  
2162 =over 4
2163  
2164 =item \%link = $orm->_link_for(\@frame, $map, $table, $other, {link => \%link, via => \%via}, $insert_method)
2165  
2166 The link a call's C<link> or C<via> option gives: C<_via_link> for C<via>,
2167 otherwise C<_fk_link> with C<link> (undef when absent) and C<$insert_method>.
2168 Croaks when both are given.
2169  
2170 =item \%link = $orm->_via_link(\@frame, $map, $table, $other, \%via)
2171  
2172 C<%via>, C<< {our_field => their_field} >>, as the link, with no foreign key
2173 behind it. Croaks unless both tables are in the map, C<%via> is a non-empty
2174 hashref, and every field it names is a field of its table.
2175  
2176 =back
2177  
2178 =cut
2179  
2180 107 ▶sub _link_for {
Subroutine _link_for: called CC=4 SCAR=13.9
2181 107 my $self = shift;
2182 107 my ($frame, $map, $table, $other, $opts, $insert_method) = @_;
2183 107 ▶ _croak_at($frame, "Give 'link' or 'via', not both") if defined($opts->{link}) && defined($opts->{via});
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"link"} and defined $opts->{"via"} 1 106 107
Condition100%3/3
defined $opts->{"link"} and defined $opts->{"via"}
!ll&&!rl&&r
85211
MC/DC100%2/2
defined $opts->{"link"} and defined $opts->{"via"}
defined $opts->{"link"} defined $opts->{"via"}
Truth table100%3/3
A and B
A= defined $opts->{"link"}B= defined $opts->{"via"}
ABresult
0X0
100
111
2184 106 ▶ return $self->_via_link($frame, $map, $table, $other, $opts->{via}) if defined $opts->{via};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"via"} 11 95 106
2185 95 return $self->_fk_link($frame, $map, $table, $other, $opts->{link}, $insert_method);
2186 }
2187  
2188 11 ▶sub _via_link {
Subroutine _via_link: called CC=10 SCAR=23.3
2189 11 my $self = shift;
2190 11 my ($frame, $map, $table, $other, $via) = @_;
2191  
2192 11 ▶ _croak_at($frame, "'via' must be a hashref of field => field") unless ref($via) eq 'HASH' && %$via;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $via eq "HASH" and %$via 1 10 11
Condition66%2/3
ref $via eq "HASH" and %$via
!ll&&!rl&&r
0110
MC/DC50%1/2
ref $via eq "HASH" and %$via
ref $via eq "HASH" %$via
Truth table66%2/3
A and B
A= ref $via eq "HASH"B= %$via
ABresult
0X0
100
111
2193 10 for my $t ($table, $other) {
2194 20 ▶ _croak_at($frame, "The table '$t' is not in the database map") unless $map->table($t);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->table($t) 1 19 20
2195 }
2196 9 for my $ours (sort keys %$via) {
2197 9 my $theirs = $via->{$ours};
2198 9 ▶ _croak_at($frame, "'via' names '$ours', which is not a field of '$table'") unless $map->field($table, $ours);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->field($table, $ours) 1 8 9
2199 8 ▶ _croak_at($frame, "'via' names '" . ($theirs // 'undef') . "', which is not a field of '$other'") unless defined($theirs) && $map->field($other, $theirs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $theirs and $map->field($other, $theirs) 1 7 8
Condition50%3/6
defined $theirs and $map->field($other, $theirs)
!ll&&!rl&&r
017
$theirs // "undef"
l!l
100
MC/DC50%1/2
defined $theirs and $map->field($other, $theirs)
defined $theirs $map->field($other, $theirs)
MC/DC0%0/1
$theirs // "undef"
$theirs
Truth table66%2/3
A and B
A= defined $theirsB= $map->field($other, $theirs)
ABresult
0X0
100
111
Truth table50%1/2
A
A= $theirs
Aresult
11
00
2200 }
2201  
2202 7 return {%$via};
2203 }
2204  
2205 =pod
2206  
2207 =over 4
2208  
2209 =item \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given)
2210  
2211 =item \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given, $insert_method)
2212  
2213 The link to follow, C<< {our_field => their_field} >>, from the foreign keys of
2214 C<$table> to C<$other> and those of C<$other> to C<$table> turned around: the
2215 one matching C<%given>, or the only one when C<%given> is undef. Croaks
2216 otherwise, and when C<$other> is not in the map, reporting at C<@frame>.
2217  
2218 With C<$insert_method> (the calling method's name, for messages), only the
2219 keys of C<$other> to C<$table> count, and a C<%given> matching a key of
2220 C<$table> to C<$other> croaks, naming the direction.
2221  
2222 =back
2223  
2224 =cut
2225  
2226 95 ▶sub _fk_link {
Subroutine _fk_link: called CC=22 SCAR=31.1
2227 95 my $self = shift;
2228 95 my ($frame, $map, $table, $other, $given, $insert_method) = @_;
2229  
2230 95 ▶ my $forward = ($map->table($table)->{fk} // {})->{$other} // [];
Condition50%3/6
+($map->table($table)->{"fk"} // {})->{$other} // []
l!l
64310
$map->table($table)->{"fk"} // {}
l!l
9500
MC/DC0%0/1
+($map->table($table)->{"fk"} // {})->{$other} // []
$map->table($table)->{"fk"}
Truth table50%1/2
A
A= $map->table($table)->{"fk"}
Aresult
11
00
2231 95 ▶ _croak_at($frame, "'$table' has a foreign key to '$other', which is not in the database map") if @$forward && !$map->table($other);
Branch: 1 branch
BranchTrueFalseTotal
if @$forward and not $map->table($other) 1 94 95
Condition100%3/3
@$forward and not $map->table($other)
!ll&&!rl&&r
31631
MC/DC100%2/2
@$forward and not $map->table($other)
@$forward not $map->table($other)
Truth table100%3/3
A and not(B)
A= @$forwardB= not $map->table($other)
ABresult
0X0
100
111
2232 94 ▶ _croak_at($frame, "The table '$other' is not in the database map") unless $map->table($other);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->table($other) 1 93 94
2233 93 ▶ my @back = map { +{reverse %$_} } @{($map->table($other)->{fk} // {})->{$table} // []};
Condition75%3/4
+($map->table($other)->{"fk"} // {})->{$table} // []
l!l
3756
$map->table($other)->{"fk"} // {}
l!l
930
MC/DC0%0/1
+($map->table($other)->{"fk"} // {})->{$table} // []
$map->table($other)->{"fk"}
Truth table50%1/2
A
A= $map->table($other)->{"fk"}
Aresult
11
00
2234 93 ▶ my @links = $insert_method ? @back : (@$forward, @back);
Branch: 1 branch
BranchTrueFalseTotal
$insert_method ? : 22 71 93
2235  
2236 137 ▶ my $key = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2237 137 my ($l) = @_;
2238 137 join "\0" => map { "$_\0$l->{$_}" } sort keys %$l;
2239 93 };
2240 93 my %found;
2241 93 ▶ $found{$key->($_)} //= $_ for @links;
Condition33%1/3
$found{&$key($_)} //= $_
l!l&&r!l&&!r
01130
MC/DC0%0/2
$found{&$key($_)} //= $_
$found{&$key($_)} $_
Truth table33%1/3
A //= B
A= $found{&$key($_)}B= $_
ABresult
1X1
011
000
2242  
2243 93 ▶ if (defined $given) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $given) 21 72 93
2244 21 ▶ _croak_at($frame, "'link' must be a hashref of field => field") unless ref($given) eq 'HASH' && %$given;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $given eq "HASH" and %$given 1 20 21
Condition66%2/3
ref $given eq "HASH" and %$given
!ll&&!rl&&r
1020
MC/DC50%1/2
ref $given eq "HASH" and %$given
ref $given eq "HASH" %$given
Truth table66%2/3
A and B
A= ref $given eq "HASH"B= %$given
ABresult
0X0
100
111
2245 20 ▶ if ($insert_method && !$found{$key->($given)} && first { $key->($_) eq $key->($given) } @$forward) {
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
if ($insert_method and not $found{&$key($given)} and &first(sub { &$key($_) eq &$key($given); } , @$forward)) 1 19 20
Condition100%6/6
$insert_method and not $found{&$key($given)} and &first(sub { &$key($_) eq &$key($given); } , @$forward)
!ll&&!rl&&r
1811
$insert_method and not $found{&$key($given)}
!ll&&!rl&&r
1712
MC/DC100%3/3
$insert_method and not $found{&$key($given)} and &first(sub { &$key($_) eq &$key($given); } , @$forward)
$insert_method not $found{&$key($given)} &first(sub { &$key($_) eq &$key($given); } , @$forward)
Truth table100%4/4
A and not(B) and C
A= $insert_methodB= not $found{&$key($given)}C= &first(sub { &$key($_) eq &$key($given); } , @$forward)
ABCresult
0XX0
10X0
1100
1111
2246 1 _croak_at($frame, "$insert_method() inserts rows that point at the '$table' row; the link (" . join(', ' => map { "$_ => $given->{$_}" } sort keys %$given) . ") points from it");
2247 }
2248 19 ▶ return $found{$key->($given)} // _croak_at($frame, "The link (" . join(', ' => map { "$_ => $given->{$_}" } sort keys %$given) . ") matches no foreign key between '$table' and '$other'");
Condition100%3/3
$found{&$key($given)} // _croak_at($frame, 'The link (' . join(", ", map({"$_ => $given->{$_}";} sort(keys %$given))) . ") matches no foreign key between '${table}' and '${other}'")
l!l&&r!l&&!r
1612
MC/DC0%0/2
$found{&$key($given)} // _croak_at($frame, 'The link (' . join(", ", map({"$_ => $given->{$_}";} sort(keys %$given))) . ") matches no foreign key between '${table}' and '${other}'")
$found{&$key($given)} _croak_at($frame, 'The link (' . join(", ", map({"$_ => $given->{$_}";} sort(keys %$given))) . ") matches no foreign key between '${table}' and '${other}'")
Truth table33%1/3
A // B
A= $found{&$key($given)}B= _croak_at($frame, 'The link (' . join(", ", map({"$_ => $given->{$_}";} sort(keys %$given))) . ") matches no foreign key between '${table}' and '${other}'")
ABresult
1X1
011
000
2249 }
2250  
2251 72 my @keys = sort keys %found;
2252 72 ▶ _croak_at($frame, "$insert_method() inserts rows that point at the '$table' row, and '$other' has no foreign key to '$table'") if $insert_method && !@keys;
Branch: 1 branch
BranchTrueFalseTotal
if $insert_method and not @keys 1 71 72
Condition100%3/3
$insert_method and not @keys
!ll&&!rl&&r
53181
MC/DC100%2/2
$insert_method and not @keys
$insert_method not @keys
Truth table100%3/3
A and not(B)
A= $insert_methodB= not @keys
ABresult
0X0
100
111
2253 71 ▶ _croak_at($frame, "There is no foreign key between '$table' and '$other'") unless @keys;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys 2 69 71
2254 69 ▶ _croak_at($frame, "There is more than one foreign key between '$table' and '$other'; choose one with 'link'") if @keys > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @keys > 1 5 64 69
2255 64 return $found{$keys[0]};
2256 }
2257  
2258 =pod
2259  
2260 =over 4
2261  
2262 =item $source = $orm->_table_source($table)
2263  
2264 The table's L<DBIx::QuickORM::Source::Table>, built on first use and then
2265 kept: sources are immutable, so every handle over the table shares it. Croaks
2266 as the source's C<new> does, keeping nothing.
2267  
2268 =back
2269  
2270 =cut
2271  
2272 241 ▶sub _table_source {
Subroutine _table_source: called CC=3 SCAR=11.4
2273 241 my $self = shift;
2274 241 my ($table) = @_;
2275 241 ▶ return $self->{+TABLE_SOURCES}->{$table // ''} //= DBIx::QuickORM::Source::Table->new(table => $table, db_map => $self->db_map);
Condition60%3/5
$self->{"table_sources"}{$table // ""} //= "DBIx::QuickORM::Source::Table"->new("table", $table, "db_map", $self->db_map)
l!l&&r!l&&!r
155860
$table // ""
l!l
2410
MC/DC0%0/2
$self->{"table_sources"}{$table // ""} //= "DBIx::QuickORM::Source::Table"->new("table", $table, "db_map", $self->db_map)
$self->{"table_sources"}{$table // ""} "DBIx::QuickORM::Source::Table"->new("table", $table, "db_map", $self->db_map)
MC/DC0%0/1
$table // ""
$table
Truth table66%2/3
A //= B
A= $self->{"table_sources"}{$table // ""}B= "DBIx::QuickORM::Source::Table"->new("table", $table, "db_map", $self->db_map)
ABresult
1X1
011
000
Truth table50%1/2
A
A= $table
Aresult
11
00
2276 }
2277  
2278 =pod
2279  
2280 =over 4
2281  
2282 =item \%fields = $orm->_table_fields($table)
2283  
2284 The table's field records from the map, kept after the first call. Rows read
2285 them on every field read, and this skips the walk through C<connection>. The
2286 map does not change after the ORM is built.
2287  
2288 In a forked child it goes through C<connection> first, so the child
2289 reconnects (or croaks) as before, whatever the parent read.
2290  
2291 =back
2292  
2293 =cut
2294  
2295 350 ▶sub _table_fields {
Subroutine _table_fields: called CC=3 SCAR=11.3
2296 350 my $self = shift;
2297 350 my ($table) = @_;
2298  
2299 350 ▶ $self->connection unless $self->{+CONNECTION}->pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connection"}->pid == $$ 0 350 350
2300 350 ▶ return $self->{+TABLE_FIELDS}->{$table} //= $self->db_map->table($table)->{fields};
Condition66%2/3
$self->{"table_fields"}{$table} //= $self->db_map->table($table)->{"fields"}
l!l&&r!l&&!r
289610
MC/DC0%0/2
$self->{"table_fields"}{$table} //= $self->db_map->table($table)->{"fields"}
$self->{"table_fields"}{$table} $self->db_map->table($table)->{"fields"}
Truth table66%2/3
A //= B
A= $self->{"table_fields"}{$table}B= $self->db_map->table($table)->{"fields"}
ABresult
1X1
011
000
2301 }
2302  
2303 =pod
2304  
2305 =over 4
2306  
2307 =item \@fields = $orm->_with_held($table, \%data, @missing)
2308  
2309 The fields the row data holds, then C<@missing>: what to read so that a read
2310 of missing fields holds everything the row already had, and so cannot
2311 replace its canonical copy with a narrower one.
2312  
2313 =back
2314  
2315 =cut
2316  
2317 7 ▶sub _with_held {
Subroutine _with_held: called CC=1 SCAR=0.0
2318 7 my $self = shift;
2319 7 my ($table, $data, @missing) = @_;
2320 7 my $fields = $self->_table_fields($table);
2321 7 return [(sort grep { $fields->{$_} } keys %$data), @missing];
2322 }
2323  
2324 =pod
2325  
2326 =over 4
2327  
2328 =item $h = $orm->_fk_handle($other, {$their_field => $value, ...})
2329  
2330 A handle on the rows of C<$other> whose fields hold these values, each field
2331 qualified as C<other.field> in the C<where>. An undef value refers to
2332 nothing: its condition is C<sql('IS NULL AND 1 = 0')>, which is never true.
2333 The handle is C<single> when the fields are exactly the primary key or a
2334 unique key of C<$other>, otherwise C<multi>. Croaks when C<$other> is not in
2335 the map.
2336  
2337 =back
2338  
2339 =cut
2340  
2341 42 ▶sub _fk_handle {
Subroutine _fk_handle: called CC=6 SCAR=18.2
2342 42 my $self = shift;
2343 42 my ($other, $values) = @_;
2344  
2345 42 my $map = $self->db_map;
2346 42 ▶ my $t = $map->table($other) or croak "The table '$other' is not in the database map";
Branch: 1 branch
BranchTrueFalseTotal
my $t = $map->table($other) or croak("The table '${other}' is not in the database map") 41 1 42
2347  
2348 41 my $theirs = join "\0" => sort keys %$values;
2349 41 ▶ my $single = grep { join("\0" => sort @$_) eq $theirs } grep { $_ && @$_ } $t->{pk}, @{$t->{unique} // []};
Condition40%2/5
$_ && @$_
!ll&&!rl&&r
0062
$t->{"unique"} // []
l!l
410
MC/DC0%0/2
$_ && @$_
$_ @$_
MC/DC0%0/1
$t->{"unique"} // []
$t->{"unique"}
Truth table33%1/3
A && B
A= $_B= @$_
ABresult
0X0
100
111
Truth table50%1/2
A
A= $t->{"unique"}
Aresult
11
00
2350  
2351 return DBIx::QuickORM::Handle->new(
2352 orm => $self,
2353 source => $self->_table_source($other),
2354 41 ▶ where => {map { ("$other.$_" => $values->{$_} // sql('IS NULL AND 1 = 0')) } keys %$values},
Branch: 1 branch
BranchTrueFalseTotal
$single ? : 33 8 41
Condition66%2/3
$values->{$_} // sql("IS NULL AND 1 = 0")
l!l&&r!l&&!r
3560
MC/DC0%0/2
$values->{$_} // sql("IS NULL AND 1 = 0")
$values->{$_} sql("IS NULL AND 1 = 0")
Truth table66%2/3
A // B
A= $values->{$_}B= sql("IS NULL AND 1 = 0")
ABresult
1X1
011
000
2355 state => $single ? 'single' : 'multi',
2356 );
2357 }
2358  
2359 =pod
2360  
2361 =over 4
2362  
2363 =item $bool = $orm->_can_connect
2364  
2365 True unless the ORM was given a C<dbh>: whether the connector can open another
2366 connection.
2367  
2368 =item $code = $orm->_build_connector
2369  
2370 Turns the one connection argument into the connector, removing it from the
2371 object, and sets C<_can_connect>.
2372  
2373 =back
2374  
2375 =cut
2376  
2377 411 ▶sub _build_connector {
Subroutine _build_connector: called CC=17 SCAR=28.3
2378 411 my $self = shift;
2379  
2380 411 my @forms = grep { exists $self->{$_} } qw/dbh connect credentials/;
2381 411 ▶ croak "new() needs exactly one of 'dbh', 'connect', or 'credentials'" . (@forms ? ", got: " . join(', ' => @forms) : '') unless @forms == 1;
Branch: 2 branches
BranchTrueFalseTotal
unless @forms == 1 2 409 411
@forms ? : 1 1 2
2382  
2383 409 my ($form) = @forms;
2384 409 my $arg = delete $self->{$form};
2385 409 $self->{+_CAN_CONNECT} = $form ne 'dbh';
2386  
2387 409 ▶ if ($form eq 'connect') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form eq "connect") 55 354 409
2388 55 ▶ croak "'connect' must be a code reference" unless ref($arg) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg eq "CODE" 1 54 55
2389 54 return $arg;
2390 }
2391  
2392 354 ▶ if ($form eq 'dbh') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form eq "dbh") 320 34 354
2393 320 ▶ croak "'dbh' must be a DBI database handle" unless blessed($arg) && $arg->isa('DBI::db');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($arg) and $arg->isa("DBI::db") 1 319 320
Condition66%2/3
builtin::blessed($arg) and $arg->isa("DBI::db")
!ll&&!rl&&r
10319
MC/DC50%1/2
builtin::blessed($arg) and $arg->isa("DBI::db")
builtin::blessed($arg) $arg->isa("DBI::db")
Truth table66%2/3
A and B
A= builtin::blessed($arg)B= $arg->isa("DBI::db")
ABresult
0X0
100
111
2394 320 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2395 320 ▶ croak "This ORM was given a 'dbh', so it cannot open another database connection" unless $arg;
Branch: 1 branch
BranchTrueFalseTotal
unless $arg 8 312 320
2396 312 my $dbh = $arg;
2397 312 undef $arg;
2398 312 return $dbh;
2399 319 };
2400 }
2401  
2402 34 ▶ croak "'credentials' must be a hashref with a 'dsn'" unless ref($arg) eq 'HASH' && $STR->($arg->{dsn});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $arg eq "HASH" and &$STR($arg->{"dsn"}) 2 32 34
Condition100%3/3
ref $arg eq "HASH" and &$STR($arg->{"dsn"})
!ll&&!rl&&r
1132
MC/DC100%2/2
ref $arg eq "HASH" and &$STR($arg->{"dsn"})
ref $arg eq "HASH" &$STR($arg->{"dsn"})
Truth table100%3/3
A and B
A= ref $arg eq "HASH"B= &$STR($arg->{"dsn"})
ABresult
0X0
100
111
2403 32 my @unknown = sort grep { !m/^(?:dsn|user|pass|attrs)$/ } keys %$arg;
2404 32 ▶ croak "Unknown key(s) in 'credentials': " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 31 32
2405 31 ▶ croak "'attrs' in 'credentials' must be a hashref" if defined($arg->{attrs}) && ref($arg->{attrs}) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if defined $arg->{"attrs"} and ref $arg->{"attrs"} ne "HASH" 1 30 31
Condition100%3/3
defined $arg->{"attrs"} and ref $arg->{"attrs"} ne "HASH"
!ll&&!rl&&r
10201
MC/DC100%2/2
defined $arg->{"attrs"} and ref $arg->{"attrs"} ne "HASH"
defined $arg->{"attrs"} ref $arg->{"attrs"} ne "HASH"
Truth table100%3/3
A and B
A= defined $arg->{"attrs"}B= ref $arg->{"attrs"} ne "HASH"
ABresult
0X0
100
111
2406  
2407 30 my ($dsn, $user, $pass) = @{$arg}{qw/dsn user pass/};
2408 croak "Do not turn AutoCommit off in 'credentials' attrs; the ORM manages transactions"
2409 30 ▶ if $arg->{attrs} && exists($arg->{attrs}->{AutoCommit}) && !$arg->{attrs}->{AutoCommit};
Branch: 1 branch
BranchTrueFalseTotal
if $arg->{"attrs"} and exists $arg->{"attrs"}{"AutoCommit"} and not $arg->{"attrs"}{"AutoCommit"} 7 23 30
Condition100%6/6
$arg->{"attrs"} and exists $arg->{"attrs"}{"AutoCommit"} and not $arg->{"attrs"}{"AutoCommit"}
!ll&&!rl&&r
1767
$arg->{"attrs"} and exists $arg->{"attrs"}{"AutoCommit"}
!ll&&!rl&&r
10713
MC/DC100%3/3
$arg->{"attrs"} and exists $arg->{"attrs"}{"AutoCommit"} and not $arg->{"attrs"}{"AutoCommit"}
$arg->{"attrs"} exists $arg->{"attrs"}{"AutoCommit"} not $arg->{"attrs"}{"AutoCommit"}
Truth table100%4/4
A and B and not(C)
A= $arg->{"attrs"}B= exists $arg->{"attrs"}{"AutoCommit"}C= not $arg->{"attrs"}{"AutoCommit"}
ABCresult
0XX0
10X0
1100
1111
2410  
2411 23 ▶ my $attrs = {%{$arg->{attrs} // {}}, RaiseError => 1, AutoCommit => 1};
Condition100%2/2
$arg->{"attrs"} // {}
l!l
1310
MC/DC100%1/1
$arg->{"attrs"} // {}
$arg->{"attrs"}
Truth table100%2/2
A
A= $arg->{"attrs"}
Aresult
11
00
2412 23 ▶ return sub { DBI->connect($dsn, $user, $pass, $attrs) };
Subroutine __ANON__: called CC=1 SCAR=0.0
2413 }
2414  
2415 =pod
2416  
2417 =over 4
2418  
2419 =item $builder = $orm->_build_sql_builder
2420  
2421 The C<sql_builder> argument as an object, the default when none was given.
2422  
2423 =back
2424  
2425 =cut
2426  
2427 396 ▶sub _build_sql_builder {
Subroutine _build_sql_builder: called CC=7 SCAR=19.5
2428 396 my $self = shift;
2429  
2430 396 my $role = 'DBIx::QuickORM::Role::SQLBuilder';
2431 396 ▶ my $builder = $self->{+SQL_BUILDER} // 'DBIx::QuickORM::SQLBuilder::SQLAbstract';
Condition100%2/2
$self->{"sql_builder"} // "DBIx::QuickORM::SQLBuilder::SQLAbstract"
l!l
5391
MC/DC100%1/1
$self->{"sql_builder"} // "DBIx::QuickORM::SQLBuilder::SQLAbstract"
$self->{"sql_builder"}
Truth table100%2/2
A
A= $self->{"sql_builder"}
Aresult
11
00
2432  
2433 396 ▶ unless (blessed($builder)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($builder)) 395 1 396
2434 395 ▶ croak "'sql_builder' must be a class name or object" unless $STR->($builder) && $builder =~ m/^\w+(?:::\w+)*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless &$STR($builder) and $builder =~ /^\w+(?:::\w+)*$/ 1 394 395
Condition66%2/3
&$STR($builder) and $builder =~ /^\w+(?:::\w+)*$/
!ll&&!rl&&r
10394
MC/DC50%1/2
&$STR($builder) and $builder =~ /^\w+(?:::\w+)*$/
&$STR($builder) $builder =~ /^\w+(?:::\w+)*$/
Truth table66%2/3
A and B
A= &$STR($builder)B= $builder =~ /^\w+(?:::\w+)*$/
ABresult
0X0
100
111
2435 394 ▶ $self->load_class("'sql_builder' names the class '$builder', which", $builder) unless $builder->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->can("new") 1 393 394
2436 393 $builder = $builder->new;
2437 }
2438  
2439 394 ▶ croak "'sql_builder' must compose $role" unless $builder->DOES($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->DOES($role) 1 393 394
2440 393 return $builder;
2441 }
2442  
2443 =pod
2444  
2445 =over 4
2446  
2447 =item \@builders = $orm->_where_builders($what, \@builders)
2448  
2449 A copy of the list, each class loaded unless it has C<build_where>. Croaks,
2450 naming C<$what>, for a list of the wrong shape (as C<new> checks it) or a
2451 builder not composing L<DBIx::QuickORM::Role::WhereBuilder>.
2452  
2453 =back
2454  
2455 =cut
2456  
2457 397 ▶sub _where_builders {
Subroutine _where_builders: called CC=6 SCAR=17.9
2458 397 my $self = shift;
2459 397 my ($what, $builders) = @_;
2460  
2461 397 my ($want, $check) = @{$SHAPES{where_builders}};
2462 397 ▶ croak "$what must be $want" unless $check->($builders);
Branch: 1 branch
BranchTrueFalseTotal
unless &$check($builders) 1 396 397
2463  
2464 396 my $role = 'DBIx::QuickORM::Role::WhereBuilder';
2465 396 for my $builder (@$builders) {
2466 1172 ▶ $self->load_class("$what names the class '$builder', which", $builder) unless blessed($builder) || $builder->can('build_where');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($builder) or $builder->can("build_where") 2 1170 1172
Condition100%3/3
builtin::blessed($builder) or $builder->can("build_where")
l!l&&r!l&&!r
111692
MC/DC100%2/2
builtin::blessed($builder) or $builder->can("build_where")
builtin::blessed($builder) $builder->can("build_where")
Truth table100%3/3
A or B
A= builtin::blessed($builder)B= $builder->can("build_where")
ABresult
1X1
011
000
2467 1171 ▶ croak "$what names '$builder', which does not compose $role" unless $builder->DOES($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->DOES($role) 1 1170 1171
2468 }
2469  
2470 394 return [@$builders];
2471 }
2472  
2473 =pod
2474  
2475 =over 4
2476  
2477 =item $conn = $orm->_connect(%args)
2478  
2479 A new Connection with these arguments and a handle from the connector.
2480  
2481 =back
2482  
2483 =cut
2484  
2485 392 ▶sub _connect {
Subroutine _connect: called CC=1 SCAR=0.0
2486 392 my $self = shift;
2487 392 return DBIx::QuickORM::Connection->new(@_, dbh => $self->{+CONNECTOR}->());
2488 }
2489  
2490 =pod
2491  
2492 =over 4
2493  
2494 =item $new = $orm->_connect_like($conn)
2495  
2496 A new Connection from the connector with the map and settings of the given
2497 one: for a forked child's reconnect, and for queries run on a second
2498 connection.
2499  
2500 =back
2501  
2502 =cut
2503  
2504 3 ▶sub _connect_like {
Subroutine _connect_like: called CC=1 SCAR=0.0
2505 3 my $self = shift;
2506 3 my ($conn) = @_;
2507 3 return $self->_connect(map { $_ => $conn->$_ } qw/db_map retain_cache enforce_canon debug isolation time_zone datetime_parsers/);
2508 }
2509  
2510 303 my @DEFAULT_AUTOTYPE = qw/UUID JSON DateTime/;
2511  
2512 =pod
2513  
2514 =over 4
2515  
2516 =item $map = $orm->_copy_map($db_map)
2517  
2518 A copy of a given map as a L<DBIx::QuickORM::Map>, or undef for undef.
2519  
2520 =back
2521  
2522 =cut
2523  
2524 391 ▶sub _copy_map {
Subroutine _copy_map: called CC=5 SCAR=16.1
2525 391 my $self = shift;
2526 391 my ($given) = @_;
2527 391 ▶ return undef unless defined $given;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $given 372 19 391
2528  
2529 19 ▶ my $data = blessed($given) && $given->isa('DBIx::QuickORM::Map') ? $given->tables : $given;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($given) && $given->isa('DBIx::QuickORM::Map') ? : 13 6 19
Condition100%3/3
builtin::blessed($given) and $given->isa("DBIx::QuickORM::Map")
!ll&&!rl&&r
5113
MC/DC100%2/2
builtin::blessed($given) and $given->isa("DBIx::QuickORM::Map")
builtin::blessed($given) $given->isa("DBIx::QuickORM::Map")
Truth table100%3/3
A and B
A= builtin::blessed($given)B= $given->isa("DBIx::QuickORM::Map")
ABresult
0X0
100
111
2530 19 ▶ croak "'db_map' must be a DBIx::QuickORM::Map or a hashref of map data" unless ref($data) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 2 17 19
2531 17 return DBIx::QuickORM::Map->new(tables => $data)->clone;
2532 }
2533  
2534 =pod
2535  
2536 =over 4
2537  
2538 =item $orm->_setup_map($map, $given)
2539  
2540 Adjusts the Connection's map in place by the arguments, in the order C<new>
2541 lists them, through the methods below. C<$given> is true when the map came
2542 from C<db_map> rather than a scan.
2543  
2544 =back
2545  
2546 =cut
2547  
2548 346 ▶sub _setup_map {
Subroutine _setup_map: called CC=1 SCAR=0.0
2549 346 my $self = shift;
2550 346 my ($map, $given) = @_;
2551  
2552 346 $self->_autotype($map, $given);
2553 339 $self->_apply_types($map);
2554 323 $self->_apply_fks($map);
2555 316 $self->_apply_default_fields($map);
2556 307 $self->_apply_row_classes($map);
2557 298 $self->_apply_key_types($map);
2558 294 $self->_apply_passthrough($map);
2559 }
2560  
2561 =pod
2562  
2563 =over 4
2564  
2565 =item $orm->_autotype($map, $given)
2566  
2567 Sets each field's C<orm_type> from the autotype list, as C<new> describes. A
2568 given map keeps its types, which are only loaded, when C<new> got neither
2569 C<autotype> nor C<append_autotype>.
2570  
2571 =back
2572  
2573 =cut
2574  
2575 346 ▶sub _autotype {
Subroutine _autotype: called CC=17 SCAR=28.3
2576 346 my $self = shift;
2577 346 my ($map, $given) = @_;
2578  
2579 346 my $asked = exists $self->{+AUTOTYPE};
2580 346 my $append = exists $self->{+APPEND_AUTOTYPE};
2581 346 ▶ return $self->_require_map_types($map) if $given && !$asked && !$append;
Branch: 1 branch
BranchTrueFalseTotal
if $given and not $asked and not $append 13 333 346
Condition100%6/6
$given and not $asked and not $append
!ll&&!rl&&r
332113
$given and not $asked
!ll&&!rl&&r
329314
MC/DC100%3/3
$given and not $asked and not $append
$given not $asked not $append
Truth table100%4/4
A and not(B) and not(C)
A= $givenB= not $askedC= not $append
ABCresult
0XX0
10X0
1100
1111
2582  
2583 333 ▶ croak "'autotype' must be undef or an arrayref of type names" if $asked && defined($self->{+AUTOTYPE}) && !$STR_LIST->($self->{+AUTOTYPE});
Branch: 1 branch
BranchTrueFalseTotal
if $asked and defined $self->{"autotype"} and not &$STR_LIST($self->{"autotype"}) 2 331 333
Condition100%6/6
$asked and defined $self->{"autotype"} and not &$STR_LIST($self->{"autotype"})
!ll&&!rl&&r
319122
$asked and defined $self->{"autotype"}
!ll&&!rl&&r
313614
MC/DC100%3/3
$asked and defined $self->{"autotype"} and not &$STR_LIST($self->{"autotype"})
$asked defined $self->{"autotype"} not &$STR_LIST($self->{"autotype"})
Truth table100%4/4
A and B and not(C)
A= $askedB= defined $self->{"autotype"}C= not &$STR_LIST($self->{"autotype"})
ABCresult
0XX0
10X0
1100
1111
2584 331 ▶ croak "'append_autotype' must be an arrayref of type names" if $append && !$STR_LIST->($self->{+APPEND_AUTOTYPE});
Branch: 1 branch
BranchTrueFalseTotal
if $append and not &$STR_LIST($self->{"append_autotype"}) 1 330 331
Condition100%3/3
$append and not &$STR_LIST($self->{"append_autotype"})
!ll&&!rl&&r
32641
MC/DC100%2/2
$append and not &$STR_LIST($self->{"append_autotype"})
$append not &$STR_LIST($self->{"append_autotype"})
Truth table100%3/3
A and not(B)
A= $appendB= not &$STR_LIST($self->{"append_autotype"})
ABresult
0X0
100
111
2585  
2586 my @types = (
2587 949 ▶ (map { $self->_load_type(autotype => $_) } $asked ? @{$self->{+AUTOTYPE} // []} : @DEFAULT_AUTOTYPE),
Branch: 1 branch
BranchTrueFalseTotal
$asked ? : 18 312 330
Condition100%2/2
$self->{"autotype"} // []
l!l
126
MC/DC100%1/1
$self->{"autotype"} // []
$self->{"autotype"}
Truth table100%2/2
A
A= $self->{"autotype"}
Aresult
11
00
2588 330 ▶ (map { $self->_load_type(append_autotype => $_) } $append ? @{$self->{+APPEND_AUTOTYPE}} : ()),
Branch: 1 branch
BranchTrueFalseTotal
$append ? : 4 324 328
2589 );
2590  
2591 327 my $dialect = $self->{+CONNECTION}->dialect;
2592 327 for my $table (values %{$map->tables}) {
2593 801 for my $name (keys %{$table->{fields}}) {
2594 2366 my $field = $table->{fields}->{$name};
2595 2366 delete $field->{orm_type};
2596 2366 ▶ next if ($field->{db_type} // '') =~ m/\[\d*\]\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($field->{"db_type"} // "") =~ /\[\d*\]\z/ 0 2366 2366
Condition100%2/2
$field->{"db_type"} // ""
l!l
23651
MC/DC100%1/1
$field->{"db_type"} // ""
$field->{"db_type"}
Truth table100%2/2
A
A= $field->{"db_type"}
Aresult
11
00
2597  
2598 2366 ▶ my $type = first { $_->[1]->{$field->{type} // ''} || ($_->[2] && $_->[0]->matches($name, $field, $dialect)) } @types;
Subroutine __ANON__: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
$_->[1]{$field->{"type"} // ""} or $_->[2] and $_->[0]->matches($name, $field, $dialect) 225 6381 6606
Condition100%8/8
$_->[1]{$field->{'type'} // ''} || $_->[2] && $_->[0]->matches($name, $field, $dialect)
l!l&&r!l&&!r
225676314
$field->{"type"} // ""
l!l
66051
$_->[2] and $_->[0]->matches($name, $field, $dialect)
!ll&&!rl&&r
2027428767
MC/DC100%3/3
$_->[1]{$field->{'type'} // ''} || $_->[2] && $_->[0]->matches($name, $field, $dialect)
$_->[1]{$field->{'type'} // ''} $_->[2] $_->[0]->matches($name, $field, $dialect)
MC/DC100%1/1
$field->{"type"} // ""
$field->{"type"}
Truth table100%4/4
A || B and C
A= $_->[1]{$field->{'type'} // ''}B= $_->[2]C= $_->[0]->matches($name, $field, $dialect)
ABCresult
1XX1
0111
00X0
0100
Truth table100%2/2
A
A= $field->{"type"}
Aresult
11
00
2599 2366 ▶ $field->{orm_type} = $type->[0] if $type;
Branch: 1 branch
BranchTrueFalseTotal
if $type 292 2074 2366
2600 }
2601 }
2602 }
2603  
2604 =pod
2605  
2606 =over 4
2607  
2608 =item $orm->_apply_types($map)
2609  
2610 Applies C<types>, loading each type it names. A named field gets the type in
2611 place of any autotype, or none for undef. Its C<format> and C<generate> hints
2612 become the ones given (none for the plain form).
2613  
2614 Then C<type_options> fills each hint a field of that type lacks. C<format> and
2615 C<generate> fall back separately. Each type it names is loaded. A field left
2616 with a hint but no type croaks.
2617  
2618 =back
2619  
2620 =cut
2621  
2622 339 ▶sub _apply_types {
Subroutine _apply_types: called CC=23 SCAR=31.4
2623 339 my $self = shift;
2624 339 my ($map) = @_;
2625  
2626 my %hints = (
2627 11 ▶ format => ['a code reference', sub { ref($_[0]) eq 'CODE' }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2628 339 ▶ generate => ["'none', 'prefer_db', or 'prefer_orm'", sub { defined($_[0]) && $_[0] =~ m/^(?:none|prefer_db|prefer_orm)\z/ }],
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and $_[0] =~ /^(?:none|prefer_db|prefer_orm)\z/ 11 1 12
2629 );
2630 23 ▶ my $hint = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2631 23 my ($arg, $name, $value) = @_;
2632 23 ▶ croak "'$arg' needs $hints{$name}->[0] for '$name'" unless $hints{$name}->[1]->($value);
Branch: 1 branch
BranchTrueFalseTotal
unless $hints{$name}[1]->($value) 4 19 23
2633 19 return $value;
2634 339 };
2635  
2636 339 ▶ my $spec = sub { $OPT_STR->($_[0]) || ref($_[0]) eq 'HASH' };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
&$OPT_STR($_[0]) or ref $_[0] eq "HASH" 105 16 121
2637 339 my $types = $self->_table_arg($map, TYPES(), 'a hashref of table => {field => type, undef, or {class => type, format => code, generate => mode}}', $HASH_OF->($spec));
2638 337 for my $table (sort keys %$types) {
2639 95 my $fields = $types->{$table};
2640 95 $self->_check_fields($map, TYPES(), $table, sort keys %$fields);
2641  
2642 94 for my $name (keys %$fields) {
2643 119 my $field = $map->field($table, $name);
2644 119 ▶ my $given = ref($fields->{$name}) ? $fields->{$name} : {class => $fields->{$name}};
Branch: 1 branch
BranchTrueFalseTotal
ref $fields->{$name} ? : 16 103 119
2645 119 ▶ my @bad = sort grep { $_ ne 'class' && !$hints{$_} } keys %$given;
Condition100%3/3
$_ ne 'class' && !$hints{$_}
!ll&&!rl&&r
113141
MC/DC100%2/2
$_ ne 'class' && !$hints{$_}
$_ ne 'class' !$hints{$_}
Truth table100%3/3
A && not(B)
A= $_ ne 'class'B= !$hints{$_}
ABresult
0X0
100
111
2646 119 ▶ croak "'types' gives the field '$name' of the table '$table' the unknown key(s): " . join(', ' => @bad) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 118 119
2647  
2648 118 for my $h (sort keys %hints) {
2649 235 delete $field->{$h};
2650 235 ▶ $field->{$h} = $hint->(TYPES(), $h, $given->{$h}) if exists $given->{$h};
Branch: 1 branch
BranchTrueFalseTotal
if exists $given->{$h} 14 221 235
2651 }
2652 116 ▶ next unless exists $given->{class};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $given->{"class"} 5 111 116
2653 111 delete $field->{orm_type};
2654 111 ▶ $field->{orm_type} = $self->require_type($given->{class}, TYPES()) if defined $given->{class};
Branch: 1 branch
BranchTrueFalseTotal
if defined $given->{"class"} 106 5 111
2655 }
2656 }
2657  
2658 331 ▶ my $options = $self->{+TYPE_OPTIONS} // {};
Condition100%2/2
$self->{"type_options"} // {}
l!l
12319
MC/DC100%1/1
$self->{"type_options"} // {}
$self->{"type_options"}
Truth table100%2/2
A
A= $self->{"type_options"}
Aresult
11
00
2659 331 ▶ croak "'type_options' must be a hashref of type => {format => code, generate => mode}" unless $HASH_OF->(sub { ref($_[0]) eq 'HASH' })->($options);
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless &$HASH_OF(sub { ref $_[0] eq "HASH"; } )->($options) 1 330 331
2660  
2661 330 my %by_type;
2662 330 for my $type (sort keys %$options) {
2663 11 my @bad = sort grep { !$hints{$_} } keys %{$options->{$type}};
2664 11 ▶ croak "'type_options' gives the type '$type' the unknown key(s): " . join(', ' => @bad) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 10 11
2665 10 my $class = $self->require_type($type, TYPE_OPTIONS());
2666 9 $by_type{$class}{$_} = $hint->(TYPE_OPTIONS(), $_, $options->{$type}->{$_}) for grep { exists $options->{$type}->{$_} } sort keys %hints;
2667 }
2668  
2669 326 for my $table (sort keys %{$map->tables}) {
2670 787 my $fields = $map->table($table)->{fields};
2671 787 for my $name (sort keys %$fields) {
2672 2311 my $field = $fields->{$name};
2673 2311 for my $h (sort keys %hints) {
2674 4620 ▶ my $value = $by_type{$field->{orm_type} // ''}{$h};
Condition100%2/2
$field->{"orm_type"} // ""
l!l
7663854
MC/DC100%1/1
$field->{"orm_type"} // ""
$field->{"orm_type"}
Truth table100%2/2
A
A= $field->{"orm_type"}
Aresult
11
00
2675 4620 ▶ $field->{$h} //= $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 22 4598 4620
Condition66%2/3
$field->{$h} //= $value
l!l&&r!l&&!r
3190
MC/DC0%0/2
$field->{$h} //= $value
$field->{$h} $value
Truth table66%2/3
A //= B
A= $field->{$h}B= $value
ABresult
1X1
011
000
2676 4620 ▶ next unless defined($field->{$h}) && !$field->{orm_type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $field->{$h} and not $field->{"orm_type"} 4617 3 4620
Condition100%3/3
defined $field->{$h} and not $field->{"orm_type"}
!ll&&!rl&&r
4589283
MC/DC100%2/2
defined $field->{$h} and not $field->{"orm_type"}
defined $field->{$h} not $field->{"orm_type"}
Truth table100%3/3
A and not(B)
A= defined $field->{$h}B= not $field->{"orm_type"}
ABresult
0X0
100
111
2677 3 croak "The field '$name' of the table '$table' has a $h but no type; a $h applies only to a typed field";
2678 }
2679 }
2680 }
2681 }
2682  
2683 =pod
2684  
2685 =over 4
2686  
2687 =item $orm->_apply_fks($map)
2688  
2689 Applies C<fks>: adds each link to the table's foreign keys, through C<_add_fk>.
2690  
2691 =back
2692  
2693 =cut
2694  
2695 323 ▶sub _apply_fks {
Subroutine _apply_fks: called CC=5 SCAR=16.1
2696 323 my $self = shift;
2697 323 my ($map) = @_;
2698  
2699 24 ▶ my $links = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2700 24 ▶ ref($_[0]) eq 'ARRAY' && !grep { !$LINK->($_) } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and not grep({not &$LINK($_);} @{$_[0];}) 23 1 24
2701 323 };
2702 323 my $fks = $self->_table_arg($map, FKS(), 'a hashref of table => {table => [{field => field}]}', $HASH_OF->($links));
2703  
2704 320 for my $table (sort keys %$fks) {
2705 19 for my $other (sort keys %{$fks->{$table}}) {
2706 21 ▶ croak "'fks' names the table '$other', which is not in the database map" unless $map->table($other);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->table($other) 1 20 21
2707  
2708 20 for my $link (@{$fks->{$table}->{$other}}) {
2709 23 $self->_check_fields($map, FKS(), $table, sort keys %$link);
2710 22 $self->_check_fields($map, FKS(), $other, sort values %$link);
2711 21 $self->_add_fk($map, $table, $other, $link);
2712 }
2713 }
2714 }
2715 }
2716  
2717 =pod
2718  
2719 =over 4
2720  
2721 =item $orm->_apply_default_fields($map)
2722  
2723 Applies C<omit> and C<default_fields>, setting each named table's default
2724 fields, with the croaks C<new> lists, then C<auto_omit> on the other tables.
2725  
2726 =back
2727  
2728 =cut
2729  
2730 316 ▶sub _apply_default_fields {
Subroutine _apply_default_fields: called CC=24 SCAR=31.8
2731 316 my $self = shift;
2732 316 my ($map) = @_;
2733  
2734 316 my $omit = $self->_table_arg($map, OMIT(), 'a hashref of table => [fields]', $STR_LIST);
2735 315 my $fields = $self->_table_arg($map, DEFAULT_FIELDS(), 'a hashref of table => [fields]', $STR_LIST);
2736  
2737 313 my @both = sort grep { exists $fields->{$_} } keys %$omit;
2738 313 ▶ croak "'omit' and 'default_fields' both name the table(s): " . join(', ' => @both) if @both;
Branch: 1 branch
BranchTrueFalseTotal
if @both 1 312 313
2739  
2740 312 for my $table (sort keys %$omit) {
2741 27 $self->_check_fields($map, OMIT(), $table, @{$omit->{$table}});
2742  
2743 26 my %omit = map { $_ => 1 } @{$omit->{$table}};
2744 26 ▶ my @pk = grep { $omit{$_} } @{$map->pk($table) // []};
Condition100%2/2
$map->pk($table) // []
l!l
251
MC/DC100%1/1
$map->pk($table) // []
$map->pk($table)
Truth table100%2/2
A
A= $map->pk($table)
Aresult
11
00
2745 26 ▶ croak "'omit' names primary key field(s) of the table '$table': " . join(', ' => @pk) if @pk;
Branch: 1 branch
BranchTrueFalseTotal
if @pk 1 25 26
2746  
2747 25 $self->_set_default_fields($map, OMIT(), $table, grep { !$omit{$_} } keys %{$map->table($table)->{fields}});
2748 }
2749  
2750 309 for my $table (sort keys %$fields) {
2751 17 $self->_check_fields($map, DEFAULT_FIELDS(), $table, @{$fields->{$table}});
2752 17 ▶ $self->_set_default_fields($map, DEFAULT_FIELDS(), $table, @{$fields->{$table}}, @{$map->pk($table) // []});
Condition100%2/2
$map->pk($table) // []
l!l
161
MC/DC100%1/1
$map->pk($table) // []
$map->pk($table)
Truth table100%2/2
A
A= $map->pk($table)
Aresult
11
00
2753 }
2754  
2755 308 ▶ my $auto = $self->{+AUTO_OMIT} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $auto = $self->{"auto_omit"} or return 9 299 308
2756 9 ▶ my @classes = map { $self->require_type($_, 'auto_omit') } @{$auto->{types} // []};
Condition100%2/2
$auto->{"types"} // []
l!l
72
MC/DC100%1/1
$auto->{"types"} // []
$auto->{"types"}
Truth table100%2/2
A
A= $auto->{"types"}
Aresult
11
00
2757 8 my $dialect = $self->{+CONNECTION}->dialect;
2758 8 ▶ my %db = map { (($dialect->_base_type($_))[0] => 1) } @{$auto->{db_types} // []};
Condition100%2/2
$auto->{"db_types"} // []
l!l
26
MC/DC100%1/1
$auto->{"db_types"} // []
$auto->{"db_types"}
Truth table100%2/2
A
A= $auto->{"db_types"}
Aresult
11
00
2759  
2760 8 ▶ for my $table (sort grep { !exists($omit->{$_}) && !exists($fields->{$_}) } keys %{$map->tables}) {
Condition100%3/3
exists $omit->{$_} || exists $fields->{$_}
l!l&&r!l&&!r
2129
MC/DC100%2/2
exists $omit->{$_} || exists $fields->{$_}
exists $omit->{$_} exists $fields->{$_}
Truth table100%3/3
A || B
A= exists $omit->{$_}B= exists $fields->{$_}
ABresult
1X1
011
000
2761 29 my $t = $map->table($table);
2762 29 ▶ next if $t->{default_fields}; # a given db_map's own
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"default_fields"} 0 29 29
2763 29 ▶ next unless @{$t->{pk} // []}; # a field left out could never be fetched for a row without a key
Branch: 1 branch
BranchTrueFalseTotal
unless @{$t->{"pk"} // [];} 8 21 29
Condition100%2/2
$t->{"pk"} // []
l!l
218
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
2764  
2765 21 ▶ my %key = map { $_ => 1 } @{$t->{pk}}, map { @$_ } @{$t->{unique} // []};
Condition50%1/2
$t->{"unique"} // []
l!l
210
MC/DC0%0/1
$t->{"unique"} // []
$t->{"unique"}
Truth table50%1/2
A
A= $t->{"unique"}
Aresult
11
00
2766 21 ▶ for my $links (values %{$t->{fk} // {}}) {
Condition50%1/2
$t->{"fk"} // {}
l!l
210
MC/DC0%0/1
$t->{"fk"} // {}
$t->{"fk"}
Truth table50%1/2
A
A= $t->{"fk"}
Aresult
11
00
2767 8 $key{$_} = 1 for map { keys %$_ } @$links;
2768 }
2769  
2770 my @out = grep {
2771 71 my $field = $t->{fields}->{$_};
2772 71 my $type = $field->{orm_type};
2773 71 ▶ !$key{$_} && ($db{$field->{type} // ''} || ($type && grep { $type->isa($_) } @classes));
Condition90%10/11
!$key{$_} && ($db{$field->{'type'} // ''} || $type && grep({$type->isa($_);} @classes))
!ll&&!rl&&r
372311
$db{$field->{"type"} // ""} or $type and grep {$type->isa($_);} @classes
l!l&&r!l&&!r
5623
$field->{"type"} // ""
l!l
340
$type and grep {$type->isa($_);} @classes
!ll&&!rl&&r
2126
MC/DC100%4/4
!$key{$_} && ($db{$field->{'type'} // ''} || $type && grep({$type->isa($_);} @classes))
!$key{$_} $db{$field->{"type"} // ""} $type grep {$type->isa($_);} @classes
MC/DC0%0/1
$field->{"type"} // ""
$field->{"type"}
Truth table100%5/5
not(A) && B or C and D
A= !$key{$_}B= $db{$field->{"type"} // ""}C= $typeD= grep {$type->isa($_);} @classes
ABCDresult
0XXX0
100X0
10100
11XX1
10111
Truth table50%1/2
A
A= $field->{"type"}
Aresult
11
00
2774 21 } keys %{$t->{fields}};
2775 21 ▶ next unless @out;
Branch: 1 branch
BranchTrueFalseTotal
unless @out 11 10 21
2776  
2777 10 my %out = map { $_ => 1 } @out;
2778 10 $self->_set_default_fields($map, AUTO_OMIT(), $table, grep { !$out{$_} } keys %{$t->{fields}});
2779 }
2780 }
2781  
2782 =pod
2783  
2784 =over 4
2785  
2786 =item $orm->_apply_row_classes($map)
2787  
2788 Applies C<row_classes>, then C<row_namespace> to each table left without a
2789 row class (through C<_namespace_class>, and a class found there must do
2790 L<DBIx::QuickORM::Role::Row>), then loads every row class the map
2791 names and the ORM's C<row_class>, unless the class already has a C<new>.
2792  
2793 =back
2794  
2795 =cut
2796  
2797 307 ▶sub _apply_row_classes {
Subroutine _apply_row_classes: called CC=9 SCAR=22.0
2798 307 my $self = shift;
2799 307 my ($map) = @_;
2800  
2801 307 my $classes = $self->_table_arg($map, ROW_CLASSES(), 'a hashref of table => class name or undef', $OPT_STR);
2802 305 $map->table($_)->{row_class} = $classes->{$_} for keys %$classes;
2803  
2804 305 ▶ if (defined(my $ns = $self->{+ROW_NAMESPACE})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $ns = $self->{"row_namespace"})) 9 296 305
2805 9 for my $name (grep { !exists $map->table($_)->{row_class} } sort keys %{$map->tables}) {
2806 34 ▶ my $class = $self->_namespace_class($ns, $name) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $class = $self->_namespace_class($ns, $name) or next 28 6 34
2807 28 my $what = "'row_namespace' gives the table '$name' the row class '$class', which";
2808 28 ▶ next unless $class->can('new') || $self->load_class($what, $class, 1);
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("new") or $self->load_class($what, $class, 1) 19 7 26
Condition100%3/3
$class->can("new") or $self->load_class($what, $class, 1)
l!l&&r!l&&!r
3421
MC/DC100%2/2
$class->can("new") or $self->load_class($what, $class, 1)
$class->can("new") $self->load_class($what, $class, 1)
Truth table100%3/3
A or B
A= $class->can("new")B= $self->load_class($what, $class, 1)
ABresult
1X1
011
000
2809 7 ▶ $class->DOES('DBIx::QuickORM::Role::Row') or croak "$what does not do DBIx::QuickORM::Role::Row";
Branch: 1 branch
BranchTrueFalseTotal
$class->DOES("DBIx::QuickORM::Role::Row") or croak("$what does not do DBIx::QuickORM::Role::Row") 6 1 7
2810 6 $map->table($name)->{row_class} = $class;
2811 }
2812 }
2813  
2814 302 $self->load_row_class($_) for grep { defined } $self->{+ROW_CLASS}, map { $_->{row_class} } values %{$map->tables};
2815 }
2816  
2817 =pod
2818  
2819 =over 4
2820  
2821 =item $class = $orm->_namespace_class($namespace, $table)
2822  
2823 The table's row class under C<row_namespace>: the namespace and the part
2824 C<row_class_name> gives for the table, or by default each C<_>-separated part
2825 of the name with its first letter upper-cased, joined.
2826  
2827 Undef when the part is undef. Warns and returns undef when the part is not an
2828 identifier.
2829  
2830 =back
2831  
2832 =cut
2833  
2834 27 ▶my $DEFAULT_ROW_CLASS_NAME = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2835 27 join '' => map { ucfirst } split /_/ => $_[0];
2836 303 };
2837  
2838 34 ▶sub _namespace_class {
Subroutine _namespace_class: called CC=4 SCAR=13.9
2839 34 my $self = shift;
2840 34 my ($ns, $table) = @_;
2841 34 ▶ my $part = ($self->{+ROW_CLASS_NAME} // $DEFAULT_ROW_CLASS_NAME)->($table);
Condition66%2/3
$self->{"row_class_name"} // $DEFAULT_ROW_CLASS_NAME
l!l&&r!l&&!r
7270
MC/DC0%0/2
$self->{"row_class_name"} // $DEFAULT_ROW_CLASS_NAME
$self->{"row_class_name"} $DEFAULT_ROW_CLASS_NAME
Truth table66%2/3
A // B
A= $self->{"row_class_name"}B= $DEFAULT_ROW_CLASS_NAME
ABresult
1X1
011
000
2842 34 ▶ return undef unless defined $part;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part 3 31 34
2843 31 ▶ return "${ns}::$part" if $part =~ m/^[A-Za-z_]\w*\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /^[A-Za-z_]\w*\z/ 28 3 31
2844 3 carp "'row_namespace' skips the table '$table': '$part' is not a valid class name part";
2845 3 return undef;
2846 }
2847  
2848 =pod
2849  
2850 =over 4
2851  
2852 =item $orm->_apply_key_types($map)
2853  
2854 Records each table's C<pk_types> (see L<DBIx::QuickORM::Map>) when a primary
2855 key field has a type. Croaks when such a type has no
2856 C<canonical_key_value>, and when a field whose type can generate values has
2857 C<< generate => 'prefer_orm' >> on a column the database refuses values for.
2858  
2859 =back
2860  
2861 =cut
2862  
2863 298 ▶sub _apply_key_types {
Subroutine _apply_key_types: called CC=10 SCAR=23.0
2864 298 my $self = shift;
2865 298 my ($map) = @_;
2866  
2867 298 for my $name (keys %{$map->tables}) {
2868 670 my $table = $map->table($name);
2869 670 delete $table->{pk_types};
2870 670 ▶ my @types = map { $table->{fields}->{$_}->{orm_type} } @{$table->{pk} // []};
Condition100%2/2
$table->{"pk"} // []
l!l
59575
MC/DC100%1/1
$table->{"pk"} // []
$table->{"pk"}
Truth table100%2/2
A
A= $table->{"pk"}
Aresult
11
00
2871 670 ▶ next unless grep { defined } @types;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_;} @types 588 82 670
2872  
2873 82 for my $i (grep { defined $types[$_] } 0 .. $#types) {
2874 92 my $field = $table->{pk}->[$i];
2875 92 my $rec = $table->{fields}->{$field};
2876 92 ▶ croak "The primary key field '$field' of the table '$name' has the type '$types[$i]', which has no canonical_key_value(); pass types => {'$name' => {'$field' => undef}} to key it by its plain value"
Branch: 1 branch
BranchTrueFalseTotal
unless $types[$i]->can("canonical_key_value") 2 90 92
2877 unless $types[$i]->can('canonical_key_value');
2878 croak "The primary key field '$field' of the table '$name' has generate => 'prefer_orm', but the database refuses values for it (such as GENERATED ALWAYS AS IDENTITY); give it generate => 'prefer_db'"
2879 90 ▶ if ($rec->{generate} // '') eq 'prefer_orm' && $rec->{db_refuses_value} && $types[$i]->can('generate_key_value');
Branch: 1 branch
BranchTrueFalseTotal
if ($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"} and $types[$i]->can("generate_key_value") 2 88 90
Condition100%8/8
($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"} and $types[$i]->can("generate_key_value")
!ll&&!rl&&r
8712
($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"}
!ll&&!rl&&r
8613
$rec->{"generate"} // ""
l!l
1377
MC/DC100%3/3
($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"} and $types[$i]->can("generate_key_value")
$rec->{"generate"} $rec->{"db_refuses_value"} $types[$i]->can("generate_key_value")
Truth table100%4/4
A and B and C
A= $rec->{"generate"}B= $rec->{"db_refuses_value"}C= $types[$i]->can("generate_key_value")
ABCresult
0XX0
10X0
1100
1111
2880 }
2881 78 $table->{pk_types} = \@types;
2882 }
2883 }
2884  
2885 =pod
2886  
2887 =over 4
2888  
2889 =item $orm->_apply_passthrough($map)
2890  
2891 Sets C<passthrough> on each typed field whose type's C<inflate_is_identity> is
2892 true for that field, and removes it from every other field.
2893  
2894 =back
2895  
2896 =cut
2897  
2898 294 ▶sub _apply_passthrough {
Subroutine _apply_passthrough: called CC=6 SCAR=17.9
2899 294 my $self = shift;
2900 294 my ($map) = @_;
2901  
2902 294 for my $table (values %{$map->tables}) {
2903 662 for my $field (values %{$table->{fields}}) {
2904 1948 delete $field->{passthrough};
2905 1948 ▶ my $type = $field->{orm_type} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $type = $field->{"orm_type"} or next 377 1571 1948
2906 377 ▶ $field->{passthrough} = 1 if $type->can('inflate_is_identity') && $type->inflate_is_identity($field);
Branch: 1 branch
BranchTrueFalseTotal
if $type->can("inflate_is_identity") and $type->inflate_is_identity($field) 61 316 377
Condition100%3/3
$type->can("inflate_is_identity") and $type->inflate_is_identity($field)
!ll&&!rl&&r
7823861
MC/DC100%2/2
$type->can("inflate_is_identity") and $type->inflate_is_identity($field)
$type->can("inflate_is_identity") $type->inflate_is_identity($field)
Truth table100%3/3
A and B
A= $type->can("inflate_is_identity")B= $type->inflate_is_identity($field)
ABresult
0X0
100
111
2907 }
2908 }
2909 }
2910  
2911 =pod
2912  
2913 =over 4
2914  
2915 =item \%arg = $orm->_table_arg($map, $name, $want, \&check)
2916  
2917 The named argument, or an empty hash when it was not given. Croaks unless it
2918 is a hashref whose values pass C<check> (C<$want> describes the shape), or
2919 when it names a table not in the map.
2920  
2921 =back
2922  
2923 =cut
2924  
2925 1600 ▶sub _table_arg {
Subroutine _table_arg: called CC=5 SCAR=16.1
2926 1600 my $self = shift;
2927 1600 my ($map, $arg, $want, $check) = @_;
2928  
2929 1600 ▶ return {} unless exists $self->{$arg};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{$arg} 1432 168 1600
2930  
2931 168 my $value = $self->{$arg};
2932 168 ▶ croak "'$arg' must be $want" unless $HASH_OF->($check)->($value);
Branch: 1 branch
BranchTrueFalseTotal
unless &$HASH_OF($check)->($value) 6 162 168
2933  
2934 162 for my $table (sort keys %$value) {
2935 198 ▶ croak "'$arg' names the table '$table', which is not in the database map" unless $map->table($table);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->table($table) 4 194 198
2936 }
2937  
2938 158 return $value;
2939 }
2940  
2941 =pod
2942  
2943 =over 4
2944  
2945 =item $orm->_check_fields($map, $name, $table, @fields)
2946  
2947 Croaks for the first field not in the table.
2948  
2949 =back
2950  
2951 =cut
2952  
2953 184 ▶sub _check_fields {
Subroutine _check_fields: called CC=3 SCAR=11.0
2954 184 my $self = shift;
2955 184 my ($map, $arg, $table, @fields) = @_;
2956  
2957 184 for my $field (@fields) {
2958 209 ▶ croak "'$arg' names the field '$field' of the table '$table', which is not in the database map" unless $map->field($table, $field);
Branch: 1 branch
BranchTrueFalseTotal
unless $map->field($table, $field) 4 205 209
2959 }
2960 }
2961  
2962 =pod
2963  
2964 =over 4
2965  
2966 =item $class = $orm->_type_class($type)
2967  
2968 The full class name for a type name.
2969  
2970 =back
2971  
2972 =cut
2973  
2974 1103 ▶sub _type_class {
Subroutine _type_class: called CC=3 SCAR=11.0
2975 1103 my $self = shift;
2976 1103 my ($type) = @_;
2977  
2978 1103 ▶ my $class = $type =~ m/^\+(.+)$/ ? $1 : "DBIx::QuickORM::Type::$type";
Branch: 1 branch
BranchTrueFalseTotal
$type =~ /^\+(.+)$/ ? : 83 1020 1103
2979 1103 ▶ croak "'$type' is not a valid type name" unless $class =~ m/^\w+(?:::\w+)*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $class =~ /^\w+(?:::\w+)*$/ 2 1101 1103
2980  
2981 1101 return $class;
2982 }
2983  
2984 =pod
2985  
2986 =over 4
2987  
2988 =item $orm->_require_map_types($map)
2989  
2990 Loads every type a given map names.
2991  
2992 =back
2993  
2994 =cut
2995  
2996 13 ▶sub _require_map_types {
Subroutine _require_map_types: called CC=3 SCAR=11.0
2997 13 my $self = shift;
2998 13 my ($map) = @_;
2999  
3000 13 for my $table (values %{$map->tables}) {
3001 36 $self->require_type("+$_->{orm_type}", 'db_map') for grep { defined $_->{orm_type} } values %{$table->{fields}};
3002 }
3003 }
3004  
3005 =pod
3006  
3007 =over 4
3008  
3009 =item [$class, \%base_types, $has_matches] = $orm->_load_type($arg, $type)
3010  
3011 Loads an autotype for C<_autotype>: its class, its C<base_types> as a set, and
3012 whether it has C<matches>. Croaks naming the argument when the type cannot be
3013 loaded, or has neither.
3014  
3015 =back
3016  
3017 =cut
3018  
3019 953 ▶sub _load_type {
Subroutine _load_type: called CC=5 SCAR=16.1
3020 953 my $self = shift;
3021 953 my ($arg, $type) = @_;
3022  
3023 953 my $class = $self->require_type($type, $arg);
3024  
3025 951 ▶ my $matches = $class->can('matches') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('matches') ? : 629 322 951
3026 951 ▶ croak "'$arg' names the type '$class', which has neither 'base_types' nor 'matches'" unless $matches || $class->can('base_types');
Branch: 1 branch
BranchTrueFalseTotal
unless $matches or $class->can("base_types") 1 950 951
Condition100%3/3
$matches or $class->can("base_types")
l!l&&r!l&&!r
6293211
MC/DC100%2/2
$matches or $class->can("base_types")
$matches $class->can("base_types")
Truth table100%3/3
A or B
A= $matchesB= $class->can("base_types")
ABresult
1X1
011
000
3027  
3028 950 ▶ my %base_types = map { $_ => 1 } $class->can('base_types') ? $class->base_types : ();
Branch: 1 branch
BranchTrueFalseTotal
$class->can('base_types') ? : 945 5 950
3029 950 return [$class, \%base_types, $matches];
3030 }
3031  
3032 =pod
3033  
3034 =over 4
3035  
3036 =item $orm->_add_fk($map, $table, $other, \%link)
3037  
3038 Adds a foreign key from the table to the other one, unless the table already
3039 has the same link. Croaks when it has a link on the same fields that points at
3040 different fields of the other table.
3041  
3042 =back
3043  
3044 =cut
3045  
3046 21 ▶sub _add_fk {
Subroutine _add_fk: called CC=5 SCAR=16.1
3047 21 my $self = shift;
3048 21 my ($map, $table, $other, $link) = @_;
3049  
3050 21 my $ours = join "\0" => sort keys %$link;
3051 21 ▶ my $known = $map->table($table)->{fk}->{$other} //= [];
Condition100%2/2
$map->table($table)->{"fk"}{$other} //= []
l!l
516
MC/DC100%1/1
$map->table($table)->{"fk"}{$other} //= []
$map->table($table)->{"fk"}{$other}
Truth table100%2/2
A
A= $map->table($table)->{"fk"}{$other}
Aresult
11
00
3052  
3053 21 for my $have (@$known) {
3054 5 ▶ next unless join("\0" => sort keys %$have) eq $ours;
Branch: 1 branch
BranchTrueFalseTotal
unless join("\0", sort(keys %$have)) eq $ours 3 2 5
3055 2 ▶ return unless grep { $have->{$_} ne $link->{$_} } keys %$link;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$have->{$_} ne $link->{$_};} keys %$link 1 1 2
3056 1 croak "'fks' gives the table '$table' a foreign key to '$other' on (" . join(', ' => sort keys %$link) . ") that differs from the one it has";
3057 }
3058  
3059 19 push @$known => {%$link};
3060 }
3061  
3062 =pod
3063  
3064 =over 4
3065  
3066 =item $orm->_set_default_fields($map, $arg, $table, @fields)
3067  
3068 Sets the table's default fields to C<@fields>, sorted and without duplicates.
3069 Croaks naming the argument when C<@fields> is empty.
3070  
3071 =back
3072  
3073 =cut
3074  
3075 52 ▶sub _set_default_fields {
Subroutine _set_default_fields: called CC=2 SCAR=6.9
3076 52 my $self = shift;
3077 52 my ($map, $arg, $table, @fields) = @_;
3078  
3079 52 my %seen;
3080 52 @fields = sort grep { !$seen{$_}++ } @fields;
3081 52 ▶ croak "'$arg' leaves no fields to select from the table '$table'" unless @fields;
Branch: 1 branch
BranchTrueFalseTotal
unless @fields 2 50 52
3082  
3083 50 $map->table($table)->{default_fields} = \@fields;
3084 }
3085  
3086 303 1;
3087  
3088 __END__
« blib/lib/DBIx/QuickORM/AggregateRow.pm ↑ Summary blib/lib/DBIx/QuickORM/Source/Join.pm »