blib/lib/DBIx/QuickORM.pm

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