NinjaORM.pm

filter: Statementstmt 67.4% 457 / 678 Branchbran 50.0% 189 / 378 Conditioncond 46.8% 90 / 192 MC/DCmcdc 25.2% 29 / 115 Subroutinesub 84.8% 56 / 66 Podpod 100% 43 / 43 totaltotal 58.7% 864 / 1472 CC 285 SCAR 57.8
CC
285
Cov
59%
retrieve_list_cache
1892.0
retrieve_list_nocache
423.8
get_object_cache_key
156.0
CRAP 323.4
↑ Summary NinjaORM/Schema/Table.pm »
1 package DBIx::NinjaORM;
2  
3 69 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 69 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 69 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 69 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 69 ▶use Class::Load qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 69 ▶use DBIx::NinjaORM::StaticClassInfo;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 69 ▶use DBIx::NinjaORM::Utils qw( dumper );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 69 ▶use Data::Validate::Type;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 69 ▶use Digest::SHA1 qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
14 69 ▶use Log::Any qw( $log );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 69 ▶use MIME::Base64 qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 69 ▶use Storable;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 69 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19  
20 =head1 NAME
21  
22 DBIx::NinjaORM - Flexible Perl ORM for easy transitions from inline SQL to objects.
23  
24  
25 =head1 VERSION
26  
27 Version 3.1.0
28  
29 =cut
30  
31 69 our $VERSION = '3.1.0';
32  
33  
34 =head1 DESCRIPTION
35  
36 L<DBIx::NinjaORM> was designed with a few goals in mind:
37  
38 =over 4
39  
40 =item *
41  
42 Expand objects with data joined from other tables, to do less queries and
43 prevent lazy-loading of ancillary information.
44  
45 =item *
46  
47 Have a short learning curve.
48  
49 =item *
50  
51 Provide advanced caching features and manage cache expiration upon database changes.
52  
53 =item *
54  
55 Allow a progressive introduction of a separate Model layer in a legacy codebase.
56  
57 =back
58  
59  
60 =head1 SYNOPSIS
61  
62 =head2 Simple example
63  
64 Let's take the example of a C<My::Model::Book> class that represents a book. You
65 would start C<My::Model::Book> with the following code:
66  
67 package My::Model::Book;
68  
69 use strict;
70 use warnings;
71  
72 use base 'DBIx::NinjaORM';
73  
74 use DBI;
75  
76  
77 sub static_class_info
78 {
79 my ( $class ) = @_;
80  
81 # Retrieve defaults from DBIx::Ninja->static_class_info().
82 my $info = $class->SUPER::static_class_info();
83  
84 $info->set(
85 {
86 # Set mandatory defaults.
87 table_name => 'books',
88 primary_key_name => 'book_id',
89 default_dbh => DBI->connect(
90 "dbi:mysql:[database_name]:localhost:3306",
91 "[user]",
92 "[password]",
93 ),
94  
95 # Add optional information.
96 # Allow filtering SELECTs on books.name.
97 filtering_fields => [ 'name' ],
98 }
99 );
100  
101 return $info;
102 }
103  
104 1;
105  
106 Inheriting with C<use base 'DBIx::NinjaORM'> and creating
107 C<sub static_class_info> (with a default database handle and a table name)
108 are the only two requirements to have a working model.
109  
110  
111 =head2 A more complex model
112  
113 If you have more than one Model class to create, for example C<My::Model::Book>
114 and C<My::Model::Library>, you probably want to create a single class
115 C<My::Model> to hold the defaults and then inherits from that main class.
116  
117 package My::Model;
118  
119 use strict;
120 use warnings;
121  
122 use base 'DBIx::NinjaORM';
123  
124 use DBI;
125 use Cache::Memcached::Fast;
126  
127  
128 sub static_class_info
129 {
130 my ( $class ) = @_;
131  
132 # Retrieve defaults from DBIx::Ninja->static_class_info().
133 my $info = $class->SUPER::static_class_info();
134  
135 # Set defaults common to all your objects.
136 $info->set(
137 {
138 default_dbh => DBI->connect(
139 "dbi:mysql:[database_name]:localhost:3306",
140 "[user]",
141 "[password]",
142 ),
143 memcache => Cache::Memcached::Fast->new(
144 {
145 servers =>
146 [
147 'localhost:11211',
148 ],
149 }
150 ),
151 }
152 );
153  
154 return $info;
155 }
156  
157 1;
158  
159 The various classes will then inherit from C<My::Model>, and the inherited
160 defaults will make C<static_class_info()> shorter in the other classes:
161  
162 package My::Model::Book;
163  
164 use strict;
165 use warnings;
166  
167 # Inherit from your base model class, not from DBIx::NinjaORM.
168 use base 'My::Model';
169  
170 sub static_class_info
171 {
172 my ( $class ) = @_;
173  
174 # Retrieve defaults from My::Model.
175 my $info = $class->SUPER::static_class_info();
176  
177 $info->set(
178 {
179 # Set mandatory defaults for this class.
180 table_name => 'books',
181 primary_key_name => 'book_id',
182  
183 # Add optional information.
184 # Allow filtering SELECTs on books.name.
185 filtering_fields => [ 'name' ],
186 }
187 );
188  
189 return $info;
190 }
191  
192 1;
193  
194 =cut
195  
196 # This hash indicates what argument names are valid in retrieve_list() calls,
197 # and for each argument it specifies whether it should be included (1) or
198 # ignored (0) when building the list cache keys that associate the arguments
199 # passed to the result IDs.
200 69 our $RETRIEVE_LIST_VALID_ARGUMENTS =
201 {
202 allow_all => 1,
203 dbh => 0,
204 limit => 1,
205 lock => 0,
206 order_by => 1,
207 pagination => 1,
208 query_extensions => 1,
209 show_queries => 0,
210 skip_cache => 0,
211 exclude_fields => 0,
212 select_fields => 0,
213 };
214  
215  
216 =head1 SUPPORTED DATABASES
217  
218 This distribution currently supports:
219  
220 =over 4
221  
222 =item * SQLite
223  
224 =item * MySQL
225  
226 =item * PostgreSQL
227  
228 =back
229  
230 Please contact me if you need support for another database type, I'm always
231 glad to add extensions if you can help me with testing.
232  
233  
234 =head1 SUBCLASSABLE METHODS
235  
236 L<DBIx::NinjaORM> is designed with inheritance in mind, and you can subclass
237 most of its public methods to extend or alter its behavior.
238  
239 This group of method covers the most commonly subclassed methods, with examples
240 and use cases.
241  
242  
243 =head2 clone()
244  
245 Clone the current object and return the clone.
246  
247 my $cloned_book = $book->clone();
248  
249 =cut
250  
251 sub clone
252 1 ▶{
Subroutine clone: called CC=1 SCAR=0.0
Pod documented
253 1 my ( $self ) = @_;
254  
255 1 return Storable::dclone( $self );
256 }
257  
258  
259 =head2 commit()
260  
261 Convenience function to insert or update the object.
262  
263 If the object has a primary key set, C<update()> is called, otherwise
264 C<insert()> is called. If there's an error, the method with croak with
265 relevant error information.
266  
267 $book->commit();
268  
269 Arguments: (none).
270  
271 =cut
272  
273 sub commit
274 2 ▶{
Subroutine commit: called CC=2 SCAR=6.9
Pod documented
275 2 my ( $self ) = @_;
276 2 my $data = Storable::dclone( $self );
277  
278 2 ▶ if ( defined( $self->id() ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->id) { } 1 1 2
279 {
280 # If id() is defined, we have a value for the primary key name
281 # and we need to delete it from the data to update.
282 1 my $primary_key_name = $self->get_info('primary_key_name');
283 1 delete( $data->{ $primary_key_name } );
284  
285 1 return $self->update( $data );
286 }
287 else
288 {
289 1 return $self->insert( $data );
290 }
291 }
292  
293  
294 =head2 get()
295  
296 Get the value corresponding to an object's field.
297  
298 my $book_name = $book->get('name');
299  
300 This method will croak if you attempt to retrieve a private field. It also
301 detects if the object was retrieved from the database, in which case it
302 has an exhaustive list of the fields that actually exist in the database and
303 it will croak if you attempt to retrieve a field that doesn't exist in the
304 database.
305  
306 =cut
307  
308 sub get
309 57 ▶{
Subroutine get: called CC=7 SCAR=19.5
Pod documented
310 57 my ( $self, $field_name ) = @_;
311  
312 57 ▶ croak "The name of the field to retrieve must be defined"
Branch: 1 branch
BranchTrueFalseTotal
if not defined $field_name or $field_name eq "" 2 55 57
Condition100%3/3
not defined $field_name or $field_name eq ""
l!l&&r!l&&!r
1155
MC/DC100%2/2
not defined $field_name or $field_name eq ""
not defined $field_name $field_name eq ""
Truth table100%3/3
not(A) or B
A= not defined $field_nameB= $field_name eq ""
ABresult
1X1
011
000
313 if !defined( $field_name ) || ( $field_name eq '' );
314  
315 # Create your own accessor for private properties.
316 55 ▶ croak 'Cannot retrieve the value of a private object property, create an accessor on the class if you need this value'
Branch: 1 branch
BranchTrueFalseTotal
if substr($field_name, 0, 1) eq "_" 1 54 55
317 if substr( $field_name, 0, 1 ) eq '_';
318  
319 # If the object was not populated by retrieve_list(), we know that the keys
320 # on the object correspond to all the columns in the database and we can then
321 # actively show errors in the log if the caller is requesting a field for
322 # which the key doesn't exist.
323 54 ▶ my $populated_by_retrieve_list = $self->{'_populated_by_retrieve_list'} // 0;
Condition100%2/2
$self->{"_populated_by_retrieve_list"} // 0
l!l
531
MC/DC100%1/1
$self->{"_populated_by_retrieve_list"} // 0
$self->{"_populated_by_retrieve_list"}
Truth table100%2/2
A
A= $self->{"_populated_by_retrieve_list"}
Aresult
11
00
324 croak "The property '$field_name' does not exist on the object"
325 54 ▶ if $populated_by_retrieve_list && !exists( $self->{ $field_name } );
Branch: 1 branch
BranchTrueFalseTotal
if $populated_by_retrieve_list and not exists $self->{$field_name} 0 54 54
Condition66%2/3
$populated_by_retrieve_list and not exists $self->{$field_name}
!ll&&!rl&&r
1530
MC/DC0%0/2
$populated_by_retrieve_list and not exists $self->{$field_name}
$populated_by_retrieve_list not exists $self->{$field_name}
Truth table66%2/3
A and not(B)
A= $populated_by_retrieve_listB= not exists $self->{$field_name}
ABresult
0X0
100
111
326  
327 54 return $self->{ $field_name };
328 }
329  
330  
331 =head2 get_current_time()
332  
333 Return the current time, to use in SQL statements.
334  
335 my $current_time = $class->get_current_time( $field_name );
336  
337 By default, DBIx::NinjaORM assumes that time is stored as unixtime (integer) in the database. If you are using a different field type for C<created> and C<modified>, you can subclass this method to return the current time in a different format.
338  
339 Arguments:
340  
341 =over 4
342  
343 =item * $field_name
344  
345 The name of the field that will be populated with the return value.
346  
347 =back
348  
349 Notes:
350  
351 =over 4
352  
353 =item *
354  
355 The return value of this method will be inserted directly into the database, so
356 you can use C<NOW()> for example, and if you are inserting strings those should
357 be quoted in the subclassed method.
358  
359 =back
360  
361 =cut
362  
363 sub get_current_time
364 105 ▶{
Subroutine get_current_time: called CC=1 SCAR=0.0
Pod documented
365 105 my ( $self, $field_name ) = @_;
366  
367 105 return time();
368 }
369  
370  
371 =head2 insert()
372  
373 Insert a row corresponding to the data passed as first parameter, and fill the
374 object accordingly upon success.
375  
376 my $book = My::Model::Book->new();
377 $book->insert(
378 {
379 name => 'Learning Perl',
380 }
381 );
382  
383 If you don't need the object afterwards, you can simply do:
384  
385 My::Model::Book->insert(
386 {
387 name => 'Learning Perl',
388 }
389 );
390  
391 This method supports the following optional arguments:
392  
393 =over 4
394  
395 =item * overwrite_created
396  
397 A UNIX timestamp to be used instead of the current time for the value of
398 'created'.
399  
400 =item * generated_primary_key_value
401  
402 A primary key value, in case the underlying table doesn't have an
403 autoincremented primary key.
404  
405 =item * dbh
406  
407 A different database handle than the default one specified in
408 C<static_class_info()>, but it has to be writable.
409  
410 =item * ignore
411  
412 INSERT IGNORE instead of plain INSERT.
413  
414 =back
415  
416 $book->insert(
417 \%data,
418 overwrite_created => $unixtime,
419 generated_primary_key_value => $value,
420 dbh => $dbh,
421 ignore => $boolean,
422 );
423  
424 =cut
425  
426 sub insert ## no critic (Subroutines::RequireArgUnpacking)
427 60 ▶{
Subroutine insert: called CC=21 SCAR=31.6
Pod documented
428 60 ▶ croak 'The first argument passed must be a hashref'
Branch: 1 branch
BranchTrueFalseTotal
unless Data::Validate::Type::is_hashref($_[1]) 1 59 60
429 if !Data::Validate::Type::is_hashref( $_[1] );
430  
431 59 my ( $self, $data, %args ) = @_;
432  
433 # Allows calling Module->insert() if we don't need the object afterwards.
434 # In this case, we turn $self from a class into an object.
435 59 ▶ $self = $self->new()
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 1 58 59
436 if !ref( $self );
437  
438 # Allow using a different database handle.
439 59 my $dbh = $self->assert_dbh( $args{'dbh'} );
440  
441 # Clean input.
442 56 my $clean_data = $self->validate_data( $data, %args );
443 56 ▶ return 0
Branch: 1 branch
BranchTrueFalseTotal
unless defined $clean_data 0 56 56
444 if !defined( $clean_data );
445  
446 # Retrieve the metadata for that table.
447 56 my $class = ref( $self );
448 56 my $table_name = $self->get_info('table_name');
449 56 ▶ croak "The table name for class '$class' is not defined"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 0 56 56
450 if !defined( $table_name );
451  
452 56 my $primary_key_name = $self->get_info('primary_key_name');
453 croak "Missing primary key name for class '$class', cannot force primary key value"
454 56 ▶ if !defined( $primary_key_name ) && defined( $args{'generated_primary_key_value'} );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $primary_key_name and defined $args{"generated_primary_key_value"} 0 56 56
Condition33%1/3
not defined $primary_key_name and defined $args{"generated_primary_key_value"}
!ll&&!rl&&r
5600
MC/DC0%0/2
not defined $primary_key_name and defined $args{"generated_primary_key_value"}
not defined $primary_key_name defined $args{"generated_primary_key_value"}
Truth table33%1/3
not(A) and B
A= not defined $primary_key_nameB= defined $args{"generated_primary_key_value"}
ABresult
0X0
100
111
455  
456 # Set defaults.
457 56 ▶ if ( $self->get_info('has_created_field') )
Branch: 1 branch
BranchTrueFalseTotal
if ($self->get_info("has_created_field")) 53 3 56
458 {
459 $clean_data->{'created'} = defined( $args{'overwrite_created'} ) && $args{'overwrite_created'} ne ''
460 53 ▶ ? $args{'overwrite_created'}
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'overwrite_created'} && $args{'overwrite_created'} ne '' ? : 2 51 53
Condition66%2/3
defined $args{"overwrite_created"} and $args{"overwrite_created"} ne ""
!ll&&!rl&&r
5102
MC/DC50%1/2
defined $args{"overwrite_created"} and $args{"overwrite_created"} ne ""
defined $args{"overwrite_created"} $args{"overwrite_created"} ne ""
Truth table66%2/3
A and B
A= defined $args{"overwrite_created"}B= $args{"overwrite_created"} ne ""
ABresult
0X0
100
111
461 : $self->get_current_time();
462 }
463 56 ▶ $clean_data->{'modified'} = $self->get_current_time()
Branch: 1 branch
BranchTrueFalseTotal
if $self->get_info("has_modified_field") 53 3 56
464 if $self->get_info('has_modified_field');
465 $clean_data->{ $primary_key_name } = $args{'generated_primary_key_value'}
466 56 ▶ if defined( $args{'generated_primary_key_value'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"generated_primary_key_value"} 1 55 56
467  
468 # Prepare the query elements.
469 56 ▶ my $ignore = defined( $args{'ignore'} ) && $args{'ignore'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'ignore'} && $args{'ignore'} ? : 0 56 56
Condition33%1/3
defined $args{"ignore"} and $args{"ignore"}
!ll&&!rl&&r
5600
MC/DC0%0/2
defined $args{"ignore"} and $args{"ignore"}
defined $args{"ignore"} $args{"ignore"}
Truth table33%1/3
A and B
A= defined $args{"ignore"}B= $args{"ignore"}
ABresult
0X0
100
111
470 56 my @sql_fields = ();
471 56 my @sql_values = ();
472 56 my @placeholder_values = ();
473 56 foreach my $key ( keys %$clean_data )
474 {
475 172 push( @sql_fields, $key );
476  
477 # 'created' and 'modified' support SQL keywords, so we don't use
478 # placeholders.
479 172 ▶ if ( $key =~ /^(?:created|modified)$/x )
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /^(?:created|modified)$/x) { } 106 66 172
480 {
481 106 push( @sql_values, $clean_data->{ $key } );
482 }
483 else
484 {
485 # All the other data need to be inserted using placeholders, for
486 # security purposes.
487 66 push( @sql_values, '?' );
488 66 push( @placeholder_values, $clean_data->{ $key } );
489 }
490 }
491  
492 56 ▶ my $query = sprintf(
Branch: 1 branch
BranchTrueFalseTotal
$ignore ? : 0 56 56
493 q|
494 INSERT %s INTO %s( %s )
495 VALUES ( %s )
496 |,
497 $ignore ? 'IGNORE' : '',
498 $dbh->quote_identifier( $table_name ),
499 join( ', ', @sql_fields ),
500 join( ', ', @sql_values ),
501 );
502  
503 # Insert.
504 try
505 56 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
506 56 local $dbh->{'RaiseError'} = 1;
507 56 $dbh->do(
508 $query,
509 {},
510 @placeholder_values,
511 );
512 }
513 catch
514 1 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
515 1 $log->fatalf(
516 "Could not insert row: %s\nQuery: %s\nValues: %s",
517 $_,
518 $query,
519 \@placeholder_values,
520 );
521 1 croak "Insert failed: $_";
522 56 };
523  
524 55 ▶ if ( defined( $primary_key_name ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $primary_key_name) 55 0 55
525 {
526 $clean_data->{ $primary_key_name } = defined( $args{'generated_primary_key_value'} )
527 55 ▶ ? $args{'generated_primary_key_value'}
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'generated_primary_key_value'} ? : 1 54 55
528 : $dbh->last_insert_id( undef, undef, $table_name, $primary_key_name );
529 }
530  
531 # Check that the object was correctly inserted.
532 croak "Could not insert into table '$table_name': " . dumper( $data )
533 55 ▶ if defined( $primary_key_name ) && !defined( $clean_data->{ $primary_key_name } );
Branch: 1 branch
BranchTrueFalseTotal
if defined $primary_key_name and not defined $clean_data->{$primary_key_name} 0 55 55
Condition33%1/3
defined $primary_key_name and not defined $clean_data->{$primary_key_name}
!ll&&!rl&&r
0550
MC/DC0%0/2
defined $primary_key_name and not defined $clean_data->{$primary_key_name}
defined $primary_key_name not defined $clean_data->{$primary_key_name}
Truth table33%1/3
A and not(B)
A= defined $primary_key_nameB= not defined $clean_data->{$primary_key_name}
ABresult
0X0
100
111
534  
535 # Make sure that the object reflects the changes in the database.
536 55 $self->set(
537 $clean_data,
538 force => 1,
539 );
540  
541 55 return;
542 }
543  
544  
545 =head2 new()
546  
547 C<new()> has two possible uses:
548  
549 =over 4
550  
551 =item * Creating a new empty object
552  
553 my $object = My::Model::Book->new();
554  
555 =item * Retrieving a single object from the database.
556  
557 # Retrieve by ID.
558 my $object = My::Model::Book->new( { id => 3 } )
559 // die 'Book #3 does not exist';
560  
561 # Retrieve by unique field.
562 my $object = My::Model::Book->new( { isbn => '9781449303587' } )
563 // die 'Book with ISBN 9781449303587 does not exist';
564  
565 =back
566  
567 When retrieving a single object from the database, the first argument should be
568 a hashref containing the following information to select a single row:
569  
570 =over 4
571  
572 =item * id
573  
574 The ID for the primary key on the underlying table. C<id> is an alias for the
575 primary key field name.
576  
577 my $object = My::Model::Book->new( { id => 3 } )
578 // die 'Book #3 does not exist';
579  
580 =item * A unique field
581  
582 Allows passing a unique field and its value, in order to load the
583 corresponding object from the database.
584  
585 my $object = My::Model::Book->new( { isbn => '9781449303587' } )
586 // die 'Book with ISBN 9781449303587 does not exist';
587  
588 Note that unique fields need to be defined in C<static_class_info()>, in the
589 C<unique_fields> key.
590  
591 =back
592  
593 This method also supports the following optional arguments, passed in a hash
594 after the filtering criteria above-mentioned:
595  
596 =over 4
597  
598 =item * skip_cache (default: 0)
599  
600 By default, if cache is enabled with C<object_cache_time()> in
601 C<static_class_info()>, then C<new> attempts to load the object from the cache
602 first. Setting C<skip_cache> to 1 forces the ORM to load the values from the
603 database.
604  
605 my $object = My::Model::Book->new(
606 { isbn => '9781449303587' },
607 skip_cache => 1,
608 ) // die 'Book with ISBN 9781449303587 does not exist';
609  
610 =item * lock (default: 0)
611  
612 By default, the underlying row is not locked when retrieving an object via
613 C<new()>. Setting C<lock> to 1 forces the ORM to bypass the cache if any, and
614 to lock the rows in the database as it retrieves them.
615  
616 my $object = My::Model::Book->new(
617 { isbn => '9781449303587' },
618 lock => 1,
619 ) // die 'Book with ISBN 9781449303587 does not exist';
620  
621 =back
622  
623 =cut
624  
625 sub new
626 79 ▶{
Subroutine new: called CC=12 SCAR=26.6
Pod documented
627 79 my ( $class, $filters, %args ) = @_;
628  
629 # If filters exist, they need to be a hashref.
630 79 ▶ croak 'The first argument must be a hashref containing filtering criteria'
Branch: 1 branch
BranchTrueFalseTotal
if defined $filters and not Data::Validate::Type::is_hashref($filters) 0 79 79
Condition66%2/3
defined $filters and not Data::Validate::Type::is_hashref($filters)
!ll&&!rl&&r
7090
MC/DC0%0/2
defined $filters and not Data::Validate::Type::is_hashref($filters)
defined $filters not Data::Validate::Type::is_hashref($filters)
Truth table66%2/3
A and not(B)
A= defined $filtersB= not Data::Validate::Type::is_hashref($filters)
ABresult
0X0
100
111
631 if defined( $filters ) && !Data::Validate::Type::is_hashref( $filters );
632  
633 # Check if we have a unique identifier passed.
634 # Note: passing an ID is a subcase of passing field defined as unique, but
635 # unique_fields() doesn't include the primary key name.
636 79 my $unique_field;
637 79 ▶ foreach my $field ( 'id', @{ $class->get_info('unique_fields') // [] } )
Condition50%1/2
$class->get_info("unique_fields") // []
l!l
790
MC/DC0%0/1
$class->get_info("unique_fields") // []
$class->get_info("unique_fields")
Truth table50%1/2
A
A= $class->get_info("unique_fields")
Aresult
11
00
638 {
639 next
640 82 ▶ if ! exists( $filters->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $filters->{$field} 73 9 82
641  
642 # If the field exists in the list of filters, it needs to be
643 # defined. Being undefined probably indicates a problem in the calling code.
644 croak "Called new() with '$field' declared but not defined"
645 9 ▶ if ! defined( $filters->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filters->{$field} 0 9 9
646  
647 # Detect if we're passing two unique fields to retrieve the object. This is
648 # obviously bad.
649 9 ▶ croak "Called new() with the unique argument '$field', but already found another unique argument '$unique_field'"
Branch: 1 branch
BranchTrueFalseTotal
if defined $unique_field 0 9 9
650 if defined( $unique_field );
651  
652 9 $unique_field = $field;
653 }
654  
655 # Retrieve the object.
656 79 my $self;
657 79 ▶ if ( defined( $unique_field ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unique_field) { } 9 70 79
658 {
659 my $objects = $class->retrieve_list(
660 {
661 $unique_field => $filters->{ $unique_field },
662 },
663 skip_cache => $args{'skip_cache'},
664 9 ▶ lock => $args{'lock'} ? 1 : 0,
Branch: 1 branch
BranchTrueFalseTotal
$args{'lock'} ? : 0 9 9
665 );
666  
667 9 my $objects_count = scalar( @$objects );
668 9 ▶ if ( $objects_count == 0 )
Branch: 2 branches
BranchTrueFalseTotal
if ($objects_count == 0) { } 0 9 9
elsif ($objects_count == 1) { } 9 0 9
669 {
670 # No row found.
671 0 $self = undef;
672 }
673 elsif ( $objects_count == 1 )
674 {
675 9 $self = $objects->[0];
676 }
677 else
678 {
679 0 croak "Called new() with a set of non-unique arguments that returned $objects_count objects: " . dumper( \%args );
680 }
681 }
682 else
683 {
684 70 $self = bless( {}, $class );
685 }
686  
687 79 return $self;
688 }
689  
690  
691 =head2 remove()
692  
693 Delete in the database the row corresponding to the current object.
694  
695 $book->remove();
696  
697 This method accepts the following arguments:
698  
699 =over 4
700  
701 =item * dbh
702  
703 A different database handle from the default specified in C<static_class_info()>.
704 This is particularly useful if you have separate reader/writer databases.
705  
706 =back
707  
708 =cut
709  
710 sub remove
711 5 ▶{
Subroutine remove: called CC=4 SCAR=13.9
Pod documented
712 5 my ( $self, %args ) = @_;
713  
714 # Retrieve the metadata for that table.
715 5 my $class = ref( $self );
716 5 my $table_name = $self->get_info('table_name');
717 5 ▶ croak "The table name for class '$class' is not defined"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 1 4 5
718 if ! defined( $table_name );
719  
720 4 my $primary_key_name = $self->get_info('primary_key_name');
721 4 ▶ croak "Missing primary key name for class '$class', cannot delete safely"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $primary_key_name 1 3 4
722 if !defined( $primary_key_name );
723  
724 3 ▶ croak "The object of class '$class' does not have a primary key value, cannot delete"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->id 1 2 3
725 if ! defined( $self->id() );
726  
727 # Allow using a different DB handle.
728 2 my $dbh = $self->assert_dbh( $args{'dbh'} );
729  
730 # Prepare the query.
731 2 my $query = sprintf(
732 q|
733 DELETE
734 FROM %s
735 WHERE %s = ?
736 |,
737 $dbh->quote_identifier( $table_name ),
738 $dbh->quote_identifier( $primary_key_name ),
739 );
740 2 my @query_values = ( $self->id() );
741  
742 # Delete the row.
743 try
744 2 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
745 2 local $dbh->{'RaiseError'} = 1;
746 2 $dbh->do(
747 $query,
748 {},
749 @query_values,
750 );
751 }
752 catch
753 1 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
754 1 $log->fatalf(
755 "Could not delete row: %s\nQuery: %s\nValues: %s",
756 $_,
757 $query,
758 \@query_values,
759 );
760 1 croak "Remove failed: $_";
761 2 };
762  
763 1 return;
764 }
765  
766  
767 =head2 retrieve_list_nocache()
768  
769 Dispatch of retrieve_list() when objects should not be retrieved from the cache.
770  
771 See C<retrieve_list()> for the parameters this method accepts.
772  
773 =cut
774  
775 sub retrieve_list_nocache ## no critic (Subroutines::ProhibitExcessComplexity)
776 27 ▶{
Subroutine retrieve_list_nocache: called CC=61 SCAR=60.5
Pod documented
777 27 my ( $class, $filters, %args ) = @_;
778  
779 # Handle a different database handle, if requested.
780 27 my $dbh = $class->assert_dbh( $args{'dbh'} );
781  
782 # TODO: If we're asked to lock the rows, we check that we're in a transaction.
783  
784 # Check if we were passed arguments we don't know how to handle. This will
785 # help the calling code to detect typos or deprecated arguments.
786 27 foreach my $arg ( keys %args )
787 {
788 36 ▶ next if defined( $RETRIEVE_LIST_VALID_ARGUMENTS->{ $arg } );
Branch: 1 branch
BranchTrueFalseTotal
if defined $DBIx::NinjaORM::RETRIEVE_LIST_VALID_ARGUMENTS->{$arg} 36 0 36
789  
790 0 croak(
791 "The argument '$arg' passed to DBIx::NinjaORM->retrieve_list() via " .
792 "${class}->retrieve_list() is not handled by the superclass. " .
793 "It could mean that you have a typo in the name or that the argument has " .
794 "been deprecated."
795 );
796 }
797  
798 # Check the parameters and prepare the corresponding where clauses.
799 27 ▶ my $where_clauses = $args{'query_extensions'}->{'where_clauses'} || [];
Condition50%1/2
$args{'query_extensions'}{'where_clauses'} || []
l!l
027
MC/DC0%0/1
$args{'query_extensions'}{'where_clauses'} || []
$args{'query_extensions'}{'where_clauses'}
Truth table50%1/2
A
A= $args{'query_extensions'}{'where_clauses'}
Aresult
11
00
800 27 ▶ my $where_values = $args{'query_extensions'}->{'where_values'} || [];
Condition50%1/2
$args{'query_extensions'}{'where_values'} || []
l!l
027
MC/DC0%0/1
$args{'query_extensions'}{'where_values'} || []
$args{'query_extensions'}{'where_values'}
Truth table50%1/2
A
A= $args{'query_extensions'}{'where_values'}
Aresult
11
00
801 27 my $filtering_field_keys_passed = 0;
802 27 my $filtering_criteria = $class->parse_filtering_criteria(
803 $filters
804 );
805 26 ▶ if ( defined( $filtering_criteria ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filtering_criteria) 26 0 26
806 {
807 26 ▶ push( @$where_clauses, @{ $filtering_criteria->[0] || [] } );
Condition50%1/2
$filtering_criteria->[0] || []
l!l
260
MC/DC0%0/1
$filtering_criteria->[0] || []
$filtering_criteria->[0]
Truth table50%1/2
A
A= $filtering_criteria->[0]
Aresult
11
00
808 26 ▶ push( @$where_values, @{ $filtering_criteria->[1] || [] } );
Condition50%1/2
$filtering_criteria->[1] || []
l!l
260
MC/DC0%0/1
$filtering_criteria->[1] || []
$filtering_criteria->[1]
Truth table50%1/2
A
A= $filtering_criteria->[1]
Aresult
11
00
809 26 $filtering_field_keys_passed = $filtering_criteria->[2];
810 }
811  
812 # Make sure there's at least one argument, unless allow_all=1 or there is
813 # custom where clauses.
814 croak 'At least one argument must be passed'
815 26 ▶ if !$args{'allow_all'} && !$filtering_field_keys_passed && scalar( @$where_clauses ) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if not $args{"allow_all"} || $filtering_field_keys_passed and scalar @$where_clauses == 0 4 22 26
Condition83%5/6
not $args{"allow_all"} || $filtering_field_keys_passed and scalar @$where_clauses == 0
!ll&&!rl&&r
2204
$args{'allow_all'} || $filtering_field_keys_passed
l!l&&r!l&&!r
2204
MC/DC66%2/3
not $args{"allow_all"} || $filtering_field_keys_passed and scalar @$where_clauses == 0
$args{'allow_all'} $filtering_field_keys_passed scalar @$where_clauses == 0
Truth table75%3/4
not(A || B) and C
A= $args{'allow_all'}B= $filtering_field_keys_passedC= scalar @$where_clauses == 0
ABCresult
1XX0
01X0
0000
0011
816  
817 # Prepare the ORDER BY.
818 22 my $table_name = $class->get_info('table_name');
819 22 ▶ my $order_by = defined( $args{'order_by'} ) && ( $args{'order_by'} ne '' )
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'order_by'} && $args{'order_by'} ne '' ? : 5 17 22
$class->get_info('has_created_field') ? : 16 1 17
Condition66%2/3
defined $args{"order_by"} and $args{"order_by"} ne ""
!ll&&!rl&&r
1705
MC/DC50%1/2
defined $args{"order_by"} and $args{"order_by"} ne ""
defined $args{"order_by"} $args{"order_by"} ne ""
Truth table66%2/3
A and B
A= defined $args{"order_by"}B= $args{"order_by"} ne ""
ABresult
0X0
100
111
820 ? "ORDER BY $args{'order_by'}"
821 : $class->get_info('has_created_field')
822 ? "ORDER BY " . $dbh->quote_identifier( $table_name ) . ".created ASC"
823 : "ORDER BY " . $dbh->quote_identifier( $table_name ) . '.' . $class->get_info('primary_key_name');
824  
825 # Prepare quoted identifiers.
826 22 my $primary_key_name = $class->get_info('primary_key_name');
827 22 my $quoted_primary_key_name = $dbh->quote_identifier( $primary_key_name );
828 22 my $quoted_table_name = $dbh->quote_identifier( $table_name );
829  
830 # Prepare the SQL request elements.
831 22 ▶ my $where = scalar( @$where_clauses ) != 0
Branch: 1 branch
BranchTrueFalseTotal
scalar @$where_clauses != 0 ? : 20 2 22
832 ? 'WHERE ( ' . join( ' ) AND ( ', @$where_clauses ) . ' )'
833 : '';
834 22 ▶ my $joins = $args{'query_extensions'}->{'joins'} || '';
Condition100%2/2
$args{'query_extensions'}{'joins'} || ''
l!l
220
MC/DC100%1/1
$args{'query_extensions'}{'joins'} || ''
$args{'query_extensions'}{'joins'}
Truth table100%2/2
A
A= $args{'query_extensions'}{'joins'}
Aresult
11
00
835 my $limit = defined( $args{'limit'} ) && ( $args{'limit'} =~ m/^\d+$/ )
836 22 ▶ ? 'LIMIT ' . $args{'limit'}
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'limit'} && $args{'limit'} =~ /^\d+$/ ? : 0 22 22
Condition33%1/3
defined $args{"limit"} and $args{"limit"} =~ /^\d+$/
!ll&&!rl&&r
2200
MC/DC0%0/2
defined $args{"limit"} and $args{"limit"} =~ /^\d+$/
defined $args{"limit"} $args{"limit"} =~ /^\d+$/
Truth table33%1/3
A and B
A= defined $args{"limit"}B= $args{"limit"} =~ /^\d+$/
ABresult
0X0
100
111
837 : '';
838  
839 # Prepare the list of fields to retrieve.
840 22 my $fields;
841 22 ▶ if ( defined( $args{'exclude_fields'} ) || defined( $args{'select_fields'} ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'exclude_fields'} or defined $args{'select_fields'}) { } 0 22 22
Condition33%1/3
defined $args{"exclude_fields"} or defined $args{"select_fields"}
l!l&&r!l&&!r
0022
MC/DC0%0/2
defined $args{"exclude_fields"} or defined $args{"select_fields"}
defined $args{"exclude_fields"} defined $args{"select_fields"}
Truth table33%1/3
A or B
A= defined $args{"exclude_fields"}B= defined $args{"select_fields"}
ABresult
1X1
011
000
842 {
843 0 my $table_schema = $class->get_table_schema();
844 0 ▶ croak "Failed to retrieve schema for table '$table_name'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_schema 0 0 0
845 if !defined( $table_schema );
846 0 my $column_names = $table_schema->get_column_names();
847 0 ▶ croak "Failed to retrieve column names for table '$table_name'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $column_names 0 0 0
848 if !defined( $column_names );
849  
850 0 my @filtered_fields = ();
851 0 ▶ if ( defined( $args{'exclude_fields'} ) && !defined( $args{'select_fields'} ) )
Branch: 2 branches
BranchTrueFalseTotal
if (defined $args{'exclude_fields'} and not defined $args{'select_fields'}) { } 0 0 0
elsif (not defined $args{'exclude_fields'} and defined $args{'select_fields'}) { } 0 0 0
Condition0%0/3
defined $args{"exclude_fields"} and not defined $args{"select_fields"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $args{"exclude_fields"} and not defined $args{"select_fields"}
defined $args{"exclude_fields"} not defined $args{"select_fields"}
Truth table0%0/3
A and not(B)
A= defined $args{"exclude_fields"}B= not defined $args{"select_fields"}
ABresult
0X0
100
111
852 {
853 0 my %excluded_fields = map { $_ => 1 } @{ $args{'exclude_fields'} };
854 0 foreach my $field ( @$column_names )
855 {
856 $excluded_fields{ $field }
857 0 ▶ ? delete( $excluded_fields{ $field } )
Branch: 1 branch
BranchTrueFalseTotal
$excluded_fields{$field} ? : 0 0 0
858 : push( @filtered_fields, $field );
859 }
860 0 ▶ croak "The following excluded fields are not valid: " . join( ', ', keys %excluded_fields )
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %excluded_fields != 0 0 0 0
861 if scalar( keys %excluded_fields ) != 0;
862 }
863 ▶ elsif ( !defined( $args{'exclude_fields'} ) && defined( $args{'select_fields'} ) )
Condition0%0/3
not defined $args{"exclude_fields"} and defined $args{"select_fields"}
!ll&&!rl&&r
000
MC/DC0%0/2
not defined $args{"exclude_fields"} and defined $args{"select_fields"}
not defined $args{"exclude_fields"} defined $args{"select_fields"}
Truth table0%0/3
not(A) and B
A= not defined $args{"exclude_fields"}B= defined $args{"select_fields"}
ABresult
0X0
100
111
864 {
865 0 my %selected_fields = map { $_ => 1 } @{ $args{'select_fields'} };
866 croak 'The primary key must be in the list of selected fields'
867 0 ▶ if defined( $primary_key_name ) && !$selected_fields{ $primary_key_name };
Branch: 1 branch
BranchTrueFalseTotal
if defined $primary_key_name and not $selected_fields{$primary_key_name} 0 0 0
Condition0%0/3
defined $primary_key_name and not $selected_fields{$primary_key_name}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $primary_key_name and not $selected_fields{$primary_key_name}
defined $primary_key_name not $selected_fields{$primary_key_name}
Truth table0%0/3
A and not(B)
A= defined $primary_key_nameB= not $selected_fields{$primary_key_name}
ABresult
0X0
100
111
868  
869 0 foreach my $field ( @$column_names )
870 {
871 0 ▶ next if !$selected_fields{ $field };
Branch: 1 branch
BranchTrueFalseTotal
unless $selected_fields{$field} 0 0 0
872 0 push( @filtered_fields, $field );
873 0 delete( $selected_fields{ $field } );
874 }
875  
876 0 ▶ croak "The following restricted fields are not valid: " . join( ', ', keys %selected_fields )
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %selected_fields != 0 0 0 0
877 if scalar( keys %selected_fields ) != 0;
878 }
879 else
880 {
881 0 croak "The 'exclude_fields' and 'select_fields' options are not compatible, use one or the other";
882 }
883  
884 0 ▶ croak "No fields left after filtering out the excluded/restricted fields"
Branch: 1 branch
BranchTrueFalseTotal
if scalar @filtered_fields == 0 0 0 0
885 if scalar( @filtered_fields ) == 0;
886  
887 $fields = join(
888 ', ',
889 0 map { "$quoted_table_name.$_" } @filtered_fields
890 );
891 }
892 else
893 {
894 22 $fields = $quoted_table_name . '.*';
895 }
896  
897 $fields .= ', ' . $args{'query_extensions'}->{'joined_fields'}
898 22 ▶ if defined( $args{'query_extensions'}->{'joined_fields'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"query_extensions"}{"joined_fields"} 2 20 22
899  
900 # We need to make an exception for lock=1 when using SQLite, since
901 # SQLite doesn't support FOR UPDATE.
902 # Per http://sqlite.org/cvstrac/wiki?p=UnsupportedSql, the entire
903 # database is locked when updating any bit of it, so we can simply
904 # ignore the locking request here.
905 22 my $lock = '';
906 22 ▶ if ( $args{'lock'} )
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"lock"}) 1 21 22
907 {
908 1 ▶ my $database_type = $dbh->{'Driver'}->{'Name'} || '';
Condition50%1/2
$dbh->{'Driver'}{'Name'} || ''
l!l
10
MC/DC0%0/1
$dbh->{'Driver'}{'Name'} || ''
$dbh->{'Driver'}{'Name'}
Truth table50%1/2
A
A= $dbh->{'Driver'}{'Name'}
Aresult
11
00
909 1 ▶ if ( $database_type eq 'SQLite' )
Branch: 1 branch
BranchTrueFalseTotal
if ($database_type eq 'SQLite') { } 1 0 1
910 {
911 1 $log->info(
912 'SQLite does not support locking since only one process at a time is ',
913 'allowed to update a given SQLite database, so lock=1 is ignored.',
914 );
915 }
916 else
917 {
918 0 $lock = 'FOR UPDATE';
919 }
920 }
921  
922 # Check if we need to paginate.
923 22 my $pagination_info = {};
924 22 ▶ if ( defined( $args{'pagination'} ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"pagination"}) 5 17 22
925 {
926 # Allow for pagination => 1 as a shortcut to get all the defaults.
927 $args{'pagination'} = {}
928 5 ▶ if !Data::Validate::Type::is_hashref( $args{'pagination'} ) && ( $args{'pagination'} eq '1' );
Branch: 1 branch
BranchTrueFalseTotal
if not Data::Validate::Type::is_hashref($args{"pagination"}) and $args{"pagination"} eq 1 1 4 5
Condition66%2/3
not Data::Validate::Type::is_hashref($args{"pagination"}) and $args{"pagination"} eq 1
!ll&&!rl&&r
401
MC/DC50%1/2
not Data::Validate::Type::is_hashref($args{"pagination"}) and $args{"pagination"} eq 1
not Data::Validate::Type::is_hashref($args{"pagination"}) $args{"pagination"} eq 1
Truth table66%2/3
not(A) and B
A= not Data::Validate::Type::is_hashref($args{"pagination"})B= $args{"pagination"} eq 1
ABresult
0X0
100
111
929  
930 # Set defaults.
931 $pagination_info->{'per_page'} = ( $args{'pagination'}->{'per_page'} || '' ) =~ m/^\d+$/
932 5 ▶ ? $args{'pagination'}->{'per_page'}
Branch: 1 branch
BranchTrueFalseTotal
($args{'pagination'}{'per_page'} || '') =~ /^\d+$/ ? : 3 2 5
Condition100%2/2
$args{'pagination'}{'per_page'} || ''
l!l
32
MC/DC100%1/1
$args{'pagination'}{'per_page'} || ''
$args{'pagination'}{'per_page'}
Truth table100%2/2
A
A= $args{'pagination'}{'per_page'}
Aresult
11
00
933 : 20;
934  
935 # Count the total number of results.
936 my $count_data = $dbh->selectrow_arrayref(
937 sprintf(
938 q|
939 SELECT COUNT(*)
940 FROM %s
941 %s
942 %s
943 |,
944 $quoted_table_name,
945 $joins,
946 $where,
947 ),
948 {},
949 5 map { @$_ } @$where_values,
950 );
951 5 ▶ $pagination_info->{'total_count'} = defined( $count_data ) && scalar( @$count_data ) != 0
Branch: 1 branch
BranchTrueFalseTotal
defined $count_data && scalar @$count_data != 0 ? : 5 0 5
Condition33%1/3
defined $count_data and scalar @$count_data != 0
!ll&&!rl&&r
005
MC/DC0%0/2
defined $count_data and scalar @$count_data != 0
defined $count_data scalar @$count_data != 0
Truth table33%1/3
A and B
A= defined $count_dataB= scalar @$count_data != 0
ABresult
0X0
100
111
952 ? $count_data->[0]
953 : undef;
954  
955 # Calculate what the max page can be.
956 5 $pagination_info->{'page_max'} = int( ( $pagination_info->{'total_count'} - 1 ) / $pagination_info->{'per_page'} ) + 1;
957  
958 # Determine what the current page is.
959 $pagination_info->{'page'} = ( ( $args{'pagination'}->{'page'} || '' ) =~ m/^\d+$/ ) && ( $args{'pagination'}->{'page'} > 0 )
960 ? $pagination_info->{'page_max'} < $args{'pagination'}->{'page'}
961 ? $pagination_info->{'page_max'}
962 5 ▶ : $args{'pagination'}->{'page'}
Branch: 2 branches
BranchTrueFalseTotal
($args{'pagination'}{'page'} || '') =~ /^\d+$/ && $args{'pagination'}{'page'} > 0 ? : 3 2 5
$pagination_info->{'page_max'} < $args{'pagination'}{'page'} ? : 0 3 3
Condition80%4/5
($args{"pagination"}{"page"} || "") =~ /^\d+$/ and $args{"pagination"}{"page"} > 0
!ll&&!rl&&r
203
$args{'pagination'}{'page'} || ''
l!l
32
MC/DC50%1/2
($args{"pagination"}{"page"} || "") =~ /^\d+$/ and $args{"pagination"}{"page"} > 0
$args{'pagination'}{'page'} $args{"pagination"}{"page"} > 0
Truth table66%2/3
A and B
A= $args{'pagination'}{'page'}B= $args{"pagination"}{"page"} > 0
ABresult
0X0
100
111
963 : 1;
964  
965 # Set LIMIT and OFFSET.
966 $limit = "LIMIT $pagination_info->{'per_page'} "
967 5 . 'OFFSET ' . ( ( $pagination_info->{'page'} - 1 ) * $pagination_info->{'per_page'} );
968 }
969  
970 # If we need to lock the rows and there's joins, let's do this in two steps:
971 # 1) Lock the rows without join.
972 # 2) Using the IDs found, do another select to retrieve the data with the joins.
973 22 ▶ if ( ( $lock ne '' ) && ( $joins ne '' ) )
Branch: 1 branch
BranchTrueFalseTotal
if ($lock ne "" and $joins ne "") 0 22 22
Condition33%1/3
$lock ne "" and $joins ne ""
!ll&&!rl&&r
2200
MC/DC0%0/2
$lock ne "" and $joins ne ""
$lock ne "" $joins ne ""
Truth table33%1/3
A and B
A= $lock ne ""B= $joins ne ""
ABresult
0X0
100
111
974 {
975 0 my $query = sprintf(
976 q|
977 SELECT %s
978 FROM %s
979 %s
980 ORDER BY %s ASC
981 %s
982 %s
983 |,
984 $quoted_primary_key_name,
985 $quoted_table_name,
986 $where,
987 $quoted_primary_key_name,
988 $limit,
989 $lock,
990 );
991  
992 0 my @query_values = map { @$_ } @$where_values;
993 $log->debugf(
994 "Performing pre-locking query:\n%s\nValues:\n%s",
995 $query,
996 \@query_values,
997 0 ▶ ) if $args{'show_queries'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"show_queries"} 0 0 0
998  
999 0 my $locked_ids;
1000 try
1001 0 ▶ {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1002 0 local $dbh->{'RaiseError'} = 1;
1003 0 $locked_ids = $dbh->selectall_arrayref(
1004 $query,
1005 {
1006 Columns => [ 1 ],
1007 },
1008 @query_values
1009 );
1010 }
1011 catch
1012 0 ▶ {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1013 0 $log->fatalf(
1014 "Could not select rows in pre-locking query: %s\nQuery: %s\nValues:\n%s",
1015 $_,
1016 $query,
1017 \@query_values,
1018 );
1019 0 croak "Failed select: $_";
1020 0 };
1021  
1022 0 ▶ if ( !defined( $locked_ids ) || ( scalar( @$locked_ids ) == 0 ) )
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $locked_ids or scalar @$locked_ids == 0) 0 0 0
Condition0%0/3
not defined $locked_ids or scalar @$locked_ids == 0
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $locked_ids or scalar @$locked_ids == 0
not defined $locked_ids scalar @$locked_ids == 0
Truth table0%0/3
not(A) or B
A= not defined $locked_idsB= scalar @$locked_ids == 0
ABresult
1X1
011
000
1023 {
1024 0 return [];
1025 }
1026  
1027 0 $where = sprintf(
1028 'WHERE %s.%s IN ( %s )',
1029 $quoted_table_name,
1030 $quoted_primary_key_name,
1031 join( ', ', ( ('?') x scalar( @$locked_ids ) ) ),
1032 );
1033 0 $where_values = [ [ map { $_->[0] } @$locked_ids ] ];
1034 0 $lock = '';
1035 }
1036  
1037 # Prepare the query elements.
1038 22 my $query = sprintf(
1039 q|
1040 SELECT %s
1041 FROM %s
1042 %s %s %s %s %s
1043 |,
1044 $fields,
1045 $quoted_table_name,
1046 $joins,
1047 $where,
1048 $order_by,
1049 $limit,
1050 $lock,
1051 );
1052 22 my @query_values = map { @$_ } @$where_values;
1053 $log->debugf(
1054 "Performing query:\n%s\nValues:\n%s",
1055 $query,
1056 \@query_values,
1057 22 ▶ ) if $args{'show_queries'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"show_queries"} 0 22 22
1058  
1059 # Retrieve the objects.
1060 22 my $sth;
1061 try
1062 22 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
1063 22 local $dbh->{'RaiseError'} = 1;
1064 22 $sth = $dbh->prepare( $query );
1065 22 $sth->execute( @query_values );
1066 }
1067 catch
1068 0 ▶ {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1069 0 $log->fatalf(
1070 "Could not select rows: %s\nQuery: %s\nValues: %s",
1071 $_,
1072 $query,
1073 \@query_values,
1074 );
1075 0 croak "Failed select: $_";
1076 22 };
1077  
1078 22 my $object_list = [];
1079 22 ▶ while ( my $ref = $sth->fetchrow_hashref() )
Branch: 1 branch
BranchTrueFalseTotal
if (my $ref = $sth->fetchrow_hashref) 84 22 106
1080 {
1081 84 my $object = Storable::dclone( $ref );
1082 84 bless( $object, $class );
1083  
1084 84 $object->reorganize_non_native_fields();
1085  
1086 # Add a flag to distinguish objects that were populated via
1087 # retrieve_list_nocache(), as those objects are known for sure to contain
1088 # all the keys for columns that exist in the database. We also won't have to
1089 # worry about missing defaults, like insert() would have to.
1090 84 $object->{'_populated_by_retrieve_list'} = 1;
1091  
1092 # Add cache debugging information.
1093 84 $object->{'_debug'}->{'list_cache_used'} = 0;
1094 84 $object->{'_debug'}->{'object_cache_used'} = 0;
1095  
1096 # Store if we've excluded any fields, as it will impact caching in
1097 # retrieve_list().
1098 $object->{'_excluded_fields'} = $args{'exclude_fields'}
1099 84 ▶ if defined( $args{'exclude_fields'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"exclude_fields"} 0 84 84
1100  
1101 # Store if we've restricted to any fields, as it will impact caching in
1102 # retrieve_list().
1103 $object->{'_selected_fields'} = $args{'select_fields'}
1104 84 ▶ if defined( $args{'select_fields'} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"select_fields"} 0 84 84
1105  
1106 84 push( @$object_list, $object );
1107 }
1108  
1109 22 ▶ if ( wantarray && defined( $args{'pagination'} ) )
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray and defined $args{'pagination'}) { } 5 17 22
Condition66%2/3
wantarray and defined $args{"pagination"}
!ll&&!rl&&r
1705
MC/DC50%1/2
wantarray and defined $args{"pagination"}
wantarray defined $args{"pagination"}
Truth table66%2/3
A and B
A= wantarrayB= defined $args{"pagination"}
ABresult
0X0
100
111
1110 {
1111 5 return ( $object_list, $pagination_info );
1112 }
1113 else
1114 {
1115 17 return $object_list;
1116 }
1117 }
1118  
1119  
1120 =head2 set()
1121  
1122 Set fields and values on an object.
1123  
1124 $book->set(
1125 {
1126 name => 'Learning Perl',
1127 isbn => '9781449303587',
1128 },
1129 );
1130  
1131 This method supports the following arguments:
1132  
1133 =over 4
1134  
1135 =item * force
1136  
1137 Set the properties on the object without going through C<validate_data()>.
1138  
1139 $book->set(
1140 {
1141 name => 'Learning Perl',
1142 isbn => '9781449303587',
1143 },
1144 force => 1,
1145 );
1146  
1147 =back
1148  
1149 =cut
1150  
1151 sub set ## no critic (NamingConventions::ProhibitAmbiguousNames, Subroutines::RequireArgUnpacking)
1152 67 ▶{
Subroutine set: called CC=4 SCAR=13.9
Pod documented
1153 67 ▶ croak 'The first argument passed must be a hashref'
Branch: 1 branch
BranchTrueFalseTotal
unless Data::Validate::Type::is_hashref($_[1]) 1 66 67
1154 if !Data::Validate::Type::is_hashref( $_[1] );
1155  
1156 66 my ( $self, $data, %args ) = @_;
1157  
1158 # Validate the data first, unless force=1.
1159 $data = $self->validate_data( $data )
1160 66 ▶ if !$args{'force'};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"force"} 5 61 66
1161  
1162 # Update the object.
1163 64 foreach ( keys %$data )
1164 {
1165 236 $self->{ $_ } = $data->{ $_ };
1166 }
1167  
1168 64 return;
1169 }
1170  
1171  
1172 =head2 static_class_info()
1173  
1174 This methods sets defaults as well as general information for a specific class.
1175  
1176 It allows for example indicating what table the objects will be related to, or
1177 what database handle to use. See L<DBIx::NinjaORM::StaticClassInfo> for the
1178 full list of options that can be set or overridden.
1179  
1180 Here's what a typical subclassed C<static_class_info()> would look like:
1181  
1182 sub static_class_info
1183 {
1184 my ( $class ) = @_;
1185  
1186 # Retrieve defaults coming from higher in the inheritance chain, up
1187 # to DBIx::NinjaORM->static_class_info().
1188 my $info = $class->SUPER::static_class_info();
1189  
1190 # Set or override information.
1191 $info->set(
1192 {
1193 table_name => 'books',
1194 primary_key_name => 'book_id',
1195 default_dbh => DBI->connect(
1196 "dbi:mysql:[database_name]:localhost:3306",
1197 "[user]",
1198 "[password]",
1199 ),
1200 }
1201 );
1202  
1203 # Return the updated information hashref.
1204 return $info;
1205 }
1206  
1207 =cut
1208  
1209 sub static_class_info
1210 79 ▶{
Subroutine static_class_info: called CC=1 SCAR=0.0
Pod documented
1211 79 return DBIx::NinjaORM::StaticClassInfo->new();
1212 }
1213  
1214  
1215 =head2 update()
1216  
1217 Update the row in the database corresponding to the current object, using the
1218 primary key and its value on the object.
1219  
1220 $book->update(
1221 {
1222 name => 'Learning Perl',
1223 }
1224 );
1225  
1226 This method supports the following optional arguments:
1227  
1228 =over 4
1229  
1230 =item * skip_modified_update (default 0)
1231  
1232 Do not update the 'modified' field. This is useful if you're using 'modified' to
1233 record when was the last time a human changed the row, but you want to exclude
1234 automated changes.
1235  
1236 =item * dbh
1237  
1238 A different database handle than the default one specified in
1239 C<static_class_info()>, but it has to be writable.
1240  
1241 =item * restrictions
1242  
1243 The update statement is limited using the primary key. This parameter however
1244 allows adding extra restrictions on the update. Additional clauses passed here
1245 are joined with AND.
1246  
1247 $book->update(
1248 {
1249 author_id => 1234,
1250 },
1251 restrictions =>
1252 {
1253 where_clauses => [ 'status != ?' ],
1254 where_values => [ 'protected' ],
1255 },
1256 );
1257  
1258 =item * set
1259  
1260 \%data contains the data to update the row with "SET field = value". It is
1261 however sometimes necessary to use more complex SETs, such as
1262 "SET field = field + value", which is what this parameter allows.
1263  
1264 Important: you will need to subclass C<update()> in your model classes and
1265 update manually the values upon success (or reload the object), as
1266 L<DBIx::NinjaORM> cannot determine the end result of those complex sets on the
1267 database side.
1268  
1269 $book->update(
1270 {
1271 name => 'Learning Perl',
1272 },
1273 set =>
1274 {
1275 placeholders => [ 'edits = edits + ?' ],
1276 values => [ 1 ],
1277 }
1278 );
1279  
1280 =back
1281  
1282 =cut
1283  
1284 sub update ## no critic (Subroutines::RequireArgUnpacking)
1285 9 ▶{
Subroutine update: called CC=21 SCAR=35.9
Pod documented
1286 9 ▶ croak 'The first argument passed must be a hashref'
Branch: 1 branch
BranchTrueFalseTotal
unless Data::Validate::Type::is_hashref($_[1]) 1 8 9
1287 if !Data::Validate::Type::is_hashref( $_[1] );
1288  
1289 8 my ( $self, $data, %args ) = @_;
1290  
1291 # Allow using a different DB handle.
1292 8 my $dbh = $self->assert_dbh( $args{'dbh'} );
1293  
1294 # Clean input
1295 6 my $clean_data = $self->validate_data( $data, %args );
1296 6 ▶ return 0
Branch: 1 branch
BranchTrueFalseTotal
unless defined $clean_data 0 6 6
1297 if !defined( $clean_data );
1298  
1299 # Set defaults
1300 $clean_data->{'modified'} = $self->get_current_time()
1301 6 ▶ if !$args{'skip_modified_update'} && $self->get_info('has_modified_field');
Branch: 1 branch
BranchTrueFalseTotal
if not $args{"skip_modified_update"} and $self->get_info("has_modified_field") 5 1 6
Condition66%2/3
not $args{"skip_modified_update"} and $self->get_info("has_modified_field")
!ll&&!rl&&r
015
MC/DC50%1/2
not $args{"skip_modified_update"} and $self->get_info("has_modified_field")
not $args{"skip_modified_update"} $self->get_info("has_modified_field")
Truth table66%2/3
not(A) and B
A= not $args{"skip_modified_update"}B= $self->get_info("has_modified_field")
ABresult
0X0
100
111
1302  
1303 # If there's nothing to update, bail out.
1304 6 ▶ if ( scalar( keys %$clean_data ) == 0 )
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$clean_data == 0) 0 6 6
1305 {
1306 0 ▶ $log->debug( 'No data left to update after validation, skipping SQL update' )
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_verbose 0 0 0
1307 if $self->is_verbose();
1308 0 return;
1309 }
1310  
1311 # Retrieve the meta-data for that table.
1312 6 my $class = ref( $self );
1313  
1314 6 my $table_name = $self->get_info('table_name');
1315 6 ▶ croak "The table name for class '$class' is not defined"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 0 6 6
1316 if ! defined( $table_name );
1317  
1318 6 my $primary_key_name = $self->get_info('primary_key_name');
1319 croak "Missing primary key name for class '$class', cannot force primary key value"
1320 6 ▶ if !defined( $primary_key_name ) && defined( $args{'generated_primary_key_value'} );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $primary_key_name and defined $args{"generated_primary_key_value"} 0 6 6
Condition33%1/3
not defined $primary_key_name and defined $args{"generated_primary_key_value"}
!ll&&!rl&&r
600
MC/DC0%0/2
not defined $primary_key_name and defined $args{"generated_primary_key_value"}
not defined $primary_key_name defined $args{"generated_primary_key_value"}
Truth table33%1/3
not(A) and B
A= not defined $primary_key_nameB= defined $args{"generated_primary_key_value"}
ABresult
0X0
100
111
1321  
1322 6 ▶ croak "The object of class '$class' does not have a primary key value, cannot update"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->id 0 6 6
1323 if ! defined( $self->id() );
1324  
1325 # Prepare the SQL request elements.
1326 6 ▶ my $where_clauses = $args{'restrictions'}->{'where_clauses'} || [];
Condition50%1/2
$args{'restrictions'}{'where_clauses'} || []
l!l
06
MC/DC0%0/1
$args{'restrictions'}{'where_clauses'} || []
$args{'restrictions'}{'where_clauses'}
Truth table50%1/2
A
A= $args{'restrictions'}{'where_clauses'}
Aresult
11
00
1327 6 ▶ my $where_values = $args{'restrictions'}->{'where_values'} || [];
Condition50%1/2
$args{'restrictions'}{'where_values'} || []
l!l
06
MC/DC0%0/1
$args{'restrictions'}{'where_values'} || []
$args{'restrictions'}{'where_values'}
Truth table50%1/2
A
A= $args{'restrictions'}{'where_values'}
Aresult
11
00
1328 6 push( @$where_clauses, $primary_key_name . ' = ?' );
1329 6 push( @$where_values, [ $self->id() ] );
1330  
1331 # Prepare the values to set.
1332 6 my @set_placeholders = ();
1333 6 my @set_values = ();
1334 6 foreach my $key ( keys %$clean_data )
1335 {
1336 11 ▶ if ( $key eq 'modified' )
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq 'modified') { } 5 6 11
1337 {
1338 # 'created' supports SQL keywords and is quoted by get_current_time() if
1339 # needed, so we don't use placeholders.
1340 5 push( @set_placeholders, $dbh->quote_identifier( $key ) . ' = ' . $clean_data->{ $key } );
1341 }
1342 else
1343 {
1344 # All the other data need to be inserted using placeholders, for
1345 # security purposes.
1346 6 push( @set_placeholders, $dbh->quote_identifier( $key ) . ' = ?' );
1347 6 push( @set_values, $clean_data->{ $key } );
1348 }
1349 }
1350 6 ▶ if ( defined( $args{'set'} ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"set"}) 0 6 6
1351 {
1352 0 ▶ push( @set_placeholders, @{ $args{'set'}->{'placeholders'} // [] } );
Condition0%0/2
$args{"set"}{"placeholders"} // []
l!l
00
MC/DC0%0/1
$args{"set"}{"placeholders"} // []
$args{"set"}{"placeholders"}
Truth table0%0/2
A
A= $args{"set"}{"placeholders"}
Aresult
11
00
1353 0 ▶ push( @set_values, @{ $args{'set'}->{'values'} // [] } );
Condition0%0/2
$args{"set"}{"values"} // []
l!l
00
MC/DC0%0/1
$args{"set"}{"values"} // []
$args{"set"}{"values"}
Truth table0%0/2
A
A= $args{"set"}{"values"}
Aresult
11
00
1354 }
1355  
1356 # Prepare the query elements.
1357 6 my $query = sprintf(
1358 qq|
1359 UPDATE %s
1360 SET %s
1361 WHERE %s
1362 |,
1363 $dbh->quote_identifier( $table_name ),
1364 join( ', ', @set_placeholders ),
1365 '( ' . join( ' ) AND ( ', @$where_clauses ) . ' )',
1366 );
1367 my @query_values =
1368 (
1369 @set_values,
1370 6 map { @$_ } @$where_values,
1371 );
1372  
1373 # Update the row.
1374 6 my $rows_updated_count;
1375 try
1376 6 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
1377 6 local $dbh->{'RaiseError'} = 1;
1378 6 my $sth = $dbh->prepare( $query );
1379 5 $sth->execute( @query_values );
1380  
1381 5 $rows_updated_count = $sth->rows();
1382 }
1383 catch
1384 1 ▶ {
Subroutine __ANON__: called CC=1 SCAR=0.0
1385 1 $log->fatalf(
1386 "Could not update rows: %s\nQuery: %s\nValues: %s",
1387 $_,
1388 $query,
1389 \@query_values,
1390 );
1391  
1392 1 croak "Update failed: $_";
1393 6 };
1394  
1395 # Also, if rows() returns -1, it's an error.
1396 5 ▶ croak 'Could not execute update: ' . $dbh->errstr()
Branch: 1 branch
BranchTrueFalseTotal
if $rows_updated_count < 0 0 5 5
1397 if $rows_updated_count < 0;
1398  
1399 5 my $object_cache_time = $self->get_info('object_cache_time');
1400 # This needs to be before the set() below, so we invalidate the cache based on the
1401 # old object. We don't need to do it twice, because you can't change primary IDs, and
1402 # you can't change unique fields to ones that are taken, and that's all that we set
1403 # the object cache keys for.
1404 5 ▶ if ( defined( $object_cache_time ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $object_cache_time) 0 5 5
1405 {
1406 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_verbose 0 0 0
1407 "An update on '%s' is forcing to clear the cache for '%s=%s'",
1408 $table_name,
1409 $primary_key_name,
1410 $self->id(),
1411 ) if $self->is_verbose();
1412  
1413 0 $self->invalidate_cached_object();
1414 }
1415  
1416 # Make sure that the object reflects $clean_data.
1417 $self->set(
1418 5 $clean_data,
1419 force => 1,
1420 );
1421  
1422 5 return $rows_updated_count;
1423 }
1424  
1425  
1426 =head2 validate_data()
1427  
1428 Validate the hashref of data passed as first argument. This is used both by
1429 C<insert()> and C<update> to check the data before performing databse
1430 operations.
1431  
1432 my $validated_data = $object->validate_data(
1433 \%data,
1434 );
1435  
1436 If there is invalid data, the method will croak with a detail of the error.
1437  
1438 =cut
1439  
1440 sub validate_data
1441 71 ▶{
Subroutine validate_data: called CC=12 SCAR=25.2
Pod documented
1442 71 my ( $self, $original_data ) = @_;
1443  
1444 71 my $data = Storable::dclone( $original_data );
1445  
1446 # Protect read-only fields.
1447 71 ▶ foreach my $field ( @{ $self->get_info('readonly_fields') // [] } )
Condition50%1/2
$self->get_info("readonly_fields") // []
l!l
710
MC/DC0%0/1
$self->get_info("readonly_fields") // []
$self->get_info("readonly_fields")
Truth table50%1/2
A
A= $self->get_info("readonly_fields")
Aresult
11
00
1448 {
1449 6 ▶ next if ! exists( $data->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $data->{$field} 3 3 6
1450  
1451 3 croak "The field '$field' is read-only and cannot be set via the model";
1452 }
1453  
1454 # Don't allow setting timestamps.
1455 68 foreach my $field ( qw( created modified ) )
1456 {
1457 136 ▶ next if ! exists( $data->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $data->{$field} 136 0 136
1458  
1459 0 $log->warnf(
1460 "The field '%s' cannot be set and will be ignored",
1461 $field,
1462 );
1463 0 delete( $data->{ $field } );
1464 }
1465  
1466 # Allow inserting the primary key, but not updating it.
1467 68 my $primary_key_name = $self->get_info('primary_key_name');
1468 68 ▶ if ( defined( $primary_key_name ) && defined( $self->{ $primary_key_name } ) && exists( $data->{ $primary_key_name } ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $primary_key_name and defined $self->{$primary_key_name} and exists $data->{$primary_key_name}) 1 67 68
Condition100%6/6
defined $primary_key_name and defined $self->{$primary_key_name} and exists $data->{$primary_key_name}
!ll&&!rl&&r
6071
defined $primary_key_name and defined $self->{$primary_key_name}
!ll&&!rl&&r
1598
MC/DC100%3/3
defined $primary_key_name and defined $self->{$primary_key_name} and exists $data->{$primary_key_name}
defined $primary_key_name defined $self->{$primary_key_name} exists $data->{$primary_key_name}
Truth table100%4/4
A and B and C
A= defined $primary_key_nameB= defined $self->{$primary_key_name}C= exists $data->{$primary_key_name}
ABCresult
0XX0
10X0
1100
1111
1469 {
1470 1 ▶ croak "'$primary_key_name' with a value of '" . ( $data->{ $primary_key_name } || 'undef' ) . "' ",
Condition50%1/2
$data->{$primary_key_name} || 'undef'
l!l
10
MC/DC0%0/1
$data->{$primary_key_name} || 'undef'
$data->{$primary_key_name}
Truth table50%1/2
A
A= $data->{$primary_key_name}
Aresult
11
00
1471 "was passed to set(), but primary keys cannot be set manually";
1472 }
1473  
1474 # Fields starting with an underscore are hidden data that shouldn't be
1475 # modified via a public interface.
1476 67 foreach my $field ( keys %$data )
1477 {
1478 77 ▶ delete( $data->{ $field } )
Branch: 1 branch
BranchTrueFalseTotal
if substr($field, 0, 1) eq "_" 1 76 77
1479 if substr( $field, 0, 1 ) eq '_';
1480 }
1481  
1482 67 return $data;
1483 }
1484  
1485  
1486 =head1 UTILITY METHODS
1487  
1488  
1489 =head2 dump()
1490  
1491 Return a string representation of the current object.
1492  
1493 my $string = $book->dump();
1494  
1495 =cut
1496  
1497 sub dump ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1498 2 ▶{
Subroutine dump: called CC=1 SCAR=0.0
Pod documented
1499 2 my ( $self ) = @_;
1500  
1501 2 return dumper( $self );
1502 }
1503  
1504  
1505 =head2 flatten_object()
1506  
1507 Return a hash with the requested key/value pairs based on the list of fields
1508 provided.
1509  
1510 Note that non-native fields (starting with an underscore) are not allowed. It
1511 also protects sensitive fields.
1512  
1513 #TODO: allow defining sensitive fields.
1514  
1515 my $book_data = $book->flatten_object(
1516 [ 'name', 'isbn' ]
1517 );
1518  
1519 =cut
1520  
1521 sub flatten_object
1522 5 ▶{
Subroutine flatten_object: called CC=6 SCAR=17.9
Pod documented
1523 5 my ( $self, $fields ) = @_;
1524 5 my @protected_fields = qw( password );
1525  
1526 5 my %data = ();
1527 5 foreach my $field ( @$fields )
1528 {
1529 6 ▶ if ( scalar( grep { $_ eq $field } @protected_fields ) != 0 )
Branch: 3 branches
BranchTrueFalseTotal
if (scalar grep({$_ eq $field;} @protected_fields) != 0) { } 1 5 6
elsif (substr($field, 0, 1) eq '_') { } 1 4 5
elsif ($field eq 'id') { } 2 2 4
1530 {
1531 1 croak "The fields '$field' is protected and cannot be added to the flattened copy";
1532 }
1533 elsif ( substr( $field, 0, 1 ) eq '_' )
1534 {
1535 1 croak "The field '$field' is hidden and cannot be added to the flattened copy";
1536 }
1537 elsif ( $field eq 'id' )
1538 {
1539 2 ▶ if ( defined( $self->get_info('primary_key_name') ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->get_info('primary_key_name')) { } 1 1 2
1540 {
1541 1 $data{'id'} = $self->id();
1542 }
1543 else
1544 {
1545 1 croak "Requested adding ID to the list of fields, but the class doesn't define a primary key name";
1546 }
1547 }
1548 else
1549 {
1550 2 $data{ $field } = $self->{ $field };
1551 }
1552 }
1553  
1554 2 return \%data;
1555 }
1556  
1557  
1558 =head2 reload()
1559  
1560 Reload the content of the current object. This always skips the cache.
1561  
1562 $book->reload();
1563  
1564 =cut
1565  
1566 sub reload
1567 1 ▶{
Subroutine reload: called CC=8 SCAR=22.3
Pod documented
1568 1 my ( $self ) = @_;
1569  
1570 # Make sure we were passed an object.
1571 1 ▶ croak 'This method can only be called on an object'
Branch: 1 branch
BranchTrueFalseTotal
unless Data::Validate::Type::is_hashref($self) 0 1 1
1572 if !Data::Validate::Type::is_hashref( $self );
1573  
1574 1 my $class = ref( $self );
1575  
1576 1 ▶ croak 'The object is not blessed with a class name'
Branch: 1 branch
BranchTrueFalseTotal
if not defined $class or $class eq "" 0 1 1
Condition33%1/3
not defined $class or $class eq ""
l!l&&r!l&&!r
001
MC/DC0%0/2
not defined $class or $class eq ""
not defined $class $class eq ""
Truth table33%1/3
not(A) or B
A= not defined $classB= $class eq ""
ABresult
1X1
011
000
1577 if !defined( $class ) || ( $class eq '' );
1578  
1579 1 ▶ croak "The class '$class' doesn't allow calling \$class->new()"
Branch: 1 branch
BranchTrueFalseTotal
unless $class->can("new") 0 1 1
1580 if ! $class->can('new');
1581  
1582 # Verify that we can reload the object.
1583 1 ▶ croak 'Cannot reload an object for which a primary key name has not been defined at the class level.'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->get_info("primary_key_name") 0 1 1
1584 if ! defined( $self->get_info('primary_key_name') );
1585 1 ▶ croak 'Cannot reload an object with no ID value for its primary key'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->id 0 1 1
1586 if ! defined( $self->id() );
1587  
1588 # Retrieve a fresh version using the object ID.
1589 1 my $id = $self->id();
1590 1 my $fresh_object = $class->new(
1591 { id => $self->id() },
1592 skip_cache => 1,
1593 );
1594  
1595 1 ▶ croak "Could not retrieve the row in the database corresponding to the current object using ID '$id'"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $fresh_object 0 1 1
1596 if ! defined( $fresh_object );
1597  
1598 # Keep the memory location intact.
1599 1 %{ $self } = %{ $fresh_object };
1600  
1601 1 return;
1602 }
1603  
1604  
1605 =head2 retrieve_list()
1606  
1607 Return an arrayref of objects matching all the criteria passed.
1608  
1609 This method supports the following filtering criteria in a hashref passed as
1610 first argument:
1611  
1612 =over 4
1613  
1614 =item * id
1615  
1616 An ID or an arrayref of IDs corresponding to the primary key.
1617  
1618 # Retrieve books with ID 1.
1619 my $books = My::Model::Book->retrieve_list(
1620 {
1621 id => 1,
1622 }
1623 );
1624  
1625 # Retrieve books with IDs 1, 2 or 3.
1626 my $books = My::Model::Book->retrieve_list(
1627 {
1628 id => [ 1, 2, 3 ]
1629 }
1630 );
1631  
1632 =item * Field names
1633  
1634 A scalar value or an arrayref of values corresponding to a field listed in
1635 C<static_class_info()> under either C<filtering_fields> or C<unique_fields>.
1636  
1637 # Retrieve books for an author.
1638 my $books = My::Model::Book->retrieve_list(
1639 {
1640 author_id => 12,
1641 }
1642 );
1643  
1644 # Retrieve books by ISBN.
1645 my $books = My::Model::Book->retrieve_list(
1646 {
1647 isbn =>
1648 [
1649 '9781449313142',
1650 '9781449393090',
1651 ]
1652 }
1653 );
1654  
1655 =back
1656  
1657 Note that you can combine filters (which is the equivalent of AND in SQL) in
1658 that hashref:
1659  
1660 # Retrieve books by ISBN for a specific author.
1661 my $books = My::Model::Book->retrieve_list(
1662 {
1663 isbn =>
1664 [
1665 '9781449313142',
1666 '9781449393090',
1667 ],
1668 author_id => 12,
1669 }
1670 );
1671  
1672 Filters as discussed above, imply an equality between the field and the values. For instance, in the last example,
1673 the request could be written as "Please provide a list of books with author_id equal to 12, which also have an
1674 ISBN equal to 9781449313142 or an ISBN equal to 9781449393090".
1675  
1676 If you wish to request records using some other operator than equals, you can create a request similar to the following:
1677  
1678 # Retrieve books for a specific author with ISBNs starting with a certain pattern.
1679 my $books = My::Model::Book->retrieve_list(
1680 {
1681 isbn =>
1682 {
1683 operator => 'like',
1684 value => [ '9781%' ],
1685 },
1686 author_id => 12,
1687 }
1688 );
1689  
1690 The above example could be written as "Please provide a list of books with author_id equal to 12, which also have
1691 an ISBN starting with 9781".
1692  
1693 Valid operators include:
1694  
1695 * =
1696 * not
1697 * <=
1698 * >=
1699 * <
1700 * >
1701 * between
1702 * null
1703 * not_null
1704 * like
1705 * not_like
1706  
1707 This method also supports the following optional arguments, passed in a hash
1708 after the filtering criteria above-mentioned:
1709  
1710 =over 4
1711  
1712 =item * dbh
1713  
1714 Retrieve the data against a different database than the default one specified
1715 in C<static_class_info>.
1716  
1717 =item * order_by
1718  
1719 Specify an ORDER BY clause to sort the objects returned.
1720  
1721 my $books = My::Model::Book->retrieve_list(
1722 {
1723 author_id => 12,
1724 },
1725 order_by => 'books.name ASC',
1726 );
1727  
1728 =item * limit
1729  
1730 Limit the number of objects to return.
1731  
1732 # Get 10 books from author #12.
1733 my $books = My::Model::Book->retrieve_list(
1734 {
1735 author_id => 12,
1736 },
1737 limit => 10,
1738 );
1739  
1740 =item * query_extensions
1741  
1742 Add joins and support different filtering criteria:
1743  
1744 =over 8
1745  
1746 =item * where_clauses
1747  
1748 An arrayref of clauses to add to WHERE.
1749  
1750 =item * where_values
1751  
1752 An arrayref of values corresponding to the clauses.
1753  
1754 =item * joins
1755  
1756 A string specifying JOIN statements.
1757  
1758 =item * joined_fields
1759  
1760 A string of extra fields to add to the SELECT.
1761  
1762 =back
1763  
1764 my $books = My::Model::Book->retrieve_list(
1765 {
1766 id => [ 1, 2, 3 ],
1767 },
1768 query_extensions =>
1769 {
1770 where_clauses => [ 'authors.name = ?' ],
1771 where_values => [ [ 'Randal L. Schwartz' ] ],
1772 joins => 'INNER JOIN authors USING (author_id)',
1773 joined_fields => 'authors.name AS _author_name',
1774 }
1775 );
1776  
1777 =item * pagination
1778  
1779 Off by default. Paginate the results. You can control the pagination options
1780 by setting this to the following hash, with each key being optional and falling
1781 back to the default if you omit it:
1782  
1783 my $books = My::Model::Book->retrieve_list(
1784 {},
1785 allow_all => 1,
1786 pagination =>
1787 {
1788 # The number of results to retrieve.
1789 per_page => $per_page,
1790 # Number of the page of results to retrieve. If you have per_page=10
1791 # and page=2, then this would retrieve rows 10-19 from the set of
1792 # matching rows.
1793 page => $page,
1794 }
1795 );
1796  
1797 Additionally, pagination can be set to '1' instead of {} and then the default
1798 options will be used.
1799  
1800 More pagination information is then returned in list context:
1801  
1802 my ( $books, $pagination ) = My::Model::Book->retrieve_list( ... );
1803  
1804 With the following pagination information inside C<$pagination>:
1805  
1806 {
1807 # The total number of rows matching the query.
1808 total_count => $total_count,
1809 # The current page being returned.
1810 page => $page,
1811 # The total number of pages to display the matching rows.
1812 page_max => $page_max,
1813 # The number of rows displayed per page.
1814 per_page => $per_page,
1815 }
1816  
1817 =item * lock (default 0)
1818  
1819 Add a lock to the rows retrieved.
1820  
1821 my $books = My::Model::Book->retrieve_list(
1822 {
1823 id => [ 1, 2, 3 ],
1824 },
1825 lock => 1,
1826 );
1827  
1828 =item * allow_all (default 0)
1829  
1830 Retrieve all the rows in the table if no criteria is passed. Off by
1831 default to prevent retrieving large tables at once.
1832  
1833 # All the books!
1834 my $books = My::Model::Book->retrieve_list(
1835 {},
1836 allow_all => 1,
1837 );
1838  
1839 =item * show_queries (default 0)
1840  
1841 Set to '1' to see in the logs the queries being performed.
1842  
1843 my $books = My::Model::Book->retrieve_list(
1844 {
1845 id => [ 1, 2, 3 ],
1846 },
1847 show_queries => 1,
1848 );
1849  
1850 =item * allow_subclassing (default 0)
1851  
1852 By default, C<retrieve_list()> cannot be subclassed to prevent accidental
1853 infinite recursions and breaking the cache features provided by NinjaORM.
1854 Typically, if you want to add functionality to how retrieving a group of
1855 objects works, you will want to modify C<retrieve_list_nocache()> instead.
1856  
1857 If you really need to subclass C<retrieve_list()>, you will then need to
1858 set C<allow_subclassing> to C<1> in subclassed method's call to its parent,
1859 to indicate that you've carefully considered the impact of this and that it
1860 is safe.
1861  
1862 =item * select_fields / exclude_fields (optional)
1863  
1864 By default, C<retrieve_list()> will select all the fields that exist on the
1865 table associated with the class. In some rare cases, it is however desirable to
1866 either select only or to exclude explicitely some fields from the table, and
1867 you can pass an arrayref with C<select_fields> and C<exclude_fields>
1868 (respectively) to specify those.
1869  
1870 Important cache consideration: when this option is used, the cache will be used
1871 to retrieve objects without polling the database when possible, but any objects
1872 retrieved from the database will not be stashed in the cache as they will not
1873 have the complete information for that object. If you have other
1874 C<retrieve_list()> calls warming the cache this most likely won't be an issue,
1875 but if you exclusively run C<retrieve_list()> calls with C<select_fields> and
1876 C<exclude_fields>, then you may be better off creating a view and tieing the
1877 class to that view.
1878  
1879 # To display an index of our library, we want all the book properties but not
1880 # the book content, which is a huge field that we won't use in the template.
1881 my $books = My::Model::Book->retrieve_list(
1882 {},
1883 allow_all => 1,
1884 exclude_fields => [ 'full_text' ],
1885 );
1886  
1887 =back
1888  
1889 =cut
1890  
1891 sub retrieve_list
1892 26 ▶{
Subroutine retrieve_list: called CC=9 SCAR=22.0
Pod documented
1893 26 my ( $class, $filters, %args ) = @_;
1894 26 ▶ my $allow_subclassing = delete( $args{'allow_subclassing'} ) || 0;
Condition100%2/2
delete $args{'allow_subclassing'} || 0
l!l
125
MC/DC100%1/1
delete $args{'allow_subclassing'} || 0
delete $args{'allow_subclassing'}
Truth table100%2/2
A
A= delete $args{'allow_subclassing'}
Aresult
11
00
1895  
1896 # Check caller and prevent calls from a subclass' retrieve_list().
1897 26 ▶ if ( !$allow_subclassing )
Branch: 1 branch
BranchTrueFalseTotal
unless ($allow_subclassing) 25 1 26
1898 {
1899 25 my $subroutine = (caller(1))[3];
1900 25 ▶ if ( defined( $subroutine ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $subroutine) 25 0 25
1901 {
1902 25 $subroutine =~ s/^.*:://;
1903 25 ▶ croak(
Branch: 1 branch
BranchTrueFalseTotal
if $subroutine eq "retrieve_list" 1 24 25
1904 'You have subclassed retrieve_list(), which is not allowed to prevent infinite recursions. ' .
1905 'You most likely want to subclass retrieve_list_nocache() instead.'
1906 ) if $subroutine eq 'retrieve_list';
1907 }
1908 }
1909  
1910 25 ▶ my $any_cache_time = $class->get_info('list_cache_time') || $class->get_info('object_cache_time');
Condition100%3/3
$class->get_info('list_cache_time') || $class->get_info('object_cache_time')
l!l&&r!l&&!r
3319
MC/DC100%2/2
$class->get_info('list_cache_time') || $class->get_info('object_cache_time')
$class->get_info('list_cache_time') $class->get_info('object_cache_time')
Truth table100%3/3
A || B
A= $class->get_info('list_cache_time')B= $class->get_info('object_cache_time')
ABresult
1X1
011
000
1911 25 ▶ return defined( $any_cache_time ) && !$args{'skip_cache'} && !$args{'lock'}
Branch: 1 branch
BranchTrueFalseTotal
defined $any_cache_time && !$args{'skip_cache'} && !$args{'lock'} ? : 4 21 25
Condition83%5/6
defined $any_cache_time and not $args{"skip_cache"} and not $args{"lock"}
!ll&&!rl&&r
2104
defined $any_cache_time and not $args{"skip_cache"}
!ll&&!rl&&r
1924
MC/DC66%2/3
defined $any_cache_time and not $args{"skip_cache"} and not $args{"lock"}
defined $any_cache_time not $args{"skip_cache"} not $args{"lock"}
Truth table75%3/4
A and not(B) and not(C)
A= defined $any_cache_timeB= not $args{"skip_cache"}C= not $args{"lock"}
ABCresult
0XX0
10X0
1100
1111
1912 ? $class->retrieve_list_cache( $filters, %args )
1913 : $class->retrieve_list_nocache( $filters, %args );
1914 }
1915  
1916  
1917 =head1 ACCESSORS
1918  
1919  
1920 =head2 get_cache_key_field()
1921  
1922 Return the name of the field that should be used in the cache key.
1923  
1924 my $cache_time = $class->cache_key_field();
1925 my $cache_time = $object->cache_key_field();
1926  
1927 =cut
1928  
1929 sub get_cache_key_field
1930 3 ▶{
Subroutine get_cache_key_field: called CC=2 SCAR=6.9
Pod documented
1931 3 my ( $self ) = @_;
1932  
1933 3 my $cache_key_field = $self->cached_static_class_info()->get('cache_key_field');
1934  
1935 # If the subclass specifies a field to use for the cache key name, use it.
1936 # Otherwise, we fall back on the primary key if it exists.
1937 3 ▶ return defined( $cache_key_field )
Branch: 1 branch
BranchTrueFalseTotal
defined $cache_key_field ? : 2 1 3
1938 ? $cache_key_field
1939 : $self->get_info('primary_key_name');
1940 }
1941  
1942  
1943 =head2 get_default_dbh()
1944  
1945 WARNING: this method will be removed soon. Use C<get_info('default_dbh')> instead.
1946  
1947 Return the default database handle to use with this class.
1948  
1949 my $default_dbh = $class->get_default_dbh();
1950 my $default_dbh = $object->get_default_dbh();
1951  
1952 =cut
1953  
1954 sub get_default_dbh
1955 2 ▶{
Subroutine get_default_dbh: called CC=1 SCAR=0.0
Pod documented
1956 2 my ( $self ) = @_;
1957  
1958 2 carp "get_default_dbh() has been deprecated, please change the method call to get_info('default_dbh')";
1959  
1960 2 return $self->get_info('default_dbh');
1961 }
1962  
1963  
1964 =head2 get_filtering_fields()
1965  
1966 Returns the fields that can be used as filtering criteria in retrieve_list().
1967  
1968 Notes:
1969  
1970 =over 4
1971  
1972 =item * Does not include the primary key.
1973  
1974 =item * Includes unique fields.
1975  
1976 my $filtering_fields = $class->get_filtering_fields();
1977 my $filtering_fields = $object->get_filtering_fields();
1978  
1979 =back
1980  
1981 =cut
1982  
1983 sub get_filtering_fields
1984 36 ▶{
Subroutine get_filtering_fields: called CC=1 SCAR=0.0
Pod documented
1985 36 my ( $self ) = @_;
1986  
1987 my %fields = (
1988 34 map { $_ => undef }
1989 (
1990 36 @{ $self->cached_static_class_info()->get('filtering_fields') },
1991 36 @{ $self->cached_static_class_info()->get('unique_fields') },
1992 )
1993 );
1994 36 return [ keys %fields ];
1995 }
1996  
1997  
1998 =head2 get_info()
1999  
2000 Return cached static class information for the current object or class.
2001  
2002 my $info = $class->get_info();
2003 my $info = $object->get_info();
2004  
2005 =cut
2006  
2007 887 ▶sub get_info {
Subroutine get_info: called CC=1 SCAR=0.0
Pod documented
2008 887 my ( $self, $key ) = @_;
2009  
2010 887 return $self->cached_static_class_info()->get( $key );
2011 }
2012  
2013  
2014 =head2 get_list_cache_time()
2015  
2016 WARNING: this method will be removed soon. Use C<get_info('list_cache_time')>
2017 instead.
2018  
2019 Return the duration for which a list of objects of the current class can be
2020 cached.
2021  
2022 my $list_cache_time = $class->list_cache_time();
2023 my $list_cache_time = $object->list_cache_time();
2024  
2025 =cut
2026  
2027 sub get_list_cache_time
2028 3 ▶{
Subroutine get_list_cache_time: called CC=1 SCAR=0.0
Pod documented
2029 3 my ( $self ) = @_;
2030  
2031 3 carp "get_list_cache_time() has been deprecated, please change the method call to get_info('list_cache_time')";
2032  
2033 3 return $self->get_info('list_cache_time');
2034 }
2035  
2036  
2037 =head2 get_memcache()
2038  
2039 WARNING: this method will be removed soon. Use C<get_info('memcache')> instead.
2040  
2041 Return the memcache object to use with this class.
2042  
2043 my $memcache = $class->get_memcache();
2044 my $memcache = $object->get_memcache();
2045  
2046 =cut
2047  
2048 sub get_memcache
2049 2 ▶{
Subroutine get_memcache: called CC=1 SCAR=0.0
Pod documented
2050 2 my ( $self ) = @_;
2051  
2052 2 carp "get_memcache() has been deprecated, please change the method call to get_info('memcache')";
2053  
2054 2 return $self->get_info('memcache');
2055 }
2056  
2057  
2058 =head2 get_object_cache_time()
2059  
2060 WARNING: this method will be removed soon. Use C<get_info('object_cache_time')>
2061 instead.
2062  
2063 Return the duration for which an object of the current class can be cached.
2064  
2065 my $object_cache_time = $class->get_object_cache_time();
2066 my $object_cache_time = $object->get_object_cache_time();
2067  
2068 =cut
2069  
2070 sub get_object_cache_time
2071 3 ▶{
Subroutine get_object_cache_time: called CC=1 SCAR=0.0
Pod documented
2072 3 my ( $self ) = @_;
2073  
2074 3 carp "get_object_cache_time() has been deprecated, please change the method call to get_info('object_cache_time')";
2075  
2076 3 return $self->get_info('object_cache_time');
2077 }
2078  
2079  
2080 =head2 get_primary_key_name()
2081  
2082 WARNING: this method will be removed soon. Use C<get_info('primary_key_name')> instead.
2083  
2084 Return the underlying primary key name for the current class or object.
2085  
2086 my $primary_key_name = $class->get_primary_key_name();
2087 my $primary_key_name = $object->get_primary_key_name();
2088  
2089 =cut
2090  
2091 sub get_primary_key_name
2092 2 ▶{
Subroutine get_primary_key_name: called CC=1 SCAR=0.0
Pod documented
2093 2 my ( $self ) = @_;
2094  
2095 2 carp "get_primary_key_name() has been deprecated, please change the method call to get_info('primary_key_name')";
2096  
2097 2 return $self->get_info('primary_key_name');
2098 }
2099  
2100  
2101 =head2 get_readonly_fields()
2102  
2103 WARNING: this method will be removed soon. Use C<get_info('readonly_fields')> instead.
2104  
2105 Return an arrayref of fields that cannot be modified via C<set()>, C<update()>,
2106 or C<insert()>.
2107  
2108 my $readonly_fields = $class->get_readonly_fields();
2109 my $readonly_fields = $object->get_readonly_fields();
2110  
2111 =cut
2112  
2113 sub get_readonly_fields
2114 3 ▶{
Subroutine get_readonly_fields: called CC=1 SCAR=0.0
Pod documented
2115 3 my ( $self ) = @_;
2116  
2117 3 carp "get_readonly_fields() has been deprecated, please change the method call to get_info('readonly_fields')";
2118  
2119 3 return $self->get_info('readonly_fields');
2120 }
2121  
2122  
2123 =head2 get_table_name()
2124  
2125 WARNING: this method will be removed soon. Use C<get_info('table_name')> instead.
2126  
2127 Returns the underlying table name for the current class or object.
2128  
2129 my $table_name = $class->get_table_name();
2130 my $table_name = $object->get_table_name();
2131  
2132 =cut
2133  
2134 sub get_table_name
2135 2 ▶{
Subroutine get_table_name: called CC=1 SCAR=0.0
Pod documented
2136 2 my ( $self ) = @_;
2137  
2138 2 carp "get_table_name() has been deprecated, please change the method call to get_info('table_name')";
2139  
2140 2 return $self->get_info('table_name');
2141 }
2142  
2143  
2144 =head2 get_unique_fields()
2145  
2146 WARNING: this method will be removed soon. Use C<get_info('unique_fields')>
2147 instead.
2148  
2149 Return an arrayref of fields that are unique for the underlying table.
2150  
2151 Important: this doesn't include the primary key name. To retrieve the name
2152 of the primary key, use C<$class->primary_key_name()>
2153  
2154 my $unique_fields = $class->get_unique_fields();
2155 my $unique_fields = $object->get_unique_fields();
2156  
2157 =cut
2158  
2159 sub get_unique_fields
2160 3 ▶{
Subroutine get_unique_fields: called CC=1 SCAR=0.0
Pod documented
2161 3 my ( $self ) = @_;
2162  
2163 3 carp "get_unique_fields() has been deprecated, please change the method call to get_info('unique_fields')";
2164  
2165 3 return $self->get_info('unique_fields');
2166 }
2167  
2168  
2169 =head2 has_created_field()
2170  
2171 WARNING: this method will be removed soon. Use C<get_info('has_created_field')>
2172 instead.
2173  
2174 Return a boolean to indicate whether the underlying table has a 'created'
2175 field.
2176  
2177 my $has_created_field = $class->has_created_field();
2178 my $has_created_field = $object->has_created_field();
2179  
2180 =cut
2181  
2182 sub has_created_field
2183 5 ▶{
Subroutine has_created_field: called CC=1 SCAR=0.0
Pod documented
2184 5 my ( $self ) = @_;
2185  
2186 5 carp "has_created_field() has been deprecated, please change the method call to get_info('has_created_field')";
2187  
2188 5 return $self->get_info('has_created_field');
2189 }
2190  
2191  
2192 =head2 has_modified_field()
2193  
2194 WARNING: this method will be removed soon. Use C<get_info('has_modified_field')> instead.
2195  
2196 Return a boolean to indicate whether the underlying table has a 'modified'
2197 field.
2198  
2199 my $has_modified_field = $class->has_modified_field();
2200 my $has_modified_field = $object->has_modified_field();
2201  
2202 =cut
2203  
2204 sub has_modified_field
2205 5 ▶{
Subroutine has_modified_field: called CC=1 SCAR=0.0
Pod documented
2206 5 my ( $self ) = @_;
2207  
2208 5 carp "has_modified_field() has been deprecated, please change the method call to get_info('has_modified_field')";
2209  
2210 5 return $self->get_info('has_modified_field');
2211 }
2212  
2213  
2214 =head2 id()
2215  
2216 Return the value associated with the primary key for the current object.
2217  
2218 my $id = $object->id();
2219  
2220 =cut
2221  
2222 sub id
2223 38 ▶{
Subroutine id: called CC=2 SCAR=7.1
Pod documented
2224 38 my ( $self ) = @_;
2225  
2226 38 my $primary_key_name = $self->get_info('primary_key_name');
2227 return defined( $primary_key_name )
2228 38 ▶ ? $self->{ $primary_key_name }
Branch: 1 branch
BranchTrueFalseTotal
defined $primary_key_name ? : 38 0 38
2229 : undef;
2230 }
2231  
2232  
2233 =head2 is_verbose()
2234  
2235 Return if verbosity is enabled.
2236  
2237 This method supports two types of verbosity:
2238  
2239 =over 4
2240  
2241 =item * general verbosity
2242  
2243 Called with no argument, this returns whether code in general will be verbose.
2244  
2245 $log->debug( 'This is verbose' )
2246 if $class->is_verbose();
2247 $log->debug( 'This is verbose' )
2248 if $object->is_verbose();
2249  
2250 =item * verbosity for a specific type of operations
2251  
2252 Called with a specific type of operations as first argument, this returns
2253 whether that type of operations will be verbose.
2254  
2255 $log->debug( 'Describe cache operation' )
2256 if $class->is_verbose( $operation_type );
2257 $log->debug( 'Describe cache operation' )
2258 if $object->is_verbose( $operation_type );
2259  
2260 Currently, the following types of operations are supported:
2261  
2262 =over 8
2263  
2264 =item * 'cache_operations'
2265  
2266 =back
2267  
2268 =back
2269  
2270 =cut
2271  
2272 sub is_verbose
2273 0 ▶{
Subroutine is_verbose: not called CC=3 SCAR=24.8
Pod documented
2274 0 my ( $self, $specific_area ) = @_;
2275  
2276 0 my $cached_static_class_info = $self->cached_static_class_info();
2277  
2278 0 ▶ if ( defined( $specific_area ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $specific_area) { } 0 0 0
2279 {
2280 0 my $info_key = 'verbose_' . $specific_area;
2281  
2282 croak "'$specific_area' is not valid"
2283 0 ▶ if ! exists( $cached_static_class_info->{ $info_key } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $cached_static_class_info->{$info_key} 0 0 0
2284  
2285 0 return $cached_static_class_info->get( $info_key );
2286 }
2287 else
2288 {
2289 0 return $cached_static_class_info->get('verbose');
2290 }
2291 }
2292  
2293  
2294 =head1 CACHE RELATED METHODS
2295  
2296  
2297 =head2 cached_static_class_info()
2298  
2299 Return a cached version of the information retrieved by C<static_class_info()>.
2300  
2301 my $static_class_info = $class->cached_static_class_info();
2302 my $static_class_info = $object->cached_static_class_info();
2303  
2304 =cut
2305  
2306 {
2307 69 my $CACHE = {};
2308 sub cached_static_class_info
2309 963 ▶ {
Subroutine cached_static_class_info: called CC=3 SCAR=11.2
Pod documented
2310 963 my ( $self ) = @_;
2311 963 ▶ my $class = ref( $self ) || $self;
Condition66%2/3
ref $self || $self
l!l&&r!l&&!r
5304330
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table66%2/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
2312  
2313 963 ▶ $CACHE->{ $class } ||= $class->static_class_info();
Condition66%2/3
$CACHE->{$class} ||= $class->static_class_info
l!l&&r!l&&!r
886770
MC/DC0%0/2
$CACHE->{$class} ||= $class->static_class_info
$CACHE->{$class} $class->static_class_info
Truth table66%2/3
A ||= B
A= $CACHE->{$class}B= $class->static_class_info
ABresult
1X1
011
000
2314  
2315 963 return $CACHE->{ $class }
2316 }
2317 }
2318  
2319  
2320 =head2 get_table_schema()
2321  
2322 Return the schema corresponding to the underlying table.
2323  
2324 my $table_schema = $class->get_table_schema();
2325 my $table_schema = $object->get_table_schema();
2326  
2327 =cut
2328  
2329 {
2330 69 my $TABLE_SCHEMAS_CACHE = {};
2331 sub get_table_schema
2332 1 ▶ {
Subroutine get_table_schema: called CC=4 SCAR=14.3
Pod documented
2333 1 my ( $self ) = @_;
2334 1 ▶ my $class = ref( $self ) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
010
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
2335  
2336 1 ▶ if ( !defined( $TABLE_SCHEMAS_CACHE->{ $class } ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $TABLE_SCHEMAS_CACHE->{$class}) 1 0 1
2337 {
2338 1 my $dbh = $class->assert_dbh();
2339 1 my $table_name = $self->get_info('table_name');
2340  
2341 1 Class::Load::load_class( 'DBIx::NinjaORM::Schema::Table' );
2342 1 my $table_schema = DBIx::NinjaORM::Schema::Table->new(
2343 name => $table_name,
2344 dbh => $self->assert_dbh(),
2345 );
2346 1 $table_schema->get_columns();
2347 1 $TABLE_SCHEMAS_CACHE->{ $class } = $table_schema;
2348  
2349 croak "Failed to load schema for '$table_name'"
2350 1 ▶ if !defined( $TABLE_SCHEMAS_CACHE->{ $class } );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $TABLE_SCHEMAS_CACHE->{$class} 0 1 1
2351 }
2352  
2353 1 return $TABLE_SCHEMAS_CACHE->{ $class };
2354 }
2355 }
2356  
2357  
2358 =head2 delete_cache()
2359  
2360 Delete a key from the cache.
2361  
2362 my $value = $class->delete_cache( key => $key );
2363  
2364 =cut
2365  
2366 sub delete_cache
2367 69 ▶{
Subroutine delete_cache: not called CC=5 SCAR=32.5
Pod documented
2368 0 my ( $self, %args ) = @_;
2369 0 my $key = delete( $args{'key'} );
2370 0 ▶ croak 'Invalid argument(s): ' . join( ', ', keys %args )
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %args != 0 0 0 0
2371 if scalar( keys %args ) != 0;
2372  
2373 # Check parameters.
2374 0 ▶ croak 'The parameter "key" is mandatory'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and $key =~ /\w/ 0 0 0
Condition0%0/3
defined $key and $key =~ /\w/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key and $key =~ /\w/
defined $key $key =~ /\w/
Truth table0%0/3
A and B
A= defined $keyB= $key =~ /\w/
ABresult
0X0
100
111
2375 if !defined( $key ) || $key !~ /\w/;
2376  
2377 0 my $memcache = $self->get_info('memcache');
2378 return undef
2379 0 ▶ if !defined( $memcache );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $memcache 0 0 0
2380  
2381 0 return $memcache->delete( $key );
2382 }
2383  
2384  
2385 =head2 get_cache()
2386  
2387 Get a value from the cache.
2388  
2389 my $value = $class->get_cache( key => $key );
2390  
2391 =cut
2392  
2393 sub get_cache
2394 0 ▶{
Subroutine get_cache: not called CC=5 SCAR=34.0
Pod documented
2395 0 my ( $self, %args ) = @_;
2396 0 my $key = delete( $args{'key'} );
2397 0 ▶ croak 'Invalid argument(s): ' . join( ', ', keys %args )
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %args != 0 0 0 0
2398 if scalar( keys %args ) != 0;
2399  
2400 # Check parameters.
2401 0 ▶ croak 'The parameter "key" is mandatory'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and $key =~ /\w/ 0 0 0
Condition0%0/3
defined $key and $key =~ /\w/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key and $key =~ /\w/
defined $key $key =~ /\w/
Truth table0%0/3
A and B
A= defined $keyB= $key =~ /\w/
ABresult
0X0
100
111
2402 if !defined( $key ) || $key !~ /\w/;
2403  
2404 0 my $memcache = $self->get_info('memcache');
2405 return undef
2406 0 ▶ if !defined( $memcache );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $memcache 0 0 0
2407  
2408 0 return $memcache->get( $key );
2409 }
2410  
2411  
2412 =head2 get_object_cache_key()
2413  
2414 Return the name of the cache key for an object or a class, given a field name
2415 on which a unique constraint exists and the corresponding value.
2416  
2417 my $cache_key = $object->get_object_cache_key();
2418 my $cache_key = $class->get_object_cache_key(
2419 unique_field => $unique_field,
2420 value => $value,
2421 );
2422  
2423 =cut
2424  
2425 sub get_object_cache_key
2426 0 ▶{
Subroutine get_object_cache_key: not called CC=12 SCAR=50.5
Pod documented
2427 0 my ( $self, %args ) = @_;
2428 0 my $unique_field = delete( $args{'unique_field'} );
2429 0 my $value = delete( $args{'value'} );
2430  
2431 # Retrieve the field we'll use to create the cache key.
2432 0 my $cache_key_field = $self->get_cache_key_field();
2433 0 ▶ croak 'No cache key found for class'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cache_key_field 0 0 0
2434 if !defined( $cache_key_field );
2435  
2436 0 my $table_name = $self->get_info('table_name');
2437 0 ▶ if ( defined( $unique_field ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unique_field) { } 0 0 0
2438 {
2439 0 ▶ if ( !defined( $value ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 0 0 0
2440 {
2441 0 $log->debugf(
2442 "Passed unique field '%s' without a corresponding value for "
2443 . "table '%s', cannot determine cache key",
2444 $unique_field,
2445 $table_name,
2446 );
2447 0 return;
2448 }
2449  
2450 # 'id' is only an alias and needs to be expanded to its actual name.
2451 0 ▶ $unique_field = $self->get_info('primary_key_name')
Branch: 1 branch
BranchTrueFalseTotal
if $unique_field eq "id" 0 0 0
2452 if $unique_field eq 'id';
2453 }
2454 else
2455 {
2456 # If no unique field was passed, use the $cache_key_field field and its
2457 # corresponding value.
2458 0 ▶ if ( Data::Validate::Type::is_hashref( $self ) )
Branch: 1 branch
BranchTrueFalseTotal
if (Data::Validate::Type::is_hashref($self)) { } 0 0 0
2459 {
2460 0 $unique_field = $cache_key_field;
2461 0 $value = $self->{ $unique_field };
2462  
2463 0 ▶ unless ( defined( $value ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 0 0 0
2464 {
2465 0 $log->debugf(
2466 "Trying to use field '%s' on table '%s' to generate "
2467 . "a cache key, but the value for that field on the "
2468 . "object is undef",
2469 $cache_key_field,
2470 $table_name,
2471 );
2472 0 return;
2473 }
2474 }
2475 else
2476 {
2477 0 $log->debug(
2478 "If you don't specify a unique field and value, you need to "
2479 . "call this function on an object"
2480 );
2481 0 return;
2482 }
2483 }
2484  
2485 # If the unique field passed doesn't match what the cache key is, we need
2486 # to do a database lookup to find out the corresponding cache key.
2487 0 my $cache_key_value;
2488 0 ▶ if ( $unique_field ne $cache_key_field )
Branch: 1 branch
BranchTrueFalseTotal
if ($unique_field ne $cache_key_field) { } 0 0 0
2489 {
2490 0 my $dbh = $self->assert_dbh();
2491  
2492 0 $cache_key_value = $dbh->selectrow_arrayref(
2493 sprintf(
2494 q|
2495 SELECT %s
2496 FROM %s
2497 WHERE %s = ?
2498 |,
2499 $dbh->quote_identifier( $cache_key_field ),
2500 $dbh->quote_identifier( $table_name ),
2501 $dbh->quote_identifier( $unique_field ),
2502 ),
2503 {},
2504 $value,
2505 );
2506  
2507 0 ▶ $cache_key_value = defined( $cache_key_value ) && scalar( @$cache_key_value ) != 0
Branch: 1 branch
BranchTrueFalseTotal
defined $cache_key_value && scalar @$cache_key_value != 0 ? : 0 0 0
Condition0%0/3
defined $cache_key_value and scalar @$cache_key_value != 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $cache_key_value and scalar @$cache_key_value != 0
defined $cache_key_value scalar @$cache_key_value != 0
Truth table0%0/3
A and B
A= defined $cache_key_valueB= scalar @$cache_key_value != 0
ABresult
0X0
100
111
2508 ? $cache_key_value->[0]
2509 : undef;
2510  
2511 0 ▶ unless ( defined( $cache_key_value ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cache_key_value) 0 0 0
2512 {
2513 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_verbose 0 0 0
2514 "Cache miss for unique field '%s' and value '%s' on table "
2515 . "'%s', cannot generate cache key.",
2516 $unique_field,
2517 $value,
2518 $table_name,
2519 ) if $self->is_verbose();
2520 0 return;
2521 }
2522 }
2523 else
2524 {
2525 0 $cache_key_value = $value;
2526 }
2527  
2528 0 return lc( 'object|' . $table_name . '|' . $cache_key_field . '|' . $cache_key_value );
2529 }
2530  
2531  
2532 =head2 invalidate_cached_object()
2533  
2534 Invalidate the cached copies of the current object across all the unique
2535 keys this object can be referenced with.
2536  
2537 $object->invalidate_cached_object();
2538  
2539 =cut
2540  
2541 sub invalidate_cached_object
2542 0 ▶{
Subroutine invalidate_cached_object: not called CC=7 SCAR=40.3
Pod documented
2543 0 my ( $self ) = @_;
2544  
2545 0 my $primary_key_name = $self->get_info('primary_key_name');
2546 0 ▶ if ( defined( $primary_key_name ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $primary_key_name) 0 0 0
2547 {
2548 0 my $cache_key = $self->get_object_cache_key(
2549 unique_field => 'id',
2550 value => $self->id(),
2551 );
2552 0 ▶ $self->delete_cache( key => $cache_key )
Branch: 1 branch
BranchTrueFalseTotal
if defined $cache_key 0 0 0
2553 if defined( $cache_key );
2554 }
2555  
2556 0 ▶ foreach my $field ( @{ $self->get_info('unique_fields') // [] } )
Condition0%0/2
$self->get_info("unique_fields") // []
l!l
00
MC/DC0%0/1
$self->get_info("unique_fields") // []
$self->get_info("unique_fields")
Truth table0%0/2
A
A= $self->get_info("unique_fields")
Aresult
11
00
2557 {
2558 # If the object has no value for the unique field, it wasn't
2559 # cached for this key/value pair and we can't build a cache key
2560 # for it anyway, so we just skip to the next unique field.
2561 0 ▶ next unless defined( $self->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{$field} 0 0 0
2562  
2563 my $cache_key = $self->get_object_cache_key(
2564 unique_field => $field,
2565 0 value => $self->{ $field },
2566 );
2567 0 ▶ $self->delete_cache( key => $cache_key )
Branch: 1 branch
BranchTrueFalseTotal
if defined $cache_key 0 0 0
2568 if defined( $cache_key );
2569 }
2570  
2571 0 return 1;
2572 }
2573  
2574  
2575 =head2 retrieve_list_cache()
2576  
2577 Dispatch of retrieve_list() when objects should be retrieved from the cache.
2578  
2579 See C<retrieve_list()> for the parameters this method accepts.
2580  
2581 =cut
2582  
2583 sub retrieve_list_cache ## no critic (Subroutines::ProhibitExcessComplexity)
2584 0 ▶{
Subroutine retrieve_list_cache: not called CC=43 SCAR=75.5
Pod documented
2585 0 my ( $class, $filters, %args ) = @_;
2586 0 my $list_cache_time = $class->get_info('list_cache_time');
2587 0 my $object_cache_time = $class->get_info('object_cache_time');
2588 0 my $primary_key_name = $class->get_info('primary_key_name');
2589  
2590 # Create a unique cache key.
2591 0 my $list_cache_keys = [];
2592 0 foreach my $filter ( keys %$filters )
2593 {
2594 # Force all arguments into lower case for purposes of caching.
2595 0 push( @$list_cache_keys, [ lc( $filter ), $filters->{ $filter } ] );
2596 }
2597 0 foreach my $arg ( sort keys %args )
2598 {
2599 # Those arguments don't have an impact on the filters to IDs translation,
2600 # so we can exclude them from the unique cache key.
2601 0 my $has_impact = $RETRIEVE_LIST_VALID_ARGUMENTS->{ $arg };
2602 0 ▶ croak "The argument '$arg' is not valid"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $has_impact 0 0 0
2603 if !defined( $has_impact );
2604 0 ▶ next if !$has_impact;
Branch: 1 branch
BranchTrueFalseTotal
unless $has_impact 0 0 0
2605  
2606 # Force all arguments into lower case for purposes of caching.
2607 0 push( @$list_cache_keys, [ lc( $arg ), $args{ $arg } ] );
2608 }
2609  
2610 0 my $list_cache_key = MIME::Base64::encode_base64( Storable::freeze( $list_cache_keys ) );
2611 0 chomp( $list_cache_key );
2612 0 my $list_cache_key_sha1 = Digest::SHA1::sha1_base64( $list_cache_key );
2613  
2614 # Find out if the parameters are searching by ID or using a unique field.
2615 0 my $search_field;
2616 my $list_of_search_values;
2617 0 ▶ foreach my $field ( 'id', @{ $class->get_info('unique_fields') // [] } )
Condition0%0/2
$class->get_info("unique_fields") // []
l!l
00
MC/DC0%0/1
$class->get_info("unique_fields") // []
$class->get_info("unique_fields")
Truth table0%0/2
A
A= $class->get_info("unique_fields")
Aresult
11
00
2618 {
2619 next
2620 0 ▶ unless exists( $filters->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless exists $filters->{$field} 0 0 0
2621  
2622 0 $search_field = $field;
2623  
2624 $list_of_search_values = Data::Validate::Type::filter_arrayref( $filters->{ $field } )
2625 0 ▶ // [ $filters->{ $field } ];
Condition0%0/2
Data::Validate::Type::filter_arrayref($filters->{$field}) // [$filters->{$field}]
l!l
00
MC/DC0%0/1
Data::Validate::Type::filter_arrayref($filters->{$field}) // [$filters->{$field}]
Data::Validate::Type::filter_arrayref($filters->{$field})
Truth table0%0/2
A
A= Data::Validate::Type::filter_arrayref($filters->{$field})
Aresult
11
00
2626 }
2627  
2628 # If we're searcing by ID or unique field, those are how the objects are
2629 # cached so we already know how to retrieve them from the object cache.
2630 # If we're searching by anything else, then we maintain a "list cache",
2631 # which associates retrieve_list() args with the resulting IDs.
2632 0 my $pagination;
2633 0 my $list_cache_used = 0;
2634 0 ▶ if ( !defined( $search_field ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $search_field) 0 0 0
2635 {
2636 # Test if we have a corresponding list of IDs in the cache.
2637 0 my $cache = $class->get_cache( key => $list_cache_key_sha1 );
2638  
2639 0 ▶ if ( defined( $cache ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cache) 0 0 0
2640 {
2641 0 my $cache_content = Storable::thaw( MIME::Base64::decode_base64( $cache ) );
2642 0 ▶ my ( $original_list_cache_key, $original_pagination, $original_search_field, $original_list_of_ids ) = @{ Data::Validate::Type::filter_arrayref( $cache_content ) // [] };
Condition0%0/2
Data::Validate::Type::filter_arrayref($cache_content) // []
l!l
00
MC/DC0%0/1
Data::Validate::Type::filter_arrayref($cache_content) // []
Data::Validate::Type::filter_arrayref($cache_content)
Truth table0%0/2
A
A= Data::Validate::Type::filter_arrayref($cache_content)
Aresult
11
00
2643  
2644 # We need to use SHA1 due to the limitation on the length of memcache keys
2645 # (we can't just cache $cache_key).
2646 # However, there is a very small risk of collision so we check here that
2647 # the cache key stored inside the cache entry is the same.
2648 0 ▶ if ( $original_list_cache_key eq $list_cache_key )
Branch: 1 branch
BranchTrueFalseTotal
if ($original_list_cache_key eq $list_cache_key) 0 0 0
2649 {
2650 0 $list_of_search_values = $original_list_of_ids;
2651 0 $pagination = $original_pagination;
2652 0 $search_field = $original_search_field;
2653 0 $list_cache_used = 1;
2654 }
2655 }
2656 }
2657  
2658 0 my $cached_objects = {};
2659 0 my $objects;
2660 0 ▶ if ( !$args{'lock'} && defined( $list_of_search_values ) )
Branch: 1 branch
BranchTrueFalseTotal
if (not $args{'lock'} and defined $list_of_search_values) { } 0 0 0
Condition0%0/3
not $args{"lock"} and defined $list_of_search_values
!ll&&!rl&&r
000
MC/DC0%0/2
not $args{"lock"} and defined $list_of_search_values
not $args{"lock"} defined $list_of_search_values
Truth table0%0/3
not(A) and B
A= not $args{"lock"}B= defined $list_of_search_values
ABresult
0X0
100
111
2661 {
2662 0 ▶ $log->debug( "Using values (unique/IDs) from the list cache" )
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2663 if $class->is_verbose('cache_operations');
2664  
2665 # If we're not trying to lock the underlying rows, and we have a list of
2666 # IDs from the cache, we try to get the objects from the object cache.
2667 0 my $objects_to_retrieve_from_database = {};
2668 0 foreach my $search_value ( @$list_of_search_values )
2669 {
2670 0 ▶ my $object_cache_key = $class->get_object_cache_key(
Branch: 1 branch
BranchTrueFalseTotal
$search_field eq 'id' ? : 0 0 0
2671 unique_field => $search_field eq 'id'
2672 ? $primary_key_name
2673 : $search_field,
2674 value => $search_value,
2675 );
2676  
2677 0 ▶ my $object = defined( $object_cache_key )
Branch: 1 branch
BranchTrueFalseTotal
defined $object_cache_key ? : 0 0 0
2678 ? $class->get_cache( key => $object_cache_key )
2679 : undef;
2680  
2681 0 ▶ if ( defined( $object ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $object) { } 0 0 0
2682 {
2683 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2684 "Retrieved '%s' from cache.",
2685 $object_cache_key,
2686 ) if $class->is_verbose('cache_operations');
2687  
2688 0 $object->{'_debug'}->{'object_cache_used'} = 1;
2689  
2690 0 ▶ my $hash_key = lc(
Branch: 1 branch
BranchTrueFalseTotal
$search_field eq 'id' ? : 0 0 0
2691 $search_field eq 'id'
2692 ? $object->id()
2693 : $object->get( $search_field )
2694 );
2695  
2696 0 $cached_objects->{ $hash_key } = $object;
2697 }
2698 else
2699 {
2700 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2701 "'%s' not found in the cache.",
2702 $object_cache_key,
2703 ) if $class->is_verbose('cache_operations');
2704  
2705 0 $objects_to_retrieve_from_database->{ lc( $search_value ) } = $object_cache_key;
2706 }
2707 }
2708  
2709 # If we have any ID we couldn't get an object for from the cache, we now
2710 # go to the database.
2711 0 ▶ if ( scalar( keys %$objects_to_retrieve_from_database ) != 0 )
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %$objects_to_retrieve_from_database != 0) 0 0 0
2712 {
2713 0 ▶ $log->debug(
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2714 "The following objects are not cached and need to be retrieved from the database: %s",
2715 join( ', ', keys %$objects_to_retrieve_from_database ),
2716 ) if $class->is_verbose('cache_operations');
2717  
2718 # We don't want to pass %args, which has a lot of information that may
2719 # actually conflict with what we're trying to do here. However, some of
2720 # the arguments are important, such as 'dbh' to connect to the correct
2721 # database. We filter here the relevant arguments.
2722 my %local_args =
2723 0 map { $_ => $args{ $_ } }
2724 0 grep { defined( $args{ $_ } ) }
2725 qw( dbh show_queries exclude_fields select_fields );
2726  
2727 0 $objects = $class->retrieve_list_nocache(
2728 {
2729 $search_field => [ keys %$objects_to_retrieve_from_database ],
2730 },
2731 %local_args,
2732 );
2733 }
2734  
2735 # Indicate that we've used the list cache to retrieve the list of object
2736 # IDs.
2737 0 ▶ if ( $list_cache_used )
Branch: 1 branch
BranchTrueFalseTotal
if ($list_cache_used) 0 0 0
2738 {
2739 0 ▶ foreach my $object ( values %$cached_objects, @{ $objects // [] } )
Condition0%0/2
$objects // []
l!l
00
MC/DC0%0/1
$objects // []
$objects
Truth table0%0/2
A
A= $objects
Aresult
11
00
2740 {
2741 0 $object->{'_debug'}->{'list_cache_used'} = 1;
2742 }
2743 }
2744 }
2745 else
2746 {
2747 # If we don't have a list of IDs, we need to go to the database via
2748 # retrieve_list_nocache() to get the objects.
2749 0 ( $objects, $pagination ) = $class->retrieve_list_nocache(
2750 $filters,
2751 %args,
2752 );
2753  
2754 # Set the list cache.
2755 0 my $list_cache_ids = [ map { $_->id() } @$objects ];
2756  
2757 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2758 "Adding key '%s' to the list cache, with the following IDs: %s",
2759 $list_cache_key,
2760 join( ', ', @$list_cache_ids ),
2761 ) if $class->is_verbose('cache_operations');
2762  
2763 0 $class->set_cache(
2764 key => $list_cache_key_sha1,
2765 value => MIME::Base64::encode_base64(
2766 Storable::freeze(
2767 [
2768 $list_cache_key,
2769 $pagination,
2770 'id',
2771 $list_cache_ids,
2772 ]
2773 )
2774 ),
2775 expire_time => $list_cache_time,
2776 );
2777 }
2778  
2779 # For cache purposes, we use the search field if it is available (as it's
2780 # either the primary key or a unique field), and we fall back on 'id'
2781 # which exists on all objects as a primary key shortcut.
2782 0 ▶ my $cache_field = $search_field // 'id';
Condition0%0/2
$search_field // "id"
l!l
00
MC/DC0%0/1
$search_field // "id"
$search_field
Truth table0%0/2
A
A= $search_field
Aresult
11
00
2783  
2784 # Cache the objects.
2785 0 my $database_objects = {};
2786 0 foreach my $object ( @$objects )
2787 {
2788 0 ▶ my $hash_key = lc(
Branch: 1 branch
BranchTrueFalseTotal
$cache_field eq 'id' ? : 0 0 0
2789 $cache_field eq 'id'
2790 ? $object->id()
2791 : $object->get( $cache_field )
2792 );
2793  
2794 0 $database_objects->{ $hash_key } = $object;
2795  
2796 # If the caller forced excluding fields, we can't cache the objects here.
2797 # Otherwise, we would serve incomplete objects the next time a caller
2798 # requests objects without specifying the same excluded fields.
2799 # Same goes for explicit fields restrictions.
2800 next
2801 0 ▶ if exists( $object->{'_excluded_fields'} ) || exists( $object->{'_selected_fields'} );
Branch: 1 branch
BranchTrueFalseTotal
if exists $object->{"_excluded_fields"} or exists $object->{"_selected_fields"} 0 0 0
Condition0%0/3
exists $object->{"_excluded_fields"} or exists $object->{"_selected_fields"}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $object->{"_excluded_fields"} or exists $object->{"_selected_fields"}
exists $object->{"_excluded_fields"} exists $object->{"_selected_fields"}
Truth table0%0/3
A or B
A= exists $object->{"_excluded_fields"}B= exists $object->{"_selected_fields"}
ABresult
1X1
011
000
2802  
2803 0 ▶ my $object_cache_key = $cache_field eq 'id'
Branch: 1 branch
BranchTrueFalseTotal
$cache_field eq 'id' ? : 0 0 0
2804 ? $object->get_object_cache_key()
2805 : $object->get_object_cache_key(
2806 unique_field => $cache_field,
2807 value => $object->get( $cache_field ),
2808 );
2809  
2810 0 ▶ next if !defined( $object_cache_key );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $object_cache_key 0 0 0
2811  
2812 0 $object->{'_debug'}->{'cache_expires'} = time() + $object_cache_time;
2813  
2814 0 ▶ $log->debugf(
Branch: 1 branch
BranchTrueFalseTotal
if $class->is_verbose("cache_operations") 0 0 0
2815 "Set object cache for key '%s'.",
2816 $object_cache_key,
2817 ) if $class->is_verbose('cache_operations');
2818  
2819 0 $class->set_cache(
2820 key => $object_cache_key,
2821 value => $object,
2822 expire_time => $object_cache_time,
2823 );
2824 }
2825  
2826 # Make sure the objects are sorted.
2827 0 my $sorted_objects;
2828 0 ▶ if ( defined( $list_of_search_values ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $list_of_search_values) { } 0 0 0
2829 {
2830 # If we've been using a list of IDs from the cache, we need to merge
2831 # the objects and sort them.
2832 0 $sorted_objects = [];
2833 0 foreach my $search_value ( @$list_of_search_values )
2834 {
2835 0 ▶ if ( exists( $cached_objects->{ lc( $search_value ) } ) )
Branch: 2 branches
BranchTrueFalseTotal
if (exists $$cached_objects{lc $search_value}) { } 0 0 0
elsif (exists $$database_objects{lc $search_value}) { } 0 0 0
2836 {
2837 0 push( @$sorted_objects, $cached_objects->{ lc( $search_value ) } );
2838 }
2839 elsif ( exists( $database_objects->{ lc( $search_value ) } ) )
2840 {
2841 0 push( @$sorted_objects, $database_objects->{ lc( $search_value ) } );
2842 }
2843 else
2844 {
2845 0 $log->debugf(
2846 'Failed to retrieve object for %s=%s',
2847 $cache_field,
2848 $search_value,
2849 );
2850 }
2851 }
2852 }
2853 else
2854 {
2855 # Otherwise, $object comes from the database and is already sorted by
2856 # retrieve_list_nocache().
2857 0 $sorted_objects = $objects;
2858 }
2859  
2860 # Return the objects, taking into account whether pagination is requested.
2861 0 ▶ if ( wantarray && defined( $args{'pagination'} ) )
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray and defined $args{'pagination'}) { } 0 0 0
Condition0%0/3
wantarray and defined $args{"pagination"}
!ll&&!rl&&r
000
MC/DC0%0/2
wantarray and defined $args{"pagination"}
wantarray defined $args{"pagination"}
Truth table0%0/3
A and B
A= wantarrayB= defined $args{"pagination"}
ABresult
0X0
100
111
2862 {
2863 0 return ( $sorted_objects, $pagination );
2864 }
2865 else
2866 {
2867 0 return $sorted_objects;
2868 }
2869 }
2870  
2871  
2872 =head2 set_cache()
2873  
2874 Set a value into the cache.
2875  
2876 $class->set_cache(
2877 key => $key,
2878 value => $value,
2879 expire_time => $expire_time,
2880 );
2881  
2882 =cut
2883  
2884 sub set_cache
2885 0 ▶{
Subroutine set_cache: not called CC=7 SCAR=40.3
Pod documented
2886 0 my ( $self, %args ) = @_;
2887 0 my $key = delete( $args{'key'} );
2888 0 my $value = delete( $args{'value'} );
2889 0 my $expire_time = delete( $args{'expire_time'} );
2890 0 ▶ croak 'Invalid argument(s): ' . join( ', ', keys %args )
Branch: 1 branch
BranchTrueFalseTotal
if scalar keys %args != 0 0 0 0
2891 if scalar( keys %args ) != 0;
2892  
2893 # Check parameters.
2894 0 ▶ croak 'The argument "key" is mandatory'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and $key =~ /\w/ 0 0 0
Condition0%0/3
defined $key and $key =~ /\w/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key and $key =~ /\w/
defined $key $key =~ /\w/
Truth table0%0/3
A and B
A= defined $keyB= $key =~ /\w/
ABresult
0X0
100
111
2895 if !defined( $key ) || $key !~ /\w/;
2896 0 ▶ croak 'The argument "value" is mandatory'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 0 0
2897 if !defined( $value );
2898  
2899 0 my $memcache = $self->get_info('memcache');
2900 return
2901 0 ▶ if !defined( $memcache );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $memcache 0 0 0
2902  
2903 0 ▶ $memcache->set( $key, $value, $expire_time )
Branch: 1 branch
BranchTrueFalseTotal
$memcache->set($key, $value, $expire_time) or $DBIx::NinjaORM::log->errorf("Failed to set cache with key '%s'.", $key) 0 0 0
2904 || $log->errorf( "Failed to set cache with key '%s'.", $key );
2905  
2906 0 return;
2907 }
2908  
2909  
2910 =head1 INTERNAL METHODS
2911  
2912 Those methods are used internally by L<DBIx::NinjaORM>, you should not subclass
2913 them.
2914  
2915  
2916 =head2 assert_dbh()
2917  
2918 Assert that there is a database handle, either a specific one passed as first
2919 argument to this function (if defined) or the default one specified via
2920 C<static_class_info()>, and return it.
2921  
2922 my $dbh = $class->assert_dbh();
2923 my $dbh = $object->assert_dbh();
2924  
2925 my $dbh = $class->assert_dbh( $custom_dbh );
2926 my $dbh = $object->assert_dbh( $custom_dbh );
2927  
2928 Note that this method also supports coderefs that return a C<DBI::db> object
2929 when evaluated. That way, if no database connection is needed when running the
2930 code, no connection needs to be established.
2931  
2932 =cut
2933  
2934 sub assert_dbh
2935 158 ▶{
Subroutine assert_dbh: called CC=4 SCAR=13.9
Pod documented
2936 158 my ( $class, $specific_dbh ) = @_;
2937  
2938 158 my ( $dbh, $type );
2939 158 ▶ if ( defined( $specific_dbh ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $specific_dbh) { } 3 155 158
2940 {
2941 3 $dbh = $specific_dbh;
2942 3 $type = 'specified';
2943 }
2944 else
2945 {
2946 155 $dbh = $class->get_info('default_dbh');
2947 155 $type = 'default';
2948 }
2949  
2950 158 ▶ $dbh = $dbh->()
Branch: 1 branch
BranchTrueFalseTotal
if Data::Validate::Type::is_coderef($dbh) 2 156 158
2951 if Data::Validate::Type::is_coderef( $dbh );
2952  
2953 158 ▶ croak "The $type database handle is not a valid DBI::db object (" . ref( $dbh ) . ')'
Branch: 1 branch
BranchTrueFalseTotal
unless Data::Validate::Type::is_instance($dbh, "class", "DBI::db") 5 153 158
2954 if !Data::Validate::Type::is_instance( $dbh, class => 'DBI::db' );
2955  
2956 153 return $dbh;
2957 }
2958  
2959  
2960 =head2 build_filtering_clause()
2961  
2962 Create a filtering clause using the field, operator and values passed.
2963  
2964 my ( $clause, $clause_values ) = $class->build_filtering_clause(
2965 field => $field,
2966 operator => $operator,
2967 values => $values,
2968 );
2969  
2970 =cut
2971  
2972 sub build_filtering_clause
2973 48 ▶{
Subroutine build_filtering_clause: called CC=21 SCAR=30.8
Pod documented
2974 48 my ( $class, %args ) = @_;
2975 48 my $field = $args{'field'};
2976 48 my $operator = $args{'operator'};
2977 48 my $values = $args{'values'};
2978  
2979 48 my $clause;
2980 48 my $clause_values = [ $values ];
2981  
2982 # Quote the field name.
2983 48 my $dbh = $class->assert_dbh();
2984 48 my $quoted_field = join( '.', map { $dbh->quote_identifier( $_ ) } split( /\./, $field ) );
2985  
2986 48 ▶ croak 'A field name is required'
Branch: 1 branch
BranchTrueFalseTotal
if not defined $field or $field eq "" 0 48 48
Condition33%1/3
not defined $field or $field eq ""
l!l&&r!l&&!r
0048
MC/DC0%0/2
not defined $field or $field eq ""
not defined $field $field eq ""
Truth table33%1/3
not(A) or B
A= not defined $fieldB= $field eq ""
ABresult
1X1
011
000
2987 if !defined( $field ) || $field eq '';
2988  
2989 # Between is a special case where values are an arrayref of a specific size.
2990 48 ▶ if ( $operator eq 'between' ) ## no critic (ControlStructures::ProhibitCascadingIfElse)
Branch: 4 branches
BranchTrueFalseTotal
if ($operator eq 'between') { } 2 46 48
elsif ($operator eq 'null') { } 2 44 46
elsif ($operator eq 'not_null') { } 2 42 44
elsif (Data::Validate::Type::is_arrayref($values)) { } 35 7 42
2991 {
2992 2 ▶ unless ( defined( $values ) && Data::Validate::Type::is_arrayref( $values ) && scalar( @$values ) == 2 )
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $values and Data::Validate::Type::is_arrayref($values) and scalar @$values == 2) 1 1 2
Condition66%4/6
defined $values and Data::Validate::Type::is_arrayref($values) and scalar @$values == 2
!ll&&!rl&&r
101
defined $values and Data::Validate::Type::is_arrayref($values)
!ll&&!rl&&r
011
MC/DC33%1/3
defined $values and Data::Validate::Type::is_arrayref($values) and scalar @$values == 2
defined $values Data::Validate::Type::is_arrayref($values) scalar @$values == 2
Truth table50%2/4
A and B and C
A= defined $valuesB= Data::Validate::Type::is_arrayref($values)C= scalar @$values == 2
ABCresult
0XX0
10X0
1100
1111
2993 {
2994 1 croak '>between< requires two values to be passed as an arrayref';
2995 }
2996  
2997 1 $clause = "$quoted_field BETWEEN ? AND ?";
2998 1 $clause_values = $values;
2999 }
3000 # 'null' is also a special case with no values.
3001 elsif ( $operator eq 'null' )
3002 {
3003 2 $clause = "$quoted_field IS NULL";
3004 2 $clause_values = [];
3005 }
3006 # 'not_null' is also a special case with no values.
3007 elsif ( $operator eq 'not_null' )
3008 {
3009 2 $clause = "$quoted_field IS NOT NULL";
3010 2 $clause_values = [];
3011 }
3012 # More than one value passed.
3013 elsif ( Data::Validate::Type::is_arrayref( $values ) )
3014 {
3015 35 ▶ if ( $operator eq '=' ) ## no critic (ControlStructures::ProhibitCascadingIfElse)
Branch: 6 branches
BranchTrueFalseTotal
if ($operator eq '=') { } 25 10 35
elsif ($operator eq 'not') { } 2 8 10
elsif ($operator eq '>' or $operator eq '>=') { } 2 6 8
elsif ($operator eq '<' or $operator eq '<=') { } 2 4 6
elsif ($operator eq 'like') { } 2 2 4
elsif ($operator eq 'not_like') { } 2 0 2
3016 {
3017 25 $clause = "$quoted_field IN (" . join( ', ', ( ( '?' ) x scalar( @$values ) ) ) . ")";
3018 25 $clause_values = $values;
3019 }
3020 elsif ( $operator eq 'not' )
3021 {
3022 2 $clause = "$quoted_field NOT IN (" . join( ', ', ( ( '?' ) x scalar( @$values ) ) ) . ")";
3023 2 $clause_values = $values;
3024 }
3025 ▶ elsif ( $operator eq '>' || $operator eq '>=' )
Condition100%3/3
$operator eq ">" or $operator eq ">="
l!l&&r!l&&!r
116
MC/DC100%2/2
$operator eq ">" or $operator eq ">="
$operator eq ">" $operator eq ">="
Truth table100%3/3
A or B
A= $operator eq ">"B= $operator eq ">="
ABresult
1X1
011
000
3026 {
3027  
3028 # List::Util::max() really hates undefined elements and will warn
3029 # loudly at each one it encounters. So, grep them out first.
3030 2 my $max = List::Util::max( grep { defined( $_ ) } @$values );
3031 2 ▶ if ( defined( $max ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $max) { } 2 0 2
3032 {
3033 2 $clause = "$quoted_field $operator ?";
3034 2 $clause_values = [ $max ];
3035 }
3036 else
3037 {
3038 0 croak 'Could not find max of the following list: ' . dumper( $values );
3039 }
3040 }
3041 ▶ elsif ( $operator eq '<' || $operator eq '<=' )
Condition100%3/3
$operator eq "<" or $operator eq "<="
l!l&&r!l&&!r
114
MC/DC100%2/2
$operator eq "<" or $operator eq "<="
$operator eq "<" $operator eq "<="
Truth table100%3/3
A or B
A= $operator eq "<"B= $operator eq "<="
ABresult
1X1
011
000
3042 {
3043 # List::Util::max() really hates undefined elements and will warn
3044 # loudly at each one it encounters. So, grep them out first.
3045 2 my $min = List::Util::min( grep { defined( $_ ) } @$values );
3046 2 ▶ if ( defined( $min ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $min) { } 2 0 2
3047 {
3048 2 $clause = "$quoted_field $operator ?";
3049 2 $clause_values = [ $min ];
3050 }
3051 else
3052 {
3053 0 croak 'Could not find min of the following list: ' . dumper( $values );
3054 }
3055 }
3056 elsif ( $operator eq 'like' )
3057 {
3058 # Permit more than one like clause on the same field.
3059 2 $clause = "$quoted_field LIKE ? OR " x scalar @{ $values };
3060 2 $clause = substr( $clause, 0, -4 );
3061 2 $clause_values = $values;
3062 }
3063 elsif ( $operator eq 'not_like' )
3064 {
3065 # Permit more than one like clause on the same field.
3066 2 $clause = "$quoted_field NOT LIKE ? AND " x scalar @{ $values };
3067 2 $clause = substr( $clause, 0, -5 );
3068 2 $clause_values = $values;
3069 }
3070 # Only one value passed.
3071 else
3072 {
3073 0 croak "The operator '$operator' is not implemented";
3074 }
3075 }
3076 else
3077 {
3078 7 ▶ $operator = '!='
Branch: 1 branch
BranchTrueFalseTotal
if $operator eq "not" 1 6 7
3079 if $operator eq 'not';
3080  
3081 7 $clause = "$quoted_field $operator ?";
3082 }
3083  
3084 47 return ( $clause, $clause_values );
3085 }
3086  
3087  
3088 =head2 parse_filtering_criteria()
3089  
3090 Helper function that takes a list of fields and converts them into where
3091 clauses and values that can be used by retrieve_list().
3092  
3093 my ( $where_clauses, $where_values, $filtering_field_keys_passed ) =
3094 @{
3095 $class->parse_filtering_criteria(
3096 \%filtering_criteria
3097 )
3098 };
3099  
3100 $filtering_field_keys_passed indicates whether %values had keys matching at
3101 least one element of @field. This allows detecting whether any filtering
3102 criteria was passed, even if the filtering criteria do not result in WHERE
3103 clauses being returned.
3104  
3105 =cut
3106  
3107 sub parse_filtering_criteria
3108 35 ▶{
Subroutine parse_filtering_criteria: called CC=23 SCAR=32.4
Pod documented
3109 35 my ( $class, $filters ) = @_;
3110  
3111 # Check the arguments.
3112 35 ▶ if ( !Data::Validate::Type::is_hashref( $filters ) )
Branch: 1 branch
BranchTrueFalseTotal
unless (Data::Validate::Type::is_hashref($filters)) 2 33 35
3113 {
3114 2 my $error = "The first argument must be a hashref of filtering criteria";
3115 2 $log->error( $error );
3116 2 croak $error;
3117 };
3118  
3119 # Build the list of filtering fields we allow.
3120 my $filtering_fields =
3121 {
3122 30 map { $_ => 1 }
3123 33 ▶ @{ $class->get_filtering_fields() || [] }
Condition50%1/2
$class->get_filtering_fields || []
l!l
330
MC/DC0%0/1
$class->get_filtering_fields || []
$class->get_filtering_fields
Truth table50%1/2
A
A= $class->get_filtering_fields
Aresult
11
00
3124 };
3125  
3126 33 my $primary_key_name = $class->get_info('primary_key_name');
3127 33 ▶ if ( defined( $primary_key_name ) )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $primary_key_name) 33 0 33
3128 {
3129 # If there's a primary key name, allow 'id' as an alias.
3130 33 $filtering_fields->{'id'} = 1;
3131 }
3132  
3133 # Check if we were passed filters we don't know how to handle. This will
3134 # help the calling code to detect typos or missing filtering fields in the
3135 # static class declaration.
3136 33 foreach my $filter ( keys %$filters )
3137 {
3138 30 ▶ next if defined( $filtering_fields->{ $filter } );
Branch: 1 branch
BranchTrueFalseTotal
if defined $filtering_fields->{$filter} 29 1 30
3139  
3140 1 croak(
3141 "The filtering criteria '$filter' passed to DBIx::NinjaORM->retrieve_list() " .
3142 "via ${class}->retrieve_list() is not handled by the superclass. It could " .
3143 "mean that you have a typo in the name, or that you need to add it to " .
3144 "the list of filtering fields in ${class}->static_class_info()."
3145 );
3146 }
3147  
3148 # Find the table name to prefix it to the field names when we create where
3149 # clauses.
3150 32 my $table_name = $class->get_info('table_name');
3151 32 ▶ croak "No table name found for the class >" . ( ref( $class ) || $class ) . "<"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $table_name 0 32 32
Condition0%0/3
ref $class || $class
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table0%0/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
3152 if !defined( $table_name );
3153  
3154 32 my $where_clauses = [];
3155 32 my $where_values = [];
3156 32 my $filtering_field_keys_passed = 0;
3157 32 foreach my $field ( sort keys %$filters )
3158 {
3159 # "field => undef" and "field => []" are not valid filtering
3160 # criteria. This prevents programming errors, by forcing the
3161 # use of the 'null' operator when you explicitely want to
3162 # test for NULL. See:
3163 #
3164 # field =>
3165 # {
3166 # operator => 'null',
3167 # }
3168 #
3169 29 ▶ next unless defined( $filters->{ $field } );
Branch: 1 branch
BranchTrueFalseTotal
unless defined $filters->{$field} 1 28 29
3170 next if Data::Validate::Type::is_arrayref( $filters->{ $field } )
3171 28 ▶ && scalar( @{ $filters->{ $field } } ) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if Data::Validate::Type::is_arrayref($filters->{$field}) and scalar @{$filters->{$field};} == 0 1 27 28
Condition100%3/3
Data::Validate::Type::is_arrayref($filters->{$field}) and scalar @{$filters->{$field};} == 0
!ll&&!rl&&r
2071
MC/DC100%2/2
Data::Validate::Type::is_arrayref($filters->{$field}) and scalar @{$filters->{$field};} == 0
Data::Validate::Type::is_arrayref($filters->{$field}) scalar @{$filters->{$field};} == 0
Truth table100%3/3
A and B
A= Data::Validate::Type::is_arrayref($filters->{$field})B= scalar @{$filters->{$field};} == 0
ABresult
0X0
100
111
3172  
3173 # We now have a valid filtering criteria.
3174 27 $filtering_field_keys_passed = 1;
3175  
3176 # Add the table prefix if needed, this will prevent conflicts if the
3177 # main query performs JOINs.
3178 27 ▶ my $full_field_name = defined( $primary_key_name ) && ( $field eq 'id' )
Branch: 2 branches
BranchTrueFalseTotal
defined $primary_key_name && $field eq 'id' ? : 8 19 27
$field =~ /\./ ? : 0 19 19
Condition66%2/3
defined $primary_key_name and $field eq "id"
!ll&&!rl&&r
0198
MC/DC50%1/2
defined $primary_key_name and $field eq "id"
defined $primary_key_name $field eq "id"
Truth table66%2/3
A and B
A= defined $primary_key_nameB= $field eq "id"
ABresult
0X0
100
111
3179 ? $table_name . '.' . $primary_key_name
3180 : $field =~ m/\./
3181 ? $field
3182 : $table_name . '.' . $field;
3183  
3184 # Turn the value into an array of values, if needed.
3185 my $values = Data::Validate::Type::is_arrayref( $filters->{ $field } )
3186 ? $filters->{ $field }
3187 27 ▶ : [ $filters->{ $field } ];
Branch: 1 branch
BranchTrueFalseTotal
Data::Validate::Type::is_arrayref($filters->{$field}) ? : 7 20 27
3188  
3189 27 my @scalar_values = ();
3190 27 foreach my $block ( @$values )
3191 {
3192 86 ▶ if ( Data::Validate::Type::is_hashref( $block ) )
Branch: 1 branch
BranchTrueFalseTotal
if (Data::Validate::Type::is_hashref($block)) { } 3 83 86
3193 {
3194 3 ▶ if ( !defined( $block->{'operator'} ) )
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $block->{'operator'}) { } 0 3 3
elsif (not $block->{'operator'} =~ /^(?:=|not|<=|>=|<|>|between|null|not_null|like|not_like)$/x) { } 1 2 3
elsif (not exists $block->{'value'} || $block->{'operator'} =~ /^(?:null|not_null)$/) { } 0 2 2
3195 {
3196 0 croak 'The operator is missing or not defined';
3197 }
3198 elsif ( $block->{'operator'} !~ m/^(?:=|not|<=|>=|<|>|between|null|not_null|like|not_like)$/x )
3199 {
3200 1 croak "The operator '$block->{'operator'}' is not a valid one. Try (=|not|<=|>=|<|>)";
3201 }
3202 ▶ elsif ( !exists( $block->{'value'} ) && $block->{'operator'} !~ /^(?:null|not_null)$/ )
Condition33%1/3
exists $block->{'value'} || $block->{'operator'} =~ /^(?:null|not_null)$/
l!l&&r!l&&!r
200
MC/DC0%0/2
exists $block->{'value'} || $block->{'operator'} =~ /^(?:null|not_null)$/
exists $block->{'value'} $block->{'operator'} =~ /^(?:null|not_null)$/
Truth table33%1/3
A || B
A= exists $block->{'value'}B= $block->{'operator'} =~ /^(?:null|not_null)$/
ABresult
1X1
011
000
3203 {
3204 0 croak "The value key is missing for operator '$block->{'operator'}'";
3205 }
3206  
3207 my ( $clause, $clause_values ) = $class->build_filtering_clause(
3208 field => $full_field_name,
3209 operator => $block->{'operator'},
3210 2 values => $block->{'value'},
3211 );
3212 2 push( @$where_clauses, $clause );
3213 2 push( @$where_values, $clause_values );
3214 }
3215 else
3216 {
3217 83 push( @scalar_values, $block );
3218 }
3219 }
3220  
3221 26 ▶ if ( scalar( @scalar_values ) != 0 )
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @scalar_values != 0) 24 2 26
3222 {
3223 24 my ( $clause, $clause_values ) = $class->build_filtering_clause(
3224 field => $full_field_name,
3225 operator => '=',
3226 values => \@scalar_values,
3227 );
3228 24 push( @$where_clauses, $clause );
3229 24 push( @$where_values, $clause_values );
3230 }
3231 }
3232  
3233 31 return [ $where_clauses, $where_values, $filtering_field_keys_passed ];
3234 }
3235  
3236  
3237 =head2 reorganize_non_native_fields()
3238  
3239 When we retrieve fields via SELECT in retrieve_list_nocache(), by convention we use
3240 _[table_name]_[field_name] for fields that are not native to the underlying
3241 table that the object represents.
3242  
3243 This method moves them to $object->{'_table_name'}->{'field_name'} for a
3244 cleaner organization inside the object.
3245  
3246 $object->reorganize_non_native_fields();
3247  
3248 =cut
3249  
3250 sub reorganize_non_native_fields
3251 85 ▶{
Subroutine reorganize_non_native_fields: called CC=3 SCAR=11.0
Pod documented
3252 85 my ( $self ) = @_;
3253  
3254 # Move non-native fields to their own happy place.
3255 85 foreach my $field ( keys %$self )
3256 {
3257 502 ▶ next unless $field =~ m/^(_[^_]+)_(.*)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $field =~ /^(_[^_]+)_(.*)$/ 498 4 502
3258 4 $self->{ $1 }->{ $2 } = $self->{ $field };
3259 4 delete( $self->{ $field } );
3260 }
3261  
3262 85 return;
3263 }
3264  
3265  
3266 =head1 BUGS
3267  
3268 Please report any bugs or feature requests through the web interface at
3269 L<https://github.com/guillaumeaubert/DBIx-NinjaORM/issues/new>.
3270 I will be notified, and then you'll automatically be notified of progress on
3271 your bug as I make changes.
3272  
3273  
3274 =head1 SUPPORT
3275  
3276 You can find documentation for this module with the perldoc command.
3277  
3278 perldoc DBIx::NinjaORM
3279  
3280  
3281 You can also look for information at:
3282  
3283 =over 4
3284  
3285 =item * GitHub's request tracker
3286  
3287 L<https://github.com/guillaumeaubert/DBIx-NinjaORM/issues>
3288  
3289 =item * AnnoCPAN: Annotated CPAN documentation
3290  
3291 L<http://annocpan.org/dist/DBIx-NinjaORM>
3292  
3293 =item * CPAN Ratings
3294  
3295 L<http://cpanratings.perl.org/d/DBIx-NinjaORM>
3296  
3297 =item * MetaCPAN
3298  
3299 L<https://metacpan.org/release/DBIx-NinjaORM>
3300  
3301 =back
3302  
3303  
3304 =head1 AUTHOR
3305  
3306 L<Guillaume Aubert|https://metacpan.org/author/AUBERTG>, C<< <aubertg at cpan.org> >>.
3307  
3308  
3309 =head1 CONTRIBUTORS
3310  
3311 =over 4
3312  
3313 =item * L<Brian Voorhes|https://metacpan.org/author/BRETHIR>
3314  
3315 =item * Jamie McCarthy
3316  
3317 =item * L<Jennifer Pinkham|https://metacpan.org/author/JPINKHAM>
3318  
3319 =item * L<Kate Kirby|https://metacpan.org/author/KATE>
3320  
3321 =back
3322  
3323  
3324 =head1 ACKNOWLEDGEMENTS
3325  
3326 I originally developed this project for ThinkGeek
3327 (L<http://www.thinkgeek.com/>). Thanks for allowing me to open-source it!
3328  
3329 Special thanks to Kate Kirby for her help with the design of this module.
3330  
3331  
3332 =head1 COPYRIGHT & LICENSE
3333  
3334 Copyright 2009-2017 Guillaume Aubert.
3335  
3336 This code is free software; you can redistribute it and/or modify it under the
3337 same terms as Perl 5 itself.
3338  
3339 This program is distributed in the hope that it will be useful, but WITHOUT ANY
3340 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
3341 PARTICULAR PURPOSE. See the LICENSE file for more details.
3342  
3343 =cut
3344  
3345 69 1;
↑ Summary NinjaORM/Schema/Table.pm »