Sims.pm

filter: Statementstmt 96.4% 273 / 283 Branchbran 86.1% 93 / 108 Conditioncond 75.3% 52 / 69 MC/DCmcdc 50.0% 19 / 38 Subroutinesub 100% 37 / 37 Podpod 33.3% 2 / 6 totaltotal 87.9% 476 / 541 CC 99 SCAR 24.8
CC
99
Cov
91%
__ANON__
26.0
load_sims
23.4
__ANON__
11.1
CRAP 11.9
↑ Summary Sims/Types.pm »
1 # vim: set sw=2 ft=perl:
2 package DBIx::Class::Sims;
3  
4 23 ▶use 5.008_004;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 #use DDP;
10  
11 23 ▶use Data::Walk qw( walk );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 23 ▶use DBIx::Class::TopoSort ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 ▶use Hash::Merge qw( merge );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 23 ▶use List::Util qw( shuffle );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 23 ▶use List::MoreUtils qw( natatime );
Subroutine BEGIN: called CC=1 SCAR=0.0
16 23 ▶use Scalar::Util qw( reftype );
Subroutine BEGIN: called CC=1 SCAR=0.0
17 23 ▶use String::Random qw( random_regex );
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 23 our $VERSION = '0.300006';
20  
21 {
22 23 my %sim_types;
23  
24 sub set_sim_type {
25 23 ▶ shift;
Subroutine set_sim_type: called CC=5 SCAR=16.5
Pod documented
26 23 my $types = shift;
27 23 ▶ return unless ref($types||'') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref($types || "") eq "HASH" 0 23 23
Condition50%1/2
$types || ''
l!l
230
MC/DC0%0/1
$types || ''
$types
Truth table50%1/2
A
A= $types
Aresult
11
00
28  
29 23 ▶ while ( my ($name, $meth) = each(%$types) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$types) 276 23 299
30 276 ▶ next unless ref($meth) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $meth eq "CODE" 0 276 276
31  
32 276 $sim_types{$name} = $meth;
33 }
34  
35 23 return;
36 }
37 23 ▶ BEGIN { *set_sim_types = \&set_sim_type; }
Subroutine BEGIN: called CC=1 SCAR=0.0
38  
39 sub sim_type {
40 3 ▶ shift;
Subroutine sim_type: called CC=3 SCAR=13.3
Pod undocumented
41  
42 3 ▶ return if @_ == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 0 3 3
43 3 ▶ return $sim_types{$_[0]} if @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 3 0 3
44 0 return map { $sim_types{$_} } @_;
45 }
46 23 ▶ BEGIN { *sim_types = \&sim_type; }
Subroutine BEGIN: called CC=1 SCAR=0.0
47 }
48 23 ▶use DBIx::Class::Sims::Types;
Subroutine BEGIN: called CC=1 SCAR=0.0
49  
50 sub add_sims {
51 2 ▶ my $class = shift;
Subroutine add_sims: called CC=5 SCAR=16.4
Pod undocumented
52 2 my ($schema, $source, @remainder) = @_;
53  
54 2 my $rsrc = $schema->source($source);
55 2 my $it = natatime(2, @remainder);
56 2 ▶ while (my ($column, $sim_info) = $it->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = &$it()) 2 2 4
57 2 ▶ my $col_info = $schema->source($source)->column_info($column) || next;
Condition50%1/2
$schema->source($source)->column_info($column) || (next)
l!l
20
MC/DC0%0/1
$schema->source($source)->column_info($column) || (next)
$schema->source($source)->column_info($column)
Truth table50%1/2
A
A= $schema->source($source)->column_info($column)
Aresult
11
00
58 $col_info->{sim} = merge(
59 $col_info->{sim} || {},
60 2 ▶ $sim_info || {},
Condition50%2/4
$col_info->{'sim'} || {}
l!l
02
$sim_info || {}
l!l
20
MC/DC0%0/1
$col_info->{'sim'} || {}
$col_info->{'sim'}
MC/DC0%0/1
$sim_info || {}
$sim_info
Truth table50%1/2
A
A= $col_info->{'sim'}
Aresult
11
00
Truth table50%1/2
A
A= $sim_info
Aresult
11
00
61 );
62 }
63  
64 2 return;
65 }
66 23 *add_sim = \&add_sims;
67  
68 sub load_sims {
69 45 ▶ my $self = shift;
Subroutine load_sims: called CC=23 SCAR=31.5
Pod documented
70 45 my $schema;
71 45 ▶ if (ref($self) && $self->isa('DBIx::Class::Schema')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self and $self->isa('DBIx::Class::Schema')) { } 39 6 45
Condition66%2/3
ref $self and $self->isa("DBIx::Class::Schema")
!ll&&!rl&&r
6039
MC/DC50%1/2
ref $self and $self->isa("DBIx::Class::Schema")
ref $self $self->isa("DBIx::Class::Schema")
Truth table66%2/3
A and B
A= ref $selfB= $self->isa("DBIx::Class::Schema")
ABresult
0X0
100
111
72 39 $schema = $self;
73 }
74 else {
75 6 $schema = shift(@_);
76 }
77 45 my ($spec_proto, $opts_proto) = @_;
78  
79 45 my $spec = expand_dots(normalize_input($spec_proto));
80 45 ▶ my $opts = normalize_input($opts_proto || {});
Condition100%2/2
$opts_proto || {}
l!l
1035
MC/DC100%1/1
$opts_proto || {}
$opts_proto
Truth table100%2/2
A
A= $opts_proto
Aresult
11
00
81  
82 ###### FROM HERE ######
83 # These are utility methods to help navigate the rel_info hash.
84 45 ▶ my $is_fk = sub { return exists $_[0]{attrs}{is_foreign_key_constraint} };
Subroutine __ANON__: called CC=1 SCAR=0.0
85 my $short_source = sub {
86 56 ▶ (my $x = $_[0]{source}) =~ s/.*:://;
Subroutine __ANON__: called CC=1 SCAR=0.0
87 56 return $x;
88 45 };
89  
90 # ribasushi says: at least make sure the cond is a hashref (not guaranteed)
91 45 ▶ my $self_fk_cols = sub { map {/^self\.(.*)/; $1} values %{$_[0]{cond}} };
Subroutine __ANON__: called CC=1 SCAR=0.0
92 45 ▶ my $self_fk_col = sub { ($self_fk_cols->(@_))[0] };
Subroutine __ANON__: called CC=1 SCAR=0.0
93 45 ▶ my $foreign_fk_cols = sub { map {/^foreign\.(.*)/; $1} keys %{$_[0]{cond}} };
Subroutine __ANON__: called CC=1 SCAR=0.0
94 45 ▶ my $foreign_fk_col = sub { ($foreign_fk_cols->(@_))[0] };
Subroutine __ANON__: called CC=1 SCAR=0.0
95 ###### TO HERE ######
96  
97 # 1. Ensure the belongs_to relationships are in $reqs
98 # 2. Set the rel_info as the leaf in $reqs
99 45 ▶ my $reqs = normalize_input($opts->{constraints} || {});
Condition100%2/2
$opts->{'constraints'} || {}
l!l
639
MC/DC100%1/1
$opts->{'constraints'} || {}
$opts->{'constraints'}
Truth table100%2/2
A
A= $opts->{'constraints'}
Aresult
11
00
100 45 my %is_foreign_key;
101 45 foreach my $name ( $schema->sources ) {
102 77 my $source = $schema->source($name);
103  
104 77 ▶ $reqs->{$name} ||= {};
Condition100%2/2
$reqs->{$name} ||= {}
l!l
671
MC/DC100%1/1
$reqs->{$name} ||= {}
$reqs->{$name}
Truth table100%2/2
A
A= $reqs->{$name}
Aresult
11
00
105 77 foreach my $rel_name ( $source->relationships ) {
106 64 my $rel_info = $source->relationship_info($rel_name);
107  
108 64 ▶ if ($is_fk->($rel_info)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$is_fk($rel_info)) 32 32 64
109 32 $reqs->{$name}{$rel_name} = 1;
110 32 $is_foreign_key{$name}{$_} = 1 for $self_fk_cols->($rel_info);
111 }
112 }
113 }
114  
115 # 2: Create the rows in toposorted order
116 45 ▶ my $hooks = $opts->{hooks} || {};
Condition50%1/2
$opts->{'hooks'} || {}
l!l
045
MC/DC0%0/1
$opts->{'hooks'} || {}
$opts->{'hooks'}
Truth table50%1/2
A
A= $opts->{'hooks'}
Aresult
11
00
117 45 ▶ $hooks->{preprocess} ||= sub {};
Subroutine __ANON__: called CC=1 SCAR=1.2
Condition33%1/3
$hooks->{"preprocess"} ||= sub {
l!l&&r!l&&!r
0450
MC/DC0%0/2
$hooks->{"preprocess"} ||= sub { }
$hooks->{"preprocess"} sub { }
Truth table33%1/3
A ||= B
A= $hooks->{"preprocess"}B= sub { }
ABresult
1X1
011
000
118 45 ▶ $hooks->{postprocess} ||= sub {};
Subroutine __ANON__: called CC=1 SCAR=1.2
Condition33%1/3
$hooks->{"postprocess"} ||= sub {
l!l&&r!l&&!r
0450
MC/DC0%0/2
$hooks->{"postprocess"} ||= sub { }
$hooks->{"postprocess"} sub { }
Truth table33%1/3
A ||= B
A= $hooks->{"postprocess"}B= sub { }
ABresult
1X1
011
000
119  
120 # Prepopulate column values (as appropriate)
121 45 my %subs;
122 $subs{fix_fk_dependencies} = sub {
123 95 ▶ my ($name, $item) = @_;
Subroutine __ANON__: called CC=11 SCAR=24.0
124  
125 # 1. If we have something, then:
126 # a. If it's a scalar, then, COND = { $fk => scalar }
127 # b. Look up the row by COND
128 # c. If the row is not there, then $create_item->($fksrc, COND)
129 # 2. If we don't have something and the column is non-nullable, then:
130 # a. If rows exists, pick a random one.
131 # b. If rows don't exist, $create_item->($fksrc, {})
132 95 my %child_deps;
133 95 my $source = $schema->source($name);
134 95 foreach my $rel_name ( $source->relationships ) {
135 84 my $rel_info = $source->relationship_info($rel_name);
136 84 ▶ unless ( $is_fk->($rel_info) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&$is_fk($rel_info)) 42 42 84
137 42 ▶ if ($item->{$rel_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item->{$rel_name}) 9 33 42
138 9 $child_deps{$rel_name} = delete $item->{$rel_name};
139 }
140 42 next;
141 }
142  
143 42 ▶ next unless $reqs->{$name}{$rel_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $reqs->{$name}{$rel_name} 0 42 42
144  
145 42 my $col = $self_fk_col->($rel_info);
146 42 my $fkcol = $foreign_fk_col->($rel_info);
147  
148 42 my $fk_src = $short_source->($rel_info);
149 42 my $rs = $schema->resultset($fk_src);
150  
151 42 my $cond;
152 42 ▶ if ( $item->{$rel_name} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($item->{$rel_name}) { } 7 35 42
elsif ($item->{$col}) { } 20 15 35
153 7 $cond = delete $item->{$rel_name};
154 7 ▶ if ( !ref($cond) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $cond) 0 7 7
155 0 $cond = { $fkcol => $cond };
156 }
157 }
158 elsif ( $item->{$col} ) {
159 20 $cond = { $fkcol => $item->{$col} };
160 }
161  
162 42 my $col_info = $source->column_info($col);
163 42 ▶ if ( $cond ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($cond) { } 27 15 42
elsif ($col_info->{'is_nullable'}) { } 3 12 15
164 27 $rs = $rs->search($cond);
165 }
166 elsif ( $col_info->{is_nullable} ) {
167 3 next;
168 }
169 else {
170 12 $cond = {};
171 }
172  
173 39 ▶ my $parent = $rs->first || $subs{create_item}->($fk_src, $cond);
Condition66%2/3
$rs->first || $subs{'create_item'}->($fk_src, $cond)
l!l&&r!l&&!r
26130
MC/DC0%0/2
$rs->first || $subs{'create_item'}->($fk_src, $cond)
$rs->first $subs{'create_item'}->($fk_src, $cond)
Truth table66%2/3
A || B
A= $rs->firstB= $subs{'create_item'}->($fk_src, $cond)
ABresult
1X1
011
000
174 38 $item->{$col} = $parent->get_column($fkcol);
175 }
176  
177 94 return \%child_deps;
178 45 };
179 {
180 45 my %added_by;
181 my $are_columns_equal = sub {
182 1 ▶ my ($src, $row, $compare) = @_;
Subroutine __ANON__: called CC=6 SCAR=18.1
183 1 foreach my $col ($schema->source($src)->columns) {
184 4 ▶ next if $is_foreign_key{$src}{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $is_foreign_key{$src}{$col} 2 2 4
185  
186 2 ▶ next unless exists $row->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $row->{$col} 1 1 2
187 1 ▶ return unless exists $compare->{$col};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $compare->{$col} 0 1 1
188 1 ▶ return if $compare->{$col} ne $row->{$col};
Branch: 1 branch
BranchTrueFalseTotal
if $compare->{$col} ne $row->{$col} 0 1 1
189 }
190 1 return 1;
191 45 };
192 $subs{add_child} = sub {
193 19 ▶ my ($src, $fkcol, $row, $adder) = @_;
Subroutine __ANON__: called CC=6 SCAR=17.9
194 # If $row has the same keys (other than parent columns) as another row
195 # added by a different parent table, then set the foreign key for this
196 # parent in the existing row.
197 19 foreach my $name (keys %added_by) {
198 8 ▶ next if $name eq $adder;
Branch: 1 branch
BranchTrueFalseTotal
if $name eq $adder 7 1 8
199 1 foreach my $compare (@{$added_by{$name}}) {
200 1 ▶ if ($are_columns_equal->($src, $row, $compare)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$are_columns_equal($src, $row, $compare)) 1 0 1
201 1 $compare->{$fkcol} = $row->{$fkcol};
202 1 return;
203 }
204 }
205 }
206 18 push @{$spec->{$src}}, $row;
207 18 ▶ push @{$added_by{$adder} ||= []}, $row;
Condition100%2/2
$added_by{$adder} ||= []
l!l
711
MC/DC100%1/1
$added_by{$adder} ||= []
$added_by{$adder}
Truth table100%2/2
A
A= $added_by{$adder}
Aresult
11
00
208 45 };
209 }
210 $subs{find_by_unique_constraints} = sub {
211 94 ▶ my ($name, $item) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
212  
213 94 my $source = $schema->source($name);
214 my @uniques = map {
215 94 [ $source->unique_constraint_columns($_) ]
216 } $source->unique_constraint_names();
217  
218 94 my $rs = $schema->resultset($name);
219 94 my $searched = 0;
220 94 foreach my $unique (@uniques) {
221 # If there are specified values for all the columns in a specific unqiue constraint ...
222 94 ▶ next if grep { ! exists $item->{$_} } @$unique;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not exists $item->{$_};} @$unique 88 6 94
223  
224 # ... then add that to the list of potential values to search.
225 $rs = $rs->search({
226 6 ( map { $_ => $item->{$_} } @{$unique})
227 });
228 6 $searched = 1;
229 }
230  
231 94 ▶ return unless $searched;
Branch: 1 branch
BranchTrueFalseTotal
unless $searched 88 6 94
232 6 return $rs->first;
233 45 };
234 $subs{fix_child_dependencies} = sub {
235 87 ▶ my ($name, $row, $child_deps) = @_;
Subroutine __ANON__: called CC=8 SCAR=20.8
236  
237 # 1. If we have something, then:
238 # a. If it's not an array, then make it an array
239 # 2. If we don't have something,
240 # a. Make an array with an empty item
241 # XXX This is more than one item would be supported
242 # In all cases, make sure to add { $fkcol => $row->get_column($col) } to the
243 # child's $item
244 87 my $source = $schema->source($name);
245 87 foreach my $rel_name ( $source->relationships ) {
246 82 my $rel_info = $source->relationship_info($rel_name);
247 82 ▶ next if $is_fk->($rel_info);
Branch: 1 branch
BranchTrueFalseTotal
if &$is_fk($rel_info) 41 41 82
248 41 ▶ next unless $child_deps->{$rel_name} || $reqs->{$name}{$rel_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $child_deps->{$rel_name} or $reqs->{$name}{$rel_name} 27 14 41
Condition100%3/3
$child_deps->{$rel_name} or $reqs->{$name}{$rel_name}
l!l&&r!l&&!r
9527
MC/DC100%2/2
$child_deps->{$rel_name} or $reqs->{$name}{$rel_name}
$child_deps->{$rel_name} $reqs->{$name}{$rel_name}
Truth table100%3/3
A or B
A= $child_deps->{$rel_name}B= $reqs->{$name}{$rel_name}
ABresult
1X1
011
000
249  
250 14 my $col = $self_fk_col->($rel_info);
251 14 my $fkcol = $foreign_fk_col->($rel_info);
252  
253 14 my $fk_src = $short_source->($rel_info);
254  
255 # Need to ensure that $child_deps >= $reqs
256  
257 14 ▶ my @children = @{$child_deps->{$rel_name} || []};
Branch: 1 branch
BranchTrueFalseTotal
$child_deps->{$rel_name} or [] 5 9 14
258 14 ▶ @children = ( ({}) x $reqs->{$name}{$rel_name} ) unless @children;
Branch: 1 branch
BranchTrueFalseTotal
unless @children 5 9 14
259 14 foreach my $child (@children) {
260 19 $child->{$fkcol} = $row->get_column($col);
261 19 $subs{add_child}->($fk_src, $fkcol, $child, $name);
262 }
263 }
264 45 };
265 $subs{fix_columns} = sub {
266 94 ▶ my ($name, $item) = @_;
Subroutine __ANON__: called CC=24 SCAR=32.6
267 94 my $source = $schema->source($name);
268 94 foreach my $col_name ( $source->columns ) {
269 273 my $sim_spec;
270 273 ▶ if ( exists $item->{$col_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $item->{$col_name}) 90 183 273
271 90 ▶ if ((reftype($item->{$col_name}) || '') eq 'REF' &&
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::reftype($item->{$col_name}) || '') eq 'REF' and builtin::reftype(${$$item{$col_name};}) eq 'HASH') { } 2 88 90
Condition80%4/5
(builtin::reftype($item->{$col_name}) || "") eq "REF" and builtin::reftype(${$$item{$col_name};}) eq "HASH"
!ll&&!rl&&r
8802
builtin::reftype($item->{$col_name}) || ''
l!l
288
MC/DC50%1/2
(builtin::reftype($item->{$col_name}) || "") eq "REF" and builtin::reftype(${$$item{$col_name};}) eq "HASH"
builtin::reftype($item->{$col_name}) builtin::reftype(${$$item{$col_name};}) eq "HASH"
Truth table66%2/3
A and B
A= builtin::reftype($item->{$col_name})B= builtin::reftype(${$$item{$col_name};}) eq "HASH"
ABresult
0X0
100
111
272 2 reftype(${$item->{$col_name}}) eq 'HASH' ) {
273 2 $sim_spec = ${ delete $item->{$col_name} };
274 }
275 # Pass the value along to DBIC - we don't know how to deal with it.
276 else {
277 88 next;
278 }
279 }
280  
281 185 my $info = $source->column_info($col_name);
282  
283 185 ▶ $sim_spec ||= $info->{sim};
Condition100%3/3
$sim_spec ||= $info->{"sim"}
l!l&&r!l&&!r
259124
MC/DC100%2/2
$sim_spec ||= $info->{"sim"}
$sim_spec $info->{"sim"}
Truth table100%3/3
A ||= B
A= $sim_specB= $info->{"sim"}
ABresult
1X1
011
000
284 185 ▶ if ( ref($sim_spec || '') eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref($sim_spec || "") eq "HASH") 61 124 185
Condition100%2/2
$sim_spec || ''
l!l
61124
MC/DC100%1/1
$sim_spec || ''
$sim_spec
Truth table100%2/2
A
A= $sim_spec
Aresult
11
00
285 61 ▶ if ( exists $sim_spec->{null_chance} && !$info->{nullable} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $sim_spec->{"null_chance"} and not $info->{"nullable"}) 0 61 61
Condition33%1/3
exists $sim_spec->{"null_chance"} and not $info->{"nullable"}
!ll&&!rl&&r
6100
MC/DC0%0/2
exists $sim_spec->{"null_chance"} and not $info->{"nullable"}
exists $sim_spec->{"null_chance"} not $info->{"nullable"}
Truth table33%1/3
A and not(B)
A= exists $sim_spec->{"null_chance"}B= not $info->{"nullable"}
ABresult
0X0
100
111
286 # Add check for not a number
287 0 ▶ if ( rand() < $sim_spec->{null_chance} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (rand() < $sim_spec->{"null_chance"}) 0 0 0
288 0 $item->{$col_name} = undef;
289 0 next;
290 }
291 }
292  
293 61 ▶ if ( ref($sim_spec->{func} || '') eq 'CODE' ) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref($sim_spec->{'func'} || '') eq 'CODE') { } 30 31 61
elsif (exists $sim_spec->{'value'}) { } 19 12 31
elsif ($sim_spec->{'type'}) { } 3 9 12
Condition100%2/2
$sim_spec->{'func'} || ''
l!l
3031
MC/DC100%1/1
$sim_spec->{'func'} || ''
$sim_spec->{'func'}
Truth table100%2/2
A
A= $sim_spec->{'func'}
Aresult
11
00
294 30 $item->{$col_name} = $sim_spec->{func}->($info);
295 }
296 elsif ( exists $sim_spec->{value} ) {
297 19 $item->{$col_name} = $sim_spec->{value};
298 }
299 elsif ( $sim_spec->{type} ) {
300 3 my $meth = $self->sim_type($sim_spec->{type});
301 3 ▶ if ( $meth ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($meth) { } 3 0 3
302 3 $item->{$col_name} = $meth->($info);
303 }
304 else {
305 0 warn "Type '$sim_spec->{type}' is not loaded";
306 }
307 }
308 else {
309 9 ▶ if ( $info->{data_type} eq 'int' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($info->{'data_type'} eq 'int') { } 4 5 9
elsif ($info->{'data_type'} eq 'varchar') { } 5 0 5
310 4 ▶ my $min = $sim_spec->{min} || 0;
Condition100%2/2
$sim_spec->{'min'} || 0
l!l
22
MC/DC100%1/1
$sim_spec->{'min'} || 0
$sim_spec->{'min'}
Truth table100%2/2
A
A= $sim_spec->{'min'}
Aresult
11
00
311 4 ▶ my $max = $sim_spec->{max} || 100;
Condition100%2/2
$sim_spec->{'max'} || 100
l!l
22
MC/DC100%1/1
$sim_spec->{'max'} || 100
$sim_spec->{'max'}
Truth table100%2/2
A
A= $sim_spec->{'max'}
Aresult
11
00
312 4 $item->{$col_name} = int(rand($max-$min))+$min;
313 }
314 elsif ( $info->{data_type} eq 'varchar' ) {
315 5 ▶ my $min = $sim_spec->{min} || 1;
Condition100%2/2
$sim_spec->{'min'} || 1
l!l
32
MC/DC100%1/1
$sim_spec->{'min'} || 1
$sim_spec->{'min'}
Truth table100%2/2
A
A= $sim_spec->{'min'}
Aresult
11
00
316 5 ▶ my $max = $sim_spec->{max} || $info->{data_length} || 255;
Condition100%5/5
$sim_spec->{'max'} || $info->{'data_length'} || 255
l!l
32
$sim_spec->{"max"} or $info->{"data_length"}
l!l&&r!l&&!r
212
MC/DC100%2/2
$sim_spec->{'max'} || $info->{'data_length'} || 255
$sim_spec->{"max"} $info->{"data_length"}
Truth table100%3/3
A or B
A= $sim_spec->{"max"}B= $info->{"data_length"}
ABresult
1X1
011
000
317 5 $item->{$col_name} = random_regex(
318 '\w' . "{$min,$max}"
319 );
320 }
321 }
322 }
323 }
324 45 };
325 $subs{create_item} = sub {
326 95 ▶ my ($name, $item) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
327  
328 95 my $child_deps = $subs{fix_fk_dependencies}->($name, $item);
329 94 $subs{fix_columns}->($name, $item);
330  
331 94 my $source = $schema->source($name);
332 94 $hooks->{preprocess}->($name, $source, $item);
333  
334 94 ▶ my $row = $subs{find_by_unique_constraints}->($name, $item)
Condition33%1/3
$subs{'find_by_unique_constraints'}->($name, $item) || $schema->resultset($name)->create($item)
l!l&&r!l&&!r
0940
MC/DC0%0/2
$subs{'find_by_unique_constraints'}->($name, $item) || $schema->resultset($name)->create($item)
$subs{'find_by_unique_constraints'}->($name, $item) $schema->resultset($name)->create($item)
Truth table33%1/3
A || B
A= $subs{'find_by_unique_constraints'}->($name, $item)B= $schema->resultset($name)->create($item)
ABresult
1X1
011
000
335 || $schema->resultset($name)->create($item);
336  
337 87 $hooks->{postprocess}->($name, $source, $row);
338  
339 87 $subs{fix_child_dependencies}->($name, $row, $child_deps);
340  
341 87 return $row;
342 45 };
343  
344 # Create a lookup of the items passed in so we can return them back.
345 45 my $initial_spec = {};
346 45 foreach my $name (keys %$spec) {
347 # Allow a number to be passed in
348 55 ▶ if ( (reftype($spec->{$name})||'') ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::reftype($spec->{$name}) || "") ne "ARRAY") 4 51 55
Condition100%2/2
builtin::reftype($spec->{$name}) || ''
l!l
532
MC/DC100%1/1
builtin::reftype($spec->{$name}) || ''
builtin::reftype($spec->{$name})
Truth table100%2/2
A
A= builtin::reftype($spec->{$name})
Aresult
11
00
349 4 ▶ if ( !ref($spec->{$name}) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $spec->{$name}) { } 2 2 4
elsif (builtin::reftype($spec->{$name}) eq 'HASH') { } 1 1 2
350 2 ▶ if ( $spec->{$name} =~ /^\d+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{$name} =~ /^\d+$/) { } 2 0 2
351 2 $spec->{$name} = [ map { {} } 1 .. $spec->{$name} ];
352 }
353 # I don't know what to do with it.
354 else {
355 0 warn "Skipping $name - I don't know what to do!\n";
356 0 delete $spec->{$name};
357 0 next;
358 }
359 }
360 # If they pass a hashref, wrap it in an arrayref.
361 elsif ( reftype($spec->{$name}) eq 'HASH' ) {
362 1 $spec->{$name} = [ $spec->{$name} ];
363 }
364 # I don't know what to do with it.
365 else {
366 1 warn "Skipping $name - I don't know what to do!\n";
367 1 delete $spec->{$name};
368 1 next;
369 }
370 }
371  
372 54 foreach my $item (@{$spec->{$name}}) {
373 68 $initial_spec->{$name}{$item} = 1;
374 }
375 }
376  
377 45 my ($rows, $additional) = ({}, {});
378 45 ▶ if (keys %{$spec}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$spec;}) 44 1 45
379 # Yes, this invokes srand() twice, once in implicitly in rand() and once
380 # again right after. But, that's okay. We don't care what the seed is and
381 # this allows DBIC to be called multiple times in the same process in the
382 # same second without problems.
383 44 ▶ $additional->{seed} = $opts->{seed} ||= rand(time & $$);
Condition66%2/3
$opts->{"seed"} ||= rand(time & $$)
l!l&&r!l&&!r
1430
MC/DC0%0/2
$opts->{"seed"} ||= rand(time & $$)
$opts->{"seed"} rand(time & $$)
Truth table66%2/3
A ||= B
A= $opts->{"seed"}B= rand(time & $$)
ABresult
1X1
011
000
384 44 srand($opts->{seed});
385  
386 $rows = $schema->txn_do(sub {
387 44 ▶ my %rows;
Subroutine __ANON__: called CC=7 SCAR=19.5
388 44 ▶ foreach my $name ( DBIx::Class::TopoSort->toposort($schema, %{$opts->{toposort} || {}}) ) {
Branch: 1 branch
BranchTrueFalseTotal
$opts->{"toposort"} or {} 41 3 44
389 73 ▶ next unless $spec->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $spec->{$name} 12 61 73
390  
391 61 ▶ while ( my $item = shift @{$spec->{$name}} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $item = shift @{$$spec{$name};}) 82 54 136
392 82 my $x = $subs{create_item}->($name, $item);
393 75 ▶ push @{$rows{$name} ||= []}, $x if $initial_spec->{$name}{$item};
Branch: 1 branch
BranchTrueFalseTotal
if $initial_spec->{$name}{$item} 57 18 75
Condition100%2/2
$rows{$name} ||= []
l!l
1245
MC/DC100%1/1
$rows{$name} ||= []
$rows{$name}
Truth table100%2/2
A
A= $rows{$name}
Aresult
11
00
394 }
395 }
396  
397 36 return \%rows;
398 44 });
399 }
400  
401 37 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 1 36 37
402 1 return ($rows, $additional);
403 }
404 else {
405 36 return $rows;
406 }
407 }
408  
409 23 ▶use YAML::Any qw( LoadFile Load );
Subroutine BEGIN: called CC=1 SCAR=0.0
410 sub normalize_input {
411 140 ▶ my ($proto) = @_;
Subroutine normalize_input: called CC=4 SCAR=13.9
Pod undocumented
412  
413 140 ▶ if ( ref($proto) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $proto) 136 4 140
414 136 return $proto;
415 }
416  
417 # Doing a stat on a filename with a newline throws an error.
418 4 my $x = eval {
419 4 ▶ if ( -e $proto ) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $proto) 2 2 4
420 2 return LoadFile($proto);
421 }
422 };
423 4 ▶ return $x if $x;
Branch: 1 branch
BranchTrueFalseTotal
if $x 2 2 4
424  
425 2 return Load($proto);
426 }
427  
428 sub expand_dots {
429 50 ▶ my $struct = shift;
Subroutine expand_dots: called CC=1 SCAR=0.0
Pod undocumented
430  
431 walk sub {
432 388 ▶ if ( ref($_) eq 'HASH' ) {
Subroutine __ANON__: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_ eq "HASH") 132 256 388
433 132 foreach my $k ( keys %$_ ) {
434 129 my $t = $_;
435 129 ▶ while ( $k =~ /([^.]*)\.(.*)/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /([^.]*)\.(.*)/) 9 129 138
436 9 $t->{$1} = { $2 => delete($t->{$k}) };
437 9 $t = $t->{$1}; $k = $2;
438 }
439 }
440 }
441 50 }, $struct;
442  
443 50 return $struct;
444 }
445  
446 23 1;
447 __END__
448  
449 =head1 NAME
450  
451 DBIx::Class::Sims - The addition of simulating data to DBIx::Class
452  
453 =head1 SYNPOSIS (CLASS VERSION)
454  
455 DBIx::Class::Sims->add_sims(
456 $schema, 'source_name',
457 address => { type => 'us_address' },
458 zip_code => { type => 'us_zipcode' },
459 # ...
460 );
461  
462 my $rows = DBIx::Class::Sims->load_sims($schema, {
463 Table1 => [
464 {}, # Take sims or default values for everything
465 { # Override some values, take sim values for others
466 column1 => 20,
467 column2 => 'something',
468 },
469 ],
470 });
471  
472 =head1 SYNOPSIS (COMPONENT VERSION)
473  
474 Within your schema class:
475  
476 __PACKAGE__->load_components('Sims');
477  
478 Within your resultsources, specify the sims generation rules for columns that
479 need specified.
480  
481 __PACKAGE__->add_columns(
482 ...
483 address => {
484 data_type => 'varchar',
485 is_nullable => 1,
486 data_length => 10,
487 sim => { type => 'us_address' },
488 },
489 zipcode => {
490 data_type => 'varchar',
491 is_nullable => 1,
492 data_length => 10,
493 sim => { type => 'us_zipcode' },
494 },
495 column1 => {
496 data_type => 'int',
497 is_nullable => 0,
498 sim => {
499 min => 10,
500 max => 20,
501 },
502 },
503 column2 => {
504 data_type => 'varchar',
505 is_nullable => 1,
506 data_length => 10,
507 default_value => 'foobar',
508 },
509 ...
510 );
511  
512 Later:
513  
514 $schema->deploy({
515 add_drop_table => 1,
516 });
517  
518 my $rows = $schema->load_sims({
519 Table1 => [
520 {}, # Take sims or default values for everything
521 { # Override some values, take sim values for others
522 column1 => 20,
523 column2 => 'something',
524 },
525 ],
526 });
527  
528 =head1 PURPOSE
529  
530 Generating test data for non-simplistic databases is extremely hard, especially
531 as the schema grows and changes. Designing scenarios B<should> be doable by only
532 specifying the minimal elements actually used in the test with the test being
533 resilient to any changes in the schema that don't affect the elements specified.
534 This includes changes like adding a new parent table, new required child tables,
535 and new non-NULL columns to the table being tested.
536  
537 With Sims, you specify only what you care about. Any required parent rows are
538 automatically generated. If a row requires a certain number of child rows (all
539 artists must have one or more albums), that can be set as well. If a column must
540 have specific data in it (a US zipcode or a range of numbers), you can specify
541 that in the table definition.
542  
543 And, in all cases, you can override anything.
544  
545 =head1 DESCRIPTION
546  
547 This is a L<DBIx::Class> component that adds a few methods to your
548 L<DBIx::Class::Schema> object. These methods make it much easier to create data
549 for testing purposes (though, obviously, it's not limited to just test data).
550  
551 Alternately, it can be used as a class method vs. a component, if that fits your
552 needs better.
553  
554 =head1 METHODS
555  
556 =head2 load_sims
557  
558 C<< $rv, $addl? = $schema->load_sims( $spec, ?$opts ) >>
559 C<< $rv, $addl? = DBIx::Class::Sims->load_sims( $schema, $spec, ?$opts ) >>
560  
561 This method will load the rows requested in C<$spec>, plus any additional rows
562 necessary to make those rows work. This includes any parent rows (as defined by
563 C<belongs_to>) and per any constraints defined in C<$opts->{constraints}>. If
564 need-be, you can pass in hooks (as described below) to manipulate the data.
565  
566 load_sims does all of its work within a call to L<DBIx::Class::Schema/txn_do>.
567 If anything goes wrong, load_sims will rethrow the error after the transaction
568 is rolled back.
569  
570 This, of course, assumes that the tables you are working with support
571 transactions. (I'm looking at you, MyISAM!) If they do not, that is on you.
572  
573 =head3 Return value
574  
575 This returns one or two values, depending on if you call load_sims in a scalar
576 or array context.
577  
578 The first value is a hash of arrays of hashes. This will match the C<$spec>,
579 except that where the C<$spec> has a requested set of things to make, the return
580 will have the DBIx::Class::Row objects that were created.
581  
582 Note that you do not get back the objects for anything other than the objects
583 specified at the top level.
584  
585 This second value is a hashref with additional items that may be useful. It may
586 contain:
587  
588 =over 4
589  
590 =item * seed
591  
592 This is the random seed that was used in this run. If you set the seed in the
593 opts parameter in the load_sims call, it will be that value. Otherwise, it will
594 be set to a usefullly random value for you. It will be different every time even
595 if you call load_sims multiple times within the same process in the same second.
596  
597 =back
598  
599 =head2 set_sim_type
600  
601 C<< $class_or_obj->set_sim_type({ $name => $handler, ... }); >>
602  
603 This method will set the handler for the C<$name> sim type. The handler must be
604 a reference to a subroutine. You may pass in as many name/handler pairs as you
605 like.
606  
607 This method may be called as a class or object method.
608  
609 This method returns nothing.
610  
611 C<set_sim_types()> is an alias to this method.
612  
613 =head1 SPECIFICATION
614  
615 The specification can be passed along as a filename that contains YAML or JSON,
616 a string that contains YAML or JSON, or as a hash of arrays of hashes. The
617 structure should look like:
618  
619 {
620 ResultSourceName => [
621 {
622 column => $value,
623 column => $value,
624 relationship => {
625 column => $value,
626 },
627 'relationship.column' => $value,
628 'rel1.rel2.rel3.column' => $value,
629 },
630 ],
631 }
632  
633 If a column is a belongs_to relationship name, then the row associated with that
634 relationship specifier will be used. This is how you would specify a specific
635 parent-child relationship. (Otherwise, a random choice will be made as to which
636 parent to use, creating one as necessary if possible.) The dots will be followed
637 as far as necessary.
638  
639 If a column's value is a reference to a hashref, then that will be treated as a
640 sim entry. Example:
641  
642 {
643 Artist => [
644 {
645 name => \{ type => 'us_name' },
646 },
647 ],
648 }
649  
650 That will use the provided sim type 'us_name'. This will override any sim entry
651 specified on the column. See L</SIM ENTRY> for more information.
652  
653 Columns that have not been specified will be populated in one of two ways. The
654 first is if the database has a default value for it. Otherwise, you can specify
655 the C<sim> key in the column_info for that column. This is a new key that is not
656 used by any other component. See L</SIM ENTRY> for more information.
657  
658 (Please see L<DBIx::Class::ResultSource/add_columns> for details on column_info)
659  
660 B<NOTE>: The keys of the outermost hash are resultsource names. The keys within
661 the row-specific hashes are either columns or relationships. Not resultsources.
662  
663 =head2 Alternatives
664  
665 =head3 Hard-coded number of things
666  
667 If you only want N of a thing, not really caring just what the column values end
668 up being, you can take a shortcut:
669  
670 {
671 ResultSourceName => 3,
672 }
673  
674 That will create 3 of that thing, taking all the defaults and sim'ed options as
675 exist.
676  
677 =head3 Just one thing
678  
679 If you are creating one of a thing and setting some of the values, you can skip
680 the arrayref and pass the hashref directly.
681  
682 {
683 ResultSourceName => {
684 column => $value,
685 column => $value,
686 relationship => {
687 column => $value,
688 },
689 'relationship.column' => $value,
690 'rel1.rel2.rel3.column' => $value,
691 },
692 }
693  
694 And that will work exactly as expected.
695  
696 =head2 Notes
697  
698 =over 4
699  
700 =item * Multiply-specified children
701  
702 Sometimes, you will have a table with more than one parent (q.v. t/t5.t for an
703 example of this). If you specify a row for each parent and, in each parent,
704 specify a child with the same characteristics, only one child will be created.
705 The assumption is that you meant the same row.
706  
707 This does B<not> apply to creating multiple rows with the same characteristics
708 as children of the same table. The assumption is that you meant to do that.
709  
710 =back
711  
712 =head1 OPTS
713  
714 There are several possible options.
715  
716 =head2 constraints
717  
718 The constraints can be passed along as a filename that contains YAML or JSON, a
719 string that contains YAML or JSON, or as a hash of arrays of hashes. The
720 structure should look like:
721  
722 {
723 Person => {
724 addresses => 2,
725 },
726 }
727  
728 All the C<belongs_to> relationships are automatically added to the constraints.
729 You can add additional constraints, as needed. The most common use for this will
730 be to add required child rows. For example, C<< Person->has_many('addresses') >>
731 would normally mean that if you create a Person, no Address rows would be
732 created. But, we could specify a constraint that says "Every person must have
733 at least 2 addresses." Now, whenever a Person is created, two Addresses will be
734 added along as well, if they weren't already created through some other
735 specification.
736  
737 =head2 seed
738  
739 If set, this will be the srand() seed used for this invocation.
740  
741 =head2 toposort
742  
743 This is passed directly to the call to C<< DBIx::Class::TopoSort->toposort >>.
744  
745 =head2 hooks
746  
747 Most people will never need to use this. But, some schema definitions may have
748 reasons that prevent a clean simulating with this module. For example, there may
749 be application-managed sequences. To that end, you may specify the following
750 hooks:
751  
752 =over 4
753  
754 =item * preprocess
755  
756 This receives C<$name, $source, $spec> and expects nothing in return. C<$spec>
757 is the hashref that will be passed to C<<$schema->resultset($name)->create()>>.
758 This hook is expected to modify C<$spec> as needed.
759  
760 =item * postprocess
761  
762 This receives C<$name, $source, $row> and expects nothing in return. This hook
763 is expected to modify the newly-created row object as needed.
764  
765 =back
766  
767 =head1 SIM ENTRY
768  
769 To control how a column's values are simulated, add a "sim" entry in the
770 column_info for that column. The sim entry is a hash that can have the followingkeys:
771  
772 =over 4
773  
774 =item * value
775  
776 This behaves just like default_value would behave, but doesn't require setting a
777 default value on the column.
778  
779 sim => {
780 value => 'The value to always use',
781 },
782  
783 =item * type
784  
785 This labels the column as having a certain type. A type is registered using
786 L</set_sim_type>. The type acts as a name for a function that's used to generate
787 the value. See L</Types> for more information.
788  
789 =item * min / max
790  
791 If the column is numeric, then the min and max bound the random value generated.
792 If the column is a string, then the min and max are the length of the random
793 value generated.
794  
795 =item * func
796  
797 This is a function that is provided the column info. Its return value is used to
798 populate the column.
799  
800 =item * null_chance
801  
802 If the column is nullable I<and> this is set I<and> it is a number between 0 and
803 1, then if C<rand()> is less than that number, the column will be set to null.
804 Otherwise, the standard behaviors will apply.
805  
806 If the column is B<not> nullable, this setting is ignored.
807  
808 =back
809  
810 (Please see L<DBIx::Class::ResultSource/add_columns> for details on column_info)
811  
812 =head2 Types
813  
814 The handler for a sim type will receive the column info (as defined in
815 L<DBIx::Class::ResultSource/add_columns>). From that, the handler returns the
816 value that will be used for this column.
817  
818 Please see L<DBIx::Class::Sims::Types> for the list of included sim types.
819  
820 =head1 TODO
821  
822 =head2 Multi-column types
823  
824 In some applications, columns like "state" and "zipcode" are correlated. Values
825 for one must be legal for the value in the other. The Sims currently has no way
826 of generating correlated columns like this.
827  
828 This is most useful for saying "These 6 columns should be a coherent address".
829  
830 =head2 Allow a column to reference other columns
831  
832 Sometimes, a column should alter its behavior based on other columns. A fullname
833 column may have the firstname and lastname columns concatenated, with other
834 things thrown in. Or, a zipcode column should only generate a zipcode that're
835 legal for the state.
836  
837 =head1 BUGS/SUGGESTIONS
838  
839 This module is hosted on Github at
840 L<https://github.com/robkinyon/dbix-class-sims>. Pull requests are strongly
841 encouraged.
842  
843 =head1 DBIx::Class::Fixtures
844  
845 L<DBIx::Class::Fixtures> is another way to load data into a database. Unlike
846 this module, L<DBIx::Class::Fixtures> approaches the problem by loading the same
847 data every time. This is complementary because some tables (such as lookup
848 tables of countries) want to be seeded with the same data every time. The ideal
849 solution would be to have a set of tables loaded with fixtures and another set
850 of tables loaded with sims.
851  
852 =head1 SEE ALSO
853  
854 L<DBIx::Class>, L<DBIx::Class::Fixtures>
855  
856 =head1 AUTHOR
857  
858 Rob Kinyon <rob.kinyon@gmail.com>
859  
860 =head1 LICENSE
861  
862 Copyright (c) 2013 Rob Kinyon. All Rights Reserved.
863 This is free software, you may use it and distribute it under the same terms
864 as Perl itself.
865  
866 =cut
↑ Summary Sims/Types.pm »