blib/lib/DBIx/Class/Fixtures.pm

filter: Statementstmt 90.3% 487 / 539 Branchbran 68.1% 180 / 264 Conditioncond 60.6% 80 / 132 MC/DCmcdc 25.3% 18 / 71 Subroutinesub 80.0% 40 / 50 Podpod 54.5% 6 / 11 totaltotal 76.0% 811 / 1067 CC 201 SCAR 35.7
CC
201
Cov
80%
dump_object
95.4
dump
38.9
populate
31.7
CRAP 35.5
↑ Summary blib/lib/DBIx/Class/Fixtures/DBI.pm »
1 package DBIx::Class::Fixtures;
2  
3 22 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 22 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 22 ▶use DBIx::Class 0.08100;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 22 ▶use DBIx::Class::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 22 ▶use Class::Accessor::Grouped;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 22 ▶use Config::Any::JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 22 ▶use Data::Dump::Streamer;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 22 ▶use Data::Visitor::Callback;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 22 ▶use Hash::Merge qw( merge );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 22 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 22 ▶use Class::C3::Componentised;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 22 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 22 ▶use IO::All;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 22 ▶use File::Temp qw/tempdir/;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 22 ▶use base qw(Class::Accessor::Grouped);
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 22 our $namespace_counter = 0;
22  
23 22 __PACKAGE__->mk_group_accessors( 'simple' => qw/config_dir
24 _inherited_attributes debug schema_class dumped_objects config_attrs/);
25  
26 22 our $VERSION = '1.001034';
27  
28 22 $VERSION = eval $VERSION;
29  
30 =head1 NAME
31  
32 DBIx::Class::Fixtures - Dump data and repopulate a database using rules
33  
34 =head1 SYNOPSIS
35  
36 use DBIx::Class::Fixtures;
37  
38 ...
39  
40 my $fixtures = DBIx::Class::Fixtures->new({
41 config_dir => '/home/me/app/fixture_configs'
42 });
43  
44 $fixtures->dump({
45 config => 'set_config.json',
46 schema => $source_dbic_schema,
47 directory => '/home/me/app/fixtures'
48 });
49  
50 $fixtures->populate({
51 directory => '/home/me/app/fixtures',
52 ddl => '/home/me/app/sql/ddl.sql',
53 connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password'],
54 post_ddl => '/home/me/app/sql/post_ddl.sql',
55 });
56  
57 =head1 DESCRIPTION
58  
59 Dump fixtures from source database to filesystem then import to another
60 database (with same schema) at any time. Use as a constant dataset for running
61 tests against or for populating development databases when impractical to use
62 production clones. Describe fixture set using relations and conditions based on
63 your DBIx::Class schema.
64  
65 =head1 DEFINE YOUR FIXTURE SET
66  
67 Fixture sets are currently defined in .json files which must reside in your
68 config_dir (e.g. /home/me/app/fixture_configs/a_fixture_set.json). They
69 describe which data to pull and dump from the source database.
70  
71 For example:
72  
73 {
74 "sets": [
75 {
76 "class": "Artist",
77 "ids": ["1", "3"]
78 },
79 {
80 "class": "Producer",
81 "ids": ["5"],
82 "fetch": [
83 {
84 "rel": "artists",
85 "quantity": "2"
86 }
87 ]
88 }
89 ]
90 }
91  
92 This will fetch artists with primary keys 1 and 3, the producer with primary
93 key 5 and two of producer 5's artists where 'artists' is a has_many DBIx::Class
94 rel from Producer to Artist.
95  
96 The top level attributes are as follows:
97  
98 =head2 sets
99  
100 Sets must be an array of hashes, as in the example given above. Each set
101 defines a set of objects to be included in the fixtures. For details on valid
102 set attributes see L</SET ATTRIBUTES> below.
103  
104 =head2 rules
105  
106 Rules place general conditions on classes. For example if whenever an artist
107 was dumped you also wanted all of their cds dumped too, then you could use a
108 rule to specify this. For example:
109  
110 {
111 "sets": [
112 {
113 "class": "Artist",
114 "ids": ["1", "3"]
115 },
116 {
117 "class": "Producer",
118 "ids": ["5"],
119 "fetch": [
120 {
121 "rel": "artists",
122 "quantity": "2"
123 }
124 ]
125 }
126 ],
127 "rules": {
128 "Artist": {
129 "fetch": [ {
130 "rel": "cds",
131 "quantity": "all"
132 } ]
133 }
134 }
135 }
136  
137 In this case all the cds of artists 1, 3 and all producer 5's artists will be
138 dumped as well. Note that 'cds' is a has_many DBIx::Class relation from Artist
139 to CD. This is eqivalent to:
140  
141 {
142 "sets": [
143 {
144 "class": "Artist",
145 "ids": ["1", "3"],
146 "fetch": [ {
147 "rel": "cds",
148 "quantity": "all"
149 } ]
150 },
151 {
152 "class": "Producer",
153 "ids": ["5"],
154 "fetch": [ {
155 "rel": "artists",
156 "quantity": "2",
157 "fetch": [ {
158 "rel": "cds",
159 "quantity": "all"
160 } ]
161 } ]
162 }
163 ]
164 }
165  
166 rules must be a hash keyed by class name.
167  
168 L</RULE ATTRIBUTES>
169  
170 =head2 includes
171  
172 To prevent repetition between configs you can include other configs. For
173 example:
174  
175 {
176 "sets": [ {
177 "class": "Producer",
178 "ids": ["5"]
179 } ],
180 "includes": [
181 { "file": "base.json" }
182 ]
183 }
184  
185 Includes must be an arrayref of hashrefs where the hashrefs have key 'file'
186 which is the name of another config file in the same directory. The original
187 config is merged with its includes using L<Hash::Merge>.
188  
189 =head2 datetime_relative
190  
191 Only available for MySQL and PostgreSQL at the moment, must be a value that
192 DateTime::Format::* can parse. For example:
193  
194 {
195 "sets": [ {
196 "class": "RecentItems",
197 "ids": ["9"]
198 } ],
199 "datetime_relative": "2007-10-30 00:00:00"
200 }
201  
202 This will work when dumping from a MySQL database and will cause any datetime
203 fields (where datatype => 'datetime' in the column def of the schema class) to
204 be dumped as a DateTime::Duration object relative to the date specified in the
205 datetime_relative value. For example if the RecentItem object had a date field
206 set to 2007-10-25, then when the fixture is imported the field will be set to 5
207 days in the past relative to the current time.
208  
209 =head2 might_have
210  
211 Specifies whether to automatically dump might_have relationships. Should be a
212 hash with one attribute - fetch. Set fetch to 1 or 0.
213  
214 {
215 "might_have": { "fetch": 1 },
216 "sets": [
217 {
218 "class": "Artist",
219 "ids": ["1", "3"]
220 },
221 {
222 "class": "Producer",
223 "ids": ["5"]
224 }
225 ]
226 }
227  
228 Note: belongs_to rels are automatically dumped whether you like it or not, this
229 is to avoid FKs to nowhere when importing. General rules on has_many rels are
230 not accepted at this top level, but you can turn them on for individual sets -
231 see L</SET ATTRIBUTES>.
232  
233 =head1 SET ATTRIBUTES
234  
235 =head2 class
236  
237 Required attribute. Specifies the DBIx::Class object class you wish to dump.
238  
239 =head2 ids
240  
241 Array of primary key ids to fetch, basically causing an $rs->find($_) for each.
242 If the id is not in the source db then it just won't get dumped, no warnings or
243 death.
244  
245 =head2 quantity
246  
247 Must be either an integer or the string 'all'. Specifying an integer will
248 effectively set the 'rows' attribute on the resultset clause, specifying 'all'
249 will cause the rows attribute to be left off and for all matching rows to be
250 dumped. There's no randomising here, it's just the first x rows.
251  
252 =head2 cond
253  
254 A hash specifying the conditions dumped objects must match. Essentially this is
255 a JSON representation of a DBIx::Class search clause. For example:
256  
257 {
258 "sets": [{
259 "class": "Artist",
260 "quantiy": "all",
261 "cond": { "name": "Dave" }
262 }]
263 }
264  
265 This will dump all artists whose name is 'dave'. Essentially
266 $artist_rs->search({ name => 'Dave' })->all.
267  
268 Sometimes in a search clause it's useful to use scalar refs to do things like:
269  
270 $artist_rs->search({ no1_singles => \'> no1_albums' })
271  
272 This could be specified in the cond hash like so:
273  
274 {
275 "sets": [ {
276 "class": "Artist",
277 "quantiy": "all",
278 "cond": { "no1_singles": "\> no1_albums" }
279 } ]
280 }
281  
282 So if the value starts with a backslash the value is made a scalar ref before
283 being passed to search.
284  
285 =head2 join
286  
287 An array of relationships to be used in the cond clause.
288  
289 {
290 "sets": [ {
291 "class": "Artist",
292 "quantiy": "all",
293 "cond": { "cds.position": { ">": 4 } },
294 "join": ["cds"]
295 } ]
296 }
297  
298 Fetch all artists who have cds with position greater than 4.
299  
300 =head2 fetch
301  
302 Must be an array of hashes. Specifies which rels to also dump. For example:
303  
304 {
305 "sets": [ {
306 "class": "Artist",
307 "ids": ["1", "3"],
308 "fetch": [ {
309 "rel": "cds",
310 "quantity": "3",
311 "cond": { "position": "2" }
312 } ]
313 } ]
314 }
315  
316 Will cause the cds of artists 1 and 3 to be dumped where the cd position is 2.
317  
318 Valid attributes are: 'rel', 'quantity', 'cond', 'has_many', 'might_have' and
319 'join'. rel is the name of the DBIx::Class rel to follow, the rest are the same
320 as in the set attributes. quantity is necessary for has_many relationships, but
321 not if using for belongs_to or might_have relationships.
322  
323 =head2 has_many
324  
325 Specifies whether to fetch has_many rels for this set. Must be a hash
326 containing keys fetch and quantity.
327  
328 Set fetch to 1 if you want to fetch them, and quantity to either 'all' or an
329 integer.
330  
331 Be careful here, dumping has_many rels can lead to a lot of data being dumped.
332  
333 =head2 might_have
334  
335 As with has_many but for might_have relationships. Quantity doesn't do anything
336 in this case.
337  
338 This value will be inherited by all fetches in this set. This is not true for
339 the has_many attribute.
340  
341 =head2 external
342  
343 In some cases your database information might be keys to values in some sort of
344 external storage. The classic example is you are using L<DBIx::Class::InflateColumn::FS>
345 to store blob information on the filesystem. In this case you may wish the ability
346 to backup your external storage in the same way your database data. The L</external>
347 attribute lets you specify a handler for this type of issue. For example:
348  
349 {
350 "sets": [{
351 "class": "Photo",
352 "quantity": "all",
353 "external": {
354 "file": {
355 "class": "File",
356 "args": {"path":"__ATTR(photo_dir)__"}
357 }
358 }
359 }]
360 }
361  
362 This would use L<DBIx::Class::Fixtures::External::File> to read from a directory
363 where the path to a file is specified by the C<file> field of the C<Photo> source.
364 We use the uninflated value of the field so you need to completely handle backup
365 and restore. For the common case we provide L<DBIx::Class::Fixtures::External::File>
366 and you can create your own custom handlers by placing a '+' in the namespace:
367  
368 "class": "+MyApp::Schema::SomeExternalStorage",
369  
370 Although if possible I'd love to get patches to add some of the other common
371 types (I imagine storage in MogileFS, Redis, etc or even Amazon might be popular.)
372  
373 See L<DBIx::Class::Fixtures::External::File> for the external handler interface.
374  
375 =head1 RULE ATTRIBUTES
376  
377 =head2 cond
378  
379 Same as with L</SET ATTRIBUTES>
380  
381 =head2 fetch
382  
383 Same as with L</SET ATTRIBUTES>
384  
385 =head2 join
386  
387 Same as with L</SET ATTRIBUTES>
388  
389 =head2 has_many
390  
391 Same as with L</SET ATTRIBUTES>
392  
393 =head2 might_have
394  
395 Same as with L</SET ATTRIBUTES>
396  
397 =head1 RULE SUBSTITUTIONS
398  
399 You can provide the following substitution patterns for your rule values. An
400 example of this might be:
401  
402 {
403 "sets": [{
404 "class": "Photo",
405 "quantity": "__ENV(NUMBER_PHOTOS_DUMPED)__",
406 }]
407 }
408  
409 =head2 ENV
410  
411 Provide a value from %ENV
412  
413 =head2 ATTR
414  
415 Provide a value from L</config_attrs>
416  
417 =head2 catfile
418  
419 Create the path to a file from a list
420  
421 =head2 catdir
422  
423 Create the path to a directory from a list
424  
425 =head1 METHODS
426  
427 =head2 new
428  
429 =over 4
430  
431 =item Arguments: \%$attrs
432  
433 =item Return Value: $fixture_object
434  
435 =back
436  
437 Returns a new DBIx::Class::Fixture object. %attrs can have the following
438 parameters:
439  
440 =over
441  
442 =item config_dir:
443  
444 required. must contain a valid path to the directory in which your .json
445 configs reside.
446  
447 =item debug:
448  
449 determines whether to be verbose
450  
451 =item ignore_sql_errors:
452  
453 ignore errors on import of DDL etc
454  
455 =item config_attrs
456  
457 A hash of information you can use to do replacements inside your configuration
458 sets. For example, if your set looks like:
459  
460 {
461 "sets": [ {
462 "class": "Artist",
463 "ids": ["1", "3"],
464 "fetch": [ {
465 "rel": "cds",
466 "quantity": "__ATTR(quantity)__",
467 } ]
468 } ]
469 }
470  
471 my $fixtures = DBIx::Class::Fixtures->new( {
472 config_dir => '/home/me/app/fixture_configs'
473 config_attrs => {
474 quantity => 100,
475 },
476 });
477  
478 You may wish to do this if you want to let whoever runs the dumps have a bit
479 more control
480  
481 =back
482  
483 my $fixtures = DBIx::Class::Fixtures->new( {
484 config_dir => '/home/me/app/fixture_configs'
485 } );
486  
487 =cut
488  
489 sub new {
490 23 ▶ my $class = shift;
Subroutine new: called CC=8 SCAR=21.3
Pod documented
491  
492 23 my ($params) = @_;
493 23 ▶ unless (ref $params eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $params eq "HASH") 0 23 23
494 0 return DBIx::Class::Exception->throw('first arg to DBIx::Class::Fixtures->new() must be hash ref');
495 }
496  
497 23 ▶ unless ($params->{config_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"config_dir"}) 1 22 23
498 1 return DBIx::Class::Exception->throw('config_dir param not specified');
499 }
500  
501 22 my $config_dir = io->dir($params->{config_dir});
502 22 ▶ unless (-e $params->{config_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $params->{"config_dir"}) 1 21 22
503 1 return DBIx::Class::Exception->throw('config_dir directory doesn\'t exist');
504 }
505  
506 my $self = {
507 config_dir => $config_dir,
508 _inherited_attributes => [qw/datetime_relative might_have rules belongs_to/],
509 debug => $params->{debug} || 0,
510 ignore_sql_errors => $params->{ignore_sql_errors},
511 dumped_objects => {},
512 use_create => $params->{use_create} || 0,
513 use_find_or_create => $params->{use_find_or_create} || 0,
514 config_attrs => $params->{config_attrs} || {},
515 21 ▶ };
Condition62%5/8
$params->{'debug'} || 0
l!l
021
$params->{'use_create'} || 0
l!l
021
$params->{'use_find_or_create'} || 0
l!l
021
$params->{'config_attrs'} || {}
l!l
120
MC/DC0%0/1
$params->{'debug'} || 0
$params->{'debug'}
MC/DC0%0/1
$params->{'use_create'} || 0
$params->{'use_create'}
MC/DC0%0/1
$params->{'use_find_or_create'} || 0
$params->{'use_find_or_create'}
MC/DC100%1/1
$params->{'config_attrs'} || {}
$params->{'config_attrs'}
Truth table50%1/2
A
A= $params->{'debug'}
Aresult
11
00
Truth table50%1/2
A
A= $params->{'use_create'}
Aresult
11
00
Truth table50%1/2
A
A= $params->{'use_find_or_create'}
Aresult
11
00
Truth table100%2/2
A
A= $params->{'config_attrs'}
Aresult
11
00
516  
517 21 bless $self, $class;
518  
519 21 return $self;
520 }
521  
522 =head2 available_config_sets
523  
524 Returns a list of all the config sets found in the L</config_dir>. These will
525 be a list of the json based files containing dump rules.
526  
527 =cut
528  
529 22 my @config_sets;
530 sub available_config_sets {
531 @config_sets = scalar(@config_sets) ? @config_sets : map {
532 14 $_->filename;
533 } grep {
534 1 ▶ -f "$_" && $_=~/json$/;
Subroutine available_config_sets: called CC=3 SCAR=12.0
Pod documented
Branch: 2 branches
BranchTrueFalseTotal
scalar @config_sets ? : 0 1 1
-f "$_" and $_ =~ /json$/ 14 0 14
535 } shift->config_dir->all;
536 }
537  
538 =head2 dump
539  
540 =over 4
541  
542 =item Arguments: \%$attrs
543  
544 =item Return Value: 1
545  
546 =back
547  
548 $fixtures->dump({
549 config => 'set_config.json', # config file to use. must be in the config
550 # directory specified in the constructor
551 schema => $source_dbic_schema,
552 directory => '/home/me/app/fixtures' # output directory
553 });
554  
555 or
556  
557 $fixtures->dump({
558 all => 1, # just dump everything that's in the schema
559 schema => $source_dbic_schema,
560 directory => '/home/me/app/fixtures' # output directory
561 });
562  
563 In this case objects will be dumped to subdirectories in the specified
564 directory. For example:
565  
566 /home/me/app/fixtures/artist/1.fix
567 /home/me/app/fixtures/artist/3.fix
568 /home/me/app/fixtures/producer/5.fix
569  
570 schema and directory are required attributes. also, one of config or all must
571 be specified.
572  
573 Lastly, the C<config> parameter can be a Perl HashRef instead of a file name.
574 If this form is used your HashRef should conform to the structure rules defined
575 for the JSON representations.
576  
577 =cut
578  
579 sub dump {
580 25 ▶ my $self = shift;
Subroutine dump: called CC=35 SCAR=36.6
Pod documented
581  
582 25 my ($params) = @_;
583 25 ▶ unless (ref $params eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $params eq "HASH") 0 25 25
584 0 return DBIx::Class::Exception->throw('first arg to dump must be hash ref');
585 }
586  
587 25 foreach my $param (qw/schema directory/) {
588 50 ▶ unless ($params->{$param}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{$param}) 0 50 50
589 0 return DBIx::Class::Exception->throw($param . ' param not specified');
590 }
591 }
592  
593 25 ▶ if($params->{excludes} && !$params->{all}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"excludes"} and not $params->{"all"}) 0 25 25
Condition66%2/3
$params->{"excludes"} and not $params->{"all"}
!ll&&!rl&&r
2410
MC/DC0%0/2
$params->{"excludes"} and not $params->{"all"}
$params->{"excludes"} not $params->{"all"}
Truth table66%2/3
A and not(B)
A= $params->{"excludes"}B= not $params->{"all"}
ABresult
0X0
100
111
594 0 return DBIx::Class::Exception->throw("'excludes' param only works when using the 'all' param");
595 }
596  
597 25 my $schema = $params->{schema};
598 25 my $config;
599 25 ▶ if ($params->{config}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($params->{'config'}) { } 23 2 25
elsif ($params->{'all'}) { } 2 0 2
600 $config = ref $params->{config} eq 'HASH' ?
601 $params->{config} :
602 23 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
ref $params->{'config'} eq 'HASH' ? : 2 21 23
603 #read config
604 21 my $config_file = io->catfile($self->config_dir, $params->{config});
605 21 $self->load_config_file("$config_file");
606 };
607 } elsif ($params->{all}) {
608 2 ▶ my %excludes = map {$_=>1} @{$params->{excludes}||[]};
Branch: 1 branch
BranchTrueFalseTotal
$params->{"excludes"} or [] 1 1 2
609 $config = {
610 might_have => { fetch => 0 },
611 has_many => { fetch => 0 },
612 belongs_to => { fetch => 0 },
613 sets => [
614 map {
615 13 { class => $_, quantity => 'all' };
616 } grep {
617 2 !$excludes{$_}
618 } $schema->sources],
619 };
620 } else {
621 0 DBIx::Class::Exception->throw('must pass config or set all');
622 }
623  
624 25 my $output_dir = io->dir($params->{directory});
625 25 ▶ unless (-e "$output_dir") {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e "$output_dir") 5 20 25
626 5 ▶ $output_dir->mkpath ||
Branch: 1 branch
BranchTrueFalseTotal
$output_dir->mkpath or "DBIx::Class::Exception"->throw("output directory does not exist at $output_dir") 0 5 5
627 DBIx::Class::Exception->throw("output directory does not exist at $output_dir");
628 }
629  
630 25 $self->msg("generating fixtures");
631 25 my $tmp_output_dir = io->dir(tempdir);
632  
633 25 ▶ if (-e "$tmp_output_dir") {
Branch: 1 branch
BranchTrueFalseTotal
if (-e "$tmp_output_dir") 25 0 25
634 25 $self->msg("- clearing existing $tmp_output_dir");
635 25 $tmp_output_dir->rmtree;
636 }
637 25 $self->msg("- creating $tmp_output_dir");
638 25 $tmp_output_dir->mkpath;
639  
640 # write version file (for the potential benefit of populate)
641 25 $tmp_output_dir->file('_dumper_version')->print($VERSION);
642  
643 # write our current config set
644 25 $tmp_output_dir->file('_config_set')->print( Dumper $config );
645  
646 25 ▶ $config->{rules} ||= {};
Condition100%2/2
$config->{"rules"} ||= {}
l!l
421
MC/DC100%1/1
$config->{"rules"} ||= {}
$config->{"rules"}
Truth table100%2/2
A
A= $config->{"rules"}
Aresult
11
00
647 25 my @sources = sort { $a->{class} cmp $b->{class} } @{delete $config->{sets}};
648  
649 25 ▶ while ( my ($k,$v) = each %{ $config->{rules} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$config{"rules"};}) 7 25 32
650 7 ▶ if ( my $source = eval { $schema->source($k) } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $source = eval { do { $schema->source($k) } }) 4 3 7
651 4 $config->{rules}{$source->source_name} = $v;
652 }
653 }
654  
655 25 foreach my $source (@sources) {
656 # apply rule to set if specified
657 44 my $rule = $config->{rules}->{$source->{class}};
658 44 ▶ $source = merge( $source, $rule ) if ($rule);
Branch: 1 branch
BranchTrueFalseTotal
if $rule 7 37 44
659  
660 # fetch objects
661 44 my $rs = $schema->resultset($source->{class});
662  
663 44 ▶ if ($source->{cond} and ref $source->{cond} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($source->{"cond"} and ref $source->{"cond"} eq "HASH") 1 43 44
Condition100%3/3
$source->{"cond"} and ref $source->{"cond"} eq "HASH"
!ll&&!rl&&r
4031
MC/DC100%2/2
$source->{"cond"} and ref $source->{"cond"} eq "HASH"
$source->{"cond"} ref $source->{"cond"} eq "HASH"
Truth table100%3/3
A and B
A= $source->{"cond"}B= ref $source->{"cond"} eq "HASH"
ABresult
0X0
100
111
664 # if value starts with \ assume it's meant to be passed as a scalar ref
665 # to dbic. ideally this would substitute deeply
666 $source->{cond} = {
667 map {
668 $_ => ($source->{cond}->{$_} =~ s/^\\//) ? \$source->{cond}->{$_}
669 1 ▶ : $source->{cond}->{$_}
Branch: 1 branch
BranchTrueFalseTotal
$source->{'cond'}{$_} =~ s/^\\// ? : 1 0 1
670 1 } keys %{$source->{cond}}
671 };
672 }
673  
674 $rs = $rs->search($source->{cond}, { join => $source->{join} })
675 44 ▶ if $source->{cond};
Branch: 1 branch
BranchTrueFalseTotal
if $source->{"cond"} 4 40 44
676  
677 44 $self->msg("- dumping $source->{class}");
678  
679 44 my %source_options = ( set => { %{$config}, %{$source} } );
680 44 ▶ if ($source->{quantity}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($source->{'quantity'}) { } 29 15 44
elsif ($source->{'ids'} and @{$source->{'ids'};}) { } 15 0 15
681 $rs = $rs->search({}, { order_by => $source->{order_by} })
682 29 ▶ if $source->{order_by};
Branch: 1 branch
BranchTrueFalseTotal
if $source->{"order_by"} 0 29 29
683  
684 29 ▶ if ($source->{quantity} =~ /^\d+$/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($source->{'quantity'} =~ /^\d+$/) { } 11 18 29
elsif ($source->{'quantity'} ne 'all') { } 0 18 18
685 11 $rs = $rs->search({}, { rows => $source->{quantity} });
686 } elsif ($source->{quantity} ne 'all') {
687 0 DBIx::Class::Exception->throw("invalid value for quantity - $source->{quantity}");
688 }
689 }
690 15 ▶ elsif ($source->{ids} && @{$source->{ids}}) {
Condition33%1/3
$source->{"ids"} and @{$source->{"ids"};}
!ll&&!rl&&r
0015
MC/DC0%0/2
$source->{"ids"} and @{$source->{"ids"};}
$source->{"ids"} @{$source->{"ids"};}
Truth table33%1/3
A and B
A= $source->{"ids"}B= @{$source->{"ids"};}
ABresult
0X0
100
111
691 15 my @ids = @{$source->{ids}};
692 15 my (@pks) = $rs->result_source->primary_columns;
693 15 ▶ die "Can't dump multiple col-pks using 'id' option" if @pks > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @pks > 1 0 15 15
694 15 $rs = $rs->search_rs( { $pks[0] => { -in => \@ids } } );
695 }
696 else {
697 0 DBIx::Class::Exception->throw('must specify either quantity or ids');
698 }
699  
700 44 $source_options{set_dir} = $tmp_output_dir;
701 44 $self->dump_rs($rs, \%source_options );
702 }
703  
704 # clear existing output dir
705 25 foreach my $child ($output_dir->all) {
706 45 ▶ if ($child->is_dir) {
Branch: 2 branches
BranchTrueFalseTotal
if ($child->is_dir) { } 11 34 45
elsif ($child =~ /_dumper_version$/) { } 7 27 34
707 11 ▶ next if ("$child" eq "$tmp_output_dir");
Branch: 1 branch
BranchTrueFalseTotal
if "$child" eq "$tmp_output_dir" 0 11 11
708 11 ▶ if (grep { $_ =~ /\.fix/ } $child->all) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ =~ /\.fix/;} $child->all) 8 3 11
709 8 $child->rmtree;
710 }
711 } elsif ($child =~ /_dumper_version$/) {
712 7 $child->unlink;
713 }
714 }
715  
716 25 $self->msg("- moving temp dir to $output_dir");
717 25 $tmp_output_dir->copy("$output_dir");
718  
719 25 ▶ if (-e "$output_dir") {
Branch: 1 branch
BranchTrueFalseTotal
if (-e "$output_dir") 25 0 25
720 25 $self->msg("- clearing tmp dir $tmp_output_dir");
721 # delete existing fixture set
722 25 $tmp_output_dir->rmtree;
723 }
724  
725 25 $self->msg("done");
726  
727 25 return 1;
728 }
729  
730 sub load_config_file {
731 21 ▶ my ($self, $config_file) = @_;
Subroutine load_config_file: called CC=15 SCAR=29.1
Pod undocumented
732 21 ▶ DBIx::Class::Exception->throw("config does not exist at $config_file")
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$config_file" 0 21 21
733 unless -e "$config_file";
734  
735 21 my $config = Config::Any::JSON->load($config_file);
736  
737 #process includes
738 21 ▶ if (my $incs = $config->{includes}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $incs = $config->{"includes"}) 1 20 21
739 1 $self->msg($incs);
740 1 ▶ DBIx::Class::Exception->throw(
Branch: 1 branch
BranchTrueFalseTotal
unless ref $incs eq "ARRAY" 0 1 1
741 'includes params of config must be an array ref of hashrefs'
742 ) unless ref $incs eq 'ARRAY';
743  
744 1 foreach my $include_config (@$incs) {
745 DBIx::Class::Exception->throw(
746 'includes params of config must be an array ref of hashrefs'
747 1 ▶ ) unless (ref $include_config eq 'HASH') && $include_config->{file};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $include_config eq "HASH" and $include_config->{"file"} 0 1 1
Condition33%1/3
ref $include_config eq "HASH" and $include_config->{"file"}
!ll&&!rl&&r
001
MC/DC0%0/2
ref $include_config eq "HASH" and $include_config->{"file"}
ref $include_config eq "HASH" $include_config->{"file"}
Truth table33%1/3
A and B
A= ref $include_config eq "HASH"B= $include_config->{"file"}
ABresult
0X0
100
111
748  
749 1 my $include_file = $self->config_dir->file($include_config->{file});
750  
751 1 ▶ DBIx::Class::Exception->throw("config does not exist at $include_file")
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$include_file" 0 1 1
752 unless -e "$include_file";
753  
754 1 my $include = Config::Any::JSON->load($include_file);
755 1 $self->msg($include);
756 1 $config = merge( $config, $include );
757 }
758 1 delete $config->{includes};
759 }
760  
761 # validate config
762 return DBIx::Class::Exception->throw('config has no sets')
763 unless $config && $config->{sets} &&
764 21 ▶ ref $config->{sets} eq 'ARRAY' && scalar @{$config->{sets}};
Branch: 1 branch
BranchTrueFalseTotal
unless $config and $config->{"sets"} and ref $config->{"sets"} eq "ARRAY" and scalar @{$config->{"sets"};} 0 21 21
Condition37%3/8
$config and $config->{"sets"} and ref $config->{"sets"} eq "ARRAY" and scalar @{$config->{"sets"};}
!ll
021
$config and $config->{"sets"} and ref $config->{"sets"} eq "ARRAY"
!ll&&!rl&&r
0021
$config and $config->{"sets"}
!ll&&!rl&&r
0021
MC/DC0%0/3
$config and $config->{"sets"} and ref $config->{"sets"} eq "ARRAY" and scalar @{$config->{"sets"};}
$config $config->{"sets"} ref $config->{"sets"} eq "ARRAY"
Truth table25%1/4
A and B and C
A= $configB= $config->{"sets"}C= ref $config->{"sets"} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
765  
766 21 ▶ $config->{might_have} = { fetch => 0 } unless exists $config->{might_have};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $config->{"might_have"} 2 19 21
767 21 ▶ $config->{has_many} = { fetch => 0 } unless exists $config->{has_many};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $config->{"has_many"} 2 19 21
768 21 ▶ $config->{belongs_to} = { fetch => 1 } unless exists $config->{belongs_to};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $config->{"belongs_to"} 20 1 21
769  
770 21 return $config;
771 }
772  
773 sub dump_rs {
774 117 ▶ my ($self, $rs, $params) = @_;
Subroutine dump_rs: called CC=2 SCAR=6.9
Pod undocumented
775  
776 117 ▶ while (my $row = $rs->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $rs->next) 203 117 320
777 203 $self->dump_object($row, $params);
778 }
779 }
780  
781 sub dump_object {
782 203 ▶ my ($self, $object, $params) = @_;
Subroutine dump_object: called CC=59 SCAR=45.6
Pod undocumented
783 203 my $set = $params->{set};
784  
785 my $v = Data::Visitor::Callback->new(
786 plain_value => sub {
787 5278 ▶ my ($visitor, $data) = @_;
Subroutine __ANON__: called CC=2 SCAR=9.7
788 my $subs = {
789 ENV => sub {
790 0 ▶ my ( $self, $v ) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
791 0 ▶ if (! defined($ENV{$v})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $ENV{$v}) { } 0 0 0
792 0 return "";
793 } else {
794 0 return $ENV{ $v };
795 }
796 },
797 ATTR => sub {
798 1 ▶ my ($self, $v) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.6
799 1 ▶ if(my $attr = $self->config_attrs->{$v}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $attr = $self->config_attrs->{$v}) { } 1 0 1
800 1 return $attr;
801 } else {
802 0 return "";
803 }
804 },
805 catfile => sub {
806 0 ▶ my ($self, @args) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
807 0 "".io->catfile(@args);
808 },
809 catdir => sub {
810 0 ▶ my ($self, @args) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
811 0 "".io->catdir(@args);
812 },
813 5278 };
814  
815 5278 my $subsre = join( '|', keys %$subs );
816 5278 ▶ $_ =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $self, $2 ? split( /,/, $2 ) : () ) }eg;
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 1 0 1
817  
818 5278 return $_;
819 }
820 203 );
821  
822 203 $v->visit( $set );
823  
824 203 ▶ die 'no dir passed to dump_object' unless $params->{set_dir};
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"set_dir"} 0 203 203
825 203 ▶ die 'no object passed to dump_object' unless $object;
Branch: 1 branch
BranchTrueFalseTotal
unless $object 0 203 203
826  
827 203 my @inherited_attrs = @{$self->_inherited_attributes};
828  
829 my @pk_vals = map {
830 203 $object->get_column($_)
831 } $object->primary_columns;
832  
833 203 my $key = join("\0", @pk_vals);
834  
835 203 my $src = $object->result_source;
836 203 my $exists = $self->dumped_objects->{$src->name}{$key}++;
837  
838  
839 # write dir and gen filename
840 203 my $source_dir = io->catdir($params->{set_dir}, $self->_name_for_source($src));
841 203 $source_dir->mkpath(0, 0777);
842  
843 # Convert characters not allowed on windows
844 my $file = io->catfile("$source_dir",
845 203 join('-', map { s|[/\\:\*\|\?"<>]|_|g; $_; } @pk_vals) . '.fix'
846 );
847  
848 # write file
849 203 ▶ unless ($exists) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($exists) 154 49 203
850 154 $self->msg('-- dumping ' . "$file", 2);
851 154 my %ds = $object->get_columns;
852  
853 154 ▶ if($set->{external}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set->{"external"}) 1 153 154
854 1 foreach my $field (keys %{$set->{external}}) {
855 1 my $key = $ds{$field};
856 1 my ($plus, $class) = ( $set->{external}->{$field}->{class}=~/^(\+)*(.+)$/);
857 1 my $args = $set->{external}->{$field}->{args};
858  
859 1 ▶ $class = "DBIx::Class::Fixtures::External::$class" unless $plus;
Branch: 1 branch
BranchTrueFalseTotal
unless $plus 1 0 1
860 1 ▶ eval "use $class";
Subroutine BEGIN: called CC=1 SCAR=0.0
861  
862 1 $ds{external}->{$field} =
863 encode_base64( $class
864 ->backup($key => $args),'');
865 }
866 }
867  
868 # mess with dates if specified
869 154 ▶ if ($set->{datetime_relative}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($set->{"datetime_relative"}) 3 151 154
870 3 my $formatter= $object->result_source->schema->storage->datetime_parser;
871 3 ▶ unless ($@ || !$formatter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $formatter) { } 0 3 3
Condition33%1/3
$@ or not $formatter
l!l&&r!l&&!r
003
MC/DC0%0/2
$@ or not $formatter
$@ not $formatter
Truth table33%1/3
A or not(B)
A= $@B= not $formatter
ABresult
1X1
011
000
872 3 my $dt;
873 3 ▶ if ($set->{datetime_relative} eq 'today') {
Branch: 1 branch
BranchTrueFalseTotal
if ($set->{'datetime_relative'} eq 'today') { } 0 3 3
874 0 $dt = DateTime->today;
875 } else {
876 3 ▶ $dt = $formatter->parse_datetime($set->{datetime_relative}) unless ($@);
Branch: 1 branch
BranchTrueFalseTotal
unless $@ 3 0 3
877 }
878  
879 3 ▶ while (my ($col, $value) = each %ds) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %ds) 11 3 14
880 11 my $col_info = $object->result_source->column_info($col);
881  
882 next unless $value
883 && $col_info->{_inflate_info}
884 && (
885 (uc($col_info->{data_type}) eq 'DATETIME')
886 or (uc($col_info->{data_type}) eq 'DATE')
887 or (uc($col_info->{data_type}) eq 'TIME')
888 or (uc($col_info->{data_type}) eq 'TIMESTAMP')
889 11 ▶ or (uc($col_info->{data_type}) eq 'INTERVAL')
Branch: 1 branch
BranchTrueFalseTotal
unless $value and $col_info->{"_inflate_info"} and uc $col_info->{"data_type"} eq "DATETIME" || uc $col_info->{"data_type"} eq "DATE" || uc $col_info->{"data_type"} eq "TIME" || uc $col_info->{"data_type"} eq "TIMESTAMP" || uc $col_info->{"data_type"} eq "INTERVAL" 10 1 11
Condition66%12/18
$value and $col_info->{"_inflate_info"} and uc $col_info->{"data_type"} eq "DATETIME" || uc $col_info->{"data_type"} eq "DATE" || uc $col_info->{"data_type"} eq "TIME" || uc $col_info->{"data_type"} eq "TIMESTAMP" || uc $col_info->{"data_type"} eq "INTERVAL"
!ll&&!rl&&r
830
$value and $col_info->{"_inflate_info"}
!ll&&!rl&&r
083
uc $col_info->{"data_type"} eq "DATETIME" or uc $col_info->{"data_type"} eq "DATE" or uc $col_info->{"data_type"} eq "TIME" or uc $col_info->{"data_type"} eq "TIMESTAMP" or uc $col_info->{"data_type"} eq "INTERVAL"
l!l&&r!l&&!r
102
uc $col_info->{"data_type"} eq "DATETIME" or uc $col_info->{"data_type"} eq "DATE" or uc $col_info->{"data_type"} eq "TIME" or uc $col_info->{"data_type"} eq "TIMESTAMP"
l!l&&r!l&&!r
102
uc $col_info->{"data_type"} eq "DATETIME" or uc $col_info->{"data_type"} eq "DATE" or uc $col_info->{"data_type"} eq "TIME"
l!l&&r!l&&!r
102
uc $col_info->{"data_type"} eq "DATETIME" or uc $col_info->{"data_type"} eq "DATE"
l!l&&r!l&&!r
102
MC/DC0%0/7
$value and $col_info->{"_inflate_info"} and uc $col_info->{"data_type"} eq "DATETIME" || uc $col_info->{"data_type"} eq "DATE" || uc $col_info->{"data_type"} eq "TIME" || uc $col_info->{"data_type"} eq "TIMESTAMP" || uc $col_info->{"data_type"} eq "INTERVAL"
$value $col_info->{"_inflate_info"} uc $col_info->{"data_type"} eq "DATETIME" uc $col_info->{"data_type"} eq "DATE" uc $col_info->{"data_type"} eq "TIME" uc $col_info->{"data_type"} eq "TIMESTAMP" uc $col_info->{"data_type"} eq "INTERVAL"
Truth table25%2/8
A and B and C or D or E or F or G
A= $valueB= $col_info->{"_inflate_info"}C= uc $col_info->{"data_type"} eq "DATETIME"D= uc $col_info->{"data_type"} eq "DATE"E= uc $col_info->{"data_type"} eq "TIME"F= uc $col_info->{"data_type"} eq "TIMESTAMP"G= uc $col_info->{"data_type"} eq "INTERVAL"
ABCDEFGresult
0XXXXXX0
10XXXXX0
11000000
111XXXX1
1101XXX1
11001XX1
110001X1
11000011
890 );
891  
892 1 $ds{$col} = $object->get_inflated_column($col)->subtract_datetime($dt);
893 }
894 } else {
895 0 warn "datetime_relative not supported for this db driver at the moment";
896 }
897 }
898  
899 # do the actual dumping
900 154 my $serialized = Dump(\%ds)->Out();
901  
902 154 $file->print($serialized);
903 }
904  
905 # don't bother looking at rels unless we are actually planning to dump at least one type
906 my ($might_have, $belongs_to, $has_many) = map {
907 203 $set->{$_}{fetch} || $set->{rules}{$src->source_name}{$_}{fetch}
908 609 ▶ } qw/might_have belongs_to has_many/;
Branch: 1 branch
BranchTrueFalseTotal
$set->{$_}{"fetch"} or $set->{"rules"}{$src->source_name}{$_}{"fetch"} 491 118 609
909  
910 return unless $might_have
911 || $belongs_to
912 || $has_many
913 203 ▶ || $set->{fetch};
Branch: 1 branch
BranchTrueFalseTotal
unless $might_have or $belongs_to or $has_many or $set->{"fetch"} 85 118 203
Condition66%6/9
$might_have or $belongs_to or $has_many or $set->{"fetch"}
l!l&&r!l&&!r
118085
$might_have or $belongs_to or $has_many
l!l&&r!l&&!r
118085
$might_have or $belongs_to
l!l&&r!l&&!r
011885
MC/DC25%1/4
$might_have or $belongs_to or $has_many or $set->{"fetch"}
$might_have $belongs_to $has_many $set->{"fetch"}
Truth table40%2/5
A or B or C or D
A= $might_haveB= $belongs_toC= $has_manyD= $set->{"fetch"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
914  
915 # dump rels of object
916 118 ▶ unless ($exists) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($exists) 70 48 118
917 70 foreach my $name (sort $src->relationships) {
918 183 my $info = $src->relationship_info($name);
919 183 my $r_source = $src->related_source($name);
920 # if belongs_to or might_have with might_have param set or has_many with
921 # has_many param set then
922 183 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{"attrs"}{"accessor"} eq "single" and !$info->{"attrs"}{"join_type"} || $might_have or $info->{"attrs"}{"accessor"} eq "filter" or $info->{"attrs"}{"accessor"} eq "multi" and $has_many) 48 135 183
Condition73%11/15
$info->{"attrs"}{"accessor"} eq "single" and !$info->{"attrs"}{"join_type"} || $might_have or $info->{"attrs"}{"accessor"} eq "filter" or $info->{"attrs"}{"accessor"} eq "multi" and $has_many
l!l&&r!l&&!r
471135
$info->{"attrs"}{"accessor"} eq "single" and !$info->{"attrs"}{"join_type"} || $might_have or $info->{"attrs"}{"accessor"} eq "filter"
l!l&&r!l&&!r
047136
$info->{"attrs"}{"accessor"} eq "single" and !$info->{"attrs"}{"join_type"} || $might_have
!ll&&!rl&&r
159240
not $info->{"attrs"}{"join_type"} or $might_have
l!l&&r!l&&!r
0024
$info->{"attrs"}{"accessor"} eq "multi" and $has_many
!ll&&!rl&&r
241111
MC/DC33%2/6
$info->{"attrs"}{"accessor"} eq "single" and !$info->{"attrs"}{"join_type"} || $might_have or $info->{"attrs"}{"accessor"} eq "filter" or $info->{"attrs"}{"accessor"} eq "multi" and $has_many
$info->{"attrs"}{"accessor"} eq "single" not $info->{"attrs"}{"join_type"} $might_have $info->{"attrs"}{"accessor"} eq "filter" $info->{"attrs"}{"accessor"} eq "multi" $has_many
Truth table30%3/10
A and not(B) or C or D or E and F
A= $info->{"attrs"}{"accessor"} eq "single"B= not $info->{"attrs"}{"join_type"}C= $might_haveD= $info->{"attrs"}{"accessor"} eq "filter"E= $info->{"attrs"}{"accessor"} eq "multi"F= $has_many
ABCDEFresult
11XXXX1
101XXX1
0XX1XX1
1001XX1
0XX0111
1000111
0XX00X0
0XX0100
10000X0
1000100
923 ( $info->{attrs}{accessor} eq 'single' &&
924 (!$info->{attrs}{join_type} || $might_have)
925 )
926 || $info->{attrs}{accessor} eq 'filter'
927 ||
928 ($info->{attrs}{accessor} eq 'multi' && $has_many)
929 ) {
930 48 my $related_rs = $object->related_resultset($name);
931 48 my $rule = $set->{rules}->{$related_rs->result_source->source_name};
932 # these parts of the rule only apply to has_many rels
933 48 ▶ if ($rule && $info->{attrs}{accessor} eq 'multi') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule and $info->{"attrs"}{"accessor"} eq "multi") 1 47 48
Condition100%3/3
$rule and $info->{"attrs"}{"accessor"} eq "multi"
!ll&&!rl&&r
7401
MC/DC100%2/2
$rule and $info->{"attrs"}{"accessor"} eq "multi"
$rule $info->{"attrs"}{"accessor"} eq "multi"
Truth table100%3/3
A and B
A= $ruleB= $info->{"attrs"}{"accessor"} eq "multi"
ABresult
0X0
100
111
934 $related_rs = $related_rs->search(
935 $rule->{cond},
936 { join => $rule->{join} }
937 1 ▶ ) if ($rule->{cond});
Branch: 1 branch
BranchTrueFalseTotal
if $rule->{"cond"} 0 1 1
938  
939 $related_rs = $related_rs->search(
940 {},
941 { rows => $rule->{quantity} }
942 1 ▶ ) if ($rule->{quantity} && $rule->{quantity} ne 'all');
Branch: 1 branch
BranchTrueFalseTotal
if $rule->{"quantity"} and $rule->{"quantity"} ne "all" 0 1 1
Condition33%1/3
$rule->{"quantity"} and $rule->{"quantity"} ne "all"
!ll&&!rl&&r
100
MC/DC0%0/2
$rule->{"quantity"} and $rule->{"quantity"} ne "all"
$rule->{"quantity"} $rule->{"quantity"} ne "all"
Truth table33%1/3
A and B
A= $rule->{"quantity"}B= $rule->{"quantity"} ne "all"
ABresult
0X0
100
111
943  
944 $related_rs = $related_rs->search(
945 {},
946 { order_by => $rule->{order_by} }
947 1 ▶ ) if ($rule->{order_by});
Branch: 1 branch
BranchTrueFalseTotal
if $rule->{"order_by"} 0 1 1
948  
949 }
950 48 ▶ if ($set->{has_many}{quantity} &&
Branch: 1 branch
BranchTrueFalseTotal
if ($set->{"has_many"}{"quantity"} and $set->{"has_many"}{"quantity"} =~ /^\d+$/) 0 48 48
Condition33%1/3
$set->{"has_many"}{"quantity"} and $set->{"has_many"}{"quantity"} =~ /^\d+$/
!ll&&!rl&&r
4800
MC/DC0%0/2
$set->{"has_many"}{"quantity"} and $set->{"has_many"}{"quantity"} =~ /^\d+$/
$set->{"has_many"}{"quantity"} $set->{"has_many"}{"quantity"} =~ /^\d+$/
Truth table33%1/3
A and B
A= $set->{"has_many"}{"quantity"}B= $set->{"has_many"}{"quantity"} =~ /^\d+$/
ABresult
0X0
100
111
951 $set->{has_many}{quantity} =~ /^\d+$/) {
952 $related_rs = $related_rs->search(
953 {},
954 { rows => $set->{has_many}->{quantity} }
955 0 );
956 }
957  
958 48 my %c_params = %{$params};
959 # inherit date param
960 my %mock_set = map {
961 146 $_ => $set->{$_}
962 48 } grep { $set->{$_} } @inherited_attrs;
963  
964 48 $c_params{set} = \%mock_set;
965 $c_params{set} = merge( $c_params{set}, $rule)
966 48 ▶ if $rule && $rule->{fetch};
Branch: 1 branch
BranchTrueFalseTotal
if $rule and $rule->{"fetch"} 6 42 48
Condition100%3/3
$rule and $rule->{"fetch"}
!ll&&!rl&&r
7356
MC/DC100%2/2
$rule and $rule->{"fetch"}
$rule $rule->{"fetch"}
Truth table100%3/3
A and B
A= $ruleB= $rule->{"fetch"}
ABresult
0X0
100
111
967  
968 48 $self->dump_rs($related_rs, \%c_params);
969 }
970 }
971 }
972  
973 118 ▶ return unless $set && $set->{fetch};
Branch: 1 branch
BranchTrueFalseTotal
unless $set and $set->{"fetch"} 93 25 118
Condition66%2/3
$set and $set->{"fetch"}
!ll&&!rl&&r
09325
MC/DC50%1/2
$set and $set->{"fetch"}
$set $set->{"fetch"}
Truth table66%2/3
A and B
A= $setB= $set->{"fetch"}
ABresult
0X0
100
111
974 25 foreach my $fetch (@{$set->{fetch}}) {
975 # inherit date param
976 25 $fetch->{$_} = $set->{$_} foreach
977 100 ▶ grep { !$fetch->{$_} && $set->{$_} } @inherited_attrs;
Branch: 1 branch
BranchTrueFalseTotal
not $fetch->{$_} and $set->{$_} 94 6 100
978 25 my $related_rs = $object->related_resultset($fetch->{rel});
979 25 my $rule = $set->{rules}->{$related_rs->result_source->source_name};
980  
981 25 ▶ if ($rule) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule) 15 10 25
982 15 my $info = $object->result_source->relationship_info($fetch->{rel});
983 15 ▶ if ($info->{attrs}{accessor} eq 'multi') {
Branch: 2 branches
BranchTrueFalseTotal
if ($info->{'attrs'}{'accessor'} eq 'multi') { } 15 0 15
elsif ($rule->{'fetch'}) { } 0 0 0
984 15 $fetch = merge( $fetch, $rule );
985 } elsif ($rule->{fetch}) {
986 0 $fetch = merge( $fetch, { fetch => $rule->{fetch} } );
987 }
988 }
989  
990 25 ▶ die "relationship $fetch->{rel} does not exist for " . $src->source_name
Branch: 1 branch
BranchTrueFalseTotal
unless $related_rs 0 25 25
991 unless ($related_rs);
992  
993 25 ▶ if ($fetch->{cond} and ref $fetch->{cond} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fetch->{"cond"} and ref $fetch->{"cond"} eq "HASH") 15 10 25
Condition100%3/3
$fetch->{"cond"} and ref $fetch->{"cond"} eq "HASH"
!ll&&!rl&&r
7315
MC/DC100%2/2
$fetch->{"cond"} and ref $fetch->{"cond"} eq "HASH"
$fetch->{"cond"} ref $fetch->{"cond"} eq "HASH"
Truth table100%3/3
A and B
A= $fetch->{"cond"}B= ref $fetch->{"cond"} eq "HASH"
ABresult
0X0
100
111
994 # if value starts with \ assume it's meant to be passed as a scalar ref
995 # to dbic. ideally this would substitute deeply
996 $fetch->{cond} = { map {
997 $_ => ($fetch->{cond}->{$_} =~ s/^\\//) ? \$fetch->{cond}->{$_}
998 15 ▶ : $fetch->{cond}->{$_}
Branch: 1 branch
BranchTrueFalseTotal
$fetch->{'cond'}{$_} =~ s/^\\// ? : 1 14 15
999 15 } keys %{$fetch->{cond}} };
1000 }
1001  
1002 $related_rs = $related_rs->search(
1003 $fetch->{cond},
1004 { join => $fetch->{join} }
1005 25 ▶ ) if $fetch->{cond};
Branch: 1 branch
BranchTrueFalseTotal
if $fetch->{"cond"} 18 7 25
1006  
1007 $related_rs = $related_rs->search(
1008 {},
1009 { rows => $fetch->{quantity} }
1010 25 ▶ ) if $fetch->{quantity} && $fetch->{quantity} ne 'all';
Branch: 1 branch
BranchTrueFalseTotal
if $fetch->{"quantity"} and $fetch->{"quantity"} ne "all" 0 25 25
Condition66%2/3
$fetch->{"quantity"} and $fetch->{"quantity"} ne "all"
!ll&&!rl&&r
15100
MC/DC0%0/2
$fetch->{"quantity"} and $fetch->{"quantity"} ne "all"
$fetch->{"quantity"} $fetch->{"quantity"} ne "all"
Truth table66%2/3
A and B
A= $fetch->{"quantity"}B= $fetch->{"quantity"} ne "all"
ABresult
0X0
100
111
1011 $related_rs = $related_rs->search(
1012 {},
1013 { order_by => $fetch->{order_by} }
1014 25 ▶ ) if $fetch->{order_by};
Branch: 1 branch
BranchTrueFalseTotal
if $fetch->{"order_by"} 0 25 25
1015  
1016 25 $self->dump_rs($related_rs, { %{$params}, set => $fetch });
1017 }
1018 }
1019  
1020 sub _generate_schema {
1021 7 ▶ my $self = shift;
Subroutine _generate_schema: called CC=9 SCAR=22.6
1022 7 ▶ my $params = shift || {};
Condition50%1/2
shift() || {}
l!l
70
MC/DC0%0/1
shift() || {}
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1023 7 require DBI;
1024 7 $self->msg("\ncreating schema");
1025  
1026 7 ▶ my $schema_class = $self->schema_class || "DBIx::Class::Fixtures::Schema";
Condition50%1/2
$self->schema_class || 'DBIx::Class::Fixtures::Schema'
l!l
07
MC/DC0%0/1
$self->schema_class || 'DBIx::Class::Fixtures::Schema'
$self->schema_class
Truth table50%1/2
A
A= $self->schema_class
Aresult
11
00
1027 7 eval "require $schema_class";
1028 7 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 7 7
1029  
1030 7 my $pre_schema;
1031 7 my $connection_details = $params->{connection_details};
1032  
1033 7 $namespace_counter++;
1034  
1035 7 my $namespace = "DBIx::Class::Fixtures::GeneratedSchema_$namespace_counter";
1036 7 Class::C3::Componentised->inject_base( $namespace => $schema_class );
1037  
1038 7 $pre_schema = $namespace->connect(@{$connection_details});
1039 7 ▶ unless( $pre_schema ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pre_schema) 0 7 7
1040 0 return DBIx::Class::Exception->throw('connection details not valid');
1041 }
1042 7 my @tables = map { $self->_name_for_source($pre_schema->source($_)) } $pre_schema->sources;
1043 7 $self->msg("Tables to drop: [". join(', ', sort @tables) . "]");
1044 7 my $dbh = $pre_schema->storage->dbh;
1045  
1046 # clear existing db
1047 7 $self->msg("- clearing DB of existing tables");
1048 $pre_schema->storage->txn_do(sub {
1049 $pre_schema->storage->with_deferred_fk_checks(sub {
1050 7 ▶ foreach my $table (@tables) {
Subroutine __ANON__: called CC=3 SCAR=11.2
1051 45 eval {
1052 45 ▶ $dbh->do("drop table $table" . ($params->{cascade} ? ' cascade' : '') )
Branch: 1 branch
BranchTrueFalseTotal
$params->{'cascade'} ? : 0 45 45
1053 };
1054 }
1055 7 ▶ });
Subroutine __ANON__: called CC=1 SCAR=0.0
1056 7 });
1057  
1058 # import new ddl file to db
1059 7 my $ddl_file = $params->{ddl};
1060 7 $self->msg("- deploying schema using $ddl_file");
1061 7 my $data = _read_sql($ddl_file);
1062 7 foreach (@$data) {
1063 59 ▶ eval { $dbh->do($_) or warn "SQL was:\n $_"};
Branch: 1 branch
BranchTrueFalseTotal
$dbh->do($_) or warn "SQL was:\n $_" 0 59 59
1064 59 ▶ if ($@ && !$self->{ignore_sql_errors}) { die "SQL was:\n $_\n$@"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($@ and not $self->{"ignore_sql_errors"}) 0 59 59
Condition33%1/3
$@ and not $self->{"ignore_sql_errors"}
!ll&&!rl&&r
5900
MC/DC0%0/2
$@ and not $self->{"ignore_sql_errors"}
$@ not $self->{"ignore_sql_errors"}
Truth table33%1/3
A and not(B)
A= $@B= not $self->{"ignore_sql_errors"}
ABresult
0X0
100
111
1065 }
1066 7 $self->msg("- finished importing DDL into DB");
1067  
1068 # load schema object from our new DB
1069 7 $namespace_counter++;
1070 7 my $namespace2 = "DBIx::Class::Fixtures::GeneratedSchema_$namespace_counter";
1071 7 Class::C3::Componentised->inject_base( $namespace2 => $schema_class );
1072 7 my $schema = $namespace2->connect(@{$connection_details});
1073 7 return $schema;
1074 }
1075  
1076 sub _read_sql {
1077 8 ▶ my $ddl_file = shift;
Subroutine _read_sql: called CC=3 SCAR=11.1
1078 8 my $fh;
1079 8 ▶ open $fh, "<$ddl_file" or die ("Can't open DDL file, $ddl_file ($!)");
Branch: 1 branch
BranchTrueFalseTotal
open $fh, "<$ddl_file" or die "Can't open DDL file, $ddl_file ($!)" 0 8 8
1080 8 my @data = split(/\n/, join('', <$fh>));
1081 8 @data = grep(!/^--/, @data);
1082 8 @data = split(/;/, join('', @data));
1083 8 close($fh);
1084 8 ▶ @data = grep { $_ && $_ !~ /^-- / } @data;
Branch: 1 branch
BranchTrueFalseTotal
$_ and not $_ =~ /^-- / 62 0 62
1085 8 return \@data;
1086 }
1087  
1088 =head2 dump_config_sets
1089  
1090 Works just like L</dump> but instead of specifying a single json config set
1091 located in L</config_dir> we dump each set named in the C<configs> parameter.
1092  
1093 The parameters are the same as for L</dump> except instead of a C<directory>
1094 parameter we have a C<directory_template> which is a coderef expected to return
1095 a scalar that is a root directory where we will do the actual dumping. This
1096 coderef get three arguments: C<$self>, C<$params> and C<$set_name>. For
1097 example:
1098  
1099 $fixture->dump_all_config_sets({
1100 schema => $schema,
1101 configs => [qw/one.json other.json/],
1102 directory_template => sub {
1103 my ($fixture, $params, $set) = @_;
1104 return io->catdir('var', 'fixtures', $params->{schema}->version, $set);
1105 },
1106 });
1107  
1108 =cut
1109  
1110 sub dump_config_sets {
1111 1 ▶ my ($self, $params) = @_;
Subroutine dump_config_sets: called CC=3 SCAR=11.1
Pod documented
1112 1 my $available_config_sets = delete $params->{configs};
1113 my $directory_template = delete $params->{directory_template} ||
1114 1 ▶ DBIx::Class::Exception->throw("'directory_template is required parameter");
Condition33%1/3
delete $params->{'directory_template'} || 'DBIx::Class::Exception'->throw(q['directory_template is required parameter])
l!l&&r!l&&!r
100
MC/DC0%0/2
delete $params->{'directory_template'} || 'DBIx::Class::Exception'->throw(q['directory_template is required parameter])
delete $params->{'directory_template'} 'DBIx::Class::Exception'->throw(q['directory_template is required parameter])
Truth table33%1/3
A || B
A= delete $params->{'directory_template'}B= 'DBIx::Class::Exception'->throw(q['directory_template is required parameter])
ABresult
1X1
011
000
1115  
1116 1 for my $set (@$available_config_sets) {
1117 2 my $localparams = $params;
1118 2 $localparams->{directory} = $directory_template->($self, $localparams, $set);
1119 2 $localparams->{config} = $set;
1120 2 $self->dump($localparams);
1121 2 $self->dumped_objects({}); ## Clear dumped for next go, if there is one!
1122 }
1123 }
1124  
1125 =head2 dump_all_config_sets
1126  
1127 my %local_params = %$params;
1128 my $local_self = bless { %$self }, ref($self);
1129 $local_params{directory} = $directory_template->($self, \%local_params, $set);
1130 $local_params{config} = $set;
1131 $self->dump(\%local_params);
1132  
1133  
1134 Works just like L</dump> but instead of specifying a single json config set
1135 located in L</config_dir> we dump each set in turn to the specified directory.
1136  
1137 The parameters are the same as for L</dump> except instead of a C<directory>
1138 parameter we have a C<directory_template> which is a coderef expected to return
1139 a scalar that is a root directory where we will do the actual dumping. This
1140 coderef get three arguments: C<$self>, C<$params> and C<$set_name>. For
1141 example:
1142  
1143 $fixture->dump_all_config_sets({
1144 schema => $schema,
1145 directory_template => sub {
1146 my ($fixture, $params, $set) = @_;
1147 return io->catdir('var', 'fixtures', $params->{schema}->version, $set);
1148 },
1149 });
1150  
1151 =cut
1152  
1153 sub dump_all_config_sets {
1154 0 ▶ my ($self, $params) = @_;
Subroutine dump_all_config_sets: not called CC=1 SCAR=6.9
Pod documented
1155 0 $self->dump_config_sets({
1156 %$params,
1157 configs=>[$self->available_config_sets],
1158 });
1159 }
1160  
1161 =head2 populate
1162  
1163 =over 4
1164  
1165 =item Arguments: \%$attrs
1166  
1167 =item Return Value: 1
1168  
1169 =back
1170  
1171 $fixtures->populate( {
1172 # directory to look for fixtures in, as specified to dump
1173 directory => '/home/me/app/fixtures',
1174  
1175 # DDL to deploy
1176 ddl => '/home/me/app/sql/ddl.sql',
1177  
1178 # database to clear, deploy and then populate
1179 connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password'],
1180  
1181 # DDL to deploy after populating records, ie. FK constraints
1182 post_ddl => '/home/me/app/sql/post_ddl.sql',
1183  
1184 # use CASCADE option when dropping tables
1185 cascade => 1,
1186  
1187 # optional, set to 1 to run ddl but not populate
1188 no_populate => 0,
1189  
1190 # optional, set to 1 to run each fixture through ->create rather than have
1191 # each $rs populated using $rs->populate. Useful if you have overridden new() logic
1192 # that effects the value of column(s).
1193 use_create => 0,
1194  
1195 # optional, same as use_create except with find_or_create.
1196 # Useful if you are populating a persistent data store.
1197 use_find_or_create => 0,
1198  
1199 # Dont try to clean the database, just populate over whats there. Requires
1200 # schema option. Use this if you want to handle removing old data yourself
1201 # no_deploy => 1
1202 # schema => $schema
1203 } );
1204  
1205 In this case the database app_dev will be cleared of all tables, then the
1206 specified DDL deployed to it, then finally all fixtures found in
1207 /home/me/app/fixtures will be added to it. populate will generate its own
1208 DBIx::Class schema from the DDL rather than being passed one to use. This is
1209 better as custom insert methods are avoided which can to get in the way. In
1210 some cases you might not have a DDL, and so this method will eventually allow a
1211 $schema object to be passed instead.
1212  
1213 If needed, you can specify a post_ddl attribute which is a DDL to be applied
1214 after all the fixtures have been added to the database. A good use of this
1215 option would be to add foreign key constraints since databases like Postgresql
1216 cannot disable foreign key checks.
1217  
1218 If your tables have foreign key constraints you may want to use the cascade
1219 attribute which will make the drop table functionality cascade, ie 'DROP TABLE
1220 $table CASCADE'.
1221  
1222 C<directory> is a required attribute.
1223  
1224 If you wish for DBIx::Class::Fixtures to clear the database for you pass in
1225 C<dll> (path to a DDL sql file) and C<connection_details> (array ref of DSN,
1226 user and pass).
1227  
1228 If you wish to deal with cleaning the schema yourself, then pass in a C<schema>
1229 attribute containing the connected schema you wish to operate on and set the
1230 C<no_deploy> attribute.
1231  
1232 =cut
1233  
1234 sub populate {
1235 12 ▶ my $self = shift;
Subroutine populate: called CC=22 SCAR=34.6
Pod documented
1236 12 my ($params) = @_;
1237 12 ▶ DBIx::Class::Exception->throw('first arg to populate must be hash ref')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $params eq "HASH" 0 12 12
1238 unless ref $params eq 'HASH';
1239  
1240 DBIx::Class::Exception->throw('directory param not specified')
1241 12 ▶ unless $params->{directory};
Branch: 1 branch
BranchTrueFalseTotal
unless $params->{"directory"} 0 12 12
1242  
1243 12 my $fixture_dir = io->dir(delete $params->{directory});
1244 12 ▶ DBIx::Class::Exception->throw("fixture directory '$fixture_dir' does not exist")
Branch: 1 branch
BranchTrueFalseTotal
unless -d "$fixture_dir" 0 12 12
1245 unless -d "$fixture_dir";
1246  
1247 12 my $ddl_file;
1248 my $dbh;
1249 12 my $schema;
1250 12 ▶ if ($params->{ddl} && $params->{connection_details}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($params->{'ddl'} and $params->{'connection_details'}) { } 7 5 12
elsif ($params->{'schema'} and $params->{'no_deploy'}) { } 5 0 5
Condition66%2/3
$params->{"ddl"} and $params->{"connection_details"}
!ll&&!rl&&r
507
MC/DC50%1/2
$params->{"ddl"} and $params->{"connection_details"}
$params->{"ddl"} $params->{"connection_details"}
Truth table66%2/3
A and B
A= $params->{"ddl"}B= $params->{"connection_details"}
ABresult
0X0
100
111
1251 7 $ddl_file = io->file(delete $params->{ddl});
1252 7 ▶ unless (-e "$ddl_file") {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e "$ddl_file") 0 7 7
1253 0 return DBIx::Class::Exception->throw('DDL does not exist at ' . $ddl_file);
1254 }
1255 7 ▶ unless (ref $params->{connection_details} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $params->{"connection_details"} eq "ARRAY") 0 7 7
1256 0 return DBIx::Class::Exception->throw('connection details must be an arrayref');
1257 }
1258 $schema = $self->_generate_schema({
1259 ddl => "$ddl_file",
1260 connection_details => delete $params->{connection_details},
1261 7 %{$params}
1262 });
1263 ▶ } elsif ($params->{schema} && $params->{no_deploy}) {
Condition33%1/3
$params->{"schema"} and $params->{"no_deploy"}
!ll&&!rl&&r
005
MC/DC0%0/2
$params->{"schema"} and $params->{"no_deploy"}
$params->{"schema"} $params->{"no_deploy"}
Truth table33%1/3
A and B
A= $params->{"schema"}B= $params->{"no_deploy"}
ABresult
0X0
100
111
1264 5 $schema = $params->{schema};
1265 } else {
1266 0 DBIx::Class::Exception->throw('you must set the ddl and connection_details params');
1267 }
1268  
1269  
1270 12 ▶ return 1 if $params->{no_populate};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"no_populate"} 0 12 12
1271  
1272 12 $self->msg("\nimporting fixtures");
1273 12 my $tmp_fixture_dir = io->dir(tempdir());
1274 12 my $config_set_path = io->file($fixture_dir, '_config_set');
1275 12 ▶ my $config_set = -e "$config_set_path" ? do { my $VAR1; eval($config_set_path->slurp); $VAR1 } : '';
Branch: 1 branch
BranchTrueFalseTotal
-e "$config_set_path" ? : 12 0 12
1276  
1277 my $v = Data::Visitor::Callback->new(
1278 plain_value => sub {
1279 225 ▶ my ($visitor, $data) = @_;
Subroutine __ANON__: called CC=2 SCAR=9.7
1280 my $subs = {
1281 ENV => sub {
1282 0 ▶ my ( $self, $v ) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
1283 0 ▶ if (! defined($ENV{$v})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $ENV{$v}) { } 0 0 0
1284 0 return "";
1285 } else {
1286 0 return $ENV{ $v };
1287 }
1288 },
1289 ATTR => sub {
1290 1 ▶ my ($self, $v) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.6
1291 1 ▶ if(my $attr = $self->config_attrs->{$v}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $attr = $self->config_attrs->{$v}) { } 1 0 1
1292 1 return $attr;
1293 } else {
1294 0 return "";
1295 }
1296 },
1297 catfile => sub {
1298 0 ▶ my ($self, @args) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1299 0 io->catfile(@args);
1300 },
1301 catdir => sub {
1302 0 ▶ my ($self, @args) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1303 0 io->catdir(@args);
1304 },
1305 225 };
1306  
1307 225 my $subsre = join( '|', keys %$subs );
1308 225 ▶ $_ =~ s{__($subsre)(?:\((.+?)\))?__}{ $subs->{ $1 }->( $self, $2 ? split( /,/, $2 ) : () ) }eg;
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 1 0 1
1309  
1310 225 return $_;
1311 }
1312 12 );
1313  
1314 12 $v->visit( $config_set );
1315  
1316  
1317 12 my %sets_by_src;
1318 12 ▶ if($config_set) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config_set) 12 0 12
1319 15 %sets_by_src = map { delete($_->{class}) => $_ }
1320 12 @{$config_set->{sets}}
1321 }
1322  
1323 12 ▶ if (-e "$tmp_fixture_dir") {
Branch: 1 branch
BranchTrueFalseTotal
if (-e "$tmp_fixture_dir") 12 0 12
1324 12 $self->msg("- deleting existing temp directory $tmp_fixture_dir");
1325 12 $tmp_fixture_dir->rmtree;
1326 }
1327 12 $self->msg("- creating temp dir");
1328 12 $tmp_fixture_dir->mkpath();
1329 12 for ( map { $self->_name_for_source($schema->source($_)) } $schema->sources) {
1330 74 my $from_dir = io->catdir($fixture_dir, $_);
1331 74 ▶ next unless -e "$from_dir";
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$from_dir" 57 17 74
1332 17 $from_dir->copy( io->catdir($tmp_fixture_dir, $_)."" );
1333 }
1334  
1335 12 ▶ unless (-d "$tmp_fixture_dir") {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d "$tmp_fixture_dir") 0 12 12
1336 0 DBIx::Class::Exception->throw("Unable to create temporary fixtures dir: $tmp_fixture_dir: $!");
1337 }
1338  
1339 12 my $fixup_visitor;
1340 12 my $formatter = $schema->storage->datetime_parser;
1341 12 ▶ unless ($@ || !$formatter) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@ or not $formatter) 12 0 12
Condition33%1/3
$@ or not $formatter
l!l&&r!l&&!r
0012
MC/DC0%0/2
$@ or not $formatter
$@ not $formatter
Truth table33%1/3
A or not(B)
A= $@B= not $formatter
ABresult
1X1
011
000
1342 12 my %callbacks;
1343 12 ▶ if ($params->{datetime_relative_to}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{'datetime_relative_to'}) { } 0 12 12
1344 $callbacks{'DateTime::Duration'} = sub {
1345 0 ▶ $params->{datetime_relative_to}->clone->add_duration($_);
Subroutine __ANON__: not called CC=1 SCAR=6.9
1346 0 };
1347 } else {
1348 $callbacks{'DateTime::Duration'} = sub {
1349 0 ▶ $formatter->format_datetime(DateTime->today->add_duration($_))
Subroutine __ANON__: not called CC=1 SCAR=6.9
1350 12 };
1351 }
1352 12 ▶ $callbacks{object} ||= "visit_ref";
Condition50%1/2
$callbacks{"object"} ||= "visit_ref"
l!l
012
MC/DC0%0/1
$callbacks{"object"} ||= "visit_ref"
$callbacks{"object"}
Truth table50%1/2
A
A= $callbacks{"object"}
Aresult
11
00
1353 12 $fixup_visitor = new Data::Visitor::Callback(%callbacks);
1354 }
1355  
1356 12 my @sorted_source_names = $self->_get_sorted_sources( $schema );
1357 $schema->storage->txn_do(sub {
1358 $schema->storage->with_deferred_fk_checks(sub {
1359 12 ▶ foreach my $source (@sorted_source_names) {
Subroutine __ANON__: called CC=15 SCAR=28.6
1360 74 $self->msg("- adding " . $source);
1361 74 my $rs = $schema->resultset($source);
1362 74 my $source_dir = io->catdir($tmp_fixture_dir, $self->_name_for_source($rs->result_source));
1363 74 ▶ next unless (-e "$source_dir");
Branch: 1 branch
BranchTrueFalseTotal
unless -e "$source_dir" 57 17 74
1364 17 my @rows;
1365 17 ▶ while (my $file = $source_dir->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $file = $source_dir->next) 21 17 38
1366 21 ▶ next unless ($file =~ /\.fix$/);
Branch: 1 branch
BranchTrueFalseTotal
unless $file =~ /\.fix$/ 0 21 21
1367 21 ▶ next if $file->is_dir;
Branch: 1 branch
BranchTrueFalseTotal
if $file->is_dir 0 21 21
1368 21 my $contents = $file->slurp;
1369 21 my $HASH1;
1370 21 eval($contents);
1371 21 ▶ $HASH1 = $fixup_visitor->visit($HASH1) if $fixup_visitor;
Branch: 1 branch
BranchTrueFalseTotal
if $fixup_visitor 21 0 21
1372 21 ▶ if(my $external = delete $HASH1->{external}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $external = delete $HASH1->{"external"}) 1 20 21
1373 1 my @fields = keys %{$sets_by_src{$source}->{external}};
1374 1 foreach my $field(@fields) {
1375 1 my $key = $HASH1->{$field};
1376 1 my $content = decode_base64 ($external->{$field});
1377 1 my $args = $sets_by_src{$source}->{external}->{$field}->{args};
1378 1 my ($plus, $class) = ( $sets_by_src{$source}->{external}->{$field}->{class}=~/^(\+)*(.+)$/);
1379 1 ▶ $class = "DBIx::Class::Fixtures::External::$class" unless $plus;
Branch: 1 branch
BranchTrueFalseTotal
unless $plus 1 0 1
1380 1 ▶ eval "use $class";
Subroutine BEGIN: called CC=1 SCAR=0.0
1381 1 $class->restore($key, $content, $args);
1382 }
1383 }
1384 21 ▶ if ( $params->{use_create} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($params->{'use_create'}) { } 1 20 21
elsif ($params->{'use_find_or_create'}) { } 11 9 20
1385 1 $rs->create( $HASH1 );
1386 } elsif( $params->{use_find_or_create} ) {
1387 11 $rs->find_or_create( $HASH1 );
1388 } else {
1389 9 push(@rows, $HASH1);
1390 }
1391 }
1392 17 ▶ $rs->populate(\@rows) if scalar(@rows);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @rows 7 10 17
1393  
1394 ## Now we need to do some db specific cleanup
1395 ## this probably belongs in a more isolated space. Right now this is
1396 ## to just handle postgresql SERIAL types that use Sequences
1397  
1398 17 my $table = $rs->result_source->name;
1399 17 for my $column(my @columns = $rs->result_source->columns) {
1400 46 my $info = $rs->result_source->column_info($column);
1401 46 ▶ if(my $sequence = $info->{sequence}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sequence = $info->{"sequence"}) 0 46 46
1402 0 $self->msg("- updating sequence $sequence");
1403 $rs->result_source->storage->dbh_do(sub {
1404 0 ▶ my ($storage, $dbh, @cols) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
1405 0 $self->msg(
1406 my $sql = sprintf("SELECT setval(?, (SELECT max(%s) FROM %s));",$dbh->quote_identifier($column),$dbh->quote_identifier($table))
1407 );
1408 0 my $sth = $dbh->prepare($sql);
1409 0 $sth->bind_param(1,$sequence);
1410  
1411 0 ▶ my $rv = $sth->execute or die $sth->errstr;
Branch: 1 branch
BranchTrueFalseTotal
my $rv = $sth->execute or die $sth->errstr 0 0 0
1412 0 $self->msg("- $sql");
1413 0 });
1414 }
1415 }
1416  
1417 }
1418 12 ▶ });
Subroutine __ANON__: called CC=1 SCAR=0.0
1419 12 });
1420 $self->do_post_ddl( {
1421 schema=>$schema,
1422 post_ddl=>$params->{post_ddl}
1423 12 ▶ } ) if $params->{post_ddl};
Branch: 1 branch
BranchTrueFalseTotal
if $params->{"post_ddl"} 1 11 12
1424  
1425 12 $self->msg("- fixtures imported");
1426 12 $self->msg("- cleaning up");
1427 12 $tmp_fixture_dir->rmtree;
1428 12 return 1;
1429 }
1430  
1431 # the overall logic is modified from SQL::Translator::Parser::DBIx::Class->parse
1432 sub _get_sorted_sources {
1433 12 ▶ my ( $self, $dbicschema ) = @_;
Subroutine _get_sorted_sources: called CC=16 SCAR=28.2
1434  
1435  
1436 12 my %table_monikers = map { $_ => 1 } $dbicschema->sources;
1437  
1438 12 my %tables;
1439 12 foreach my $moniker (sort keys %table_monikers) {
1440 74 my $source = $dbicschema->source($moniker);
1441  
1442 74 my $table_name = $source->name;
1443 74 my @primary = $source->primary_columns;
1444 74 my @rels = $source->relationships();
1445  
1446 74 my %created_FK_rels;
1447 74 foreach my $rel (sort @rels) {
1448 48 my $rel_info = $source->relationship_info($rel);
1449  
1450 # Ignore any rel cond that isn't a straight hash
1451 48 ▶ next unless ref $rel_info->{cond} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rel_info->{"cond"} eq "HASH" 0 48 48
1452  
1453 48 my @keys = map {$rel_info->{cond}->{$_} =~ /^\w+\.(\w+)$/} keys(%{$rel_info->{cond}});
1454  
1455 # determine if this relationship is a self.fk => foreign.pk (i.e. belongs_to)
1456 48 my $fk_constraint;
1457 48 ▶ if ( exists $rel_info->{attrs}{is_foreign_key_constraint} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $rel_info->{'attrs'}{'is_foreign_key_constraint'}) { } 24 24 48
elsif ($rel_info->{'attrs'}{'accessor'} and $rel_info->{'attrs'}{'accessor'} eq 'multi') { } 20 4 24
1458 24 $fk_constraint = $rel_info->{attrs}{is_foreign_key_constraint};
1459 ▶ } elsif ( $rel_info->{attrs}{accessor}
Condition66%2/3
$rel_info->{"attrs"}{"accessor"} and $rel_info->{"attrs"}{"accessor"} eq "multi"
!ll&&!rl&&r
0420
MC/DC50%1/2
$rel_info->{"attrs"}{"accessor"} and $rel_info->{"attrs"}{"accessor"} eq "multi"
$rel_info->{"attrs"}{"accessor"} $rel_info->{"attrs"}{"accessor"} eq "multi"
Truth table66%2/3
A and B
A= $rel_info->{"attrs"}{"accessor"}B= $rel_info->{"attrs"}{"accessor"} eq "multi"
ABresult
0X0
100
111
1460 && $rel_info->{attrs}{accessor} eq 'multi' ) {
1461 20 $fk_constraint = 0;
1462 } else {
1463 4 $fk_constraint = not $source->_compare_relationship_keys(\@keys, \@primary);
1464 }
1465  
1466 # Dont add a relation if its not constraining
1467 48 ▶ next unless $fk_constraint;
Branch: 1 branch
BranchTrueFalseTotal
unless $fk_constraint 24 24 48
1468  
1469 24 my $rel_table = $source->related_source($rel)->source_name;
1470 # Make sure we don't create the same relation twice
1471 24 my $key_test = join("\x00", sort @keys);
1472 24 ▶ next if $created_FK_rels{$rel_table}->{$key_test};
Branch: 1 branch
BranchTrueFalseTotal
if $created_FK_rels{$rel_table}{$key_test} 0 24 24
1473  
1474 24 ▶ if (scalar(@keys)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @keys) 24 0 24
1475 24 $created_FK_rels{$rel_table}->{$key_test} = 1;
1476  
1477 # calculate dependencies: do not consider deferrable constraints and
1478 # self-references for dependency calculations
1479 24 ▶ if (! $rel_info->{attrs}{is_deferrable} and $rel_table ne $table_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $rel_info->{"attrs"}{"is_deferrable"} and $rel_table ne $table_name) 24 0 24
Condition33%1/3
not $rel_info->{"attrs"}{"is_deferrable"} and $rel_table ne $table_name
!ll&&!rl&&r
0024
MC/DC0%0/2
not $rel_info->{"attrs"}{"is_deferrable"} and $rel_table ne $table_name
not $rel_info->{"attrs"}{"is_deferrable"} $rel_table ne $table_name
Truth table33%1/3
not(A) and B
A= not $rel_info->{"attrs"}{"is_deferrable"}B= $rel_table ne $table_name
ABresult
0X0
100
111
1480 24 $tables{$moniker}{$rel_table}++;
1481 }
1482 }
1483 }
1484 74 ▶ $tables{$moniker} = {} unless exists $tables{$moniker};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $tables{$moniker} 54 20 74
1485 }
1486  
1487 # resolve entire dep tree
1488 my $dependencies = {
1489 12 map { $_ => _resolve_deps ($_, \%tables) } (keys %tables)
1490 };
1491  
1492 # return the sorted result
1493 return sort {
1494 12 ▶ keys %{$dependencies->{$a} || {} } <=> keys %{ $dependencies->{$b} || {} }
Branch: 3 branches
BranchTrueFalseTotal
keys %{$dependencies->{$a} or {};} <=> keys %{$dependencies->{$b} or {};} or $a cmp $b 88 35 123
$dependencies->{$a} or {} 0 123 123
$dependencies->{$b} or {} 0 123 123
1495 ||
1496 $a cmp $b
1497 } (keys %tables);
1498 }
1499  
1500 sub _resolve_deps {
1501 110 ▶ my ( $question, $answers, $seen ) = @_;
Subroutine _resolve_deps: called CC=5 SCAR=16.1
1502 110 my $ret = {};
1503 110 ▶ $seen ||= {};
Condition100%2/2
$seen ||= {}
l!l
3674
MC/DC100%1/1
$seen ||= {}
$seen
Truth table100%2/2
A
A= $seen
Aresult
11
00
1504  
1505 110 my %seen = map { $_ => $seen->{$_} + 1 } ( keys %$seen );
1506 110 $seen{$question} = 1;
1507  
1508 110 for my $dep (keys %{ $answers->{$question} }) {
1509 36 ▶ return {} if $seen->{$dep};
Branch: 1 branch
BranchTrueFalseTotal
if $seen->{$dep} 0 36 36
1510 36 my $subdeps = _resolve_deps( $dep, $answers, \%seen );
1511 36 $ret->{$_} += $subdeps->{$_} for ( keys %$subdeps );
1512 36 ++$ret->{$dep};
1513 }
1514 110 return $ret;
1515 }
1516  
1517 sub do_post_ddl {
1518 1 ▶ my ($self, $params) = @_;
Subroutine do_post_ddl: called CC=5 SCAR=17.5
Pod undocumented
1519  
1520 1 my $schema = $params->{schema};
1521 1 my $data = _read_sql($params->{post_ddl});
1522 1 foreach (@$data) {
1523 3 ▶ eval { $schema->storage->dbh->do($_) or warn "SQL was:\n $_"};
Branch: 1 branch
BranchTrueFalseTotal
$schema->storage->dbh->do($_) or warn "SQL was:\n $_" 0 3 3
1524 3 ▶ if ($@ && !$self->{ignore_sql_errors}) { die "SQL was:\n $_\n$@"; }
Branch: 1 branch
BranchTrueFalseTotal
if ($@ and not $self->{"ignore_sql_errors"}) 0 3 3
Condition33%1/3
$@ and not $self->{"ignore_sql_errors"}
!ll&&!rl&&r
300
MC/DC0%0/2
$@ and not $self->{"ignore_sql_errors"}
$@ not $self->{"ignore_sql_errors"}
Truth table33%1/3
A and not(B)
A= $@B= not $self->{"ignore_sql_errors"}
ABresult
0X0
100
111
1525 }
1526 1 $self->msg("- finished importing post-populate DDL into DB");
1527 }
1528  
1529 sub msg {
1530 520 ▶ my $self = shift;
Subroutine msg: called CC=5 SCAR=20.2
Pod undocumented
1531 520 ▶ my $subject = shift || return;
Condition50%1/2
shift() || (return)
l!l
5200
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1532 520 ▶ my $level = shift || 1;
Condition100%2/2
shift() || 1
l!l
154366
MC/DC100%1/1
shift() || 1
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
1533 520 ▶ return unless $self->debug >= $level;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->debug >= $level 520 0 520
1534 0 ▶ if (ref $subject) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $subject) { } 0 0 0
1535 0 print Dumper($subject);
1536 } else {
1537 0 print $subject . "\n";
1538 }
1539 }
1540  
1541 # Helper method for ensuring that the name used for a given source
1542 # is always the same (This is used to name the fixture directories
1543 # for example)
1544  
1545 sub _name_for_source {
1546 396 ▶ my ($self, $source) = @_;
Subroutine _name_for_source: called CC=2 SCAR=6.9
1547  
1548 396 ▶ return ref $source->name ? $source->source_name : $source->name;
Branch: 1 branch
BranchTrueFalseTotal
ref $source->name ? : 63 333 396
1549 }
1550  
1551 =head1 AUTHOR
1552  
1553 Luke Saunders <luke@shadowcatsystems.co.uk>
1554  
1555 Initial development sponsored by and (c) Takkle, Inc. 2007
1556  
1557 =head1 CONTRIBUTORS
1558  
1559 Ash Berlin <ash@shadowcatsystems.co.uk>
1560  
1561 Matt S. Trout <mst@shadowcatsystems.co.uk>
1562  
1563 John Napiorkowski <jjnapiork@cpan.org>
1564  
1565 Drew Taylor <taylor.andrew.j@gmail.com>
1566  
1567 Frank Switalski <fswitalski@gmail.com>
1568  
1569 Chris Akins <chris.hexx@gmail.com>
1570  
1571 Tom Bloor <t.bloor@shadowcat.co.uk>
1572  
1573 Samuel Kaufman <skaufman@cpan.org>
1574  
1575 =head1 LICENSE
1576  
1577 This library is free software under the same license as perl itself
1578  
1579 =cut
1580  
1581 22 1;
↑ Summary blib/lib/DBIx/Class/Fixtures/DBI.pm »