blib/lib/DBIx/QuickORM.pm

filter: Statementstmt 96.1% 1063 / 1106 Branchbran 88.7% 527 / 594 Conditioncond 79.4% 348 / 438 MC/DCmcdc 61.8% 154 / 249 Subroutinesub 97.9% 145 / 148 Podpod 94.7% 36 / 38 totaltotal 88.3% 2273 / 2573 CC 942 SCAR 24.9
CC
942
Cov
91%
_insert_fk
28.0
_insert_fk
28.0
_apply_default_fields
24.0
CRAP 12.1
« blib/lib/DBIx/QuickORM/Source/Join.pm ↑ Summary blib/lib/DBIx/QuickORM/Row.pm »
1 package DBIx::QuickORM;
2 258 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 258 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 258 our $VERSION = '0.000033';
6  
7 258 ▶use Carp qw/carp croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 258 ▶use List::Util qw/first/;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 258 ▶use Scalar::Util qw/blessed/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 258 ▶use DBI();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 258 ▶use DBIx::QuickORM::Connection();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 258 ▶use DBIx::QuickORM::Handle();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 258 ▶use DBIx::QuickORM::RowState();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 258 ▶use DBIx::QuickORM::Map();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 258 ▶use DBIx::QuickORM::SchemaBuilder::Table::Temp();
Subroutine BEGIN: called CC=1 SCAR=0.0
17 258 ▶use DBIx::QuickORM::Source::Table::Temp();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 258 ▶use DBIx::QuickORM::Row();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 258 ▶use DBIx::QuickORM::Source::Query();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 258 ▶use DBIx::QuickORM::Source::Table();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 258 ▶use DBIx::QuickORM::SQLBuilder::SQLAbstract();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 258 ▶use DBIx::QuickORM::WhereBuilder::RawSQL();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 258 ▶use DBIx::QuickORM::WhereBuilder::Simple();
Subroutine BEGIN: called CC=1 SCAR=0.0
24 258 ▶use DBIx::QuickORM::WhereBuilder::SQLAbstract();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 258 ▶use DBIx::QuickORM::Value qw/raw sql/;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 # Our own new() wraps init(). Predeclared so Object::HashBase does not add one.
28 sub new;
29  
30 258 ▶use Object::HashBase qw{
Subroutine BEGIN: called CC=1 SCAR=0.0
31 <row_class
32 <row_classes
33 <row_namespace
34 <row_class_name
35 <omit
36 <default_fields
37 <auto_omit
38 <debug
39 <types
40 <autotype
41 <append_autotype
42 <fks
43 <sql_builder
44 <connector
45 +connection
46 <_can_connect
47 <like_aggregates
48 <type_options
49 +table_sources
50 +table_fields
51 <where_builders
52 +fast_bless
53 +finished_map
54 <pks
55 <elective
56 258 };
57  
58 =pod
59  
60 =encoding UTF-8
61  
62 =head1 NAME
63  
64 DBIx::QuickORM - An ORM that quickly gives you what you need with minimal boilerplate, and easily extends to more complex use cases.
65  
66 =head1 EXPERIMENTAL STATUS
67  
68 This distribution is still considered experimental and may change
69 significantly without warning.
70  
71 Once we release version 1.x, we will have a settled final shape and will be
72 careful about breaking public APIs. Until then there is no guarantee of
73 compatibility between releases.
74  
75 =head1 WHERE TO START
76  
77 New to the ORM? Read L<DBIx::QuickORM::Manual::Quickstart>: short examples of
78 everything most applications need. See L<DBIx::QuickORM::Manual> for
79 additional resources.
80  
81 =head1 AI/LLM POLICY AND INFORMATION
82  
83 This project does allow the use of AI/LLM in contributions. However, it is not a
84 low-effort "slop" project. The project was originally entirely hand-coded
85 without AI/LLM, and its intended audience is humans writing code, not bots. It
86 has since been reworked several times and AI/LLM tools have been used to
87 shuffle around and restructure much of the code. It was never unreviewed or
88 low-effort.
89  
90 I cannot promise some hard to read AI documentation will not slip through, and
91 I cannot promise the AI/LLM portions of the code are bug free. But I can say
92 they have been held to the same standard as any human contribution, including
93 my own. Humans can also write bugs and bad documentation. I do review what
94 agents produce, and I have caught many cases of terrible documentation wording,
95 terrible code, and bugs where the agent was a moron. I am sure plenty of others
96 have slipped through despite my thorough review.
97  
98 If you want to avoid AI/LLM code completely, use another distribution. If you
99 want to send me slop or unreviewed and terrible low-effort PRs then use
100 another distribution. Responsible and vetted AI use is perfectly acceptable.
101  
102 Discussions, PRs and bug reports should remain civil, and must not become a
103 place to debate if or when AI/LLM should be used. That said, we absolutely can
104 call out low-effort slop, and reject it for that reason. But AI/LLM being
105 involved is not in itself enough to reject submissions, so long as the quality
106 is good, and the person submitting it understands it, reviews it, and stands by
107 it.
108  
109 The full AI/LLM policy is covered in the AI_AND_LLM_POLICY.md file included with
110 this distribution.
111  
112 =head1 DESCRIPTION
113  
114 Connect and start working. DBIx::QuickORM scans the live database and uses
115 what it finds as the schema. There is no schema, table, or column metadata
116 to declare. Most of it is automatic. Insert, find, update, delete, and query
117 rows right away.
118  
119 Rows come back as L<DBIx::QuickORM::Row> objects, but custom row classes can be
120 defined, or you can request plain hashrefs be returned if you do not want the
121 overhead of a full row object.
122  
123 When the scan gets something wrong, or you need custom behavior, it is easy to
124 adjust: omit fields by default, give a field a data type for inflation, add
125 foreign keys the database does not declare, and so on. See C<new> (under
126 L</Constructor>), or the easy to use DSL (L<DBIx::QuickORM::DSL>), for details.
127  
128 Larger applications can declare the ORM and its row classes in their own
129 modules. See L<DBIx::QuickORM::ORM>.
130  
131 Supported databases: PostgreSQL, MySQL, MariaDB, SQLite, and DuckDB.
132  
133 =head1 SYNOPSIS
134  
135 use DBIx::QuickORM;
136  
137 my $orm = DBIx::QuickORM->new(
138 credentials => {
139 dsn => $dsn,
140 user => $user,
141 pass => $pass,
142 },
143 );
144  
145 my $bob = $orm->insert(users => {name => 'Bob'});
146 my $row = $orm->find(users => $bob->field('id'));
147  
148 $bob->update({name => 'Robert'});
149  
150 my @roberts = $orm->handle('users')
151 ->where({name => 'Robert'})
152 ->all;
153  
154 $orm->txn(sub {
155 $orm->insert(users => {name => 'Ann'});
156 $orm->insert(users => {name => 'Cy'});
157 });
158  
159 $bob->delete;
160  
161 =head1 PUBLIC METHODS
162  
163 The examples use the C<users> and C<posts> tables shown in the DESCRIPTION
164 of L<DBIx::QuickORM::Manual::Quickstart>, on PostgreSQL. C<$id> is a
165 C<users> primary key, and C<%credentials> holds C<dsn>, C<user>, and C<pass>.
166  
167 =head2 Constructor
168  
169 =over 4
170  
171 =item $orm = DBIx::QuickORM->new(%args)
172  
173 =item $orm = DBIx::QuickORM->new(\%args)
174  
175 Connects, scans the database into a map of its tables and fields
176 (L<DBIx::QuickORM::Map>), and returns the ORM. Pass exactly one of C<dbh>,
177 C<connect>, or C<credentials>. An unknown argument croaks.
178  
179 my $orm = DBIx::QuickORM->new(
180 credentials => {
181 dsn => $dsn,
182 user => $user,
183 pass => $pass,
184 },
185 omit => {users => ['prefs']}, # selected only when asked for
186 row_classes => {posts => undef}, # posts come back as plain hashrefs
187 retain_cache => 1, # keep rows cached until clear_cache()
188 );
189  
190 The connection argument, one of:
191  
192 =over 4
193  
194 =item dbh => $dbh
195  
196 A connected L<DBI> handle with C<RaiseError> and C<AutoCommit> on.
197  
198 my $dbh = DBI->connect(
199 $dsn, $user, $pass,
200 {
201 RaiseError => 1,
202 AutoCommit => 1,
203 },
204 );
205 my $orm = DBIx::QuickORM->new(dbh => $dbh);
206  
207 The ORM takes it over and may change its attributes. Using it elsewhere is
208 unsupported.
209  
210 With this form the ORM cannot open a second connection: using the ORM from a
211 forked child croaks, and so do C<aside> and C<forked> on its handles (see
212 L<DBIx::QuickORM::Handle/Running elsewhere>).
213  
214 =item connect => sub { ... }
215  
216 A code reference that returns a new, uncached handle with C<RaiseError> and
217 C<AutoCommit> on each time it is called.
218  
219 my $orm = DBIx::QuickORM->new(
220 connect => sub {
221 DBI->connect(
222 $dsn, $user, $pass,
223 {
224 RaiseError => 1,
225 AutoCommit => 1,
226 },
227 );
228 },
229 );
230  
231 Unlike C<dbh>, the ORM can open another handle, as a forked child does.
232  
233 =item credentials => {dsn => $dsn, user => $user, pass => $pass, attrs => \%attrs}
234  
235 Arguments for C<< DBI->connect >>. C<dsn> is required. C<user>, C<pass>, and
236 C<attrs> are optional.
237  
238 my $orm = DBIx::QuickORM->new(
239 credentials => {
240 dsn => $dsn,
241 user => $user,
242 pass => $pass,
243 attrs => {pg_server_prepare => 0}, # more DBI attributes
244 },
245 );
246  
247 Other keys croak. C<RaiseError> and C<AutoCommit> are always turned on, and
248 C<AutoCommit> given false in C<attrs> croaks.
249  
250 =back
251  
252 The ORM manages transactions, so every form needs C<AutoCommit> on. A handle
253 with C<AutoCommit> off, or with a transaction already open, croaks.
254  
255 The remaining arguments adjust the map. The database is scanned into a
256 L<DBIx::QuickORM::Map> unless C<db_map> is given, once per process (see
257 C<rescan>). These arguments then change it, in this order. Each type or row class they name is loaded during C<new>.
258  
259 Some examples below use a table or view of their own (C<audit>, C<user_names>,
260 C<sessions>, C<files>), shown in a comment. Like any table, it must exist
261 before this process first scans the database, or pass C<rescan>.
262  
263 Naming a table or field not in the map croaks, as does an argument of the
264 wrong type.
265  
266 =over 4
267  
268 =item db_map => $map
269  
270 A L<DBIx::QuickORM::Map>, or a hashref of map data, used instead of a scan.
271  
272 # no scan: start from another ORM's map. Take it while that ORM has no
273 # temporary tables or views, or the copy holds their records too.
274 my $copy = DBIx::QuickORM->new(
275 credentials => \%credentials,
276 db_map => $orm->db_map,
277 );
278  
279 It is deep-copied, so the original is never changed. The arguments below
280 adjust the copy.
281  
282 =item rescan => 1
283  
284 Scans the database even when this process scanned it before.
285  
286 # a migration, through its own database handle
287 $migration_dbh->do('CREATE TABLE tags (id SERIAL PRIMARY KEY, name TEXT NOT NULL)');
288  
289 # without rescan, the map would come from this process's first scan: no tags
290 my $orm = DBIx::QuickORM->new(
291 credentials => \%credentials,
292 rescan => 1,
293 );
294 my $tag = $orm->insert(tags => {name => 'perl'});
295  
296 The first scan of a database in a process is kept, and every later C<new>
297 without a C<db_map> starts from a copy of it, so building an ORM again (after
298 a lost connection, say) does not scan again. Each ORM still applies its own
299 arguments to its copy. The cache is keyed by which database the connection
300 reaches and what the session sees of it: the server, database, user, and
301 schema (or search path, or active roles), or the database file. In-memory
302 SQLite and DuckDB databases are never cached.
303  
304 Tables changed after the first scan are not seen. Pass C<rescan> after
305 changing tables in a running process, as a migration script does, or restart
306 the process. L<DBIx::QuickORM::Connection/"The scan cache"> has the details.
307  
308 =item autotype => \@types
309  
310 =item autotype => undef
311  
312 =item append_autotype => \@types
313  
314 The types tried, in order, on each field when the map is built. The first
315 that matches becomes the field's C<orm_type>. Default: C<UUID>, C<JSON>, then
316 C<DateTime> (L<DBIx::QuickORM::Type::UUID>, L<DBIx::QuickORM::Type::JSON>,
317 L<DBIx::QuickORM::Type::DateTime>).
318  
319 # JSON only: created comes back as the database's text, not a DateTime
320 my $json_only = DBIx::QuickORM->new(
321 credentials => \%credentials,
322 autotype => ['JSON'],
323 );
324  
325 # no types at all: the ORM inflates nothing, so a non-NULL prefs comes
326 # back as the JSON text the database gives, not a hashref
327 my $untyped = DBIx::QuickORM->new(
328 credentials => \%credentials,
329 autotype => undef,
330 );
331  
332 # the default list, then a type of your own for the fields it claims
333 my $more = DBIx::QuickORM->new(
334 credentials => \%credentials,
335 append_autotype => ['+My::Type::Trimmed'],
336 );
337  
338 C<< autotype => undef >> or C<[]> turns this off. C<append_autotype> adds to
339 the C<autotype> list, or to the default. With a C<db_map>, the map keeps its
340 types unless either is given. Then every field is typed again.
341  
342 A type matches through its C<base_types> or C<matches> (see
343 L<DBIx::QuickORM::Role::Type>).
344  
345 Type names work the same everywhere: a bare name such as C<JSON> means
346 C<DBIx::QuickORM::Type::JSON>, and a leading C<+> marks a full class name,
347 such as C<+My::Type>. The map holds the full name.
348  
349 Array fields are never typed automatically: those whose C<db_type> ends in
350 C<[]> or C<[N]> (PostgreSQL arrays, DuckDB lists and fixed-size arrays). Use
351 C<types> to give one a type.
352  
353 =item types => {table => {field => $type_or_undef}}
354  
355 =item types => {table => {field => {class => $type_or_undef, format => \&code, generate => $mode}}}
356  
357 Sets a field's type. Undef removes it.
358  
359 # CREATE TABLE sessions (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), note TEXT)
360 # -- gen_random_uuid() is built in from PostgreSQL 13, from pgcrypto before
361 my $orm = DBIx::QuickORM->new(
362 credentials => \%credentials,
363 types => {
364 users => {
365 # no type: the database's JSON text in and out
366 prefs => undef,
367  
368 # no class, so it stays DateTime. format gets the text the type
369 # deflated to, such as '2024-01-02 03:04:05.5', and returns the
370 # text to write: whole seconds
371 created => {
372 format => sub {
373 my ($text) = @_;
374 return $text =~ s/\.\d+//r;
375 },
376 },
377 },
378  
379 # a type the scan would not choose
380 posts => {title => '+My::Type::Trimmed'},
381  
382 # the ORM's version 7 UUIDs, not the database's default
383 sessions => {
384 id => {
385 class => 'UUID',
386 generate => 'prefer_orm',
387 },
388 },
389 },
390 );
391  
392 The hashref form also sets field hints: C<format> and C<generate> (see
393 L<DBIx::QuickORM::Role::Type/Field hints>). Without C<class> it keeps the
394 field's type.
395  
396 Either form replaces the field's hints with the ones given (none for the plain
397 form). C<type_options> then fills in the rest. Other keys croak, and so does a
398 hint on a field left without a type.
399  
400 =item type_options => {$type => {format => \&code, generate => $mode}}
401  
402 Field hints for every field of a type.
403  
404 # a DateTime the ORM deflates, on any field, is written without
405 # fractional seconds
406 my $orm = DBIx::QuickORM->new(
407 credentials => \%credentials,
408 type_options => {
409 DateTime => {
410 format => sub {
411 my ($text) = @_;
412 return $text =~ s/\.\d+//r;
413 },
414 },
415 },
416 );
417  
418 A field's own hints in C<types> win, each hint separately.
419  
420 =item fks => {table => {other_table => [{field => other_field}, ...]}}
421  
422 Foreign keys to add to the scanned ones.
423  
424 # CREATE TABLE audit (id SERIAL PRIMARY KEY, user_id INTEGER, action TEXT)
425 # -- audit.user_id holds a users.id, but declares no key
426 my $orm = DBIx::QuickORM->new(
427 credentials => \%credentials,
428 fks => {audit => {users => [{user_id => 'id'}]}},
429 );
430  
431 my $entry = $orm->insert(
432 audit => {
433 user_id => $id,
434 action => 'login',
435 },
436 );
437 my $who = $orm->follow_fk(audit => $entry, 'users')->only;
438  
439 A key identical to one the table
440 already has is ignored. A key over the same fields that maps them differently
441 croaks.
442  
443 =item elective => \@tables
444  
445 Tables the database may lack.
446  
447 # only some installs have legacy_log
448 my $orm = DBIx::QuickORM->new(
449 credentials => \%credentials,
450 elective => ['legacy_log'],
451 omit => {legacy_log => ['payload']},
452 );
453  
454 my $has_log = $orm->db_map->table('legacy_log') ? 1 : 0;
455  
456 When one is absent, the per-table arguments
457 naming it (C<types>, C<omit>, C<default_fields>, C<pks>, C<row_classes>, and
458 C<fks>, as the table or as a target) are dropped instead of croaking, and a
459 handle on it croaks, saying it is elective and absent. A table present
460 behaves like any other.
461  
462 =item pks => {view => \@fields, table => \@fields}
463  
464 Declares the primary key of a view, which the database cannot report, or of a
465 table the database reports none for (a legacy or staging table, or one keyed
466 by a C<UNIQUE NOT NULL> column).
467  
468 # CREATE VIEW user_names AS SELECT id, name FROM users
469 my $orm = DBIx::QuickORM->new(
470 credentials => \%credentials,
471 pks => {user_names => ['id']},
472 );
473  
474 my $named = $orm->find(user_names => $id);
475  
476 Its rows then go through the row cache, and
477 C<find> and the row writes work on it (for a view, the database decides
478 whether a write through it succeeds). Naming a table that has a primary key,
479 or a field the table or view lacks, croaks.
480  
481 The database need not enforce the declared key: the ORM trusts it. If two
482 rows share a key, C<update_row> and C<delete_row> change both, and the row
483 cache takes them for one row.
484  
485 The row cache clears rows by table name, so a write to a view's base table
486 does not clear rows read through the view. A view row can stay canonical
487 after the database changed it, so refresh view rows that must be current.
488  
489 =item omit => {table => \@fields}
490  
491 =item default_fields => {table => \@fields}
492  
493 Set which fields a table's queries select by default (the table's
494 C<default_fields>).
495  
496 my $orm = DBIx::QuickORM->new(
497 credentials => \%credentials,
498 omit => {users => ['prefs']}, # every users field but prefs
499 default_fields => {posts => ['title']}, # id and title
500 );
501  
502 C<omit> selects every field but the ones listed. C<default_fields> selects the
503 ones listed plus the primary key. A table named in neither selects every
504 field, unless a given C<db_map> sets its default fields.
505  
506 Croaks when both name the same table, when C<omit> names a primary key field,
507 or when no field is left.
508  
509 =item auto_omit => {types => \@types, db_types => \@db_types}
510  
511 Leaves fields of these types out of default selects, on every table C<omit>
512 and C<default_fields> do not name. Nothing is left out unless asked.
513  
514 # CREATE TABLE files (id SERIAL PRIMARY KEY, name TEXT, payload BYTEA)
515 my $orm = DBIx::QuickORM->new(
516 credentials => \%credentials,
517 auto_omit => {
518 types => ['JSON'], # users.prefs
519 db_types => ['bytea'], # files.payload
520 },
521 );
522  
523 my $user = $orm->find(users => $id); # selects every field but prefs
524  
525 # reading a field left out fetches it from the database
526 my $prefs = $user->field('prefs');
527  
528 C<types> names ORM types as C<types> does (C<JSON>, C<+My::Type>), matching a
529 field whose C<orm_type> is that class or a subclass. Each is loaded, and one
530 that cannot be croaks. C<db_types> names database types, matched against the
531 field's base type (C<type> in L<DBIx::QuickORM::Map>): lowercased, without
532 sizes or array markers, so C<bytea> also matches C<bytea[]>.
533  
534 Give each name as the map reports it, which is not always the short name.
535 PostgreSQL reports C<timestamp without time zone>, C<character varying>, and
536 C<double precision>, so C<timestamp> or C<varchar> matches nothing there.
537  
538 A field left out is fetched the first time a row reads it (see
539 L<DBIx::QuickORM::Manual::Caching/"FIELDS LEFT OUT OF A SELECT">).
540  
541 Primary, unique, and foreign key fields are never left out, and neither is any
542 field of a table without a primary key, which a row could not fetch later. A
543 given C<db_map> keeps the default fields it carries, including ones an
544 earlier C<auto_omit> set. Name a table in C<omit> or C<default_fields> to
545 change it. In a table class, a bare C<omit;> selects every field again.
546  
547 =item row_classes => {table => $class_or_undef}
548  
549 The row class for one table's rows. Undef means hashrefs.
550  
551 my $orm = DBIx::QuickORM->new(
552 credentials => \%credentials,
553 row_classes => {
554 users => 'My::App::User', # loaded from My/App/User.pm
555 posts => undef, # plain hashrefs
556 },
557 );
558  
559 Every row class named anywhere is loaded unless it already has a C<new>
560 method. One that cannot be loaded croaks.
561  
562 =item row_namespace => $namespace
563  
564 Gives each table a row class under C<$namespace>, named from the table:
565 C<user_posts> gets C<${namespace}::UserPosts>.
566  
567 # users rows are My::App::Row::Users, where that module exists
568 my $orm = DBIx::QuickORM->new(
569 credentials => \%credentials,
570 row_namespace => 'My::App::Row',
571 );
572  
573 A table with an entry in C<row_classes> (or in a given C<db_map>) keeps it.
574  
575 A table whose class is not loaded and has no module keeps the default row
576 class. A module that
577 fails to load croaks with its error.
578  
579 A class found this way must do L<DBIx::QuickORM::Role::Row>. One that does
580 not croaks, naming the table and the class.
581  
582 A table name that gives no valid class name (it must start with a letter or
583 C<_> and hold only word characters) warns and keeps the default row class.
584  
585 =item row_class_name => sub { my ($table) = @_; return $name }
586  
587 Replaces how C<row_namespace> names a table's class. It gets the table name
588 and returns the part after the namespace, such as C<'Person'> for C<people>.
589  
590 # users gets My::App::Row::User, posts My::App::Row::Post, where each exists
591 my $orm = DBIx::QuickORM->new(
592 credentials => \%credentials,
593 row_namespace => 'My::App::Row',
594 row_class_name => sub {
595 my ($table) = @_;
596 return ucfirst($table =~ s/s\z//r);
597 },
598 );
599  
600 Returning undef keeps the default row class for that table, without a
601 warning. Returning an invalid name (one holding C<::>, say) warns and keeps
602 the default.
603  
604 =back
605  
606 C<row_class>, C<sql_builder>, C<where_builders>, and C<like_aggregates> are
607 described under L</ATTRIBUTES>. C<lookup>, C<retain_cache>, C<enforce_canon>,
608 C<debug>, C<isolation>, C<time_zone> (or C<tz>), and C<datetime_parsers> are
609 described under L</Settings>. A setting of the wrong type croaks.
610  
611 A subclass constructor can pass C<< caller => [caller] >> so errors from
612 C<new> name its own caller's line. It is not kept on the object.
613  
614 =back
615  
616 =cut
617  
618 258 my %ARGS;
619 258 my @DEFAULT_WHERE_BUILDERS = map { "DBIx::QuickORM::WhereBuilder::$_" } qw/RawSQL Simple SQLAbstract/;
620  
621 502 ▶sub new {
Subroutine new: called CC=5 SCAR=21.6
Pod documented
622 0 ▶ my $class = shift;
Subroutine new: not called CC=5 SCAR=21.6
Pod documented
623 0 ▶ my $self = bless(@_ == 1 && ref($_[0]) eq 'HASH' ? {%{$_[0]}} : {@_}, $class);
Branch: 2 branches
BranchTrueFalseTotal
@_ == 1 && ref $_[0] eq 'HASH' ? : 1 501 502
@_ == 1 && ref $_[0] eq 'HASH' ? : 0 0 0
Condition33%2/6
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
50101
@_ == 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
624 0 ▶ my $frame = delete($self->{caller}) // [caller];
Condition50%2/4
delete $self->{"caller"} // [caller]
l!l
47455
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
625  
626 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()", $@) 353 149 502
eval { do { $self->init; 1 } } or _rethrow_at($frame, "$class->new()", $@) 0 0 0
627  
628 0 return $self;
629 }
630  
631 502 ▶sub init {
Subroutine init: called CC=10 SCAR=31.3
Pod undocumented
632 0 ▶ my $self = shift;
Subroutine init: not called CC=10 SCAR=31.3
Pod undocumented
633  
634 0 my @unknown = sort grep { !$ARGS{$_} } keys %$self;
635 0 ▶ croak "Unknown argument(s) to new(): " . join(', ' => @unknown) if @unknown;
Branch: 2 branches
BranchTrueFalseTotal
if @unknown 4 498 502
if @unknown 0 0 0
636  
637 0 $self->_check_args;
638  
639 0 my $offline = delete $self->{_offline};
640 0 ▶ $self->{+CONNECTOR} = $offline ? sub { croak "An offline ORM cannot connect to a database" } : $self->_build_connector;
Subroutine __ANON__: not called CC=1 SCAR=1.7
Branch: 2 branches
BranchTrueFalseTotal
$offline ? : 18 462 480
$offline ? : 0 0 0
641 0 $self->{+SQL_BUILDER} = $self->_build_sql_builder;
642  
643 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
6456
$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
644  
645 0 ▶ $self->{+ROW_CLASS} = 'DBIx::QuickORM::Row' unless exists $self->{+ROW_CLASS};
Branch: 2 branches
BranchTrueFalseTotal
unless exists $self->{"row_class"} 335 125 460
unless exists $self->{"row_class"} 0 0 0
646  
647 0 ▶ my %settings = map { exists($self->{$_}) ? ($_ => delete $self->{$_}) : () } qw/retain_cache enforce_canon isolation time_zone datetime_parsers/;
Branch: 2 branches
BranchTrueFalseTotal
exists $self->{$_} ? : 58 2242 2300
exists $self->{$_} ? : 0 0 0
648 0 ▶ $settings{lookup_class} = $self->_lookup_class(delete $self->{lookup}) if exists $self->{lookup};
Branch: 2 branches
BranchTrueFalseTotal
if exists $self->{"lookup"} 9 451 460
if exists $self->{"lookup"} 0 0 0
649 0 my $given = delete $self->{db_map};
650 0 ▶ $self->{+DEBUG} = $self->{+DEBUG} ? $self->_build_debug : undef; # kept here too, so a call checks it without reaching the Connection
Branch: 2 branches
BranchTrueFalseTotal
$self->{'debug'} ? : 4 456 460
$self->{'debug'} ? : 0 0 0
651 0 my $rescan = delete $self->{rescan};
652 0 my @dbh;
653 0 ▶ if ($offline) {
Branch: 2 branches
BranchTrueFalseTotal
if ($offline) 18 442 460
if ($offline) 0 0 0
654 0 require DBIx::QuickORM::Connection::Offline;
655 0 my $conn = $self->{+CONNECTION} = DBIx::QuickORM::Connection::Offline->new(%settings, %$offline, debug => $self->{+DEBUG});
656 0 $self->_drop_absent_elective($conn->db_map);
657 0 $self->_setup_map($conn->db_map, 0);
658 0 $self->{+FINISHED_MAP} = $conn->db_map->shallow_copy;
659 0 return;
660 }
661 0 ▶ if (my $build = delete $self->{_build_schema}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $build = delete $self->{"_build_schema"}) 3 439 442
if (my $build = delete $self->{"_build_schema"}) 0 0 0
662 0 my $dbh = $self->{+CONNECTOR}->();
663 0 $build->($dbh);
664 0 @dbh = (dbh => $dbh);
665 0 $rescan = 1; # a scan of the database before it was built may be cached
666 }
667 0 my $conn = $self->{+CONNECTION} = $self->_connect(%settings, debug => $self->{+DEBUG}, db_map => $self->_copy_map($given), rescan => $rescan, @dbh);
668 0 $self->_drop_absent_elective($conn->db_map);
669 0 $self->_setup_map($conn->db_map, defined $given);
670 0 $self->{+FINISHED_MAP} = $conn->db_map->shallow_copy;
671 }
672  
673 =pod
674  
675 =head2 Settings
676  
677 =over 4
678  
679 =item $conn = $orm->connection
680  
681 The current L<DBIx::QuickORM::Connection>.
682  
683 In a forked child, the ORM drops the inherited handle without closing the
684 parent's session. It then opens a new Connection from the connector, keeping
685 the map and settings.
686  
687 That croaks when the ORM was given a C<dbh>, and when a second connection
688 cannot reach the same data (an in-memory SQLite database, or DuckDB).
689  
690 =back
691  
692 =cut
693  
694 4878 ▶sub connection {
Subroutine connection: called CC=4 SCAR=14.0
Pod documented
695 4878 my $self = shift;
696  
697 4878 my $conn = $self->{+CONNECTION};
698 4878 ▶ return $conn if $conn->pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
if $conn->pid == $$ 4875 3 4878
699  
700 3 my $shared = $conn->dialect->supports_second_connection($conn->dbh);
701 3 $conn->release_inherited;
702 3 ▶ 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: 1 branch
BranchTrueFalseTotal
unless $shared 0 3 3
703 3 ▶ $self->{+DEBUG}->note_clear if $self->{+DEBUG}; # the new lookup table holds nothing
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 3 3
704 3 return $self->{+CONNECTION} = $self->_connect_like($conn);
705 }
706  
707 =pod
708  
709 =over 4
710  
711 =item $map = $orm->db_map
712  
713 The current Connection's L<DBIx::QuickORM::Map>: the one built when the ORM
714 was constructed, plus the Connection's temporary tables and views.
715  
716 =item $class = $orm->lookup_class
717  
718 The lookup table class, from the C<lookup> argument to C<new>:
719 L<DBIx::QuickORM::LookupTable::Identity> unless given. A bare name gets the
720 C<DBIx::QuickORM::LookupTable::> prefix, and a leading C<+> marks a fully
721 qualified class. L<DBIx::QuickORM::LookupTable> lists the classes that ship
722 and what each protects.
723  
724 my $orm = DBIx::QuickORM->new(credentials => \%credentials, lookup => 'Identity');
725  
726 =item $bool = $orm->retain_cache
727  
728 Whether canonical copies stay in the row cache outside a transaction.
729 Default 0.
730  
731 With 0 they are held weakly and freed once nothing else uses them. With 1 they
732 stay until C<clear_cache>. Croaks at construction when true and the lookup
733 table does not cache.
734  
735 =item $bool = $orm->enforce_canon
736  
737 Whether C<update_row> and C<delete_row> refuse row data that is not
738 canonical. Default 1.
739  
740 Outside a transaction, they croak when given row data that is not the
741 canonical copy. Inside one, the check is on by default whatever this says. Each
742 call can override it.
743  
744 =item $orm->set_enforce_canon($bool)
745  
746 Change C<enforce_canon> on the current Connection, for every write after the
747 call.
748  
749 =item $debug = $orm->debug
750  
751 The L<DBIx::QuickORM::Debug> that records which call made row data stop being
752 canonical, for C<canon_status> and the non-canonical croak, or undef. Off by
753 default. Pass C<< debug => 1 >> to C<new> to turn it on.
754  
755 my $orm = DBIx::QuickORM->new(credentials => \%credentials, debug => 1);
756  
757 It adds about 1 to 5 µs to each single-row write and about 1 µs to each
758 C<find>, and nothing per row to a fetch of many rows unless a row it reads
759 replaces a copy already held: 3% to 12% on a loop of small writes, and about
760 1% of a web request's query time.
761 L<DBIx::QuickORM::Manual::Caching/"WHY A ROW IS NOT CANONICAL"> says what it
762 records, and gives the numbers.
763  
764 =item $level = $orm->isolation
765  
766 The default isolation level for outermost transactions. Undef means
767 C<'read committed'>. Takes the levels C<txn> takes (see C<txn> under
768 L</Transactions>).
769  
770 =item $tz = $orm->time_zone
771  
772 The session time zone, C<UTC> unless given. MySQL and MariaDB get C<UTC> as
773 C<+00:00>. SQLite has no session time zone.
774 C<new> also accepts it as C<tz>. Giving both croaks.
775  
776 =item \@parsers = $orm->datetime_parsers
777  
778 Parsers for date and time text that neither the database's own parser nor
779 L<DateTime::Format::ISO8601> reads, tried in order. Empty unless given.
780  
781 use DateTime::Format::Strptime;
782  
783 my $orm = DBIx::QuickORM->new(
784 credentials => {
785 dsn => $dsn,
786 user => $user,
787 pass => $pass,
788 },
789 datetime_parsers => [
790 DateTime::Format::Strptime->new(pattern => '%d/%m/%Y %H:%M'),
791 # epoch seconds
792 sub { $_[0] =~ m/^\d+\z/ ? DateTime->from_epoch(epoch => $_[0]) : undef },
793 ],
794 );
795  
796 Each is a class or object with C<parse_datetime>, or a code reference taking
797 the text. C<new> loads each class, and croaks when one cannot be loaded or has
798 no C<parse_datetime>.
799  
800 A parser says no by returning undef or dying. The first DateTime returned
801 wins. Returning anything else croaks.
802  
803 =item $orm->set_datetime_parsers(\@parsers)
804  
805 Replace C<datetime_parsers> on the current Connection, checked as C<new>
806 checks it, for values read after the call.
807  
808 A DateTime field read before the call keeps the parsers it was read with, even
809 while still unparsed.
810  
811 =back
812  
813 Only C<enforce_canon> and C<datetime_parsers> have setters. The other settings
814 are fixed when the ORM is built. Build a new ORM to change them. A forked
815 child's new Connection keeps the changed values.
816  
817 =cut
818  
819 1916 ▶sub db_map { $_[0]->connection->db_map }
Subroutine db_map: called CC=1 SCAR=0.0
Pod documented
820 3 ▶sub lookup_class { $_[0]->connection->lookup_class }
Subroutine lookup_class: called CC=1 SCAR=0.0
Pod documented
821 4 ▶sub retain_cache { $_[0]->connection->retain_cache }
Subroutine retain_cache: called CC=1 SCAR=0.0
Pod documented
822 3 ▶sub enforce_canon { $_[0]->connection->enforce_canon }
Subroutine enforce_canon: called CC=1 SCAR=0.0
Pod documented
823 2 ▶sub set_enforce_canon { $_[0]->connection->set_enforce_canon($_[1]) }
Subroutine set_enforce_canon: called CC=1 SCAR=0.0
Pod documented
824 4 ▶sub isolation { $_[0]->connection->isolation }
Subroutine isolation: called CC=1 SCAR=0.0
Pod documented
825 7 ▶sub time_zone { $_[0]->connection->time_zone }
Subroutine time_zone: called CC=1 SCAR=0.0
Pod documented
826 3 ▶sub datetime_parsers { $_[0]->connection->datetime_parsers }
Subroutine datetime_parsers: called CC=1 SCAR=0.0
Pod documented
827  
828 5 ▶sub set_datetime_parsers {
Subroutine set_datetime_parsers: called CC=2 SCAR=6.9
Pod documented
829 5 my $self = shift;
830 5 my $frame = [caller];
831 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
832 }
833  
834 =pod
835  
836 =head2 The row cache
837  
838 With the default lookup table, the ORM caches one canonical copy of each
839 row's data, by primary key. A row is canonical when its data is that copy.
840 That does not mean it matches the database right now. Other lookup tables
841 decide what is canonical differently (see
842 L<< lookup_class|/"$class = $orm->lookup_class" >>).
843  
844 =over 4
845  
846 =item $bool = $orm->is_canon($table, $row_or_data)
847  
848 True when the row data (or a row object's C<row_data>) is canonical: with
849 the default lookup table, the copy the row cache holds for its primary key.
850  
851 my $user = $orm->find(users => $id);
852 my $obj = $orm->is_canon(users => $user); # a row object: true
853 my $data = $orm->is_canon(users => $user->row_data); # its row data: true
854  
855 # a hashref the row cache never saw: false
856 my ($bare) = $orm->handle('users')
857 ->where({id => $id})
858 ->bare
859 ->all;
860 my $other = $orm->is_canon(users => $bare);
861  
862 With the default, false when it is not that copy, when the row cache has no
863 copy for that key, and for row data that is deleted or not in the database (a
864 new row from C<vivify>, say), key or no key. Otherwise croaks when the primary
865 key cannot be determined.
866  
867 The lookup table decides, so the others behave differently:
868  
869 =over 4
870  
871 =item L<DBIx::QuickORM::LookupTable::Identity/is_canon>
872  
873 The default, described above.
874  
875 =item L<DBIx::QuickORM::LookupTable::Scoped/canon_status>
876  
877 No row cache: every copy is canonical, except across a transaction boundary,
878 or once deleted or not in the database.
879  
880 =item L<DBIx::QuickORM::LookupTable::Unchecked/DESCRIPTION>
881  
882 All row data is canonical.
883  
884 =back
885  
886 =item $status = $orm->canon_status($table, $row_or_data)
887  
888 Why the row data (or a row object's C<row_data>) is not canonical: undef
889 while it is, otherwise a hashref with its C<cause>. A row's own
890 C<canon_status> calls this.
891  
892 The lookup table gives the cause:
893 L<DBIx::QuickORM::LookupTable::Identity/canon_status> (the default),
894 L<DBIx::QuickORM::LookupTable::Scoped/canon_status>, or
895 L<DBIx::QuickORM::LookupTable::Unchecked/DESCRIPTION> (always undef). The
896 causes the shipped lookup tables give:
897  
898 =over 4
899  
900 =item C<replaced>
901  
902 Another copy took its place: a read of changed data or of fewer fields, a
903 write, or a primary key change.
904  
905 =item C<cache_cleared>
906  
907 Its copy was cleared on its own (C<< clear_cache($table => $pk) >>).
908  
909 =item C<txn>
910  
911 It was read before the open transaction began.
912  
913 =item C<deleted>
914  
915 The row was deleted, or found gone.
916  
917 =item C<not_in_db>
918  
919 The row is not in the database: built by C<vivify>, or its insert was rolled
920 back.
921  
922 =item C<not_cached>
923  
924 The row cache holds no copy of it: it was read around the cache (C<no_cache>,
925 C<bare>), its transaction rolled back, or its table or the whole cache was
926 cleared.
927  
928 =item C<rolled_back>
929  
930 With C<< lookup => 'Scoped' >>: it was read or written in a transaction that
931 rolled back.
932  
933 =back
934  
935 C<by> is the call behind a C<replaced>, C<cache_cleared>, or C<deleted>, and
936 C<last_clear> the call that last cleared the table or the whole cache for a
937 C<not_cached>, each when known, as a C<caller> frame: package, file, line, and
938 the public method called. When a public method calls another, the outer one is
939 recorded. They are recorded only with C<< debug => 1 >> (see C<debug>).
940  
941 Without C<debug> the cause is what can be worked out when asked: row data
942 whose key another hash holds is C<replaced> (a copy that was never canonical
943 looks the same), and a cleared key is C<not_cached>.
944  
945 # with debug => 1
946 my $one = $orm->find(users => $id);
947 my $two = $orm->handle('users')->fields(['name'])->where({id => $id})->only;
948  
949 my $why = $orm->canon_status(users => $one);
950 # {cause => 'replaced', by => ['main', 'app.pl', 3, 'DBIx::QuickORM::Handle::only']}
951  
952 Writing non-canonical row data croaks naming the same cause and call. A row
953 object that is deleted or not in the database is refused earlier by the row
954 method, with its own error.
955  
956 A deleted or C<not_in_db> row needs no primary key here. Any other croaks as
957 C<is_canon> does when the key cannot be determined.
958  
959 =item $orm->clear_cache
960  
961 =item $orm->clear_cache($table)
962  
963 =item $orm->clear_cache($table => $pk)
964  
965 Forgets canonical copies: all of them, one table's, or one row's.
966 They are read from the database again when next looked up.
967  
968 my $user = $orm->find(users => $id);
969 my $held = $orm->is_canon(users => $user); # true: $user's data is the canonical copy
970  
971 $orm->clear_cache(users => $id); # or clear_cache('users'), or clear_cache()
972 my $still = $orm->is_canon(users => $user); # false
973 $user->refresh; # canonical again
974  
975 C<$pk> takes the forms C<find> takes (see L<DBIx::QuickORM::Handle>), and its
976 values are deflated (turned into database form) the same way.
977  
978 A typed key matches in any form: a C<DateTime> or the database's text, a
979 UUID in upper case or as 16 bytes.
980  
981 Inside a transaction, it clears the current transaction or savepoint level,
982 and the cache from before the outermost transaction. A savepoint rollback
983 restores what the enclosing level held. L</Transactions> says what ending the
984 outermost transaction does.
985  
986 A handle that already ran keeps its rows. Call its C<clear> to query again.
987  
988 =back
989  
990 =cut
991  
992 111 ▶sub is_canon { my $self = shift; $self->connection->is_canon(@_) }
Subroutine is_canon: called CC=1 SCAR=0.0
Pod documented
993 26 ▶sub canon_status { my $self = shift; $self->connection->canon_status(@_) }
Subroutine canon_status: called CC=1 SCAR=0.0
Pod documented
994  
995 64 ▶sub clear_cache {
Subroutine clear_cache: called CC=4 SCAR=13.9
Pod documented
996 64 my $self = shift;
997 64 my ($table, @pk) = @_;
998 64 my $conn = $self->connection;
999 64 my $lookup = $conn->lookup;
1000 64 my $debug = $self->{+DEBUG};
1001 64 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 2 62 64
Condition66%2/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
6202
MC/DC50%1/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table66%2/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1002 64 ▶ return $lookup->forget(@_) unless @pk;
Branch: 1 branch
BranchTrueFalseTotal
unless @pk 43 21 64
1003 21 return $lookup->forget($table, $conn->_plain($conn->_pk_values($table, $pk[0])));
1004 }
1005  
1006 =head2 CRUD operations
1007  
1008 # a row object
1009 my $ann = $orm->insert(
1010 users => {
1011 name => 'Ann',
1012 prefs => {theme => 'dark'},
1013 },
1014 );
1015  
1016 # row data: a hashref
1017 my $ben = $orm->insert(
1018 users => {name => 'Ben'},
1019 data => 1,
1020 );
1021  
1022 $orm->insert(users => {name => 'Cy'}); # void: nothing read back
1023  
1024 # compare-and-swap on any hashref, a bare one included: undef if the name
1025 # changed since it was read
1026 my ($cy) = $orm->handle('users')->where({name => 'Cy'})->bare->all;
1027 my $renamed = $orm->cas_update(users => $cy, {name => 'Cyrus'});
1028  
1029 # an arrayref of rows, or with count => 1, how many went in
1030 my $rows = $orm->insert_many(users => [{name => 'Di'}, {name => 'Ed'}]);
1031 my $n = $orm->insert_many(
1032 users => [{name => 'Flo'}],
1033 count => 1,
1034 );
1035  
1036 $orm->update_row(users => $ann, {name => 'Anne'}); # updates the row object given
1037  
1038 my $fresh = $orm->update_row(
1039 users => $ben,
1040 {email => 'ben@example.com'},
1041 cas => ['email'],
1042 );
1043  
1044  
1045 my $again = $orm->refresh_row(users => {id => $ben->{id}}); # a row object, from the cache
1046 my $gone = $orm->delete_row(users => $fresh); # 1
1047  
1048 # rows have the same operations as methods
1049 $ann->update({email => 'ann@example.com'}); # $orm->update_row(users => $ann, {...})
1050 $ann->refresh; # $orm->refresh_row(users => $ann, cache => 0)
1051 $ann->delete; # $orm->delete_row(users => $ann)
1052  
1053 The CRUD operations work on row data: plain hashrefs where a missing key means
1054 the field was not fetched and an undef value means NULL. Wherever row data is
1055 expected, a row object works too, and its C<row_data> is used.
1056  
1057 A row object given to C<update_row> or C<refresh_row> must also have
1058 C<set_row_data>, which takes the new row data. One without it, or an aggregate
1059 row, croaks before anything is sent.
1060  
1061 Each CRUD operation croaks on an argument it does not know.
1062  
1063 The CRUD operations that return rows (C<insert>, C<insert_many>,
1064 C<update_row>, and C<refresh_row>) share one rule. C<find>,
1065 C<find_or_insert>, C<insert_fk>, and C<insert_many_fk> follow it too, and
1066 C<vivify> takes C<row_class>:
1067  
1068 =over 4
1069  
1070 =item *
1071  
1072 In void context they do the work and return nothing.
1073  
1074 =item *
1075  
1076 Given a row object, C<update_row> and C<refresh_row> return that same object,
1077 now holding the new row data (it takes the new data in void context too).
1078  
1079 =item *
1080  
1081 C<< data => 1 >> returns the row data instead of a row. A given row object
1082 still takes the new data. A handle's C<data_only> does the same for the
1083 rows it returns.
1084  
1085 =item *
1086  
1087 C<< row_class => $class >> builds the rows with that class for this call,
1088 loading it when needed. C<< row_class => undef >> returns the row data. With
1089 C<< data => 1 >> too, C<data> wins. A given row object still takes the new
1090 data. A handle passes its own C<row_class> this
1091 way.
1092  
1093 =item *
1094  
1095 Otherwise they return a new row object. The class is the table's
1096 C<row_class> in the map when set (even to undef), else the ORM's
1097 C<row_class>. When that class is undef (as with C<< row_class => undef >>
1098 to C<new>), they return the row data.
1099  
1100 =item *
1101  
1102 C<insert_many> returns an arrayref of these, never a list.
1103  
1104 =item *
1105  
1106 When no row matched, C<update_row> and C<refresh_row> return undef. A row
1107 object given keeps its row data, but a C<refresh_row> that finds no row marks
1108 it deleted (see C<was_deleted> in L<DBIx::QuickORM::Role::Row>).
1109  
1110 =back
1111  
1112 For row class authors: the object is built with
1113 C<< $class->new(row_data => \%data, orm => $orm, table => $table) >>, or
1114 blessed from those directly when the class's C<fast_bless> is true.
1115  
1116 Writes replace the canonical copy for that primary key. A read keeps the
1117 canonical copy when every fetched value matches it and it fetched every field
1118 the copy holds, adding any new fields. Otherwise the read replaces it, and
1119 row objects holding the old copy are no longer canonical
1120 (L<DBIx::QuickORM::Manual::Caching/"FIELDS LEFT OUT OF A SELECT">).
1121  
1122 A row written through C<RETURNING> comes back with the table's default
1123 fields, the fields written, and for an update the fields the row held.
1124 Without C<RETURNING> (MySQL always, MariaDB for updates) it holds only the
1125 primary key.
1126  
1127 Values sent are never copied into the returned row data (except with
1128 C<insert>'s C<as_given>): defaults, triggers, and generated columns can change
1129 them.
1130  
1131 Every CRUD operation takes C<raw>. Without it, every value sent (inserted
1132 values, changes, compare-and-swap values, and primary key values) is deflated,
1133 turned from a Perl value into database form, by its field's type:
1134  
1135 =over 4
1136  
1137 =item *
1138  
1139 A reference on a typed field is deflated.
1140  
1141 =item *
1142  
1143 A reference on a field without a type croaks.
1144  
1145 =item *
1146  
1147 A plain value on a typed field is deflated when the type's C<is_inflated> says
1148 it is inflated. A plain value can be ambiguous (is C<123> JSON, or already
1149 encoded?). Wrap it in C<raw()> or C<inflated()> to say which.
1150  
1151 =item *
1152  
1153 Anything else is sent as given.
1154  
1155 =back
1156  
1157 C<< raw => 1 >> says every value is already in database form and skips
1158 deflation. It is also how to send a reference to a field without a type (a
1159 PostgreSQL array, say).
1160  
1161 C<raw> covers only the values you gave. Values the ORM generates, such as a
1162 primary key from its type, are deflated as above whatever C<raw> says.
1163  
1164 To mark one value instead of all, wrap it in a marker from
1165 L<DBIx::QuickORM::Value>. A marker overrides both the default and C<raw>:
1166  
1167 use DBIx::QuickORM::Value qw/raw inflated sql/;
1168  
1169 my $dee = $orm->insert(
1170 users => {
1171 name => 'Dee',
1172 prefs => raw('{"theme":"dark"}'), # already JSON text: sent as is
1173 created => sql('now()'), # literal SQL
1174 },
1175 );
1176  
1177 # raw => 1 for every value, but deflate this one
1178 my $eli = $orm->insert(
1179 users => {
1180 name => 'Eli',
1181 prefs => inflated({theme => 'light'}),
1182 },
1183 raw => 1,
1184 );
1185  
1186 C<raw()> sends one value as given, and C<inflated()> deflates one even under
1187 C<< raw => 1 >>. C<binary()> binds bytes, and C<sql()> is literal SQL.
1188 L<DBIx::QuickORM::Manual::Values> covers each marker, deflation, and
1189 inflation on read.
1190  
1191 The single-row CRUD operations reuse prepared statements (DBI's
1192 C<prepare_cached>). Behind a pooler in transaction mode, such as PgBouncer,
1193 turn off server-side prepares (DBD::Pg's C<pg_server_prepare>).
1194  
1195 =over 4
1196  
1197 =item $row = $orm->insert($table => \%fields, raw => $bool)
1198  
1199 =item \%data = $orm->insert($table => \%fields, data => 1, raw => $bool)
1200  
1201 =item $row = $orm->insert($table => \%fields, as_given => 1, raw => $bool)
1202  
1203 Inserts one row and returns it. At least one field is required.
1204  
1205 The new primary key comes from C<RETURNING>, from the given values, or from
1206 the database's last insert id for a single-field key.
1207  
1208 A typed primary key field left out can get its value from its type (a version
1209 7 UUID for a UUID field). The ORM skips this when the database fills the
1210 column and can return it with C<RETURNING>. On MySQL it always generates. The
1211 field's C<generate> hint changes this (see
1212 L<DBIx::QuickORM::Role::Type/Field hints>).
1213  
1214 A field passed as undef is sent as NULL and is not generated.
1215  
1216 Generated values are sent like your own, and C<as_given> includes them.
1217 C<insert_many> generates them the same way for each row.
1218  
1219 In void context it only inserts. It sends no C<RETURNING>, caches no canonical
1220 copy, builds no row, and skips the checks below.
1221  
1222 Without C<RETURNING> (MySQL), unless in void context:
1223  
1224 =over 4
1225  
1226 =item *
1227  
1228 A table without a primary key croaks.
1229  
1230 =item *
1231  
1232 A compound key not given in full croaks before anything is sent.
1233  
1234 =item *
1235  
1236 A single-field key not given (or given as C<sql()>) is read from the last
1237 insert id after the insert. When the database generated none (a key that is
1238 not auto-increment gives 0), the insert croaks with the row already in the
1239 table.
1240  
1241 =back
1242  
1243 C<< as_given => 1 >> returns a copy of the fields as sent, in database form,
1244 plus the new primary key, instead of reading the row back. Fields sent as
1245 C<sql()> are left out.
1246  
1247 # the fields as sent, plus the new id: no read back
1248 my $hal = $orm->insert(
1249 users => {name => 'Hal'},
1250 as_given => 1,
1251 );
1252 # created was not sent, so reading it fetches it from the database
1253 my $created = $hal->field('created');
1254  
1255 The copy is not canonical, so C<update> and C<delete> on it croak while
1256 C<enforce_canon> is on. Refresh it first. A row object fetches a field the
1257 copy lacks when it is read.
1258  
1259 On a table without a primary key it returns the copy even without
1260 C<RETURNING>, but nothing can be written or fetched through it.
1261  
1262 =back
1263  
1264 =cut
1265  
1266 291 ▶sub insert {
Subroutine insert: called CC=3 SCAR=11.0
Pod documented
1267 291 my $self = shift;
1268 291 my $debug = $self->{+DEBUG};
1269 291 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller}; # see DBIx::QuickORM::Debug, "The caller slot"
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 1 290 291
Condition66%2/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
29001
MC/DC50%1/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table66%2/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1270 291 $self->_primitive(insert => @_);
1271 }
1272  
1273 =pod
1274  
1275 =over 4
1276  
1277 =item \@rows = $orm->insert_many($table => \@rows, raw => $bool)
1278  
1279 =item \@data = $orm->insert_many($table => \@rows, data => 1, raw => $bool)
1280  
1281 =item $count = $orm->insert_many($table => \@rows, count => 1, raw => $bool)
1282  
1283 Inserts many rows and returns an arrayref of the new rows. Every row must
1284 have the same fields, at least one.
1285  
1286 # an arrayref of row objects
1287 my $rows = $orm->insert_many(
1288 users => [
1289 {name => 'Ola'},
1290 {name => 'Pia'},
1291 ],
1292 );
1293  
1294 # an arrayref of row data (hashrefs)
1295 my $data = $orm->insert_many(
1296 users => [{name => 'Quin'}],
1297 data => 1,
1298 );
1299  
1300 # how many went in: 2, nothing read back
1301 my $count = $orm->insert_many(
1302 users => [
1303 {name => 'Rae'},
1304 {name => 'Sol'},
1305 ],
1306 count => 1,
1307 );
1308  
1309 # raw => 1: every value is sent as given, so prefs must be JSON text
1310 my $raw = $orm->insert_many(
1311 users => [
1312 {
1313 name => 'Tam',
1314 prefs => '{"theme":"dark"}',
1315 },
1316 ],
1317 raw => 1,
1318 );
1319  
1320 # void context: inserts, reads nothing back
1321 $orm->insert_many(users => [{name => 'Uma'}]);
1322  
1323 On a table with a primary key, the new rows become canonical. Copies already
1324 in the row cache stay.
1325  
1326 C<< count => 1 >> returns how many rows were inserted instead. It works on
1327 every database, never reads rows back, and cannot be combined with
1328 C<< data => 1 >>.
1329  
1330 In void context it only inserts: nothing is read back or made canonical.
1331  
1332 An empty C<\@rows> sends nothing and returns an empty arrayref (0 with
1333 C<count>).
1334  
1335 The rows go in multi-row C<INSERT> statements, each holding as many rows as
1336 the database's bind limit allows. When it takes more than one statement, they
1337 run in one transaction, so either every row is inserted or none is.
1338  
1339 Inside an open transaction it always takes a savepoint, even for one
1340 statement: a failure rolls back only these rows and leaves the open
1341 transaction usable. On DuckDB, which has no savepoints, the open transaction
1342 is used as it is.
1343  
1344 The returned rows come in the order the database gives them, with the table's
1345 default fields.
1346  
1347 Without C<RETURNING> (MySQL) each row holds only its primary key, so every
1348 row must carry its whole primary key. A row without it, or a table without a
1349 primary key, croaks before anything is sent. Use C<count> or void context.
1350  
1351 =back
1352  
1353 =cut
1354  
1355 61 ▶sub insert_many {
Subroutine insert_many: called CC=3 SCAR=12.0
Pod documented
1356 61 my $self = shift;
1357 61 my $debug = $self->{+DEBUG};
1358 61 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 0 61 61
Condition33%1/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
6100
MC/DC0%0/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table33%1/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1359 61 $self->_primitive(insert_many => @_);
1360 }
1361  
1362 =pod
1363  
1364 =over 4
1365  
1366 =item $row = $orm->update_row($table, $row_or_data, \%changes, %opts)
1367  
1368 =item \%data = $orm->update_row($table, $row_or_data, \%changes, data => 1, %opts)
1369  
1370 Updates the row with the row data's primary key and returns it, or undef when
1371 no row matched. At least one change is required. A row object given follows
1372 the rule in L</"CRUD operations">.
1373  
1374 Options:
1375  
1376 =over 4
1377  
1378 =item enforce_canon => $bool
1379  
1380 When true, croaks unless the row data is canonical (see C<is_canon>). Undef or
1381 absent means true inside a transaction, otherwise the ORM's C<enforce_canon>.
1382  
1383 0 skips that check, but C<cas> and C<auto_cas> still apply. It also skips the
1384 row state checks: a row not in the database (vivified, or deleted) is still
1385 updated by its key, where the row's own C<update> croaks. Not recommended.
1386  
1387 =item cas => \@fields
1388  
1389 Compare-and-swap: update only while these fields still hold the row data's
1390 values (undef matches NULL). Otherwise return undef and change nothing. Each
1391 field must be in the row data, or it croaks.
1392  
1393 It compares with C<=>, so it does not suit floats, PostgreSQL C<json>, or
1394 MySQL C<JSON>.
1395  
1396 =item auto_cas => $bool
1397  
1398 Compare-and-swap on every field present in both the row data and the changes.
1399  
1400 my $user = $orm->find(users => $id); # holds email, a default field
1401  
1402 # writes only while email still holds what $user read, else undef
1403 my $done = $orm->update_row(
1404 users => $user,
1405 {email => 'new@example.com'},
1406 auto_cas => 1,
1407 );
1408  
1409 =back
1410  
1411 =back
1412  
1413 =cut
1414  
1415 137 ▶sub update_row {
Subroutine update_row: called CC=3 SCAR=11.0
Pod documented
1416 137 my $self = shift;
1417 137 my $debug = $self->{+DEBUG};
1418 137 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 2 135 137
Condition100%3/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
12872
MC/DC100%2/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table100%3/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1419 137 $self->_primitive(update_row => @_);
1420 }
1421  
1422 =pod
1423  
1424 =over 4
1425  
1426 =item \%data = $orm->cas_update($table, \%data, \%changes)
1427  
1428 =item $row = $orm->cas_update($table, $row, \%changes, cas => \@fields)
1429  
1430 C<update_row> as a compare-and-swap: writes the changes only while the
1431 database still holds the row data's values for the changed fields (or the
1432 C<cas> fields), and returns undef otherwise, changing nothing.
1433  
1434 # a row object: set the email only while the name is still what it read
1435 my $user = $orm->find(users => $id);
1436 my $same = $orm->cas_update(
1437 users => $user,
1438 {email => 'robert@example.com'},
1439 cas => ['name'],
1440 );
1441  
1442 The row data need not be canonical, so it takes any hashref holding the
1443 primary key and the compared fields, a C<bare> one included, and returns the
1444 new row data, or a row of C<row_class> when that option is given. Given a row
1445 object it returns that object, holding the new data (L</"CRUD operations">). A
1446 row's own C<cas_update> calls this.
1447  
1448 The row data's values, its primary key included, are used as the database
1449 returned them, as a fetch gives them, not deflated as C<update_row> deflates
1450 them. A hand-built hashref must hold stored values, or wrap an inflated one in
1451 C<inflated()> (L<DBIx::QuickORM::Value>). The changes are deflated as for
1452 C<update_row>, unless C<raw> is true.
1453  
1454 It croaks on any option but C<cas>, C<raw>, and C<row_class>, on an empty
1455 C<cas> list (an unconditional write), on row data not in the database
1456 (vivified, or deleted), and when the row data lacks a field it compares.
1457  
1458 Inside a transaction, the returned row data keeps the row's
1459 inserted-in-this-transaction mark when the given hashref or the row's cached
1460 copy carries it. When neither does (say a hashref fetched again with C<bare>
1461 after C<clear_cache>), it cannot. If a rollback then undoes the insert, it may
1462 still report being in the database. Find the row again before relying on it.
1463  
1464 =back
1465  
1466 =cut
1467  
1468 258 my %CAS_UPDATE_ARGS = map { $_ => 1 } qw/cas raw row_class/;
1469  
1470 30 ▶sub cas_update {
Subroutine cas_update: called CC=16 SCAR=28.0
Pod documented
1471 30 my $self = shift;
1472 30 my ($table, $row, $changes, @args) = @_;
1473 30 ▶ croak "cas_update() needs a hashref of changes" unless ref($changes) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $changes eq "HASH" 1 29 30
1474 29 ▶ croak "Odd number of options to cas_update()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 28 29
1475 28 my %params = @args;
1476 28 my @unknown = sort grep { !$CAS_UPDATE_ARGS{$_} } keys %params;
1477 28 ▶ croak "Unknown argument(s) to cas_update(): " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 27 28
1478 27 ▶ 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 25 27
Condition100%3/3
ref $params{"cas"} eq "ARRAY" and not @{$params{"cas"};}
!ll&&!rl&&r
1782
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
1479  
1480 25 my $debug = $self->{+DEBUG};
1481 25 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 0 25 25
Condition33%1/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
2500
MC/DC0%0/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table33%1/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1482  
1483 25 ▶ my $data = blessed($row) && $row->can('row_data') ? $row->row_data : $row;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($row) && $row->can('row_data') ? : 13 12 25
Condition66%2/3
builtin::blessed($row) and $row->can("row_data")
!ll&&!rl&&r
12013
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
1484 25 ▶ croak "Cannot cas_update a row that is not in the database; insert it first" if ref($data) eq 'HASH' && DBIx::QuickORM::RowState->state($data);
Branch: 1 branch
BranchTrueFalseTotal
if ref $data eq "HASH" and "DBIx::QuickORM::RowState"->state($data) 1 24 25
Condition66%2/3
ref $data eq "HASH" and "DBIx::QuickORM::RowState"->state($data)
!ll&&!rl&&r
0241
MC/DC50%1/2
ref $data eq "HASH" and "DBIx::QuickORM::RowState"->state($data)
ref $data eq "HASH" "DBIx::QuickORM::RowState"->state($data)
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= "DBIx::QuickORM::RowState"->state($data)
ABresult
0X0
100
111
1485  
1486 # The row data is compared as fetched, so only the changes are deflated.
1487 24 ▶ $changes = $self->connection->deflate($table, $changes) unless delete $params{raw};
Branch: 1 branch
BranchTrueFalseTotal
unless delete $params{"raw"} 24 0 24
1488  
1489 24 ▶ my $cas = $params{cas} // [keys %$changes];
Condition100%2/2
$params{"cas"} // [keys %$changes]
l!l
816
MC/DC100%1/1
$params{"cas"} // [keys %$changes]
$params{"cas"}
Truth table100%2/2
A
A= $params{"cas"}
Aresult
11
00
1490 24 ▶ my @back = blessed($row) || exists $params{row_class} ? () : (data => 1);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($row) || exists $params{'row_class'} ? : 14 10 24
Condition100%3/3
builtin::blessed($row) or exists $params{"row_class"}
l!l&&r!l&&!r
13110
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
1491 24 return $self->_primitive(update_row => $table, $row, $changes, %params, @back, cas => $cas, enforce_canon => 0, raw => 1);
1492 }
1493  
1494 =pod
1495  
1496 =over 4
1497  
1498 =item $count = $orm->delete_row($table, $row_or_data, enforce_canon => $bool, raw => $bool)
1499  
1500 Deletes the row with the row data's primary key and returns how many rows were
1501 deleted (0 or 1). The ORM stops holding it and marks the row data deleted (see
1502 C<was_deleted> in L<DBIx::QuickORM::Role::Row>).
1503  
1504 A delete that matches no row also marks it deleted (it is not in the
1505 database) and returns 0.
1506  
1507 C<enforce_canon> is as for C<update_row>, including what 0 bypasses.
1508  
1509 =back
1510  
1511 =cut
1512  
1513 19 ▶sub delete_row {
Subroutine delete_row: called CC=3 SCAR=12.0
Pod documented
1514 19 my $self = shift;
1515 19 my $debug = $self->{+DEBUG};
1516 19 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 0 19 19
Condition33%1/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
1900
MC/DC0%0/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table33%1/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1517 19 return $self->connection->delete_row(@_);
1518 }
1519  
1520 =pod
1521  
1522 =over 4
1523  
1524 =item $row = $orm->refresh_row($table, $row_or_data, cache => $bool, db => $bool, fields => \@fields, raw => $bool)
1525  
1526 =item \%data = $orm->refresh_row($table, $row_or_data, data => 1, %opts)
1527  
1528 The canonical row for a primary key, or undef when there is none. It takes row
1529 data, a row, or a primary key in any form (a value, an arrayref, or a
1530 hashref).
1531  
1532 # always a query
1533 my $fresh = $orm->refresh_row(
1534 users => $id,
1535 cache => 0,
1536 );
1537  
1538 # never a query: the canonical copy, or undef
1539 my $cached = $orm->refresh_row(
1540 users => $id,
1541 db => 0,
1542 );
1543  
1544 # a query for the key and name only
1545 my $named = $orm->refresh_row(
1546 users => $id,
1547 fields => ['name'],
1548 cache => 0,
1549 );
1550  
1551 # a row object takes the new data, and data => 1 returns it as a hashref
1552 my $data = $orm->refresh_row(
1553 users => $user,
1554 data => 1,
1555 cache => 0,
1556 );
1557  
1558 A row object given follows the rule in L</"CRUD operations">.
1559  
1560 It reads C<fields> plus the primary key, or the table's default fields plus
1561 the fields the given row data holds.
1562  
1563 By default it returns the canonical copy when that has every field asked for,
1564 and reads the database otherwise. C<< cache => 0 >> always reads the database.
1565 C<< db => 0 >> only looks in the cache, returning the canonical copy as it is,
1566 or undef. Both 0 croaks.
1567  
1568 =back
1569  
1570 =cut
1571  
1572 136 ▶sub refresh_row {
Subroutine refresh_row: called CC=3 SCAR=11.0
Pod documented
1573 136 my $self = shift;
1574 136 my $debug = $self->{+DEBUG};
1575 136 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 1 135 136
Condition100%3/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
13411
MC/DC100%2/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table100%3/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1576 136 $self->_primitive(refresh_row => @_);
1577 }
1578  
1579 =head2 Finding by primary key
1580  
1581 my $user = $orm->find(users => $id);
1582 my $data = $orm->find(users => $id, data => 1); # row data
1583 my $none = $orm->find(users => -1); # undef
1584  
1585 Reads one row by primary key, like C<refresh_row>. It never writes to the
1586 database.
1587  
1588 =over 4
1589  
1590 =item $row = $orm->find($table, $pk, %opts)
1591  
1592 =item \%data = $orm->find($table, $pk, data => 1, %opts)
1593  
1594 The row with primary key C<$pk>, or undef. C<$pk> takes any key form (see
1595 C<find> in L<DBIx::QuickORM::Handle>). The options are C<refresh_row>'s.
1596  
1597 A row object passed in gives its key. It may also show the state the read
1598 found, such as new values or that the row is gone.
1599  
1600 =back
1601  
1602 =cut
1603  
1604 206 ▶sub find {
Subroutine find: called CC=11 SCAR=24.0
Pod documented
1605 206 my $self = shift;
1606 206 my $debug = $self->{+DEBUG};
1607 206 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 16 190 206
Condition66%2/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
190016
MC/DC50%1/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table66%2/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
1608 206 my ($table, $pk, @args) = @_;
1609 206 ▶ $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 203 206
Condition100%3/3
builtin::blessed($pk) and $pk->can("row_data")
!ll&&!rl&&r
19583
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
1610 206 ▶ 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" 57 149 206
Condition100%9/9
ref $pk or @args and not @args == 2 && $args[0] eq "row_class"
l!l&&r!l&&!r
2928149
@args and not @args == 2 && $args[0] eq "row_class"
!ll&&!rl&&r
140928
@args == 2 && $args[0] eq 'row_class'
!ll&&!rl&&r
8209
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
1611  
1612 # A plain key and no options but row_class: what _primitive does, without its argument handling.
1613 149 ▶ my @build = @args ? $self->_row_class_opt({@args}) : ();
Branch: 1 branch
BranchTrueFalseTotal
@args ? : 9 140 149
1614 147 my $out = $self->connection->refresh_row($table, $pk);
1615 140 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 1 139 140
1616 139 return $self->_row($table, $out, @build);
1617 }
1618  
1619 =head2 Finding or inserting
1620  
1621 my $gil = $orm->find_or_insert(
1622 users => {
1623 name => 'Gil',
1624 email => 'gil@example.com',
1625 },
1626 by => ['email'],
1627 );
1628 my $same = $orm->find_or_insert(
1629 users => {email => 'gil@example.com'},
1630 by => ['email'],
1631 );
1632  
1633 =over 4
1634  
1635 =item $row = $orm->find_or_insert($table => \%fields, by => \@fields, raw => $bool)
1636  
1637 =item \%data = $orm->find_or_insert($table => \%fields, data => 1, %opts)
1638  
1639 Returns the row whose C<by> fields hold the given values, inserting it from
1640 C<\%fields> when there is none. It follows the CRUD operations' return rule.
1641  
1642 # no by: matched by the primary key. The row exists, so it is returned
1643 # as it is: name is neither compared nor written.
1644 my $robert = $orm->find_or_insert(
1645 users => {
1646 id => $id,
1647 name => 'Someone',
1648 },
1649 );
1650  
1651 # by email: only email is matched. The other fields are used only when
1652 # inserting, so Gil keeps the name Gil.
1653 my $gil = $orm->find_or_insert(
1654 users => {
1655 email => 'gil@example.com',
1656 name => 'Someone',
1657 },
1658 by => ['email'],
1659 );
1660  
1661 # without raw, values are deflated: prefs goes in as JSON text, and the
1662 # DateTime is matched and inserted as the database's text
1663 my $when = DateTime->new(
1664 year => 2025,
1665 month => 3,
1666 day => 4,
1667 hour => 5,
1668 );
1669 my $kit = $orm->find_or_insert(
1670 users => {
1671 name => 'Kit',
1672 created => $when,
1673 prefs => {theme => 'dark'},
1674 },
1675 by => ['name', 'created'],
1676 );
1677  
1678 # raw => 1: every value, by values included, is sent as given, so each
1679 # must already be database text. This finds Kit.
1680 my $same = $orm->find_or_insert(
1681 users => {
1682 name => 'Kit',
1683 created => '2025-03-04 05:00:00',
1684 prefs => '{"theme":"dark"}',
1685 },
1686 by => ['name', 'created'],
1687 raw => 1,
1688 );
1689  
1690 C<by> defaults to the primary key. A table without one needs C<by>. Every
1691 C<by> field must be in C<\%fields>. Croaks when more than one row matches, or
1692 for a field the table does not have, whether or not the row exists.
1693  
1694 An undef C<by> value croaks: NULL does not identify a row, since a unique key
1695 allows many.
1696  
1697 The insert runs in a savepoint, or in a transaction when none is open, so a
1698 failed insert leaves an open transaction usable. When the insert fails (say
1699 another process inserted the row first), it looks the row up again and returns
1700 it. If it still finds none, it rethrows the insert's error.
1701  
1702 This recovery needs a unique key on the C<by> fields. Without one, two
1703 racing calls can both insert.
1704  
1705 Recovery works at the default C<'read committed'>. Inside a transaction at
1706 C<'repeatable read'> or C<'serializable'> (when chosen, or the MySQL family's
1707 server default under C<'server'>), the second lookup reads the transaction's
1708 snapshot. A row another session committed after this transaction started
1709 stays invisible, so the insert's error is rethrown.
1710  
1711 C<< raw => 1 >> also covers the C<by> values used to look the row up. They
1712 must then be in exact database form, or the lookup misses and the insert fails
1713 on a duplicate key.
1714  
1715 On DuckDB, which has no savepoints, an insert inside an open transaction runs
1716 without one, and a failed insert leaves that transaction unusable.
1717  
1718 A table handle has it too: C<< $h->find_or_insert(\%fields, %opts) >> (see
1719 L<DBIx::QuickORM::Handle>).
1720  
1721 =back
1722  
1723 =cut
1724  
1725 32 ▶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 32 32
1726  
1727 =head2 Rows not in the database
1728  
1729 A row can exist in memory before it is inserted. Change it with C<modify>,
1730 then write it with its C<insert>.
1731  
1732 =over 4
1733  
1734 =item $row = $orm->vivify($table => \%fields)
1735  
1736 =item $row = $orm->vivify($table => \%fields, row_class => $class_or_undef)
1737  
1738 A new row that is not in the database yet. Nothing is written until you call
1739 its C<insert>. Until then, C<modify> changes it (see
1740 L<DBIx::QuickORM::Role::Row>).
1741  
1742 my $ivy = $orm->vivify(users => {name => 'Ivy'});
1743 $ivy->modify({email => 'ivy@example.com'}); # still nothing written
1744 $ivy->insert; # now in the database
1745  
1746 # the row data, not a row object
1747 my $data = $orm->vivify(
1748 users => {name => 'Jo'},
1749 row_class => undef,
1750 );
1751  
1752 The fields are checked and deflated as C<insert> does, into a new hashref. An
1753 empty hashref is fine. Fill it in with C<modify>. The row is built as the
1754 CRUD operations build rows, so with no row class it is the row data.
1755 C<row_class> picks the class for this row, as for the CRUD operations.
1756  
1757 =back
1758  
1759 =cut
1760  
1761 14 ▶sub vivify {
Subroutine vivify: called CC=5 SCAR=16.3
Pod documented
1762 14 my $self = shift;
1763 14 my ($table, $fields, @args) = @_;
1764 14 ▶ 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 14 14
Condition33%1/3
defined $table and ref $fields eq "HASH"
!ll&&!rl&&r
0014
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
1765 14 ▶ croak "Odd number of options to vivify()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 13 14
1766 13 my %opts = @args;
1767 13 my @build = $self->_row_class_opt(\%opts);
1768 13 ▶ croak "Unknown argument(s) to vivify(): " . join(', ' => sort keys %opts) if %opts;
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 12 13
1769  
1770 12 my $data = $self->connection->deflate($table, $fields);
1771 11 DBIx::QuickORM::RowState->mark_vivified($data);
1772 11 return $self->_row($table, $data, @build);
1773 }
1774  
1775 =head2 Following foreign keys
1776  
1777 my $post = $orm->insert(
1778 posts => {
1779 user_id => $id,
1780 title => 'Hi',
1781 },
1782 );
1783  
1784 my $author = $orm->follow_fk(posts => $post, 'users')->only;
1785 my @posts = $orm->follow_fk(users => $author, 'posts')->order_by('id')->all;
1786  
1787 # the same, as a row method: no table needed
1788 my $writer = $post->follow_fk('users')->only;
1789  
1790 =over 4
1791  
1792 =item $h = $orm->follow_fk($table, $row_or_data, $other_table, link => \%link)
1793  
1794 =item $h = $orm->follow_fk($table, $row_or_data, $other_table, via => \%via)
1795  
1796 A table handle (L<DBIx::QuickORM::Handle>) on C<$other_table> for the rows
1797 linked to this row by a foreign key: the row it points to, or the rows that
1798 point to it.
1799  
1800 # users.referred_by points at users.id: link gives the direction
1801  
1802 # the user $ann points to: who referred her
1803 my $referrer = $orm->follow_fk(
1804 users => $ann,
1805 'users',
1806 link => {referred_by => 'id'},
1807 )->only;
1808  
1809 # the users pointing to $ann: whom she referred
1810 my @referred = $orm->follow_fk(
1811 users => $ann,
1812 'users',
1813 link => {id => 'referred_by'},
1814 )->all;
1815  
1816 # audit.user_id declares no key: via gives the mapping
1817 my $who = $orm->follow_fk(
1818 audit => $entry,
1819 'users',
1820 via => {user_id => 'id'},
1821 )->only;
1822  
1823 The handle's C<where> holds the linked fields' values from the row, qualified
1824 as C<other_table.field>, so the handle can be joined to other tables. Narrow
1825 the handle with C<and>, since C<where> would replace the link.
1826  
1827 C<link> is C<< {our_field => their_field, ...} >>, as foreign keys are written
1828 in the map, and gives the direction. On a self-referencing C<employees> table,
1829 C<< {manager_id => 'id'} >> follows to an employee's manager and
1830 C<< {id => 'manager_id'} >> to their reports. It must match a foreign key of
1831 C<$table> to C<$other_table>, or one of C<$other_table> to C<$table> reversed.
1832 Without it there must be exactly one such key.
1833  
1834 C<via> takes the same mapping for a key the map does not know, such as one
1835 the database never declared: C<< via => {editor_id => 'id'} >>. No foreign key
1836 need exist, but both tables must be in the map and every field it names must
1837 exist. To declare the key for every call instead, give C<fks> to C<new>.
1838  
1839 Croaks on a link that matches no key, on more than one key without a C<link>,
1840 on a key to a table not in the map, on a C<via> field that does not exist, and
1841 when given both C<link> and C<via>.
1842  
1843 The handle expects one row (C<single>, see L<DBIx::QuickORM::Iterator>) when
1844 the fields it looks up are the other table's primary key or a unique key.
1845 Otherwise it expects many (C<multi>), whatever the data.
1846  
1847 Linked fields missing from the row data are fetched first, with one
1848 C<refresh_row>. It croaks if the row is gone. A NULL linked value refers to
1849 nothing, so the handle matches no rows.
1850  
1851 =back
1852  
1853 =cut
1854  
1855 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
1856  
1857 =head2 Inserting linked rows
1858  
1859 my $post = $orm->insert_fk(users => $alice, 'posts', {title => 'One'});
1860 my $posts = $orm->insert_many_fk(users => $alice, 'posts', {title => 'A'}, {title => 'B'});
1861  
1862 # the same, as row methods
1863 my $draft = $alice->insert_fk('posts', {title => 'Draft'});
1864  
1865 Inserts rows into C<$other_table> that point at this row, filling their
1866 foreign key fields from it. Only that direction: a key of C<$table> to
1867 C<$other_table> cannot be followed this way, since the new row would have to
1868 be written back into this one.
1869  
1870 =over 4
1871  
1872 =item $row = $orm->insert_fk($table, $row_or_data, $other_table, %opts, \%fields)
1873  
1874 =item \@rows = $orm->insert_many_fk($table, $row_or_data, $other_table, %opts, @fields)
1875  
1876 C<insert_fk> inserts exactly one row and returns it, as C<insert> does.
1877 C<insert_many_fk> inserts any number, as C<insert_many> does: an arrayref of
1878 rows, the count with C<< count => 1 >>, nothing in void context.
1879  
1880 After C<$other_table>, a string is an option name taking the next argument as
1881 its value, and every other hashref is a row's fields:
1882  
1883 $alice->insert_fk('posts', link => {id => 'user_id'}, {title => 'Linked'});
1884  
1885 C<link> chooses the key when more than one of C<$other_table> points at
1886 C<$table>, written C<< {our_field => their_field} >> as C<follow_fk> takes it.
1887 C<via> gives a mapping with no key behind it, as for C<follow_fk>. The new
1888 rows' right-hand fields are filled from this row's left-hand fields.
1889 The other options are those of C<insert> (C<raw>, C<data>, C<as_given>,
1890 C<row_class>) or C<insert_many> (C<raw>, C<data>, C<count>, C<row_class>).
1891  
1892 Croaks, before anything is inserted, when the fields set a link field, when
1893 the row's linked value is NULL, when the row is not in the database, and on a
1894 C<link> that points from C<$table>. A linked field missing from the row data
1895 is fetched first, with one C<refresh_row>. The linked values are sent as they
1896 are in the row data, so a hashref must hold them in database form, as row
1897 data does.
1898  
1899 =back
1900  
1901 =cut
1902  
1903 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
1904 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
1905  
1906 =head2 Handles
1907  
1908 my @bobs = $orm->handle('users')
1909 ->where({name => 'Bob'})
1910 ->order_by('id')
1911 ->all;
1912 my @rows = $orm->handle(\['SELECT id, name FROM users WHERE id > ?', 10])->all;
1913  
1914 L<DBIx::QuickORM::Handle> covers everything a handle does.
1915  
1916 =over 4
1917  
1918 =item $h = $orm->handle($table)
1919  
1920 =item $h = $orm->handle(\$sql)
1921  
1922 =item $h = $orm->handle(\[$sql, @binds])
1923  
1924 =item $h = $orm->handle($source)
1925  
1926 A L<DBIx::QuickORM::Handle> over a table, an SQL query, or a source object
1927 (L<DBIx::QuickORM::Role::Source>).
1928  
1929 # SQL with no binds
1930 my @all = $orm->handle(\'SELECT id, name FROM users')->all;
1931  
1932 # a source object, such as a temporary table
1933 my $temp = $orm->temp_table($orm->handle('posts'));
1934 my @copy = $orm->handle($temp)->all;
1935  
1936 An SQL query runs as written, and its binds are not deflated. Its rows belong
1937 to no table: they are never canonical and cannot be written through the ORM.
1938  
1939 =back
1940  
1941 =cut
1942  
1943 352 ▶sub handle {
Subroutine handle: called CC=9 SCAR=22.1
Pod documented
1944 352 my $self = shift;
1945 352 my ($what) = @_;
1946  
1947 352 my $type = ref($what);
1948 my $source =
1949 blessed($what) && $what->DOES('DBIx::QuickORM::Role::Source') ? $what
1950 : $type eq 'SCALAR' ? DBIx::QuickORM::Source::Query->new(sql => $$what)
1951 352 ▶ : $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') ? : 41 311 352
$type eq 'SCALAR' ? : 12 299 311
$type eq 'REF' && ref $$what eq 'ARRAY' ? : 2 297 299
$type || !defined($what) ? : 1 296 297
$self->db_map->table($what) ? : 287 9 296
Condition66%6/9
builtin::blessed($what) and $what->DOES("DBIx::QuickORM::Role::Source")
!ll&&!rl&&r
311041
$type eq "REF" and ref $$what eq "ARRAY"
!ll&&!rl&&r
29702
$type or not defined $what
l!l&&r!l&&!r
10296
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
1952 : $type || !defined($what) ? croak "handle() takes a table name, \\\$sql, \\[\$sql, \@binds], or a source"
1953 : $self->db_map->table($what) ? $self->_table_source($what)
1954 : croak "The table '$what' is not in the database map" . $self->_absent_note($what);
1955  
1956 342 return DBIx::QuickORM::Handle->new(orm => $self, source => $source);
1957 }
1958  
1959 =head2 Transactions
1960  
1961 L<DBIx::QuickORM::Txn> shows the block and object forms. Nesting gives
1962 savepoints. C<isolation> sets the level and C<retry> replays a block:
1963  
1964 $orm->txn(sub {
1965 $orm->insert(users => {name => 'Outer'});
1966 eval {
1967 $orm->txn(sub {
1968 $orm->insert(users => {name => 'Inner'});
1969 die "undo only the inner work\n";
1970 });
1971 };
1972 }); # Outer is committed, Inner was rolled back with its savepoint
1973  
1974 my $count = $orm->txn(
1975 sub { $orm->handle('users')->count }, # the block's return value
1976 isolation => 'serializable',
1977 retry => 3,
1978 );
1979  
1980 =over 4
1981  
1982 =item $txn = $orm->txn
1983  
1984 =item $txn = $orm->txn(isolation => $level)
1985  
1986 =item @result = $orm->txn(sub { my $txn = shift; ... })
1987  
1988 =item @result = $orm->txn(sub { ... }, retry => $n, isolation => $level)
1989  
1990 Opens a transaction, or a savepoint inside the open one, as a
1991 L<DBIx::QuickORM::Txn>. Given a block, runs it with the transaction and
1992 returns what the block returns.
1993  
1994 # the object form: finish it yourself
1995 my $txn = $orm->txn;
1996 $orm->insert(users => {name => 'Kim'});
1997 $txn->commit; # or $txn->rollback
1998  
1999 # an outermost transaction at another level
2000 my $strict = $orm->txn(isolation => 'serializable');
2001 my $count = $orm->handle('users')->count;
2002 $strict->commit;
2003  
2004 Without a block, commit or roll back through the returned object. Only the
2005 innermost open transaction can be committed or rolled back. One that goes out
2006 of scope unfinished is rolled back with a warning.
2007  
2008 With a block, a normal return commits, unless the block already committed or
2009 rolled back the transaction. An exception rolls back and is rethrown.
2010  
2011 C<< retry => $n >> runs the block of an outermost transaction again, up to
2012 C<$n> more times, while the exception is a database error whose C<retriable>
2013 is true (a deadlock, a serialization failure, or a lock timeout). See
2014 L<DBIx::QuickORM::Exception::DB>. The block must be safe to run again.
2015 C<retry> croaks without a block, and on a nested transaction, which cannot be
2016 replayed alone.
2017  
2018 An outermost transaction opens at the ORM's C<isolation>, or C<'read
2019 committed'> by default. It states that level when it opens, so a changed
2020 server or session default cannot alter it.
2021  
2022 C<'server'> is the exception: it sends a plain C<BEGIN> and uses the
2023 database's own default.
2024  
2025 C<< isolation => $level >> opens an outermost transaction at another level:
2026 C<'read committed'>, C<'repeatable read'>, C<'serializable'>, C<'read
2027 uncommitted'>, or C<'server'>, in any case. Each C<retry> begins at the same
2028 level.
2029  
2030 C<isolation> croaks on a nested transaction and for any other value.
2031  
2032 The ORM's C<isolation> setting takes the same levels, and C<new> croaks for
2033 any other. It is undef unless given, and is stored in lower case.
2034  
2035 SQLite and DuckDB cannot set a level. There the default is C<'server'>, and
2036 any other level croaks when the transaction opens. PostgreSQL runs C<'read
2037 uncommitted'> as C<'read committed'>.
2038 L<DBIx::QuickORM::Manual::Transactions/ISOLATION> has the details.
2039  
2040 Savepoints need a database that has them, so nesting croaks on DuckDB.
2041  
2042 Inside a transaction, C<update_row> and C<delete_row> check that row data is
2043 canonical by default, whatever C<enforce_canon> says. Canonical copies are
2044 held strongly.
2045  
2046 Inside a transaction, rows read before it are not canonical until read again.
2047 A rollback restores the row cache and row state from before. A commit keeps
2048 what the transaction read. After a rollback, refresh a row object you still
2049 hold. See L<DBIx::QuickORM::Manual::Transactions> for the details.
2050  
2051 =back
2052  
2053 =cut
2054  
2055 166 ▶sub txn {
Subroutine txn: called CC=3 SCAR=11.0
Pod documented
2056 166 my $self = shift;
2057 166 my $debug = $self->{+DEBUG};
2058 166 ▶ local $debug->{caller} = [(caller(0))[0 .. 3]] if $debug && !$debug->{caller};
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 2 164 166
Condition66%2/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
16402
MC/DC50%1/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table66%2/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
2059 166 return $self->connection->txn(@_, caller => [caller]);
2060 }
2061  
2062 =head2 Temporary tables and views
2063  
2064 my $t = $orm->temp_table(sub {
2065 my $t = shift;
2066 $t->add_column(
2067 id => {
2068 db_type => 'integer',
2069 primary_key => 1,
2070 },
2071 );
2072 $t->add_column(name => {db_type => 'varchar(50)'});
2073 });
2074 $t->handle->insert({
2075 id => 1,
2076 name => 'Alice',
2077 });
2078  
2079 my $v = $orm->temp_view($orm->handle('posts')->where({views => 0}));
2080 my @names = $orm->temp_tables;
2081 $orm->temp($v->name)->drop;
2082  
2083 Temporary tables and views live in the current connection's map, beside the
2084 scanned tables, until dropped, until the transaction that created them rolls
2085 back, or until the connection ends. L<DBIx::QuickORM::Manual::TempTables> has
2086 the rules on every database.
2087  
2088 =over 4
2089  
2090 =item $temp = $orm->temp_table(sub { my $builder = shift; ... }, name => $name)
2091  
2092 =item $builder = $orm->temp_table(name => $name)
2093  
2094 =item $temp = $orm->temp_table($handle, name => $name, pk => \@fields)
2095  
2096 =item $temp = $orm->temp_table(\[$select_sql, @binds], name => $name, pk => \@fields)
2097  
2098 =item $temp = $orm->temp_table(\$create_sql, name => $name)
2099  
2100 Creates a temporary table and returns its L<DBIx::QuickORM::Source::Table::Temp>, or, with no
2101 block, handle, or SQL, returns a L<DBIx::QuickORM::SchemaBuilder::Table::Temp> builder whose
2102 C<build> creates it. Every option is optional except C<name> with
2103 C<\$create_sql>.
2104  
2105 # no block: a builder, built when you say
2106 my $builder = $orm->temp_table(name => 'staged');
2107 $builder->add_column(
2108 id => {
2109 db_type => 'integer',
2110 primary_key => 1,
2111 },
2112 );
2113 my $staged = $builder->build;
2114  
2115 # from a query's rows
2116 my $busy = $orm->temp_table(
2117 $orm->handle('posts')->where({views => {'>' => 100}}),
2118 pk => ['id'],
2119 );
2120 my $mine = $orm->temp_table(
2121 \['SELECT id, title FROM posts WHERE user_id = ?', $id],
2122 name => 'mine',
2123 pk => ['id'],
2124 );
2125  
2126 # a whole CREATE statement
2127 my $scratch = $orm->temp_table(
2128 \'CREATE TEMPORARY TABLE scratch (k TEXT PRIMARY KEY, v TEXT)',
2129 name => 'scratch',
2130 );
2131  
2132 =over 4
2133  
2134 =item *
2135  
2136 A block describes it through the builder, or the keywords of
2137 L<DBIx::QuickORM::DSL>'s C<:temp>, and the table is built when the block
2138 returns. A block that returns a handle or C<\[$select_sql, @binds]> fills
2139 the table from it, as the builder's C<fill> does (croaking when C<fill> got
2140 something else).
2141  
2142 =item *
2143  
2144 A handle, or a C<SELECT> as C<\[$select_sql, @binds]> (even with no binds),
2145 creates the table from the query's rows (C<CREATE TEMPORARY TABLE ... AS
2146 SELECT>). The database picks the column types and copies no key. C<pk> names
2147 the fields that identify a row, for the ORM only. From a handle, a row class
2148 it set (C<row_class>, C<data_only>, or C<bare>) becomes the table's, and a
2149 background mode croaks (see C<sync> in L<DBIx::QuickORM::Handle>).
2150  
2151 =item *
2152  
2153 C<\$create_sql> is a complete C<CREATE TEMPORARY TABLE> statement, and
2154 C<name> must be the name it creates.
2155  
2156 =back
2157  
2158 Without a C<name>, one is made up: C<qorm_tmp_> with a counter and random
2159 hex. A given name croaks when it is already in the map, or was dropped in a
2160 transaction still open.
2161  
2162 =item $temp = $orm->temp_view(\$select_sql, name => $name, pk => \@fields)
2163  
2164 =item $temp = $orm->temp_view(\[$select_sql, @binds], name => $name, pk => \@fields)
2165  
2166 =item $temp = $orm->temp_view($handle, name => $name, pk => \@fields)
2167  
2168 Creates a temporary view over the SQL or the handle's query and returns its
2169 L<DBIx::QuickORM::Source::Table::Temp>.
2170  
2171 my $popular = $orm->temp_view(
2172 \['SELECT id, title FROM posts WHERE views > ?', 100],
2173 name => 'popular',
2174 pk => ['id'],
2175 );
2176  
2177 # no binds
2178 my $untitled = $orm->temp_view(\"SELECT id FROM posts WHERE title = ''");
2179  
2180 C<name> is made up when not given, and a handle's row
2181 class and background mode are treated as by C<temp_table>. A view cannot hold
2182 placeholders, so every bind is written into the view as a literal: the view
2183 keeps the values it was created with. C<pk> is optional, as in C<pks>.
2184  
2185 Croaks on MySQL and MariaDB, which have no temporary views.
2186  
2187 =item @names = $orm->temp_tables
2188  
2189 The current connection's temporary tables and views, sorted.
2190  
2191 =item $temp = $orm->temp($name)
2192  
2193 A L<DBIx::QuickORM::Source::Table::Temp> for one of them. Croaks for any other name.
2194  
2195 =back
2196  
2197 =cut
2198  
2199 258 my $TEMP_COUNT = 0;
2200  
2201 53 ▶sub temp_table { my $self = shift; $self->_temp_table(0, @_) }
Subroutine temp_table: called CC=1 SCAR=0.0
Pod documented
2202 9 ▶sub temp_view { my $self = shift; $self->_temp_view(0, @_) }
Subroutine temp_view: called CC=1 SCAR=0.0
Pod documented
2203  
2204 4 ▶sub temp_tables { $_[0]->connection->temp_names }
Subroutine temp_tables: called CC=1 SCAR=0.0
Pod documented
2205  
2206 2 ▶sub temp {
Subroutine temp: called CC=2 SCAR=6.9
Pod documented
2207 2 my $self = shift;
2208 2 my ($name) = @_;
2209 2 my $conn = $self->connection;
2210 2 ▶ my $kind = $conn->temp_kind($name) or croak "'$name' is not a temporary table or view of the current connection" . $conn->_gone_note($name);
Branch: 1 branch
BranchTrueFalseTotal
my $kind = $conn->temp_kind($name) or croak("'${name}' is not a temporary table or view of the current connection" . $conn->_gone_note($name)) 1 1 2
2211 1 return DBIx::QuickORM::Source::Table::Temp->new(orm => $self, table => $name, db_map => $conn->db_map, kind => $kind, connection => $conn);
2212 }
2213  
2214 =head2 Loading classes
2215  
2216 =over 4
2217  
2218 =item $bool = DBIx::QuickORM->load_class($what, $class)
2219  
2220 =item $bool = DBIx::QuickORM->load_class($what, $class, $missing_ok)
2221  
2222 Loads a class from its module file and returns true. Croaks "$what could not
2223 be loaded" with the error when it cannot.
2224  
2225 # 1, or croaks "The JSON type could not be loaded: ..."
2226 my $ok = DBIx::QuickORM->load_class('The JSON type', 'DBIx::QuickORM::Type::JSON');
2227  
2228 # 0 when the module is not installed
2229 my $have = DBIx::QuickORM->load_class('My plugin', 'My::Optional::Plugin', 1);
2230  
2231 With C<$missing_ok>, a missing module file returns false instead. An error
2232 inside the file still croaks.
2233  
2234 =back
2235  
2236 =cut
2237  
2238 303 ▶sub load_class {
Subroutine load_class: called CC=4 SCAR=13.9
Pod documented
2239 303 my $self = shift;
2240 303 my ($what, $class, $missing_ok) = @_;
2241  
2242 303 (my $file = "$class.pm") =~ s{::}{/}g;
2243 303 ▶ return 1 if eval { require $file; 1 };
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { require $file; 1 } } 258 45 303
2244 45 ▶ 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/ 21 24 45
Condition100%3/3
$missing_ok and $@ =~ /^Can't locate \Q$file\E in \@INC/
!ll&&!rl&&r
21321
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
2245 24 croak "$what could not be loaded: $@";
2246 }
2247  
2248 =pod
2249  
2250 =over 4
2251  
2252 =item $class = $orm->require_type($type)
2253  
2254 =item $class = $orm->require_type($type, $context)
2255  
2256 Returns the full class name for a type name (C<JSON>, or C<+My::Type> for a
2257 class outside C<DBIx::QuickORM::Type>), loading it unless it already has
2258 C<deflate>.
2259  
2260 my $json = $orm->require_type('JSON'); # 'DBIx::QuickORM::Type::JSON'
2261  
2262 # 'My::Type::Trimmed', or croaks "'my config' names the type ..."
2263 my $class = $orm->require_type('+My::Type::Trimmed', 'my config');
2264  
2265 Croaks when it cannot be loaded. C<$context>, when given, says in that error
2266 what asked for the type.
2267  
2268 =back
2269  
2270 =cut
2271  
2272 1479 ▶sub require_type {
Subroutine require_type: called CC=3 SCAR=11.0
Pod documented
2273 1479 my $self = shift;
2274 1479 my ($type, $context) = @_;
2275  
2276 1479 my $class = $self->_type_class($type);
2277 1477 ▶ return $class if $class->can('deflate');
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("deflate") 1256 221 1477
2278  
2279 221 ▶ $self->load_class(defined($context) ? "'$context' names the type '$type', which" : "The type '$type'", $class);
Branch: 1 branch
BranchTrueFalseTotal
defined $context ? : 219 2 221
2280 213 return $class;
2281 }
2282  
2283 =pod
2284  
2285 =over 4
2286  
2287 =item $orm->load_row_class($class)
2288  
2289 Loads a row class unless it already has a C<new>. Croaks when the name is not
2290 a valid package name or the class cannot be loaded.
2291  
2292 =back
2293  
2294 =cut
2295  
2296 336 ▶sub load_row_class {
Subroutine load_row_class: called CC=3 SCAR=11.0
Pod documented
2297 336 my $self = shift;
2298 336 my ($class) = @_;
2299  
2300 336 ▶ 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 332 336
2301 332 ▶ $self->load_class("The row class '$class'", $class) unless $class->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("new") 9 323 332
2302 }
2303  
2304 =head1 ATTRIBUTES
2305  
2306 Read-only accessors. Each returns the constructor argument of the same name,
2307 or its default. C<connector>, C<sql_builder>, and C<where_builders> hold what
2308 C<new> built from it.
2309  
2310 =over 4
2311  
2312 =item $class = $orm->row_class
2313  
2314 The default row class, C<DBIx::QuickORM::Row> unless given. Undef means plain
2315 hashrefs.
2316  
2317 =item \%classes = $orm->row_classes
2318  
2319 =item $namespace = $orm->row_namespace
2320  
2321 =item $code = $orm->row_class_name
2322  
2323 =item \%omit = $orm->omit
2324  
2325 =item \%fields = $orm->default_fields
2326  
2327 =item \%types = $orm->types
2328  
2329 =item \%options = $orm->type_options
2330  
2331 =item \@types = $orm->autotype
2332  
2333 =item \@types = $orm->append_autotype
2334  
2335 =item \%auto_omit = $orm->auto_omit
2336  
2337 =item \%fks = $orm->fks
2338  
2339 The arguments as given to C<new>, or undef. See C<new> for what each does.
2340 C<db_map> holds the result. C<autotype> is undef unless given, even though a
2341 default list applies.
2342  
2343 =item $builder = $orm->sql_builder
2344  
2345 The SQL builder that handles use. Default:
2346 L<DBIx::QuickORM::SQLBuilder::SQLAbstract>.
2347  
2348 C<new> takes an object composing L<DBIx::QuickORM::Role::SQLBuilder>, or the
2349 name of a class that does. A class is loaded unless it has C<new>, then built
2350 with no arguments. Anything else croaks.
2351  
2352 my $orm = DBIx::QuickORM->new(
2353 credentials => \%credentials,
2354 sql_builder => 'My::SQLBuilder', # or My::SQLBuilder->new(...)
2355 );
2356  
2357 =item \@builders = $orm->where_builders
2358  
2359 The where builders that render a handle's C<where>. The first that can build
2360 it wins (see L<DBIx::QuickORM::Role::WhereBuilder>).
2361  
2362 Default: L<DBIx::QuickORM::WhereBuilder::RawSQL>,
2363 L<DBIx::QuickORM::WhereBuilder::Simple>, then
2364 L<DBIx::QuickORM::WhereBuilder::SQLAbstract>.
2365  
2366 C<new> takes a non-empty arrayref of classes or objects composing the role. A
2367 class is loaded unless it has C<build_where>. Anything else croaks. A handle
2368 can use its own list through its C<where_builders>.
2369  
2370 # SQL::Abstract conditions only
2371 my $orm = DBIx::QuickORM->new(
2372 credentials => \%credentials,
2373 where_builders => ['DBIx::QuickORM::WhereBuilder::SQLAbstract'],
2374 );
2375  
2376 =item $code = $orm->connector
2377  
2378 The code reference the ORM calls to open a database handle, built from the
2379 connection argument.
2380  
2381 =item \@names = $orm->like_aggregates
2382  
2383 Extra aggregate functions whose result keeps the field's type and foreign
2384 keys, like the built-in C<min> and C<max>. Undef unless given.
2385  
2386 A computed column C<[$func, $field]> using one of them gets the field's type
2387 and foreign keys (see L<DBIx::QuickORM::Handle/Computed columns>). Names are
2388 matched case-insensitively.
2389  
2390 my $orm = DBIx::QuickORM->new(
2391 credentials => \%credentials,
2392 like_aggregates => ['any_value'], # PostgreSQL 16 and later
2393 );
2394  
2395 my ($group) = $orm->handle('users')
2396 ->group_by('name')
2397 ->fields({
2398 name => 'name',
2399 joined => [any_value => 'created'],
2400 })
2401 ->all;
2402  
2403 # a lazy DateTime (DBIx::QuickORM::Type::DateTime::Lazy), as created gives
2404 my $year = $group->field('joined')->datetime_ref->year;
2405  
2406 =back
2407  
2408 =head1 PRIVATE METHODS
2409  
2410 =over 4
2411  
2412 =item $out = $orm->_primitive($method, $table, $row_or_data, @args)
2413  
2414 Runs the Connection's CRUD operation and returns its result by the rule the
2415 CRUD operations share. In void context it returns nothing. Given a row object
2416 for C<update_row> or C<refresh_row>, it returns that row after C<set_row_data>
2417 (which runs in void context too). With C<< data => 1 >> it returns the row
2418 data. Otherwise it returns a new row built by C<_row>, with the C<row_class>
2419 option when given (see C<_row_class_opt>). Handles pass their C<row_class>
2420 that way, before the caller's options.
2421  
2422 An undef result is undef, and the row is left alone.
2423  
2424 An arrayref result (C<insert_many>) comes back as an arrayref, of rows or of
2425 row data. A plain result (C<insert_many>'s C<count>) comes back as it is.
2426  
2427 Croaks before running the CRUD operation when a row object given to
2428 C<update_row> or C<refresh_row> cannot take new data: it has no
2429 C<set_row_data>, or it is an aggregate row.
2430  
2431 =back
2432  
2433 =cut
2434  
2435 258 my %TAKES_ROW = (update_row => 1, refresh_row => 1);
2436  
2437 799 ▶sub _primitive {
Subroutine _primitive: called CC=22 SCAR=30.9
2438 799 my $self = shift;
2439 799 my ($method, $table, $arg, @args) = @_;
2440  
2441 799 ▶ my @changes = $method eq 'update_row' ? (shift @args) : ();
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'update_row' ? : 170 629 799
2442 799 ▶ croak "Odd number of options to $method()" if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 798 799
2443 798 my %opts = @args;
2444 798 ▶ 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 787 798
2445 798 ▶ delete $opts{row_class} if $data; # data wins
Branch: 1 branch
BranchTrueFalseTotal
if $data 51 747 798
2446 798 my @build = $self->_row_class_opt(\%opts);
2447 798 my $void = !defined wantarray;
2448 798 ▶ $opts{void} = 1 if $void && !$TAKES_ROW{$method};
Branch: 1 branch
BranchTrueFalseTotal
if $void and not $TAKES_ROW{$method} 218 580 798
Condition100%3/3
$void and not $TAKES_ROW{$method}
!ll&&!rl&&r
48199218
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
2449  
2450 798 ▶ 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') ? : 125 673 798
Condition100%6/6
$TAKES_ROW{$method} and builtin::blessed($arg) and $arg->can("row_data")
!ll&&!rl&&r
6658125
$TAKES_ROW{$method} and builtin::blessed($arg)
!ll&&!rl&&r
433232133
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
2451 798 ▶ 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 792 798
Condition100%6/6
$row and !$row->can("set_row_data") || $row->isa("DBIx::QuickORM::AggregateRow")
!ll&&!rl&&r
6731196
not $row->can("set_row_data") or $row->isa("DBIx::QuickORM::AggregateRow")
l!l&&r!l&&!r
33119
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
2452 if $row && (!$row->can('set_row_data') || $row->isa('DBIx::QuickORM::AggregateRow'));
2453  
2454 792 my $out = $self->connection->$method($table, $arg, @changes, %opts);
2455 696 ▶ $row->set_row_data($out) if $row && $out;
Branch: 1 branch
BranchTrueFalseTotal
if $row and $out 89 607 696
Condition100%3/3
$row and $out
!ll&&!rl&&r
5941389
MC/DC100%2/2
$row and $out
$row $out
Truth table100%3/3
A and B
A= $rowB= $out
ABresult
0X0
100
111
2456  
2457 696 ▶ return if $void;
Branch: 1 branch
BranchTrueFalseTotal
if $void 226 470 696
2458 470 ▶ return $out unless ref $out;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $out 50 420 470
2459  
2460 420 ▶ if (ref($out) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $out eq "ARRAY") 24 396 420
2461 24 ▶ return $out if $data;
Branch: 1 branch
BranchTrueFalseTotal
if $data 1 23 24
2462 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
2463 12 return [map { $build->($_) } @$out];
2464 }
2465  
2466 396 ▶ return $data ? $out : $row || $self->_row($table, $out, @build);
Branch: 1 branch
BranchTrueFalseTotal
$data ? : 41 355 396
Condition66%2/3
$row or $self->_row($table, $out, @build)
l!l&&r!l&&!r
612940
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
2467 }
2468  
2469 =pod
2470  
2471 =over 4
2472  
2473 =item $out = $orm->_find_or_insert(\@frame, $table, \%fields, %opts)
2474  
2475 C<find_or_insert>, reporting its errors at C<@frame>, the public method's
2476 C<caller(0)> frame, which its reads and insert also run under in the Debug
2477 object's C<caller> slot. Handles pass their C<row_class> as the option of that
2478 name, before the caller's options.
2479  
2480 =back
2481  
2482 =cut
2483  
2484 258 my %FIND_OR_INSERT_ARGS = map { $_ => 1 } qw/by data raw row_class/;
2485  
2486 40 ▶sub _find_or_insert {
Subroutine _find_or_insert: called CC=20 SCAR=30.1
2487 40 my $self = shift;
2488 40 my ($frame, $table, $fields, @args) = @_;
2489 40 ▶ _croak_at($frame, "Odd number of options to find_or_insert()") if @args % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 39 40
2490 39 my %opts = @args;
2491  
2492 39 my @unknown = sort grep { !$FIND_OR_INSERT_ARGS{$_} } keys %opts;
2493 39 ▶ _croak_at($frame, "Unknown argument(s) to find_or_insert(): " . join(', ' => @unknown)) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 38 39
2494 38 ▶ _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 38 38
2495 38 ▶ delete $opts{row_class} if $opts{data}; # data wins
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"data"} 2 36 38
2496 38 my @build = $self->_row_class_opt(\%opts);
2497  
2498 38 ▶ 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
3710
$opts{"by"} // $self->db_map->pk($table)
l!l&&r!l&&!r
23141
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
2499 37 ▶ _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 35 37
Condition100%3/3
ref $by eq "ARRAY" and @$by
!ll&&!rl&&r
1135
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
2500 35 my @missing = grep { !exists $fields->{$_} } @$by;
2501 35 ▶ _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 34 35
2502  
2503 34 my $conn = $self->connection;
2504 34 my $debug = $self->{+DEBUG};
2505 34 ▶ local $debug->{caller} = $frame if $debug && !$debug->{caller}; # the reads and the insert below can replace row data
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 0 34 34
Condition33%1/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
3400
MC/DC0%0/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table33%1/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
2506 34 $conn->_check_fields($table, sort keys %$fields);
2507 32 my $where = $conn->deflate($table, {map { $_ => $fields->{$_} } @$by}, raw => $opts{raw});
2508 32 my @undef = grep { !defined $where->{$_} } @$by;
2509 32 ▶ _croak_at($frame, "find_or_insert() cannot find by an undef value: (" . join(', ' => @undef) . ")") if @undef;
Branch: 1 branch
BranchTrueFalseTotal
if @undef 2 30 32
2510  
2511 30 my $h = $self->handle($table)->data_only->where($where)->limit(2);
2512 35 ▶ my $find = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2513 35 $h->clear; # a retry after a failed insert must query again
2514 35 my @found = $h->all;
2515 35 ▶ _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 34 35
2516 34 return $found[0];
2517 30 };
2518  
2519 30 my $data = $find->();
2520 29 ▶ unless ($data) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($data) 15 14 29
2521 15 ▶ my $insert = sub { $self->insert($table => $fields, data => 1, raw => $opts{raw}) };
Subroutine __ANON__: called CC=1 SCAR=0.0
2522 15 ▶ my $bare = @{$conn->txns} && !$conn->dialect->supports_savepoints;
Condition66%2/3
@{$conn->txns;} && !$conn->dialect->supports_savepoints
!ll&&!rl&&r
1140
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
2523 15 ▶ unless (eval { $data = $bare ? $insert->() : $self->txn($insert); 1 }) {
Branch: 2 branches
BranchTrueFalseTotal
unless (eval { do { $data = $bare ? &$insert() : $self->txn($insert); 1 } }) 5 10 15
$bare ? : 0 15 15
2524 5 my $err = $@;
2525 5 ▶ $data = eval { $find->() } or die $err;
Branch: 1 branch
BranchTrueFalseTotal
$data = eval { do { &$find() } } or die $err 2 3 5
2526 }
2527 }
2528  
2529 26 ▶ return unless defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 0 26 26
2530 26 ▶ return $opts{data} ? $data : $self->_row($table, $data, @build);
Branch: 1 branch
BranchTrueFalseTotal
$opts{'data'} ? : 2 24 26
2531 }
2532  
2533 =pod
2534  
2535 =over 4
2536  
2537 =item $row = $orm->_row($table, \%data, %opts)
2538  
2539 The row data, or a row object over it when the table has a row class. Undef
2540 for undef. A C<row_class> option, when present (even undef), replaces the
2541 table's class. Handles and the C<row_class> CRUD option pass it this way.
2542 Built by C<_row_builder>.
2543  
2544 =back
2545  
2546 =cut
2547  
2548 469 ▶sub _row {
Subroutine _row: called CC=3 SCAR=11.0
2549 469 my $self = shift;
2550 469 my ($table, $data, %opts) = @_;
2551 469 ▶ return undef unless $data;
Branch: 1 branch
BranchTrueFalseTotal
unless $data 13 456 469
2552  
2553 456 ▶ my $build = $self->_row_builder($table, %opts) or return $data;
Branch: 1 branch
BranchTrueFalseTotal
my $build = $self->_row_builder($table, %opts) or return $data 221 235 456
2554 221 return $build->($data);
2555 }
2556  
2557 =pod
2558  
2559 =over 4
2560  
2561 =item $build = $orm->_row_builder($table, %opts)
2562  
2563 What turns row data into rows of the table, resolved once for a whole result
2564 set: a code reference taking the row data and returning the row object, or
2565 undef when rows are hashrefs (no row class). The C<row_class> option is as for
2566 C<_row>.
2567  
2568 Every place that builds table rows uses it. When the class's C<fast_bless> is
2569 true the row is blessed directly, otherwise built with C<new>. The ORM asks
2570 each class for C<fast_bless> once and remembers the answer.
2571  
2572 =back
2573  
2574 =cut
2575  
2576 782 ▶sub _row_builder {
Subroutine _row_builder: called CC=7 SCAR=19.5
2577 782 my $self = shift;
2578 782 my ($table, %opts) = @_;
2579  
2580 782 ▶ my $class = exists $opts{row_class} ? $opts{row_class} : $self->_row_class($table);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'row_class'} ? : 100 682 782
2581 782 ▶ return undef unless defined $class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class 410 372 782
2582  
2583 372 ▶ 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 ? : 70 15 85
Condition100%5/5
$self->{"fast_bless"}{$class} //= $class->can("fast_bless") && $class->fast_bless ? 1 : 0
l!l
28785
$class->can("fast_bless") and $class->fast_bless
!ll&&!rl&&r
51070
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
2584 427 ▶ return sub { bless({orm => $self, table => $table, row_data => $_[0]}, $class) }
Subroutine __ANON__: called CC=1 SCAR=0.0
2585 372 ▶ if $fast;
Branch: 1 branch
BranchTrueFalseTotal
if $fast 355 17 372
2586 17 ▶ return sub { $class->new(row_data => $_[0], orm => $self, table => $table) };
Subroutine __ANON__: called CC=1 SCAR=0.0
2587 }
2588  
2589 =pod
2590  
2591 =over 4
2592  
2593 =item @args = $orm->_row_class_opt(\%opts)
2594  
2595 Takes the C<row_class> option out of a CRUD call's options and returns it as
2596 named arguments for C<_row> and C<_row_builder>: C<< (row_class => $class) >>
2597 when present (undef for row data), or an empty list when absent. Loads a class
2598 that is not loaded yet. Croaks for a reference.
2599  
2600 =back
2601  
2602 =cut
2603  
2604 858 ▶sub _row_class_opt {
Subroutine _row_class_opt: called CC=4 SCAR=13.9
2605 858 my $self = shift;
2606 858 my ($opts) = @_;
2607 858 ▶ return () unless exists $opts->{row_class};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts->{"row_class"} 830 28 858
2608  
2609 28 my $class = delete $opts->{row_class};
2610 28 ▶ croak "'row_class' must be a class name or undef" if ref $class;
Branch: 1 branch
BranchTrueFalseTotal
if ref $class 1 27 28
2611 27 ▶ $self->load_row_class($class) if defined $class;
Branch: 1 branch
BranchTrueFalseTotal
if defined $class 18 9 27
2612 26 return (row_class => $class);
2613 }
2614  
2615 =pod
2616  
2617 =over 4
2618  
2619 =item $class = $orm->_row_class($table)
2620  
2621 The table's row class: its C<row_class> in the map when set (even to undef),
2622 otherwise the ORM's, which is also the class for an undef table.
2623  
2624 =back
2625  
2626 =cut
2627  
2628 727 ▶sub _row_class {
Subroutine _row_class: called CC=4 SCAR=13.9
2629 727 my $self = shift;
2630 727 my ($table) = @_;
2631 727 ▶ my $t = defined($table) ? $self->db_map->table($table) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $table ? : 715 12 727
2632 727 ▶ return $t->{row_class} if $t && exists $t->{row_class};
Branch: 1 branch
BranchTrueFalseTotal
if $t and exists $t->{"row_class"} 22 705 727
Condition100%3/3
$t and exists $t->{"row_class"}
!ll&&!rl&&r
1269322
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
2633 705 return $self->{+ROW_CLASS};
2634 }
2635  
2636 2265 ▶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] 2241 24 2265
Condition100%3/3
defined $_[0] and not ref $_[0]
!ll&&!rl&&r
2222241
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
2637 295 ▶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]) 117 178 295
2638 107 ▶my $STR_LIST = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2639 107 ▶ ref($_[0]) eq 'ARRAY' && !grep { !$STR->($_) } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and not grep({not &$STR($_);} @{$_[0];}) 103 4 107
2640 258 };
2641 1383 ▶my $HASH_OF = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2642 1383 my ($check) = @_;
2643 726 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2644 726 ▶ ref($_[0]) eq 'HASH' && !grep { !$check->($_) } values %{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "HASH" and not grep({not &$check($_);} values %{$_[0];}) 724 2 726
2645 1383 };
2646 258 };
2647 27 ▶my $LINK = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
2648 27 ▶ 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];}) 26 1 27
Condition66%2/3
ref $_[0] eq "HASH" and %{$_[0];}
!ll&&!rl&&r
0126
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
2649 258 };
2650  
2651 my %SHAPES = (
2652 row_class => ['a class name or undef', $OPT_STR],
2653 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
2654 3 ▶ row_class_name => ['a code reference', sub { ref($_[0]) eq 'CODE' }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2655 14 ▶ retain_cache => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2656 5 ▶ enforce_canon => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2657 4 ▶ debug => ['a boolean', sub { !ref($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2658 10 ▶ lookup => ['a lookup table class 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
2659 time_zone => ['a time zone name', $STR],
2660  
2661 auto_omit => [
2662 'undef, or a hashref of types => [type names] and db_types => [type names]',
2663 12 ▶ sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
2664 12 ▶ !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 12 12
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
0102
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
2010
ref $_[0] eq "HASH" and not grep({not /^(?:types|db_types)\z/;} keys %{$_[0];})
!ll&&!rl&&r
1110
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
2665 }
2666 ],
2667  
2668 like_aggregates => [
2669 'an arrayref of function names',
2670 3 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
2671 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
2672 }
2673 ],
2674  
2675 14 ▶ elective => ['an arrayref of table names', sub { $STR_LIST->($_[0]) }],
Subroutine __ANON__: called CC=1 SCAR=0.0
2676  
2677 where_builders => [
2678 'a non-empty arrayref of where builders: classes or objects',
2679 475 ▶ sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
2680 475 ▶ 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];}) 472 3 475
Condition88%8/9
ref $_[0] eq "ARRAY" and @{$_[0];}
!ll&&!rl&&r
12472
builtin::blessed($_) || &$STR($_) && /^\w+(?:::\w+)*\z/
l!l&&r!l&&!r
213871
&$STR($_) and /^\w+(?:::\w+)*\z/
!ll&&!rl&&r
101387
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
2681 }
2682 258 ],
2683 );
2684  
2685 258 %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 pks sql_builder _build_schema _offline/;
2686  
2687 =pod
2688  
2689 =over 4
2690  
2691 =item $orm->_check_args
2692  
2693 Turns C<tz> into C<time_zone>, then croaks naming the first argument in
2694 C<%SHAPES> whose shape is wrong. The Connection checks C<datetime_parsers>.
2695  
2696 =back
2697  
2698 =cut
2699  
2700 498 ▶sub _check_args {
Subroutine _check_args: called CC=6 SCAR=17.9
2701 498 my $self = shift;
2702  
2703 498 ▶ if (exists $self->{tz}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"tz"}) 7 491 498
2704 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
2705 5 $self->{time_zone} = delete $self->{tz};
2706 }
2707  
2708 496 for my $arg (sort keys %SHAPES) {
2709 5880 ▶ next unless exists $self->{$arg};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{$arg} 5641 239 5880
2710 239 my ($want, $check) = @{$SHAPES{$arg}};
2711 239 ▶ croak "'$arg' must be $want" unless $check->($self->{$arg});
Branch: 1 branch
BranchTrueFalseTotal
unless &$check($self->{$arg}) 16 223 239
2712 }
2713 }
2714  
2715 =pod
2716  
2717 =over 4
2718  
2719 =item _croak_at(\@frame, $message)
2720  
2721 Dies with the message at the frame's file and line, worded as C<croak> words
2722 it. C<@frame> is a C<caller> frame that a public method captured, so an error
2723 found deeper, reached through a handle or a row, reports the user's line.
2724  
2725 =item _rethrow_at(\@frame, $what, $error)
2726  
2727 Rethrows an error caught at a public entry, with the frame's file and line
2728 appended: C<< (from $what at FILE line N) >>. The error keeps its own location,
2729 so a bug report still shows where it was thrown. Exception objects are
2730 rethrown unchanged, and so is a message that already ends at the frame's line.
2731  
2732 Use it where one public call reaches many errors in other modules, such as
2733 C<new>. C<_croak_at> suits a chain with a few known errors.
2734  
2735 =back
2736  
2737 =cut
2738  
2739 44 ▶sub _croak_at {
Subroutine _croak_at: called CC=1 SCAR=0.0
2740 44 my ($frame, $msg) = @_;
2741 44 die "$msg at $frame->[1] line $frame->[2].\n";
2742 }
2743  
2744 169 ▶sub _rethrow_at {
Subroutine _rethrow_at: called CC=3 SCAR=11.0
2745 169 my ($frame, $what, $err) = @_;
2746  
2747 169 ▶ die $err if ref $err;
Branch: 1 branch
BranchTrueFalseTotal
if ref $err 1 168 169
2748  
2749 168 my $at = " at $frame->[1] line $frame->[2].\n";
2750 168 ▶ die $err if substr($err, -length($at)) eq $at;
Branch: 1 branch
BranchTrueFalseTotal
if substr($err, -length($at)) eq $at 114 54 168
2751  
2752 54 chomp($err);
2753 54 die "$err\n (from $what at $frame->[1] line $frame->[2])\n";
2754 }
2755  
2756 =pod
2757  
2758 =over 4
2759  
2760 =item $h = $orm->_follow_fk(\@frame, $table, $row_or_data, $other_table, %params)
2761  
2762 C<follow_fk>, reporting its errors at C<@frame>: the C<caller(0)> frame of the
2763 public C<follow_fk> (the ORM's or a row's). When the row lacks link fields,
2764 the read of them runs under C<@frame> in the Debug object's C<caller> slot.
2765  
2766 =back
2767  
2768 =cut
2769  
2770 258 my %FOLLOW_ARGS = (link => 1, via => 1);
2771  
2772 46 ▶sub _follow_fk {
Subroutine _follow_fk: called CC=13 SCAR=26.3
2773 46 my $self = shift;
2774 46 my ($frame, $table, $data, $other, %params) = @_;
2775  
2776 46 my @unknown = sort grep { !$FOLLOW_ARGS{$_} } keys %params;
2777 46 ▶ _croak_at($frame, "Unknown argument(s) to follow_fk(): " . join(', ' => @unknown)) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 45 46
2778  
2779 45 my $conn = $self->connection;
2780 45 my $map = $conn->db_map;
2781 45 ▶ _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 45 45
Condition33%1/3
defined $table and $map->table($table)
!ll&&!rl&&r
0045
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
2782 45 ▶ _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 45 45
Condition33%1/3
defined $other and length $other
!ll&&!rl&&r
0045
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
2783  
2784 45 my $link = $self->_link_for($frame, $map, $table, $other, \%params);
2785 31 ▶ $data = $data->row_data if blessed($data) && $data->can('row_data');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($data) and $data->can("row_data") 22 9 31
Condition66%2/3
builtin::blessed($data) and $data->can("row_data")
!ll&&!rl&&r
9022
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
2786 31 ▶ _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 30 31
2787 30 ▶ if (my @missing = grep { !exists $data->{$_} } sort keys %$link) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@missing) = grep({not exists $data->{$_};} sort(keys %$link))) 5 25 30
2788 5 my $debug = $self->{+DEBUG};
2789 5 ▶ local $debug->{caller} = $frame if $debug && !$debug->{caller}; # the read can replace the row's canonical copy
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 1 4 5
Condition66%2/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
401
MC/DC50%1/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table66%2/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
2790 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
2791 }
2792  
2793 29 return $self->_fk_handle($other, {map { ($link->{$_} => $data->{$_}) } keys %$link});
2794 }
2795  
2796 =pod
2797  
2798 =over 4
2799  
2800 =item $out = $orm->_insert_fk(\@frame, $method, $table, $row_or_data, $other_table, @args)
2801  
2802 C<insert_fk> (C<$method> C<insert>) or C<insert_many_fk> (C<insert_many>),
2803 reporting its errors at C<@frame>: the C<caller(0)> frame of the public method
2804 (the ORM's or a row's), which its reads and inserts also run under in the
2805 Debug object's C<caller> slot.
2806  
2807 =back
2808  
2809 =cut
2810  
2811 my %INSERT_FK_ARGS = (
2812 1548 insert => {map { $_ => 1 } qw/link via raw data as_given row_class/},
2813 258 insert_many => {map { $_ => 1 } qw/link via raw data count row_class/},
2814 );
2815  
2816 32 ▶sub _insert_fk {
Subroutine _insert_fk: called CC=26 SCAR=33.3
2817 32 my $self = shift;
2818 32 my ($frame, $method, $table, $data, $other, @args) = @_;
2819 32 my $name = "${method}_fk";
2820  
2821 32 my (%opts, @rows);
2822 32 ▶ while (@args) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args) 49 27 76
2823 49 my $arg = shift @args;
2824 49 ▶ if (ref($arg) eq 'HASH') { push @rows => $arg; next }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg eq "HASH") 31 18 49
2825 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
Condition60%3/5
ref $arg or not defined $arg
l!l&&r!l&&!r
1017
$arg // "undef"
l!l
10
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
2826 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
2827 14 ▶ _croak_at($frame, "The option '$arg' to $name() has no value") unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 13 14
2828 13 $opts{$arg} = shift @args;
2829 }
2830 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
2831  
2832 25 my $conn = $self->connection;
2833 25 my $map = $conn->db_map;
2834 25 my $debug = $self->{+DEBUG};
2835 25 ▶ local $debug->{caller} = $frame if $debug && !$debug->{caller}; # the reads and the inserts below can replace row data
Branch: 1 branch
BranchTrueFalseTotal
if $debug and not $debug->{"caller"} 0 25 25
Condition33%1/3
$debug and not $debug->{"caller"}
!ll&&!rl&&r
2500
MC/DC0%0/2
$debug and not $debug->{"caller"}
$debug not $debug->{"caller"}
Truth table33%1/3
A and not(B)
A= $debugB= not $debug->{"caller"}
ABresult
0X0
100
111
2836 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
2837 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
2838 25 my $link = $self->_link_for($frame, $map, $table, $other, {map { ($_ => delete $opts{$_}) } grep { exists $opts{$_} } qw/link via/}, $name);
2839  
2840 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
2841 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
2842 21 ▶ _croak_at($frame, "Cannot insert rows linked to a '$table' row that is not in the database") if DBIx::QuickORM::RowState->state($data);
Branch: 1 branch
BranchTrueFalseTotal
if "DBIx::QuickORM::RowState"->state($data) 2 19 21
2843 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
2844 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
2845 }
2846 19 my %values = map { ($link->{$_} => $data->{$_}) } keys %$link;
2847 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
2848 1 _croak_at($frame, "Cannot insert rows linked to a '$table' row whose linked value is NULL (" . join(', ' => @null) . ")");
2849 }
2850 18 for my $row (@rows) {
2851 21 my @set = sort grep { exists $row->{$_} } keys %values;
2852 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
2853 }
2854  
2855 16 my %link_values = map { ($_ => raw($values{$_})) } keys %values; # row data is in database form already
2856 16 my @filled = map { +{%$_, %link_values} } @rows;
2857 16 ▶ return $self->_primitive($method, $other, $method eq 'insert' ? $filled[0] : \@filled, %opts);
Branch: 1 branch
BranchTrueFalseTotal
$method eq 'insert' ? : 8 8 16
2858 }
2859  
2860 =pod
2861  
2862 =over 4
2863  
2864 =item \%link = $orm->_link_for(\@frame, $map, $table, $other, {link => \%link, via => \%via}, $insert_method)
2865  
2866 The link a call's C<link> or C<via> option gives: C<_via_link> for C<via>,
2867 otherwise C<_fk_link> with C<link> (undef when absent) and C<$insert_method>.
2868 Croaks when both are given.
2869  
2870 =item \%link = $orm->_via_link(\@frame, $map, $table, $other, \%via)
2871  
2872 C<%via>, C<< {our_field => their_field} >>, as the link, with no foreign key
2873 behind it. Croaks unless both tables are in the map, C<%via> is a non-empty
2874 hashref, and every field it names is a field of its table.
2875  
2876 =back
2877  
2878 =cut
2879  
2880 119 ▶sub _link_for {
Subroutine _link_for: called CC=4 SCAR=13.9
2881 119 my $self = shift;
2882 119 my ($frame, $map, $table, $other, $opts, $insert_method) = @_;
2883 119 ▶ _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 118 119
Condition100%3/3
defined $opts->{"link"} and defined $opts->{"via"}
!ll&&!rl&&r
97211
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
2884 118 ▶ return $self->_via_link($frame, $map, $table, $other, $opts->{via}) if defined $opts->{via};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts->{"via"} 15 103 118
2885 103 return $self->_fk_link($frame, $map, $table, $other, $opts->{link}, $insert_method);
2886 }
2887  
2888 15 ▶sub _via_link {
Subroutine _via_link: called CC=10 SCAR=23.3
2889 15 my $self = shift;
2890 15 my ($frame, $map, $table, $other, $via) = @_;
2891  
2892 15 ▶ _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 14 15
Condition66%2/3
ref $via eq "HASH" and %$via
!ll&&!rl&&r
0114
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
2893 14 for my $t ($table, $other) {
2894 28 ▶ _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 27 28
2895 }
2896 13 for my $ours (sort keys %$via) {
2897 13 my $theirs = $via->{$ours};
2898 13 ▶ _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 12 13
2899 12 ▶ _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 11 12
Condition50%3/6
defined $theirs and $map->field($other, $theirs)
!ll&&!rl&&r
0111
$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
2900 }
2901  
2902 11 return {%$via};
2903 }
2904  
2905 =pod
2906  
2907 =over 4
2908  
2909 =item \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given)
2910  
2911 =item \%link = $orm->_fk_link(\@frame, $map, $table, $other, \%given, $insert_method)
2912  
2913 The link to follow, C<< {our_field => their_field} >>, from the foreign keys of
2914 C<$table> to C<$other> and those of C<$other> to C<$table> turned around: the
2915 one matching C<%given>, or the only one when C<%given> is undef. Croaks
2916 otherwise, and when C<$other> is not in the map, reporting at C<@frame>.
2917  
2918 With C<$insert_method> (the calling method's name, for messages), only the
2919 keys of C<$other> to C<$table> count, and a C<%given> matching a key of
2920 C<$table> to C<$other> croaks, naming the direction.
2921  
2922 =back
2923  
2924 =cut
2925  
2926 103 ▶sub _fk_link {
Subroutine _fk_link: called CC=22 SCAR=31.1
2927 103 my $self = shift;
2928 103 my ($frame, $map, $table, $other, $given, $insert_method) = @_;
2929  
2930 103 ▶ my $forward = ($map->table($table)->{fk} // {})->{$other} // [];
Condition50%3/6
+($map->table($table)->{"fk"} // {})->{$other} // []
l!l
72310
$map->table($table)->{"fk"} // {}
l!l
10300
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
2931 103 ▶ _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 102 103
Condition100%3/3
@$forward and not $map->table($other)
!ll&&!rl&&r
31711
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
2932 102 ▶ _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 101 102
2933 101 ▶ my @back = map { +{reverse %$_} } @{($map->table($other)->{fk} // {})->{$table} // []};
Condition75%3/4
+($map->table($other)->{"fk"} // {})->{$table} // []
l!l
3764
$map->table($other)->{"fk"} // {}
l!l
1010
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
2934 101 ▶ my @links = $insert_method ? @back : (@$forward, @back);
Branch: 1 branch
BranchTrueFalseTotal
$insert_method ? : 22 79 101
2935  
2936 145 ▶ my $key = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2937 145 my ($l) = @_;
2938 145 join "\0" => map { "$_\0$l->{$_}" } sort keys %$l;
2939 101 };
2940 101 my %found;
2941 101 ▶ $found{$key->($_)} //= $_ for @links;
Condition33%1/3
$found{&$key($_)} //= $_
l!l&&r!l&&!r
01210
MC/DC0%0/2
$found{&$key($_)} //= $_
$found{&$key($_)} $_
Truth table33%1/3
A //= B
A= $found{&$key($_)}B= $_
ABresult
1X1
011
000
2942  
2943 101 ▶ if (defined $given) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $given) 21 80 101
2944 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
2945 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
2946 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");
2947 }
2948 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
2949 }
2950  
2951 80 my @keys = sort keys %found;
2952 80 ▶ _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 79 80
Condition100%3/3
$insert_method and not @keys
!ll&&!rl&&r
61181
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
2953 79 ▶ _croak_at($frame, "There is no foreign key between '$table' and '$other'") unless @keys;
Branch: 1 branch
BranchTrueFalseTotal
unless @keys 2 77 79
2954 77 ▶ _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 72 77
2955 72 return $found{$keys[0]};
2956 }
2957  
2958 =pod
2959  
2960 =over 4
2961  
2962 =item $temp = $orm->_temp_table($from_handle, ...)
2963  
2964 =item $temp = $orm->_temp_view($from_handle, ...)
2965  
2966 C<temp_table> and C<temp_view>. A handle's own C<temp_table> and
2967 C<temp_view> call them with C<$from_handle> true, so the L<DBIx::QuickORM::Source::Table::Temp>
2968 says in its errors how to get a new one from that handle.
2969  
2970 =back
2971  
2972 =cut
2973  
2974 57 ▶sub _temp_table {
Subroutine _temp_table: called CC=19 SCAR=29.5
2975 57 my $self = shift;
2976 57 my $from_handle = shift;
2977 57 ▶ my $what = @_ % 2 ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 54 3 57
2978 57 ▶ croak "temp_table() takes a name as name => \$name" if defined($what) && !ref($what);
Branch: 1 branch
BranchTrueFalseTotal
if defined $what and not ref $what 1 56 57
Condition100%3/3
defined $what and not ref $what
!ll&&!rl&&r
3531
MC/DC100%2/2
defined $what and not ref $what
defined $what not ref $what
Truth table100%3/3
A and not(B)
A= defined $whatB= not ref $what
ABresult
0X0
100
111
2979 56 my %opts = $self->_temp_opts(temp_table => @_);
2980 54 ▶ my $name = $opts{name} // $self->_temp_name;
Condition66%2/3
$opts{"name"} // $self->_temp_name
l!l&&r!l&&!r
21330
MC/DC0%0/2
$opts{"name"} // $self->_temp_name
$opts{"name"} $self->_temp_name
Truth table66%2/3
A // B
A= $opts{"name"}B= $self->_temp_name
ABresult
1X1
011
000
2981  
2982 54 ▶ if (!defined($what) || ref($what) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $what or ref $what eq "CODE") 44 10 54
Condition100%3/3
not defined $what or ref $what eq "CODE"
l!l&&r!l&&!r
14310
MC/DC100%2/2
not defined $what or ref $what eq "CODE"
not defined $what ref $what eq "CODE"
Truth table100%3/3
not(A) or B
A= not defined $whatB= ref $what eq "CODE"
ABresult
1X1
011
000
2983 44 ▶ croak "temp_table() takes 'pk' only with a handle or a SELECT; a builder declares its own key" if exists $opts{pk};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"pk"} 1 43 44
2984 43 my $builder = DBIx::QuickORM::SchemaBuilder::Table::Temp->new(orm => $self, name => $name);
2985 43 ▶ return $builder unless $what;
Branch: 1 branch
BranchTrueFalseTotal
unless $what 1 42 43
2986 42 require DBIx::QuickORM::DSL;
2987 42 my $got = DBIx::QuickORM::DSL->_temp_building($builder, $what);
2988 40 ▶ if ((blessed($got) && $got->isa('DBIx::QuickORM::Handle')) || (ref($got) eq 'REF' && ref($$got) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($got) and $got->isa("DBIx::QuickORM::Handle") or ref $got eq "REF" and ref $$got eq "ARRAY") 4 36 40
Condition88%8/9
builtin::blessed($got) and $got->isa("DBIx::QuickORM::Handle") or ref $got eq "REF" and ref $$got eq "ARRAY"
l!l&&r!l&&!r
3136
builtin::blessed($got) and $got->isa("DBIx::QuickORM::Handle")
!ll&&!rl&&r
3343
ref $got eq "REF" and ref $$got eq "ARRAY"
!ll&&!rl&&r
3601
MC/DC75%3/4
builtin::blessed($got) and $got->isa("DBIx::QuickORM::Handle") or ref $got eq "REF" and ref $$got eq "ARRAY"
builtin::blessed($got) $got->isa("DBIx::QuickORM::Handle") ref $got eq "REF" ref $$got eq "ARRAY"
Truth table57%4/7
A and B or C and D
A= builtin::blessed($got)B= $got->isa("DBIx::QuickORM::Handle")C= ref $got eq "REF"D= ref $$got eq "ARRAY"
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2989 4 my $fill = $builder->_fill;
2990 4 ▶ croak "The temp_table() callback called fill() and returned something else to fill from; give one" if $fill && $fill != $got;
Branch: 1 branch
BranchTrueFalseTotal
if $fill and $fill != $got 1 3 4
Condition100%3/3
$fill and $fill != $got
!ll&&!rl&&r
211
MC/DC100%2/2
$fill and $fill != $got
$fill $fill != $got
Truth table100%3/3
A and B
A= $fillB= $fill != $got
ABresult
0X0
100
111
2991 3 ▶ $builder->fill($got) unless $fill;
Branch: 1 branch
BranchTrueFalseTotal
unless $fill 2 1 3
2992 }
2993 39 return $builder->build;
2994 }
2995  
2996 10 my $dialect = $self->connection->dialect;
2997 10 ▶ if (ref($what) eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $what eq "SCALAR") 2 8 10
2998 2 ▶ croak "temp_table(\\\$create_sql) needs the 'name' the statement creates" unless exists $opts{name};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"name"} 1 1 2
2999 1 ▶ croak "temp_table(\\\$create_sql) takes no 'pk'; the database reports the table's key" if exists $opts{pk};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"pk"} 0 1 1
3000 1 return $self->_create_temp($name, table => [$$what], [$dialect->drop_sql($name, 'table', undef, temp => 1)], {});
3001 }
3002  
3003 8 my ($source, $sql, $binds, %spec) = $self->_temp_select(temp_table => $what, 1);
3004 8 my @create = ([$source, $dialect->create_table_as_sql($name, $sql, temp => 1), $binds]);
3005 8 return $self->_create_temp($name, table => \@create, [$dialect->drop_sql($name, 'table', undef, temp => 1)], {%spec, declare_pk => $opts{pk}}, $from_handle);
3006 }
3007  
3008 11 ▶sub _temp_view {
Subroutine _temp_view: called CC=4 SCAR=14.0
3009 11 my $self = shift;
3010 11 my $from_handle = shift;
3011 11 my $what = shift;
3012 11 ▶ croak "temp_view() takes a name as name => \$name, after the SQL or handle" unless ref($what);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $what 0 11 11
3013 11 my %opts = $self->_temp_opts(temp_view => @_);
3014 11 ▶ my $name = $opts{name} // $self->_temp_name;
Condition66%2/3
$opts{"name"} // $self->_temp_name
l!l&&r!l&&!r
1100
MC/DC0%0/2
$opts{"name"} // $self->_temp_name
$opts{"name"} $self->_temp_name
Truth table66%2/3
A // B
A= $opts{"name"}B= $self->_temp_name
ABresult
1X1
011
000
3015  
3016 11 my $conn = $self->connection;
3017 11 my $dialect = $conn->dialect;
3018 11 ▶ croak "The " . $dialect->name . " dialect has no temporary views" unless $dialect->supports_temp_views;
Branch: 1 branch
BranchTrueFalseTotal
unless $dialect->supports_temp_views 0 11 11
3019  
3020 11 my ($source, $sql, $binds, %spec) = $self->_temp_select(temp_view => $what, 0);
3021 11 my $select = $conn->inline_binds($source, $sql, $binds);
3022 11 return $self->_create_temp($name, view => [$dialect->create_view_sql($name, $select, temp => 1)], [$dialect->drop_sql($name, 'view', undef, temp => 1)], {%spec, declare_pk => $opts{pk}}, $from_handle);
3023 }
3024  
3025 =pod
3026  
3027 =over 4
3028  
3029 =item %opts = $orm->_temp_opts($method, %opts)
3030  
3031 C<temp_table>'s and C<temp_view>'s options, checked: C<name> (a non-empty
3032 string when given) and C<pk>.
3033  
3034 =item ($source, $sql, \@binds, %spec) = $orm->_temp_select($method, $what, $binds_ok)
3035  
3036 The query a temporary table or view is made from: a handle's C<SELECT>, or
3037 C<\[$sql, @binds]> (or C<\$sql> when C<$binds_ok> is false, for a view). From
3038 a handle, C<%spec> holds the C<row_class> it set, if any, and a background
3039 mode croaks.
3040  
3041 =back
3042  
3043 =cut
3044  
3045 258 my %TEMP_OPTS = map { $_ => 1 } qw/name pk/;
3046  
3047 67 ▶sub _temp_opts {
Subroutine _temp_opts: called CC=9 SCAR=22.7
3048 67 my $self = shift;
3049 67 my ($method, %opts) = @_;
3050 67 my @bad = sort grep { !$TEMP_OPTS{$_} } keys %opts;
3051 67 ▶ croak "$method() got unknown option(s): " . join(', ' => @bad) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 66 67
3052 66 ▶ croak "$method(): 'name' must be a non-empty string" if exists($opts{name}) && !(defined($opts{name}) && !ref($opts{name}) && length($opts{name}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"name"} and not defined $opts{"name"} && !ref($opts{"name"}) && length $opts{"name"} 1 65 66
Condition77%7/9
exists $opts{"name"} and not defined $opts{"name"} && !ref($opts{"name"}) && length $opts{"name"}
!ll&&!rl&&r
43221
defined $opts{'name'} && !ref($opts{'name'}) && length $opts{'name'}
!ll&&!rl&&r
1022
defined $opts{"name"} and not ref $opts{"name"}
!ll&&!rl&&r
1022
MC/DC50%2/4
exists $opts{"name"} and not defined $opts{"name"} && !ref($opts{"name"}) && length $opts{"name"}
exists $opts{"name"} defined $opts{"name"} not ref $opts{"name"} length $opts{'name'}
Truth table60%3/5
A and not(B and not(C) && D)
A= exists $opts{"name"}B= defined $opts{"name"}C= not ref $opts{"name"}D= length $opts{'name'}
ABCDresult
0XXX0
11110
10XX1
110X1
11101
3053 65 ▶ croak "$method(): 'pk' must be an arrayref of field names" if exists($opts{pk}) && !(ref($opts{pk}) eq 'ARRAY' && @{$opts{pk}});
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"pk"} and not ref $opts{"pk"} eq "ARRAY" && @{$opts{"pk"};} 0 65 65
Condition50%3/6
exists $opts{"pk"} and not ref $opts{"pk"} eq "ARRAY" && @{$opts{"pk"};}
!ll&&!rl&&r
5780
ref $opts{'pk'} eq 'ARRAY' && @{$opts{'pk'};}
!ll&&!rl&&r
008
MC/DC0%0/3
exists $opts{"pk"} and not ref $opts{"pk"} eq "ARRAY" && @{$opts{"pk"};}
exists $opts{"pk"} ref $opts{'pk'} eq 'ARRAY' @{$opts{'pk'};}
Truth table50%2/4
A and not(B && C)
A= exists $opts{"pk"}B= ref $opts{'pk'} eq 'ARRAY'C= @{$opts{'pk'};}
ABCresult
0XX0
1110
10X1
1101
3054 65 return %opts;
3055 }
3056  
3057 40 ▶sub _temp_select {
Subroutine _temp_select: called CC=10 SCAR=23.9
3058 40 my $self = shift;
3059 40 my ($method, $what, $create) = @_;
3060 40 my $dialect = $self->connection->dialect;
3061  
3062 40 ▶ if (blessed($what) && $what->isa('DBIx::QuickORM::Handle')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($what) and $what->isa("DBIx::QuickORM::Handle")) 32 8 40
Condition66%2/3
builtin::blessed($what) and $what->isa("DBIx::QuickORM::Handle")
!ll&&!rl&&r
8032
MC/DC50%1/2
builtin::blessed($what) and $what->isa("DBIx::QuickORM::Handle")
builtin::blessed($what) $what->isa("DBIx::QuickORM::Handle")
Truth table66%2/3
A and B
A= builtin::blessed($what)B= $what->isa("DBIx::QuickORM::Handle")
ABresult
0X0
100
111
3063 32 ▶ if (my $mode = $what->mode) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $mode = $what->mode) 0 32 32
3064 0 croak "$method() cannot use a handle with the $mode mode; call ->sync on it for one without";
3065 }
3066 32 my $source = $what->source;
3067 32 my ($sql, $binds) = $self->sql_builder->select($source, $dialect, $what->_select_request);
3068 32 return ($source, $sql, $binds, $what->_temp_row_class);
3069 }
3070  
3071 8 my $type = ref($what);
3072 8 ▶ my $bound = $type eq 'REF' && ref($$what) eq 'ARRAY';
Condition66%2/3
$type eq 'REF' && ref $$what eq 'ARRAY'
!ll&&!rl&&r
404
MC/DC50%1/2
$type eq 'REF' && ref $$what eq 'ARRAY'
$type eq 'REF' ref $$what eq 'ARRAY'
Truth table66%2/3
A && B
A= $type eq 'REF'B= ref $$what eq 'ARRAY'
ABresult
0X0
100
111
3073 8 ▶ my $forms = $create ? "a handle or \\[\$select_sql, \@binds]" : "\\\$sql, \\[\$sql, \@binds], or a handle";
Branch: 1 branch
BranchTrueFalseTotal
$create ? : 3 5 8
3074 8 ▶ croak "$method() takes $forms" unless $bound || (!$create && $type eq 'SCALAR');
Branch: 1 branch
BranchTrueFalseTotal
unless $bound or not $create and $type eq "SCALAR" 0 8 8
Condition50%3/6
$bound or not $create and $type eq "SCALAR"
l!l&&r!l&&!r
440
not $create and $type eq "SCALAR"
!ll&&!rl&&r
004
MC/DC0%0/3
$bound or not $create and $type eq "SCALAR"
$bound not $create $type eq "SCALAR"
Truth table50%2/4
A or not(B) and C
A= $boundB= not $createC= $type eq "SCALAR"
ABCresult
1XX1
0111
00X0
0100
3075 8 ▶ my $source = $bound ? DBIx::QuickORM::Source::Query->new(sql => $$what->[0], binds => [@{$$what}[1 .. $#$$what]]) : DBIx::QuickORM::Source::Query->new(sql => $$what);
Branch: 1 branch
BranchTrueFalseTotal
$bound ? : 4 4 8
3076 8 return ($source, $source->query_sql);
3077 }
3078  
3079 =pod
3080  
3081 =over 4
3082  
3083 =item $temp = $orm->_build_temp_table($builder)
3084  
3085 Creates the table a L<DBIx::QuickORM::SchemaBuilder::Table::Temp> describes: resolves each
3086 column's C<db_type> and C<type> (an enum column is C<text> with a check where
3087 the database has enum types, which would outlive the table), has the dialect
3088 write the SQL (with the C<INSERT ... SELECT> of its C<fill>, if any), and
3089 creates it through C<_create_temp>.
3090  
3091 =back
3092  
3093 =cut
3094  
3095 40 ▶sub _build_temp_table {
Subroutine _build_temp_table: called CC=10 SCAR=23.0
3096 40 my $self = shift;
3097 40 my ($builder) = @_;
3098 40 my $name = $builder->name;
3099 40 my $spec = $builder->spec;
3100 40 my $conn = $self->connection;
3101 40 my $dialect = $conn->dialect;
3102  
3103 40 for my $column (grep { !exists $_->{sql} } @{$spec->{columns}}) {
3104 68 ▶ if (exists $column->{enum}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $column->{"enum"}) 3 65 68
3105 3 require DBIx::QuickORM::DSL;
3106 3 my $what = "The column '$column->{name}' of the temporary table '$name'";
3107 3 ▶ my ($enum, $values) = DBIx::QuickORM::DSL->enum_values($self->isa('DBIx::QuickORM::ORM') ? ref($self) : undef, delete($column->{enum}), $what);
Branch: 1 branch
BranchTrueFalseTotal
$self->isa('DBIx::QuickORM::ORM') ? : 1 2 3
3108 3 ▶ my ($db_type, $check) = $dialect->enum_column($column->{name}, $enum // "${name}_enum", $values, temp => 1);
Condition100%2/2
$enum // "${name}_enum"
l!l
12
MC/DC100%1/1
$enum // "${name}_enum"
$enum
Truth table100%2/2
A
A= $enum
Aresult
11
00
3109 3 $column->{db_type} = $db_type;
3110 3 ▶ push @{$spec->{checks}} => {sql => \$check} if defined $check;
Branch: 1 branch
BranchTrueFalseTotal
if defined $check 3 0 3
3111 }
3112 68 ▶ $column->{type} = $self->require_type($column->{type}, "column '$column->{name}'") if defined $column->{type};
Branch: 1 branch
BranchTrueFalseTotal
if defined $column->{"type"} 3 65 68
3113 68 $column->{db_type} = $dialect->column_type($column);
3114 }
3115  
3116 39 my @create = $dialect->create_table_sql($name, $spec, temp => 1);
3117 37 my @drop = $dialect->drop_sql($name, 'table', $spec, temp => 1);
3118 37 ▶ if (my $fill = $builder->_fill) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fill = $builder->_fill) 8 29 37
3119 8 my ($source, $sql, $binds) = $self->_temp_select(fill => $fill, 1);
3120 8 ▶ my $columns = blessed($fill) && $fill->isa('DBIx::QuickORM::Handle') ? $self->_fill_columns($fill, $spec) : undef;
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($fill) && $fill->isa('DBIx::QuickORM::Handle') ? : 6 2 8
Condition66%2/3
builtin::blessed($fill) and $fill->isa("DBIx::QuickORM::Handle")
!ll&&!rl&&r
206
MC/DC50%1/2
builtin::blessed($fill) and $fill->isa("DBIx::QuickORM::Handle")
builtin::blessed($fill) $fill->isa("DBIx::QuickORM::Handle")
Truth table66%2/3
A and B
A= builtin::blessed($fill)B= $fill->isa("DBIx::QuickORM::Handle")
ABresult
0X0
100
111
3121 6 push @create => [$source, $dialect->insert_select_sql($name, $sql, $columns), $binds];
3122 }
3123 35 return $self->_create_temp($name, table => \@create, \@drop, $spec);
3124 }
3125  
3126 =pod
3127  
3128 =over 4
3129  
3130 =item \@names = $orm->_fill_columns($handle, \%spec)
3131  
3132 The columns a handle's C<fill> inserts into, by name, in the order its
3133 C<SELECT> lists them: its fields as the source selects them (a table adds its
3134 primary key), or its computed fields in sorted order. Croaks for a join, for
3135 a handle whose columns have no names, and for a name the table does not
3136 have.
3137  
3138 =back
3139  
3140 =cut
3141  
3142 6 ▶sub _fill_columns {
Subroutine _fill_columns: called CC=6 SCAR=18.0
3143 6 my $self = shift;
3144 6 my ($handle, $spec) = @_;
3145 6 my $source = $handle->source;
3146 6 ▶ croak "fill() cannot name a join's columns; give it \\[\$select_sql, \@binds] instead" if $source->isa('DBIx::QuickORM::Source::Join');
Branch: 1 branch
BranchTrueFalseTotal
if $source->isa("DBIx::QuickORM::Source::Join") 1 5 6
3147 5 my $fields = $source->select_fields($handle->fields);
3148 5 ▶ croak "fill() needs to know the handle's column names; give the handle fields(), or give fill() \\[\$select_sql, \@binds]" unless ref($fields);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $fields 0 5 5
3149 5 ▶ my @names = ref($fields) eq 'HASH' ? sort keys %$fields : @$fields;
Branch: 1 branch
BranchTrueFalseTotal
ref $fields eq 'HASH' ? : 0 5 5
3150 5 my %have = map { ($_->{name} => 1) } @{$spec->{columns}};
3151 5 ▶ $have{$_} or croak "fill(): the handle selects '$_', which the temporary table does not have" for @names;
Branch: 1 branch
BranchTrueFalseTotal
$have{$_} or croak("fill(): the handle selects '${_}', which the temporary table does not have") 8 1 9
3152 4 return \@names;
3153 }
3154  
3155 =pod
3156  
3157 =over 4
3158  
3159 =item $temp = $orm->_create_temp($name, $kind, \@create, \@drop, \%spec, $from_handle)
3160  
3161 Creates a temporary table or view through the Connection's C<create_temp>,
3162 then adjusts the record the database reports, as C<new> would a scanned one,
3163 but with only what concerns this table: autotyping, then the spec's types,
3164 row class, map-only foreign keys (C<references> and C<foreign_keys>), and a declared primary key
3165 (C<declare_pk>, for a view or a table made from a query), then the key types
3166 and passthrough fields. Returns its L<DBIx::QuickORM::Source::Table::Temp>, marked as made
3167 by a handle when C<$from_handle> is true.
3168  
3169 =back
3170  
3171 =cut
3172  
3173 55 ▶sub _create_temp {
Subroutine _create_temp: called CC=2 SCAR=6.9
3174 55 my $self = shift;
3175 55 my ($name, $kind, $create, $drop, $spec, $from_handle) = @_;
3176 55 my $conn = $self->connection;
3177 55 ▶ $conn->create_temp($name, $kind, $create, $drop, sub { $self->_setup_temp($name, $_[0], $spec) });
Subroutine __ANON__: called CC=1 SCAR=0.0
3178 52 ▶ return DBIx::QuickORM::Source::Table::Temp->new(orm => $self, table => $name, db_map => $conn->db_map, kind => $kind, connection => $conn, from_handle => $from_handle ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$from_handle ? : 6 46 52
3179 }
3180  
3181 =pod
3182  
3183 =over 4
3184  
3185 =item $orm->_setup_temp($name, \%record, \%spec)
3186  
3187 The adjustments C<_create_temp> describes, in place.
3188  
3189 =back
3190  
3191 =cut
3192  
3193 53 ▶sub _setup_temp {
Subroutine _setup_temp: called CC=18 SCAR=29.0
3194 53 my $self = shift;
3195 53 my ($name, $record, $spec) = @_;
3196 53 my $one = DBIx::QuickORM::Map->new(tables => {$name => $record});
3197 53 my $fields = $record->{fields};
3198 53 $self->_autotype($one, 0);
3199  
3200 53 my @links;
3201 53 ▶ for my $column (@{$spec->{columns} // []}) {
Condition100%2/2
$spec->{"columns"} // []
l!l
3320
MC/DC100%1/1
$spec->{"columns"} // []
$spec->{"columns"}
Truth table100%2/2
A
A= $spec->{"columns"}
Aresult
11
00
3202 62 ▶ my $rec = $fields->{$column->{name}} or croak "The database reports no field '$column->{name}' in the temporary table '$name'";
Branch: 1 branch
BranchTrueFalseTotal
my $rec = $$fields{$column->{"name"}} or croak(qq[The database reports no field '$column->{"name"}' in the temporary table '${name}']) 62 0 62
3203 62 ▶ $rec->{orm_type} = $column->{type} if $column->{type};
Branch: 1 branch
BranchTrueFalseTotal
if $column->{"type"} 3 59 62
3204 62 ▶ my $refs = $column->{references} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $refs = $column->{"references"} or next 1 61 62
3205 1 push @links => ["The column '$column->{name}'", $refs->{table}, [$column->{name}], [$refs->{column}]];
3206 }
3207 53 ▶ push @links => map { ["The foreign key on (" . join(', ' => @{$_->{columns}}) . ")", $_->{table}, $_->{columns}, $_->{their_columns}] } @{$spec->{foreign_keys} // []};
Condition100%2/2
$spec->{"foreign_keys"} // []
l!l
3320
MC/DC100%1/1
$spec->{"foreign_keys"} // []
$spec->{"foreign_keys"}
Truth table100%2/2
A
A= $spec->{"foreign_keys"}
Aresult
11
00
3208 53 for my $link (@links) {
3209 2 my ($what, $other, $ours, $theirs) = @$link;
3210 2 ▶ my $target = $other eq $name ? $record : $self->db_map->table($other);
Branch: 1 branch
BranchTrueFalseTotal
$other eq $name ? : 0 2 2
3211 2 ▶ croak "$what references the table '$other', which is not in the database map" unless $target;
Branch: 1 branch
BranchTrueFalseTotal
unless $target 0 2 2
3212 2 ▶ $target->{fields}->{$_} or croak "$what references the column '$_' of '$other', which it does not have" for @$theirs;
Branch: 1 branch
BranchTrueFalseTotal
$target->{"fields"}{$_} or croak("$what references the column '${_}' of '${other}', which it does not have") 2 0 2
3213 2 my %link;
3214 2 @link{@$ours} = @$theirs;
3215 2 push @{$record->{fk}->{$other}} => \%link;
3216 }
3217  
3218 53 ▶ if (my $pk = $spec->{declare_pk}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pk = $spec->{"declare_pk"}) 7 46 53
3219 7 ▶ my $what = $record->{view} ? 'view' : 'table';
Branch: 1 branch
BranchTrueFalseTotal
$record->{'view'} ? : 4 3 7
3220 7 ▶ $fields->{$_} or croak "'pk' names the field '$_', which the $what '$name' does not have" for @$pk;
Branch: 1 branch
BranchTrueFalseTotal
$fields->{$_} or croak("'pk' names the field '${_}', which the $what '${name}' does not have") 6 1 7
3221 6 $record->{pk} = [@$pk];
3222 }
3223  
3224 52 ▶ if (exists $spec->{row_class}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $spec->{"row_class"}) 2 50 52
3225 2 $record->{row_class} = $spec->{row_class};
3226 2 ▶ $self->load_row_class($spec->{row_class}) if defined $spec->{row_class};
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"row_class"} 2 0 2
3227 }
3228  
3229 52 $self->_apply_key_types($one);
3230 52 $self->_apply_passthrough($one);
3231 }
3232  
3233 =pod
3234  
3235 =over 4
3236  
3237 =item $name = $orm->_temp_name
3238  
3239 A new temporary table or view name: C<qorm_tmp_>, a counter that never
3240 repeats in the process, and random hex.
3241  
3242 =back
3243  
3244 =cut
3245  
3246 43 ▶sub _temp_name { sprintf('qorm_tmp_%d_%08x', ++$TEMP_COUNT, int(rand(2**32))) }
Subroutine _temp_name: called CC=1 SCAR=0.0
3247  
3248 =pod
3249  
3250 =over 4
3251  
3252 =item $source = $orm->_table_source($table)
3253  
3254 The table's L<DBIx::QuickORM::Source::Table>, built on first use and then
3255 kept: sources are immutable, so every handle over the table shares it. Croaks
3256 as the source's C<new> does, keeping nothing. A temporary table or view gets
3257 a new L<DBIx::QuickORM::Source::Table::Temp> each time, never kept, since its
3258 name can later belong to another one.
3259  
3260 =back
3261  
3262 =cut
3263  
3264 332 ▶sub _table_source {
Subroutine _table_source: called CC=9 SCAR=22.7
3265 332 my $self = shift;
3266 332 my ($table) = @_;
3267 332 ▶ my $sources = $self->{+TABLE_SOURCES} //= {};
Condition100%2/2
$self->{"table_sources"} //= {}
l!l
24686
MC/DC100%1/1
$self->{"table_sources"} //= {}
$self->{"table_sources"}
Truth table100%2/2
A
A= $self->{"table_sources"}
Aresult
11
00
3268 332 ▶ return $sources->{$table // ''} if $sources->{$table // ''};
Branch: 1 branch
BranchTrueFalseTotal
if $$sources{$table // ""} 209 123 332
Condition50%2/4
$table // ""
l!l
3320
$table // ""
l!l
2090
MC/DC0%0/1
$table // ""
$table
MC/DC0%0/1
$table // ""
$table
Truth table50%1/2
A
A= $table
Aresult
11
00
Truth table50%1/2
A
A= $table
Aresult
11
00
3269 123 my $map = $self->db_map;
3270 123 ▶ my $t = defined($table) ? $map->table($table) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $table ? : 123 0 123
3271 123 ▶ return DBIx::QuickORM::Source::Table::Temp->new(orm => $self, table => $table, db_map => $map, kind => $t->{view} ? 'view' : 'table') if $t && $t->{temp};
Branch: 2 branches
BranchTrueFalseTotal
if $t and $t->{"temp"} 1 122 123
$t->{'view'} ? : 0 1 1
Condition66%2/3
$t and $t->{"temp"}
!ll&&!rl&&r
01221
MC/DC50%1/2
$t and $t->{"temp"}
$t $t->{"temp"}
Truth table66%2/3
A and B
A= $tB= $t->{"temp"}
ABresult
0X0
100
111
3272 122 return $sources->{$table} = DBIx::QuickORM::Source::Table->new(table => $table, db_map => $map);
3273 }
3274  
3275 =pod
3276  
3277 =over 4
3278  
3279 =item \%fields = $orm->_table_fields($table)
3280  
3281 The table's field records from the map, kept after the first call. Rows read
3282 them on every field read, and this skips the walk through C<connection>. The
3283 map does not change after the ORM is built.
3284  
3285 In a forked child it goes through C<connection> first, so the child
3286 reconnects (or croaks) as before, whatever the parent read.
3287  
3288 =back
3289  
3290 =cut
3291  
3292 410 ▶sub _table_fields {
Subroutine _table_fields: called CC=4 SCAR=13.9
3293 410 my $self = shift;
3294 410 my ($table) = @_;
3295  
3296 410 ▶ $self->connection unless $self->{+CONNECTION}->pid == $$;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"connection"}->pid == $$ 0 410 410
3297 410 my $cached = $self->{+TABLE_FIELDS}->{$table};
3298 410 ▶ return $cached if $cached;
Branch: 1 branch
BranchTrueFalseTotal
if $cached 329 81 410
3299 81 my $t = $self->db_map->table($table);
3300 81 ▶ return $t->{fields} if $t->{temp}; # a temporary name can be reused for another table
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"temp"} 5 76 81
3301 76 return $self->{+TABLE_FIELDS}->{$table} = $t->{fields};
3302 }
3303  
3304 =pod
3305  
3306 =over 4
3307  
3308 =item \@fields = $orm->_with_held($table, \%data, @missing)
3309  
3310 The fields the row data holds, then C<@missing>: what to read so that a read
3311 of missing fields holds everything the row already had, and so cannot
3312 replace its canonical copy with a narrower one.
3313  
3314 =back
3315  
3316 =cut
3317  
3318 7 ▶sub _with_held {
Subroutine _with_held: called CC=1 SCAR=0.0
3319 7 my $self = shift;
3320 7 my ($table, $data, @missing) = @_;
3321 7 my $fields = $self->_table_fields($table);
3322 7 return [(sort grep { $fields->{$_} } keys %$data), @missing];
3323 }
3324  
3325 =pod
3326  
3327 =over 4
3328  
3329 =item $h = $orm->_fk_handle($other, {$their_field => $value, ...})
3330  
3331 A handle on the rows of C<$other> whose fields hold these values, each field
3332 qualified as C<other.field> in the C<where>. An undef value refers to
3333 nothing: its condition is C<sql('IS NULL AND 1 = 0')>, which is never true.
3334 The handle is C<single> when the fields are exactly the primary key or a
3335 unique key of C<$other>, otherwise C<multi>. Croaks when C<$other> is not in
3336 the map.
3337  
3338 =back
3339  
3340 =cut
3341  
3342 46 ▶sub _fk_handle {
Subroutine _fk_handle: called CC=6 SCAR=18.2
3343 46 my $self = shift;
3344 46 my ($other, $values) = @_;
3345  
3346 46 my $map = $self->db_map;
3347 46 ▶ 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") 45 1 46
3348  
3349 45 my $theirs = join "\0" => sort keys %$values;
3350 45 ▶ my $single = grep { join("\0" => sort @$_) eq $theirs } grep { $_ && @$_ } $t->{pk}, @{$t->{unique} // []};
Condition40%2/5
$_ && @$_
!ll&&!rl&&r
0066
$t->{"unique"} // []
l!l
450
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
3351  
3352 return DBIx::QuickORM::Handle->new(
3353 orm => $self,
3354 source => $self->_table_source($other),
3355 45 ▶ where => {map { ("$other.$_" => $values->{$_} // sql('IS NULL AND 1 = 0')) } keys %$values},
Branch: 1 branch
BranchTrueFalseTotal
$single ? : 37 8 45
Condition66%2/3
$values->{$_} // sql("IS NULL AND 1 = 0")
l!l&&r!l&&!r
3960
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
3356 state => $single ? 'single' : 'multi',
3357 );
3358 }
3359  
3360 =pod
3361  
3362 =over 4
3363  
3364 =item $bool = $orm->_can_connect
3365  
3366 True unless the ORM was given a C<dbh>: whether the connector can open another
3367 connection.
3368  
3369 =item _offline => {dialect => $dialect, db_map => $map, raw_tables => \%names}
3370  
3371 A private C<new> argument from L<DBIx::QuickORM::ORM>'s C<offline>: C<init>
3372 connects through a L<DBIx::QuickORM::Connection::Offline> with these instead
3373 of a database, and needs no connection argument.
3374  
3375 =item _build_schema => sub { my ($dbh) = @_; ... }
3376  
3377 A private C<new> argument from L<DBIx::QuickORM::ORM>'s C<deploy>: C<init>
3378 calls it with the first handle before connecting on that handle, and the
3379 connection rescans.
3380  
3381 =item $code = $orm->_build_connector
3382  
3383 Turns the one connection argument into the connector, removing it from the
3384 object, and sets C<_can_connect>.
3385  
3386 =item ($code, $can_connect) = $class->_connector_for(\%args)
3387  
3388 What C<_build_connector> builds, from the connection form in C<%args>,
3389 which it removes: the connector, and whether it can open more than one
3390 handle (not for a C<dbh>). Croaks as C<new> does for a missing, doubled, or
3391 malformed form.
3392  
3393 =back
3394  
3395 =cut
3396  
3397 462 ▶sub _build_connector {
Subroutine _build_connector: called CC=1 SCAR=0.0
3398 462 my $self = shift;
3399 462 my ($code, $can_connect) = $self->_connector_for($self);
3400 447 $self->{+_CAN_CONNECT} = $can_connect;
3401 447 return $code;
3402 }
3403  
3404 465 ▶sub _connector_for {
Subroutine _connector_for: called CC=17 SCAR=28.3
3405 465 my $class = shift;
3406 465 my ($args) = @_;
3407  
3408 465 my @forms = grep { exists $args->{$_} } qw/dbh connect credentials/;
3409 465 ▶ 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 463 465
@forms ? : 1 1 2
3410  
3411 463 my ($form) = @forms;
3412 463 my $arg = delete $args->{$form};
3413 463 my $can = $form ne 'dbh';
3414  
3415 463 ▶ if ($form eq 'connect') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form eq "connect") 55 408 463
3416 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
3417 54 return ($arg, $can);
3418 }
3419  
3420 408 ▶ if ($form eq 'dbh') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form eq "dbh") 374 34 408
3421 374 ▶ 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 373 374
Condition66%2/3
builtin::blessed($arg) and $arg->isa("DBI::db")
!ll&&!rl&&r
10373
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
3422 374 ▶ my $code = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3423 374 ▶ croak "This ORM was given a 'dbh', so it cannot open another database connection" unless $arg;
Branch: 1 branch
BranchTrueFalseTotal
unless $arg 8 366 374
3424 366 my $dbh = $arg;
3425 366 undef $arg;
3426 366 return $dbh;
3427 373 };
3428 373 return ($code, $can);
3429 }
3430  
3431 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
3432 32 my @unknown = sort grep { !m/^(?:dsn|user|pass|attrs)$/ } keys %$arg;
3433 32 ▶ croak "Unknown key(s) in 'credentials': " . join(', ' => @unknown) if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 31 32
3434 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
3435  
3436 30 my ($dsn, $user, $pass) = @{$arg}{qw/dsn user pass/};
3437 croak "Do not turn AutoCommit off in 'credentials' attrs; the ORM manages transactions"
3438 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
3439  
3440 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
3441 23 ▶ return (sub { DBI->connect($dsn, $user, $pass, $attrs) }, $can);
Subroutine __ANON__: called CC=1 SCAR=0.0
3442 }
3443  
3444 =pod
3445  
3446 =over 4
3447  
3448 =item $debug = $orm->_build_debug
3449  
3450 A new L<DBIx::QuickORM::Debug>, loaded only here, so an ORM without
3451 C<debug> never loads it.
3452  
3453 =item $builder = $orm->_build_sql_builder
3454  
3455 The C<sql_builder> argument as an object, the default when none was given.
3456  
3457 =back
3458  
3459 =cut
3460  
3461 4 ▶sub _build_debug {
Subroutine _build_debug: called CC=1 SCAR=0.0
3462 4 require DBIx::QuickORM::Debug;
3463 4 return DBIx::QuickORM::Debug->new;
3464 }
3465  
3466 465 ▶sub _build_sql_builder {
Subroutine _build_sql_builder: called CC=7 SCAR=19.5
3467 465 my $self = shift;
3468  
3469 465 my $role = 'DBIx::QuickORM::Role::SQLBuilder';
3470 465 ▶ my $builder = $self->{+SQL_BUILDER} // 'DBIx::QuickORM::SQLBuilder::SQLAbstract';
Condition100%2/2
$self->{"sql_builder"} // "DBIx::QuickORM::SQLBuilder::SQLAbstract"
l!l
6459
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
3471  
3472 465 ▶ unless (blessed($builder)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($builder)) 464 1 465
3473 464 ▶ 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 463 464
Condition66%2/3
&$STR($builder) and $builder =~ /^\w+(?:::\w+)*$/
!ll&&!rl&&r
10463
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
3474 463 ▶ $self->load_class("'sql_builder' names the class '$builder', which", $builder) unless $builder->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->can("new") 1 462 463
3475 462 $builder = $builder->new;
3476 }
3477  
3478 463 ▶ croak "'sql_builder' must compose $role" unless $builder->DOES($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->DOES($role) 1 462 463
3479 462 return $builder;
3480 }
3481  
3482 =pod
3483  
3484 =over 4
3485  
3486 =item \@builders = $orm->_where_builders($what, \@builders)
3487  
3488 A copy of the list, each class loaded unless it has C<build_where>. Croaks,
3489 naming C<$what>, for a list of the wrong shape (as C<new> checks it) or a
3490 builder not composing L<DBIx::QuickORM::Role::WhereBuilder>.
3491  
3492 =back
3493  
3494 =cut
3495  
3496 466 ▶sub _where_builders {
Subroutine _where_builders: called CC=6 SCAR=17.9
3497 466 my $self = shift;
3498 466 my ($what, $builders) = @_;
3499  
3500 466 my ($want, $check) = @{$SHAPES{where_builders}};
3501 466 ▶ croak "$what must be $want" unless $check->($builders);
Branch: 1 branch
BranchTrueFalseTotal
unless &$check($builders) 1 465 466
3502  
3503 465 my $role = 'DBIx::QuickORM::Role::WhereBuilder';
3504 465 for my $builder (@$builders) {
3505 1380 ▶ $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 1378 1380
Condition100%3/3
builtin::blessed($builder) or $builder->can("build_where")
l!l&&r!l&&!r
113772
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
3506 1379 ▶ croak "$what names '$builder', which does not compose $role" unless $builder->DOES($role);
Branch: 1 branch
BranchTrueFalseTotal
unless $builder->DOES($role) 1 1378 1379
3507 }
3508  
3509 463 return [@$builders];
3510 }
3511  
3512 =pod
3513  
3514 =over 4
3515  
3516 =item $conn = $orm->_connect(%args)
3517  
3518 A new Connection with these arguments, on a new handle from the connector
3519 unless they give a C<dbh>.
3520  
3521 =back
3522  
3523 =cut
3524  
3525 442 ▶sub _connect {
Subroutine _connect: called CC=2 SCAR=6.9
3526 442 my $self = shift;
3527 442 my %args = @_;
3528 442 ▶ $args{dbh} //= $self->{+CONNECTOR}->();
Condition100%3/3
$args{"dbh"} //= $self->{"connector"}->()
l!l&&r!l&&!r
24391
MC/DC100%2/2
$args{"dbh"} //= $self->{"connector"}->()
$args{"dbh"} $self->{"connector"}->()
Truth table100%3/3
A //= B
A= $args{"dbh"}B= $self->{"connector"}->()
ABresult
1X1
011
000
3529 440 return DBIx::QuickORM::Connection->new(%args);
3530 }
3531  
3532 =pod
3533  
3534 =over 4
3535  
3536 =item $new = $orm->_connect_like($conn)
3537  
3538 A new Connection from the connector with the settings of the given one and
3539 the map as the ORM finished building it, without any temporary tables or
3540 views: for a forked child's reconnect, and for queries run on a second
3541 connection.
3542  
3543 =back
3544  
3545 =cut
3546  
3547 3 ▶sub _connect_like {
Subroutine _connect_like: called CC=1 SCAR=0.0
3548 3 my $self = shift;
3549 3 my ($conn) = @_;
3550 3 return $self->_connect(db_map => $self->{+FINISHED_MAP}, map { $_ => $conn->$_ } qw/retain_cache enforce_canon debug isolation time_zone datetime_parsers lookup_class/);
3551 }
3552  
3553 258 my @DEFAULT_AUTOTYPE = qw/UUID JSON DateTime/;
3554  
3555 =pod
3556  
3557 =over 4
3558  
3559 =item $map = $orm->_copy_map($db_map)
3560  
3561 A copy of a given map as a L<DBIx::QuickORM::Map>, or undef for undef.
3562  
3563 =back
3564  
3565 =cut
3566  
3567 441 ▶sub _copy_map {
Subroutine _copy_map: called CC=5 SCAR=16.1
3568 441 my $self = shift;
3569 441 my ($given) = @_;
3570 441 ▶ return undef unless defined $given;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $given 422 19 441
3571  
3572 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
3573 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
3574 17 return DBIx::QuickORM::Map->new(tables => $data)->clone;
3575 }
3576  
3577 =pod
3578  
3579 =over 4
3580  
3581 =item $orm->_drop_absent_elective($map)
3582  
3583 Drops the per-table arguments naming an C<elective> table the map lacks, as
3584 the table or as an C<fks> target, before C<_setup_map> checks them.
3585  
3586 =item $note = $orm->_absent_note($name)
3587  
3588 What a "not in the database map" error adds: the Connection's
3589 C<_gone_note>, or that the table is elective and absent.
3590  
3591 =item $orm->_setup_map($map, $given)
3592  
3593 Adjusts the Connection's map in place by the arguments, in the order C<new>
3594 lists them, through the methods below. C<$given> is true when the map came
3595 from C<db_map> rather than a scan.
3596  
3597 =back
3598  
3599 =cut
3600  
3601 410 ▶sub _drop_absent_elective {
Subroutine _drop_absent_elective: called CC=10 SCAR=23.0
3602 410 my $self = shift;
3603 410 my ($map) = @_;
3604 410 ▶ my @absent = grep { !$map->table($_) } @{$self->{+ELECTIVE} // []} or return;
Branch: 1 branch
BranchTrueFalseTotal
my(@absent) = grep({not $map->table($_);} @{$self->{"elective"} // [];}) or return 12 398 410
Condition100%2/2
$self->{"elective"} // []
l!l
12398
MC/DC100%1/1
$self->{"elective"} // []
$self->{"elective"}
Truth table100%2/2
A
A= $self->{"elective"}
Aresult
11
00
3605 12 my %absent = map { $_ => 1 } @absent;
3606  
3607 12 for my $arg (TYPES(), OMIT(), DEFAULT_FIELDS(), PKS(), ROW_CLASSES()) {
3608 60 my $given = $self->{$arg};
3609 60 ▶ next unless ref($given) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $given eq "HASH" 49 11 60
3610 11 ▶ $self->{$arg} = {map { $absent{$_} ? () : ($_ => $given->{$_}) } keys %$given};
Branch: 1 branch
BranchTrueFalseTotal
$absent{$_} ? : 19 4 23
3611 }
3612 12 ▶ if (ref(my $fks = $self->{+FKS}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref(my $fks = $self->{"fks"}) eq "HASH") 1 11 12
3613 $self->{+FKS} = {
3614 map {
3615 1 my $t = $_;
3616 2 ▶ $absent{$t} ? () : ($t => ref($fks->{$t}) eq 'HASH' ? {map { $absent{$_} ? () : ($_ => $fks->{$t}->{$_}) } keys %{$fks->{$t}}} : $fks->{$t})
Branch: 3 branches
BranchTrueFalseTotal
$absent{$t} ? : 1 1 2
ref $fks->{$t} eq 'HASH' ? : 1 0 1
$absent{$_} ? : 1 0 1
3617 } keys %$fks
3618 };
3619 }
3620 12 return;
3621 }
3622  
3623 9 ▶sub _absent_note {
Subroutine _absent_note: called CC=4 SCAR=13.9
3624 9 my $self = shift;
3625 9 my ($name) = @_;
3626 9 my $gone = $self->connection->_gone_note($name);
3627 9 ▶ return $gone if length $gone;
Branch: 1 branch
BranchTrueFalseTotal
if length $gone 3 6 9
3628 6 ▶ return " (it is elective, and this database does not have it)" if grep { $_ eq $name } @{$self->{+ELECTIVE} // []};
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ eq $name;} @{$self->{"elective"} // [];} 3 3 6
Condition100%2/2
$self->{"elective"} // []
l!l
33
MC/DC100%1/1
$self->{"elective"} // []
$self->{"elective"}
Truth table100%2/2
A
A= $self->{"elective"}
Aresult
11
00
3629 3 return '';
3630 }
3631  
3632 410 ▶sub _setup_map {
Subroutine _setup_map: called CC=1 SCAR=0.0
3633 410 my $self = shift;
3634 410 my ($map, $given) = @_;
3635  
3636 410 $self->_autotype($map, $given);
3637 403 $self->_apply_types($map);
3638 386 $self->_apply_fks($map);
3639 379 $self->_apply_pks($map);
3640 375 $self->_apply_default_fields($map);
3641 366 $self->_apply_row_classes($map);
3642 357 $self->_apply_key_types($map);
3643 353 $self->_apply_passthrough($map);
3644 }
3645  
3646 =pod
3647  
3648 =over 4
3649  
3650 =item $orm->_autotype($map, $given)
3651  
3652 Sets each field's C<orm_type> from the autotype list, as C<new> describes. A
3653 given map keeps its types, which are only loaded, when C<new> got neither
3654 C<autotype> nor C<append_autotype>.
3655  
3656 =back
3657  
3658 =cut
3659  
3660 463 ▶sub _autotype {
Subroutine _autotype: called CC=17 SCAR=28.3
3661 463 my $self = shift;
3662 463 my ($map, $given) = @_;
3663  
3664 463 my $asked = exists $self->{+AUTOTYPE};
3665 463 my $append = exists $self->{+APPEND_AUTOTYPE};
3666 463 ▶ return $self->_require_map_types($map) if $given && !$asked && !$append;
Branch: 1 branch
BranchTrueFalseTotal
if $given and not $asked and not $append 13 450 463
Condition100%6/6
$given and not $asked and not $append
!ll&&!rl&&r
449113
$given and not $asked
!ll&&!rl&&r
446314
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
3667  
3668 450 ▶ 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 448 450
Condition100%6/6
$asked and defined $self->{"autotype"} and not &$STR_LIST($self->{"autotype"})
!ll&&!rl&&r
436122
$asked and defined $self->{"autotype"}
!ll&&!rl&&r
430614
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
3669 448 ▶ 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 447 448
Condition100%3/3
$append and not &$STR_LIST($self->{"append_autotype"})
!ll&&!rl&&r
44341
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
3670  
3671 my @types = (
3672 1300 ▶ (map { $self->_load_type(autotype => $_) } $asked ? @{$self->{+AUTOTYPE} // []} : @DEFAULT_AUTOTYPE),
Branch: 1 branch
BranchTrueFalseTotal
$asked ? : 18 429 447
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
3673 447 ▶ (map { $self->_load_type(append_autotype => $_) } $append ? @{$self->{+APPEND_AUTOTYPE}} : ()),
Branch: 1 branch
BranchTrueFalseTotal
$append ? : 4 441 445
3674 );
3675  
3676 444 my $dialect = $self->{+CONNECTION}->dialect;
3677 444 for my $table (values %{$map->tables}) {
3678 1011 for my $name (keys %{$table->{fields}}) {
3679 2920 my $field = $table->{fields}->{$name};
3680 2920 delete $field->{orm_type};
3681 2920 ▶ next if ($field->{db_type} // '') =~ m/\[\d*\]\z/;
Branch: 1 branch
BranchTrueFalseTotal
if ($field->{"db_type"} // "") =~ /\[\d*\]\z/ 0 2920 2920
Condition100%2/2
$field->{"db_type"} // ""
l!l
29191
MC/DC100%1/1
$field->{"db_type"} // ""
$field->{"db_type"}
Truth table100%2/2
A
A= $field->{"db_type"}
Aresult
11
00
3682  
3683 2920 ▶ 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) 244 7997 8241
Condition100%8/8
$_->[1]{$field->{'type'} // ''} || $_->[2] && $_->[0]->matches($name, $field, $dialect)
l!l&&r!l&&!r
244767921
$field->{"type"} // ""
l!l
82401
$_->[2] and $_->[0]->matches($name, $field, $dialect)
!ll&&!rl&&r
2553536876
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
3684 2920 ▶ $field->{orm_type} = $type->[0] if $type;
Branch: 1 branch
BranchTrueFalseTotal
if $type 320 2600 2920
3685 }
3686 }
3687 }
3688  
3689 =pod
3690  
3691 =over 4
3692  
3693 =item $orm->_apply_types($map)
3694  
3695 Applies C<types>, loading each type it names. A named field gets the type in
3696 place of any autotype, or none for undef. Its C<format> and C<generate> hints
3697 become the ones given (none for the plain form).
3698  
3699 Then C<type_options> fills each hint a field of that type lacks. C<format> and
3700 C<generate> fall back separately. Each type it names is loaded. A field left
3701 with a hint but no type croaks.
3702  
3703 =back
3704  
3705 =cut
3706  
3707 403 ▶sub _apply_types {
Subroutine _apply_types: called CC=23 SCAR=31.4
3708 403 my $self = shift;
3709 403 my ($map) = @_;
3710  
3711 my %hints = (
3712 14 ▶ format => ['a code reference', sub { ref($_[0]) eq 'CODE' }],
Subroutine __ANON__: called CC=1 SCAR=0.0
3713 403 ▶ 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
3714 );
3715 26 ▶ my $hint = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3716 26 my ($arg, $name, $value) = @_;
3717 26 ▶ croak "'$arg' needs $hints{$name}->[0] for '$name'" unless $hints{$name}->[1]->($value);
Branch: 1 branch
BranchTrueFalseTotal
unless $hints{$name}[1]->($value) 4 22 26
3718 22 return $value;
3719 403 };
3720  
3721 403 ▶ 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" 116 18 134
3722 403 my $types = $self->_table_arg($map, TYPES(), 'a hashref of table => {field => type, undef, or {class => type, format => code, generate => mode}}', $HASH_OF->($spec));
3723 400 for my $table (sort keys %$types) {
3724 105 my $fields = $types->{$table};
3725 105 $self->_check_fields($map, TYPES(), $table, sort keys %$fields);
3726  
3727 104 for my $name (keys %$fields) {
3728 131 my $field = $map->field($table, $name);
3729 131 ▶ my $given = ref($fields->{$name}) ? $fields->{$name} : {class => $fields->{$name}};
Branch: 1 branch
BranchTrueFalseTotal
ref $fields->{$name} ? : 18 113 131
3730 131 ▶ my @bad = sort grep { $_ ne 'class' && !$hints{$_} } keys %$given;
Condition100%3/3
$_ ne 'class' && !$hints{$_}
!ll&&!rl&&r
125161
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
3731 131 ▶ 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 130 131
3732  
3733 130 for my $h (sort keys %hints) {
3734 259 delete $field->{$h};
3735 259 ▶ $field->{$h} = $hint->(TYPES(), $h, $given->{$h}) if exists $given->{$h};
Branch: 1 branch
BranchTrueFalseTotal
if exists $given->{$h} 16 243 259
3736 }
3737 128 ▶ next unless exists $given->{class};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $given->{"class"} 5 123 128
3738 123 delete $field->{orm_type};
3739 123 ▶ $field->{orm_type} = $self->require_type($given->{class}, TYPES()) if defined $given->{class};
Branch: 1 branch
BranchTrueFalseTotal
if defined $given->{"class"} 118 5 123
3740 }
3741 }
3742  
3743 394 ▶ my $options = $self->{+TYPE_OPTIONS} // {};
Condition100%2/2
$self->{"type_options"} // {}
l!l
13381
MC/DC100%1/1
$self->{"type_options"} // {}
$self->{"type_options"}
Truth table100%2/2
A
A= $self->{"type_options"}
Aresult
11
00
3744 394 ▶ 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 393 394
3745  
3746 393 my %by_type;
3747 393 for my $type (sort keys %$options) {
3748 12 my @bad = sort grep { !$hints{$_} } keys %{$options->{$type}};
3749 12 ▶ croak "'type_options' gives the type '$type' the unknown key(s): " . join(', ' => @bad) if @bad;
Branch: 1 branch
BranchTrueFalseTotal
if @bad 1 11 12
3750 11 my $class = $self->require_type($type, TYPE_OPTIONS());
3751 10 $by_type{$class}{$_} = $hint->(TYPE_OPTIONS(), $_, $options->{$type}->{$_}) for grep { exists $options->{$type}->{$_} } sort keys %hints;
3752 }
3753  
3754 389 for my $table (sort keys %{$map->tables}) {
3755 940 my $fields = $map->table($table)->{fields};
3756 940 for my $name (sort keys %$fields) {
3757 2755 my $field = $fields->{$name};
3758 2755 for my $h (sort keys %hints) {
3759 5508 ▶ my $value = $by_type{$field->{orm_type} // ''}{$h};
Condition100%2/2
$field->{"orm_type"} // ""
l!l
8344674
MC/DC100%1/1
$field->{"orm_type"} // ""
$field->{"orm_type"}
Truth table100%2/2
A
A= $field->{"orm_type"}
Aresult
11
00
3760 5508 ▶ $field->{$h} //= $value if defined $value;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 23 5485 5508
Condition66%2/3
$field->{$h} //= $value
l!l&&r!l&&!r
4190
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
3761 5508 ▶ next unless defined($field->{$h}) && !$field->{orm_type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $field->{$h} and not $field->{"orm_type"} 5505 3 5508
Condition100%3/3
defined $field->{$h} and not $field->{"orm_type"}
!ll&&!rl&&r
5475303
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
3762 3 croak "The field '$name' of the table '$table' has a $h but no type; a $h applies only to a typed field";
3763 }
3764 }
3765 }
3766 }
3767  
3768 =pod
3769  
3770 =over 4
3771  
3772 =item $orm->_apply_fks($map)
3773  
3774 Applies C<fks>: adds each link to the table's foreign keys, through C<_add_fk>.
3775  
3776 =back
3777  
3778 =cut
3779  
3780 386 ▶sub _apply_fks {
Subroutine _apply_fks: called CC=5 SCAR=16.1
3781 386 my $self = shift;
3782 386 my ($map) = @_;
3783  
3784 25 ▶ my $links = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3785 25 ▶ ref($_[0]) eq 'ARRAY' && !grep { !$LINK->($_) } @{$_[0]};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq "ARRAY" and not grep({not &$LINK($_);} @{$_[0];}) 24 1 25
3786 386 };
3787 386 my $fks = $self->_table_arg($map, FKS(), 'a hashref of table => {table => [{field => field}]}', $HASH_OF->($links));
3788  
3789 383 for my $table (sort keys %$fks) {
3790 21 for my $other (sort keys %{$fks->{$table}}) {
3791 22 ▶ 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 21 22
3792  
3793 21 for my $link (@{$fks->{$table}->{$other}}) {
3794 24 $self->_check_fields($map, FKS(), $table, sort keys %$link);
3795 23 $self->_check_fields($map, FKS(), $other, sort values %$link);
3796 22 $self->_add_fk($map, $table, $other, $link);
3797 }
3798 }
3799 }
3800 }
3801  
3802 =pod
3803  
3804 =over 4
3805  
3806 =item $orm->_apply_pks($map)
3807  
3808 Applies C<pks>: sets the primary key of each named view, or of a table the
3809 database reports no primary key for. Croaks for a table that has one and for a
3810 field the table or view lacks.
3811  
3812 =back
3813  
3814 =cut
3815  
3816 379 ▶sub _apply_pks {
Subroutine _apply_pks: called CC=6 SCAR=18.0
3817 379 my $self = shift;
3818 379 my ($map) = @_;
3819 379 my $pks = $self->_table_arg($map, PKS(), 'a hashref of table or view => [fields]', $STR_LIST);
3820 378 for my $name (sort keys %$pks) {
3821 12 my $record = $map->table($name);
3822 12 ▶ croak "'pks' gives '$name' no fields" unless @{$pks->{$name}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$pks->{$name};} 0 12 12
3823 2 croak "'pks' names the table '$name', which has a primary key (" . join(', ' => @{$record->{pk}}) . "), so 'pk' cannot declare one"
3824 12 ▶ if !$record->{view} && $record->{pk} && @{$record->{pk}};
Branch: 1 branch
BranchTrueFalseTotal
if not $record->{"view"} and $record->{"pk"} and @{$record->{"pk"};} 2 10 12
Condition83%5/6
not $record->{"view"} and $record->{"pk"} and @{$record->{"pk"};}
!ll&&!rl&&r
1002
not $record->{"view"} and $record->{"pk"}
!ll&&!rl&&r
822
MC/DC66%2/3
not $record->{"view"} and $record->{"pk"} and @{$record->{"pk"};}
not $record->{"view"} $record->{"pk"} @{$record->{"pk"};}
Truth table75%3/4
not(A) and B and C
A= not $record->{"view"}B= $record->{"pk"}C= @{$record->{"pk"};}
ABCresult
0XX0
10X0
1100
1111
3825 10 $self->_check_fields($map, PKS(), $name, @{$pks->{$name}});
3826 9 $map->table($name)->{pk} = [@{$pks->{$name}}];
3827 }
3828 }
3829  
3830 =pod
3831  
3832 =over 4
3833  
3834 =item $orm->_apply_default_fields($map)
3835  
3836 Applies C<omit> and C<default_fields>, setting each named table's default
3837 fields, with the croaks C<new> lists, then C<auto_omit> on the other tables.
3838  
3839 =back
3840  
3841 =cut
3842  
3843 375 ▶sub _apply_default_fields {
Subroutine _apply_default_fields: called CC=24 SCAR=31.8
3844 375 my $self = shift;
3845 375 my ($map) = @_;
3846  
3847 375 my $omit = $self->_table_arg($map, OMIT(), 'a hashref of table => [fields]', $STR_LIST);
3848 374 my $fields = $self->_table_arg($map, DEFAULT_FIELDS(), 'a hashref of table => [fields]', $STR_LIST);
3849  
3850 372 my @both = sort grep { exists $fields->{$_} } keys %$omit;
3851 372 ▶ croak "'omit' and 'default_fields' both name the table(s): " . join(', ' => @both) if @both;
Branch: 1 branch
BranchTrueFalseTotal
if @both 1 371 372
3852  
3853 371 for my $table (sort keys %$omit) {
3854 27 $self->_check_fields($map, OMIT(), $table, @{$omit->{$table}});
3855  
3856 26 my %omit = map { $_ => 1 } @{$omit->{$table}};
3857 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
3858 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
3859  
3860 25 $self->_set_default_fields($map, OMIT(), $table, grep { !$omit{$_} } keys %{$map->table($table)->{fields}});
3861 }
3862  
3863 368 for my $table (sort keys %$fields) {
3864 17 $self->_check_fields($map, DEFAULT_FIELDS(), $table, @{$fields->{$table}});
3865 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
3866 }
3867  
3868 367 ▶ my $auto = $self->{+AUTO_OMIT} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $auto = $self->{"auto_omit"} or return 10 357 367
3869 10 ▶ my @classes = map { $self->require_type($_, 'auto_omit') } @{$auto->{types} // []};
Condition100%2/2
$auto->{"types"} // []
l!l
82
MC/DC100%1/1
$auto->{"types"} // []
$auto->{"types"}
Truth table100%2/2
A
A= $auto->{"types"}
Aresult
11
00
3870 9 my $dialect = $self->{+CONNECTION}->dialect;
3871 9 ▶ my %db = map { (($dialect->_base_type($_))[0] => 1) } @{$auto->{db_types} // []};
Condition100%2/2
$auto->{"db_types"} // []
l!l
27
MC/DC100%1/1
$auto->{"db_types"} // []
$auto->{"db_types"}
Truth table100%2/2
A
A= $auto->{"db_types"}
Aresult
11
00
3872  
3873 9 ▶ for my $table (sort grep { !exists($omit->{$_}) && !exists($fields->{$_}) } keys %{$map->tables}) {
Condition100%3/3
exists $omit->{$_} || exists $fields->{$_}
l!l&&r!l&&!r
2133
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
3874 33 my $t = $map->table($table);
3875 33 ▶ next if $t->{default_fields}; # a given db_map's own
Branch: 1 branch
BranchTrueFalseTotal
if $t->{"default_fields"} 0 33 33
3876 33 ▶ 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"} // [];} 9 24 33
Condition100%2/2
$t->{"pk"} // []
l!l
249
MC/DC100%1/1
$t->{"pk"} // []
$t->{"pk"}
Truth table100%2/2
A
A= $t->{"pk"}
Aresult
11
00
3877  
3878 24 ▶ my %key = map { $_ => 1 } @{$t->{pk}}, map { @$_ } @{$t->{unique} // []};
Condition50%1/2
$t->{"unique"} // []
l!l
240
MC/DC0%0/1
$t->{"unique"} // []
$t->{"unique"}
Truth table50%1/2
A
A= $t->{"unique"}
Aresult
11
00
3879 24 ▶ for my $links (values %{$t->{fk} // {}}) {
Condition50%1/2
$t->{"fk"} // {}
l!l
240
MC/DC0%0/1
$t->{"fk"} // {}
$t->{"fk"}
Truth table50%1/2
A
A= $t->{"fk"}
Aresult
11
00
3880 9 $key{$_} = 1 for map { keys %$_ } @$links;
3881 }
3882  
3883 my @out = grep {
3884 81 my $field = $t->{fields}->{$_};
3885 81 my $type = $field->{orm_type};
3886 81 ▶ !$key{$_} && ($db{$field->{type} // ''} || ($type && grep { $type->isa($_) } @classes));
Condition90%10/11
!$key{$_} && ($db{$field->{'type'} // ''} || $type && grep({$type->isa($_);} @classes))
!ll&&!rl&&r
422613
$db{$field->{"type"} // ""} or $type and grep {$type->isa($_);} @classes
l!l&&r!l&&!r
5826
$field->{"type"} // ""
l!l
390
$type and grep {$type->isa($_);} @classes
!ll&&!rl&&r
2428
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
3887 24 } keys %{$t->{fields}};
3888 24 ▶ next unless @out;
Branch: 1 branch
BranchTrueFalseTotal
unless @out 12 12 24
3889  
3890 12 my %out = map { $_ => 1 } @out;
3891 12 $self->_set_default_fields($map, AUTO_OMIT(), $table, grep { !$out{$_} } keys %{$t->{fields}});
3892 }
3893 }
3894  
3895 =pod
3896  
3897 =over 4
3898  
3899 =item $orm->_apply_row_classes($map)
3900  
3901 Applies C<row_classes>, then C<row_namespace> to each table left without a
3902 row class (through C<_namespace_class>, and a class found there must do
3903 L<DBIx::QuickORM::Role::Row>), then loads every row class the map
3904 names and the ORM's C<row_class>, unless the class already has a C<new>.
3905  
3906 =back
3907  
3908 =cut
3909  
3910 366 ▶sub _apply_row_classes {
Subroutine _apply_row_classes: called CC=9 SCAR=22.0
3911 366 my $self = shift;
3912 366 my ($map) = @_;
3913  
3914 366 my $classes = $self->_table_arg($map, ROW_CLASSES(), 'a hashref of table => class name or undef', $OPT_STR);
3915 364 $map->table($_)->{row_class} = $classes->{$_} for keys %$classes;
3916  
3917 364 ▶ if (defined(my $ns = $self->{+ROW_NAMESPACE})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $ns = $self->{"row_namespace"})) 9 355 364
3918 9 for my $name (grep { !exists $map->table($_)->{row_class} } sort keys %{$map->tables}) {
3919 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
3920 28 my $what = "'row_namespace' gives the table '$name' the row class '$class', which";
3921 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
3922 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
3923 6 $map->table($name)->{row_class} = $class;
3924 }
3925 }
3926  
3927 361 $self->load_row_class($_) for grep { defined } $self->{+ROW_CLASS}, map { $_->{row_class} } values %{$map->tables};
3928 }
3929  
3930 =pod
3931  
3932 =over 4
3933  
3934 =item $class = $orm->_namespace_class($namespace, $table)
3935  
3936 The table's row class under C<row_namespace>: the namespace and the part
3937 C<row_class_name> gives for the table, or by default each C<_>-separated part
3938 of the name with its first letter upper-cased, joined.
3939  
3940 Undef when the part is undef. Warns and returns undef when the part is not an
3941 identifier.
3942  
3943 =back
3944  
3945 =cut
3946  
3947 27 ▶my $DEFAULT_ROW_CLASS_NAME = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
3948 27 join '' => map { ucfirst } split /_/ => $_[0];
3949 258 };
3950  
3951 34 ▶sub _namespace_class {
Subroutine _namespace_class: called CC=4 SCAR=13.9
3952 34 my $self = shift;
3953 34 my ($ns, $table) = @_;
3954 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
3955 34 ▶ return undef unless defined $part;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part 3 31 34
3956 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
3957 3 carp "'row_namespace' skips the table '$table': '$part' is not a valid class name part";
3958 3 return undef;
3959 }
3960  
3961 =pod
3962  
3963 =over 4
3964  
3965 =item $orm->_apply_key_types($map)
3966  
3967 Records each table's C<pk_types> (see L<DBIx::QuickORM::Map>) when a primary
3968 key field has a type. Croaks when such a type has no
3969 C<canonical_key_value>, and when a field whose type can generate values has
3970 C<< generate => 'prefer_orm' >> on a column the database refuses values for.
3971  
3972 =back
3973  
3974 =cut
3975  
3976 409 ▶sub _apply_key_types {
Subroutine _apply_key_types: called CC=10 SCAR=23.0
3977 409 my $self = shift;
3978 409 my ($map) = @_;
3979  
3980 409 for my $name (keys %{$map->tables}) {
3981 863 my $table = $map->table($name);
3982 863 delete $table->{pk_types};
3983 863 ▶ my @types = map { $table->{fields}->{$_}->{orm_type} } @{$table->{pk} // []};
Condition100%2/2
$table->{"pk"} // []
l!l
762101
MC/DC100%1/1
$table->{"pk"} // []
$table->{"pk"}
Truth table100%2/2
A
A= $table->{"pk"}
Aresult
11
00
3984 863 ▶ next unless grep { defined } @types;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {defined $_;} @types 767 96 863
3985  
3986 96 for my $i (grep { defined $types[$_] } 0 .. $#types) {
3987 106 my $field = $table->{pk}->[$i];
3988 106 my $rec = $table->{fields}->{$field};
3989 106 ▶ 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 104 106
3990 unless $types[$i]->can('canonical_key_value');
3991 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'"
3992 104 ▶ 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 102 104
Condition100%8/8
($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"} and $types[$i]->can("generate_key_value")
!ll&&!rl&&r
10112
($rec->{"generate"} // "") eq "prefer_orm" and $rec->{"db_refuses_value"}
!ll&&!rl&&r
10013
$rec->{"generate"} // ""
l!l
1391
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
3993 }
3994 92 $table->{pk_types} = \@types;
3995 }
3996 }
3997  
3998 =pod
3999  
4000 =over 4
4001  
4002 =item $orm->_apply_passthrough($map)
4003  
4004 Sets C<passthrough> on each typed field whose type's C<inflate_is_identity> is
4005 true for that field, and removes it from every other field.
4006  
4007 =back
4008  
4009 =cut
4010  
4011 405 ▶sub _apply_passthrough {
Subroutine _apply_passthrough: called CC=6 SCAR=17.9
4012 405 my $self = shift;
4013 405 my ($map) = @_;
4014  
4015 405 for my $table (values %{$map->tables}) {
4016 855 for my $field (values %{$table->{fields}}) {
4017 2456 delete $field->{passthrough};
4018 2456 ▶ my $type = $field->{orm_type} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $type = $field->{"orm_type"} or next 414 2042 2456
4019 414 ▶ $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) 70 344 414
Condition100%3/3
$type->can("inflate_is_identity") and $type->inflate_is_identity($field)
!ll&&!rl&&r
8126370
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
4020 }
4021 }
4022 }
4023  
4024 =pod
4025  
4026 =over 4
4027  
4028 =item \%arg = $orm->_table_arg($map, $name, $want, \&check)
4029  
4030 The named argument, or an empty hash when it was not given. Croaks unless it
4031 is a hashref whose values pass C<check> (C<$want> describes the shape), or
4032 when it names a table not in the map.
4033  
4034 =back
4035  
4036 =cut
4037  
4038 2283 ▶sub _table_arg {
Subroutine _table_arg: called CC=5 SCAR=16.1
4039 2283 my $self = shift;
4040 2283 my ($map, $arg, $want, $check) = @_;
4041  
4042 2283 ▶ return {} unless exists $self->{$arg};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{$arg} 2083 200 2283
4043  
4044 200 my $value = $self->{$arg};
4045 200 ▶ croak "'$arg' must be $want" unless $HASH_OF->($check)->($value);
Branch: 1 branch
BranchTrueFalseTotal
unless &$HASH_OF($check)->($value) 6 194 200
4046  
4047 194 for my $table (sort keys %$value) {
4048 225 ▶ 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) 6 219 225
4049 }
4050  
4051 188 return $value;
4052 }
4053  
4054 =pod
4055  
4056 =over 4
4057  
4058 =item $orm->_check_fields($map, $name, $table, @fields)
4059  
4060 Croaks for the first field not in the table.
4061  
4062 =back
4063  
4064 =cut
4065  
4066 206 ▶sub _check_fields {
Subroutine _check_fields: called CC=3 SCAR=11.0
4067 206 my $self = shift;
4068 206 my ($map, $arg, $table, @fields) = @_;
4069  
4070 206 for my $field (@fields) {
4071 233 ▶ 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) 5 228 233
4072 }
4073 }
4074  
4075 =pod
4076  
4077 =over 4
4078  
4079 =item $class = $orm->_lookup_class($name)
4080  
4081 The full class name for the C<lookup> argument. The Connection loads it and
4082 checks its role.
4083  
4084 =item $class = $orm->_type_class($type)
4085  
4086 The full class name for a type name.
4087  
4088 =back
4089  
4090 =cut
4091  
4092 9 ▶sub _lookup_class {
Subroutine _lookup_class: called CC=2 SCAR=6.9
4093 9 my $self = shift;
4094 9 my ($name) = @_;
4095  
4096 9 ▶ return $name =~ m/^\+(.+)$/ ? $1 : "DBIx::QuickORM::LookupTable::$name";
Branch: 1 branch
BranchTrueFalseTotal
$name =~ /^\+(.+)$/ ? : 4 5 9
4097 }
4098  
4099 1479 ▶sub _type_class {
Subroutine _type_class: called CC=3 SCAR=11.0
4100 1479 my $self = shift;
4101 1479 my ($type) = @_;
4102  
4103 1479 ▶ my $class = $type =~ m/^\+(.+)$/ ? $1 : "DBIx::QuickORM::Type::$type";
Branch: 1 branch
BranchTrueFalseTotal
$type =~ /^\+(.+)$/ ? : 89 1390 1479
4104 1479 ▶ croak "'$type' is not a valid type name" unless $class =~ m/^\w+(?:::\w+)*$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $class =~ /^\w+(?:::\w+)*$/ 2 1477 1479
4105  
4106 1477 return $class;
4107 }
4108  
4109 =pod
4110  
4111 =over 4
4112  
4113 =item $orm->_require_map_types($map)
4114  
4115 Loads every type a given map names.
4116  
4117 =back
4118  
4119 =cut
4120  
4121 13 ▶sub _require_map_types {
Subroutine _require_map_types: called CC=3 SCAR=11.0
4122 13 my $self = shift;
4123 13 my ($map) = @_;
4124  
4125 13 for my $table (values %{$map->tables}) {
4126 36 $self->require_type("+$_->{orm_type}", 'db_map') for grep { defined $_->{orm_type} } values %{$table->{fields}};
4127 }
4128 }
4129  
4130 =pod
4131  
4132 =over 4
4133  
4134 =item [$class, \%base_types, $has_matches] = $orm->_load_type($arg, $type)
4135  
4136 Loads an autotype for C<_autotype>: its class, its C<base_types> as a set, and
4137 whether it has C<matches>. Croaks naming the argument when the type cannot be
4138 loaded, or has neither.
4139  
4140 =back
4141  
4142 =cut
4143  
4144 1304 ▶sub _load_type {
Subroutine _load_type: called CC=5 SCAR=16.1
4145 1304 my $self = shift;
4146 1304 my ($arg, $type) = @_;
4147  
4148 1304 my $class = $self->require_type($type, $arg);
4149  
4150 1302 ▶ my $matches = $class->can('matches') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$class->can('matches') ? : 863 439 1302
4151 1302 ▶ 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 1301 1302
Condition100%3/3
$matches or $class->can("base_types")
l!l&&r!l&&!r
8634381
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
4152  
4153 1301 ▶ my %base_types = map { $_ => 1 } $class->can('base_types') ? $class->base_types : ();
Branch: 1 branch
BranchTrueFalseTotal
$class->can('base_types') ? : 1296 5 1301
4154 1301 return [$class, \%base_types, $matches];
4155 }
4156  
4157 =pod
4158  
4159 =over 4
4160  
4161 =item $orm->_add_fk($map, $table, $other, \%link)
4162  
4163 Adds a foreign key from the table to the other one, unless the table already
4164 has the same link. Croaks when it has a link on the same fields that points at
4165 different fields of the other table.
4166  
4167 =back
4168  
4169 =cut
4170  
4171 22 ▶sub _add_fk {
Subroutine _add_fk: called CC=5 SCAR=16.1
4172 22 my $self = shift;
4173 22 my ($map, $table, $other, $link) = @_;
4174  
4175 22 my $ours = join "\0" => sort keys %$link;
4176 22 ▶ my $known = $map->table($table)->{fk}->{$other} //= [];
Condition100%2/2
$map->table($table)->{"fk"}{$other} //= []
l!l
517
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
4177  
4178 22 for my $have (@$known) {
4179 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
4180 2 ▶ return unless grep { $have->{$_} ne $link->{$_} } keys %$link;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$have->{$_} ne $link->{$_};} keys %$link 1 1 2
4181 1 croak "'fks' gives the table '$table' a foreign key to '$other' on (" . join(', ' => sort keys %$link) . ") that differs from the one it has";
4182 }
4183  
4184 20 push @$known => {%$link};
4185 }
4186  
4187 =pod
4188  
4189 =over 4
4190  
4191 =item $orm->_set_default_fields($map, $arg, $table, @fields)
4192  
4193 Sets the table's default fields to C<@fields>, sorted and without duplicates.
4194 Croaks naming the argument when C<@fields> is empty.
4195  
4196 =back
4197  
4198 =cut
4199  
4200 54 ▶sub _set_default_fields {
Subroutine _set_default_fields: called CC=2 SCAR=6.9
4201 54 my $self = shift;
4202 54 my ($map, $arg, $table, @fields) = @_;
4203  
4204 54 my %seen;
4205 54 @fields = sort grep { !$seen{$_}++ } @fields;
4206 54 ▶ croak "'$arg' leaves no fields to select from the table '$table'" unless @fields;
Branch: 1 branch
BranchTrueFalseTotal
unless @fields 2 52 54
4207  
4208 52 $map->table($table)->{default_fields} = \@fields;
4209 }
4210  
4211 258 1;
4212  
4213 __END__
« blib/lib/DBIx/QuickORM/Source/Join.pm ↑ Summary blib/lib/DBIx/QuickORM/Row.pm »