Sims.pm

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