- Added post_ddl and cascade attributes to populate().
[dbsrgits/DBIx-Class-Fixtures.git] / lib / DBIx / Class / Fixtures.pm
1 package DBIx::Class::Fixtures;
2
3 use strict;
4 use warnings;
5
6 use DBIx::Class::Exception;
7 use Class::Accessor::Grouped;
8 use Path::Class qw(dir file);
9 use File::Slurp;
10 use Config::Any::JSON;
11 use Data::Dump::Streamer;
12 use Data::Visitor::Callback;
13 use File::Path;
14 use File::Copy::Recursive qw/dircopy/;
15 use File::Copy qw/move/;
16 use Hash::Merge qw( merge );
17 use Data::Dumper;
18 use Class::C3::Componentised;
19
20 use base qw(Class::Accessor::Grouped);
21
22 our $namespace_counter = 0;
23
24 __PACKAGE__->mk_group_accessors( 'simple' => qw/config_dir _inherited_attributes debug schema_class/);
25
26 =head1 VERSION
27
28 Version 1.000001
29
30 =cut
31
32 our $VERSION = '1.000001';
33
34 =head1 NAME
35
36 DBIx::Class::Fixtures
37
38 =head1 SYNOPSIS
39
40   use DBIx::Class::Fixtures;
41
42   ...
43
44   my $fixtures = DBIx::Class::Fixtures->new({ config_dir => '/home/me/app/fixture_configs' });
45
46   $fixtures->dump({
47     config => 'set_config.json',
48     schema => $source_dbic_schema,
49     directory => '/home/me/app/fixtures'
50   });
51
52   $fixtures->populate({
53     directory => '/home/me/app/fixtures',
54     ddl => '/home/me/app/sql/ddl.sql',
55     connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password'],
56     post_ddl => '/home/me/app/sql/post_ddl.sql',
57   });
58
59 =head1 DESCRIPTION
60
61 Dump fixtures from source database to filesystem then import to another database (with same schema)
62 at any time. Use as a constant dataset for running tests against or for populating development databases
63 when impractical to use production clones. Describe fixture set using relations and conditions based 
64 on your DBIx::Class schema.
65
66 =head1 DEFINE YOUR FIXTURE SET
67
68 Fixture sets are currently defined in .json files which must reside in your config_dir 
69 (e.g. /home/me/app/fixture_configs/a_fixture_set.json). They describe which data to pull and dump 
70 from the source database.
71
72 For example:
73
74     {
75         sets: [{
76             class: 'Artist',
77             ids: ['1', '3']
78         }, {
79             class: 'Producer',
80             ids: ['5'],
81             fetch: [{
82                 rel: 'artists',
83                 quantity: '2'
84             }]
85         }] 
86     }
87
88 This will fetch artists with primary keys 1 and 3, the producer with primary key 5 and two of producer 5's 
89 artists where 'artists' is a has_many DBIx::Class rel from Producer to Artist.
90
91 The top level attributes are as follows:
92
93 =head2 sets
94
95 Sets must be an array of hashes, as in the example given above. Each set defines a set of objects to be
96 included in the fixtures. For details on valid set attributes see L</SET ATTRIBUTES> below.
97
98 =head2 rules
99
100 Rules place general conditions on classes. For example if whenever an artist was dumped you also wanted all
101 of their cds dumped too, then you could use a rule to specify this. For example:
102
103     {
104         sets: [{
105             class: 'Artist',
106             ids: ['1', '3']
107         }, {
108             class: 'Producer',
109             ids: ['5'],
110             fetch: [{ 
111                 rel: 'artists',
112                 quantity: '2'
113             }]
114         }],
115         rules: {
116             Artist: {
117                 fetch: [{
118                     rel: 'cds',
119                     quantity: 'all'
120                 }]
121             }
122         }
123     }
124
125 In this case all the cds of artists 1, 3 and all producer 5's artists will be dumped as well. Note that 'cds' is a
126 has_many DBIx::Class relation from Artist to CD. This is eqivalent to:
127
128     {
129         sets: [{
130             class: 'Artist',
131             ids: ['1', '3'],
132             fetch: [{
133                 rel: 'cds',
134                 quantity: 'all'
135             }]
136         }, {
137             class: 'Producer',
138             ids: ['5'],
139             fetch: [{ 
140                 rel: 'artists',
141                 quantity: '2',
142                 fetch: [{
143                     rel: 'cds',
144                     quantity: 'all'
145                 }]
146             }]
147         }]
148     }
149
150 rules must be a hash keyed by class name.
151
152 L</RULE ATTRIBUTES>
153
154 =head2 includes
155
156 To prevent repetition between configs you can include other configs. For example:
157
158     {
159         sets: [{
160             class: 'Producer',
161             ids: ['5']
162         }],
163         includes: [{
164             file: 'base.json'
165         }]
166     }
167
168 Includes must be an arrayref of hashrefs where the hashrefs have key 'file' which is the name of another config
169 file in the same directory. The original config is merged with its includes using Hash::Merge.
170
171 =head2 datetime_relative
172
173 Only available for MySQL and PostgreSQL at the moment, must be a value that DateTime::Format::*
174 can parse. For example:
175
176     {
177         sets: [{
178             class: 'RecentItems',
179             ids: ['9']
180         }],
181         datetime_relative : "2007-10-30 00:00:00"
182     }
183
184 This will work when dumping from a MySQL database and will cause any datetime fields (where datatype => 'datetime' 
185 in the column def of the schema class) to be dumped as a DateTime::Duration object relative to the date specified in
186 the datetime_relative value. For example if the RecentItem object had a date field set to 2007-10-25, then when the
187 fixture is imported the field will be set to 5 days in the past relative to the current time.
188
189 =head2 might_have
190
191 Specifies whether to automatically dump might_have relationships. Should be a hash with one attribute - fetch. Set fetch to 1 or 0.
192
193     {
194         might_have: [{
195             fetch: 1
196         },
197         sets: [{
198             class: 'Artist',
199             ids: ['1', '3']
200         }, {
201             class: 'Producer',
202             ids: ['5']
203         }]
204     }
205
206 Note: belongs_to rels are automatically dumped whether you like it or not, this is to avoid FKs to nowhere when importing.
207 General rules on has_many rels are not accepted at this top level, but you can turn them on for individual
208 sets - see L</SET ATTRIBUTES>.
209
210 =head1 SET ATTRIBUTES
211
212 =head2 class
213
214 Required attribute. Specifies the DBIx::Class object class you wish to dump.
215
216 =head2 ids
217
218 Array of primary key ids to fetch, basically causing an $rs->find($_) for each. If the id is not in the source db then it
219 just won't get dumped, no warnings or death.
220
221 =head2 quantity
222
223 Must be either an integer or the string 'all'. Specifying an integer will effectively set the 'rows' attribute on the resultset clause,
224 specifying 'all' will cause the rows attribute to be left off and for all matching rows to be dumped. There's no randomising
225 here, it's just the first x rows.
226
227 =head2 cond
228
229 A hash specifying the conditions dumped objects must match. Essentially this is a JSON representation of a DBIx::Class search clause. For example:
230
231     {
232         sets: [{
233             class: 'Artist',
234             quantiy: 'all',
235             cond: { name: 'Dave' }
236         }]
237     }
238
239 This will dump all artists whose name is 'dave'. Essentially $artist_rs->search({ name => 'Dave' })->all.
240
241 Sometimes in a search clause it's useful to use scalar refs to do things like:
242
243 $artist_rs->search({ no1_singles => \'> no1_albums' })
244
245 This could be specified in the cond hash like so:
246
247     {
248         sets: [{
249             class: 'Artist',
250             quantiy: 'all',
251             cond: { no1_singles: '\> no1_albums' }
252         }]
253     }
254
255 So if the value starts with a backslash the value is made a scalar ref before being passed to search.
256
257 =head2 join
258
259 An array of relationships to be used in the cond clause.
260
261     {
262         sets: [{
263             class: 'Artist',
264             quantiy: 'all',
265             cond: { 'cds.position': { '>': 4 } },
266             join: ['cds']
267         }]
268     }
269
270 Fetch all artists who have cds with position greater than 4.
271
272 =head2 fetch
273
274 Must be an array of hashes. Specifies which rels to also dump. For example:
275
276     {
277         sets: [{
278             class: 'Artist',
279             ids: ['1', '3'],
280             fetch: [{
281                 rel: 'cds',
282                 quantity: '3',
283                 cond: { position: '2' }
284             }]
285         }]
286     }
287
288 Will cause the cds of artists 1 and 3 to be dumped where the cd position is 2.
289
290 Valid attributes are: 'rel', 'quantity', 'cond', 'has_many', 'might_have' and 'join'. rel is the name of the DBIx::Class
291 rel to follow, the rest are the same as in the set attributes. quantity is necessary for has_many relationships,
292 but not if using for belongs_to or might_have relationships.
293
294 =head2 has_many
295
296 Specifies whether to fetch has_many rels for this set. Must be a hash containing keys fetch and quantity. 
297
298 Set fetch to 1 if you want to fetch them, and quantity to either 'all' or an integer.
299
300 Be careful here, dumping has_many rels can lead to a lot of data being dumped.
301
302 =head2 might_have
303
304 As with has_many but for might_have relationships. Quantity doesn't do anything in this case.
305
306 This value will be inherited by all fetches in this set. This is not true for the has_many attribute.
307
308 =head1 RULE ATTRIBUTES
309
310 =head2 cond
311
312 Same as with L</SET ATTRIBUTES>
313
314 =head2 fetch
315
316 Same as with L</SET ATTRIBUTES>
317
318 =head2 join
319
320 Same as with L</SET ATTRIBUTES>
321
322 =head2 has_many
323
324 Same as with L</SET ATTRIBUTES>
325
326 =head2 might_have
327
328 Same as with L</SET ATTRIBUTES>
329
330 =head1 METHODS
331
332 =head2 new
333
334 =over 4
335
336 =item Arguments: \%$attrs
337
338 =item Return Value: $fixture_object
339
340 =back
341
342 Returns a new DBIx::Class::Fixture object. %attrs has only two valid keys at the
343 moment - 'debug' which determines whether to be verbose and 'config_dir' which is required and much contain a valid path to
344 the directory in which your .json configs reside.
345
346   my $fixtures = DBIx::Class::Fixtures->new({ config_dir => '/home/me/app/fixture_configs' });
347
348 =cut
349
350 sub new {
351   my $class = shift;
352
353   my ($params) = @_;
354   unless (ref $params eq 'HASH') {
355     return DBIx::Class::Exception->throw('first arg to DBIx::Class::Fixtures->new() must be hash ref');
356   }
357
358   unless ($params->{config_dir}) {
359     return DBIx::Class::Exception->throw('config_dir param not specified');
360   }
361
362   my $config_dir = dir($params->{config_dir});
363   unless (-e $params->{config_dir}) {
364     return DBIx::Class::Exception->throw('config_dir directory doesn\'t exist');
365   }
366
367   my $self = {
368               config_dir => $config_dir,
369               _inherited_attributes => [qw/datetime_relative might_have rules/],
370               debug => $params->{debug}
371   };
372
373   bless $self, $class;
374
375   return $self;
376 }
377
378 =head2 dump
379
380 =over 4
381
382 =item Arguments: \%$attrs
383
384 =item Return Value: 1
385
386 =back
387
388   $fixtures->dump({
389     config => 'set_config.json', # config file to use. must be in the config directory specified in the constructor
390     schema => $source_dbic_schema,
391     directory => '/home/me/app/fixtures' # output directory
392   });
393
394   or
395
396   $fixtures->dump({
397     all => 1, # just dump everything that's in the schema
398     schema => $source_dbic_schema,
399     directory => '/home/me/app/fixtures' # output directory
400   });
401
402 In this case objects will be dumped to subdirectories in the specified directory. For example:
403
404   /home/me/app/fixtures/artist/1.fix
405   /home/me/app/fixtures/artist/3.fix
406   /home/me/app/fixtures/producer/5.fix
407
408 schema and directory are required attributes. also, one of config or all must be specified.
409
410 =cut
411
412 sub dump {
413   my $self = shift;
414
415   my ($params) = @_;
416   unless (ref $params eq 'HASH') {
417     return DBIx::Class::Exception->throw('first arg to dump must be hash ref');
418   }
419
420   foreach my $param (qw/schema directory/) {
421     unless ($params->{$param}) {
422       return DBIx::Class::Exception->throw($param . ' param not specified');
423     }
424   }
425
426   my $schema = $params->{schema};
427   my $config_file;
428   my $config;
429   if ($params->{config}) {
430     #read config
431     $config_file = file($self->config_dir, $params->{config});
432     unless (-e $config_file) {
433       return DBIx::Class::Exception->throw('config does not exist at ' . $config_file);
434     }
435     $config = Config::Any::JSON->load($config_file);
436
437     #process includes
438     if ($config->{includes}) {
439       $self->msg($config->{includes});
440       unless (ref $config->{includes} eq 'ARRAY') {
441         return DBIx::Class::Exception->throw('includes params of config must be an array ref of hashrefs');
442       }
443       foreach my $include_config (@{$config->{includes}}) {
444         unless ((ref $include_config eq 'HASH') && $include_config->{file}) {
445           return DBIx::Class::Exception->throw('includes params of config must be an array ref of hashrefs');
446         }
447         
448         my $include_file = file($self->config_dir, $include_config->{file});
449         unless (-e $include_file) {
450           return DBIx::Class::Exception->throw('config does not exist at ' . $include_file);
451         }
452         my $include = Config::Any::JSON->load($include_file);
453         $self->msg($include);
454         $config = merge( $config, $include );
455       }
456       delete $config->{includes};
457     }
458     
459     # validate config
460     unless ($config && $config->{sets} && ref $config->{sets} eq 'ARRAY' && scalar(@{$config->{sets}})) {
461       return DBIx::Class::Exception->throw('config has no sets');
462     }
463         
464     $config->{might_have} = { fetch => 0 } unless (exists $config->{might_have});
465     $config->{has_many} = { fetch => 0 } unless (exists $config->{has_many});
466     $config->{belongs_to} = { fetch => 1 } unless (exists $config->{belongs_to});
467   } elsif ($params->{all}) {
468     $config = { might_have => { fetch => 0 }, has_many => { fetch => 0 }, belongs_to => { fetch => 0 }, sets => [map {{ class => $_, quantity => 'all' }} $schema->sources] };
469     print Dumper($config);
470   } else {
471     return DBIx::Class::Exception->throw('must pass config or set all');
472   }
473
474   my $output_dir = dir($params->{directory});
475   unless (-e $output_dir) {
476     $output_dir->mkpath ||
477       return DBIx::Class::Exception->throw('output directory does not exist at ' . $output_dir);
478   }
479
480   $self->msg("generating  fixtures");
481   my $tmp_output_dir = dir($output_dir, '-~dump~-' . $<);
482
483   if (-e $tmp_output_dir) {
484     $self->msg("- clearing existing $tmp_output_dir");
485     $tmp_output_dir->rmtree;
486   }
487   $self->msg("- creating $tmp_output_dir");
488   $tmp_output_dir->mkpath;
489
490   # write version file (for the potential benefit of populate)
491   my $version_file = file($tmp_output_dir, '_dumper_version');
492   write_file($version_file->stringify, $VERSION);
493
494   $config->{rules} ||= {};
495   my @sources = sort { $a->{class} cmp $b->{class} } @{delete $config->{sets}};
496   my %options = ( is_root => 1 );
497   foreach my $source (@sources) {
498     # apply rule to set if specified
499     my $rule = $config->{rules}->{$source->{class}};
500     $source = merge( $source, $rule ) if ($rule);
501
502     # fetch objects
503     my $rs = $schema->resultset($source->{class});
504     $rs = $rs->search($source->{cond}, { join => $source->{join} }) if ($source->{cond});
505     $self->msg("- dumping $source->{class}");
506     my @objects;
507     my %source_options = ( set => { %{$config}, %{$source} } );
508     if ($source->{quantity}) {
509       $rs = $rs->search({}, { order_by => $source->{order_by} }) if ($source->{order_by});
510       if ($source->{quantity} eq 'all') {
511         push (@objects, $rs->all);
512       } elsif ($source->{quantity} =~ /^\d+$/) {
513         push (@objects, $rs->search({}, { rows => $source->{quantity} }));
514       } else {
515         DBIx::Class::Exception->throw('invalid value for quantity - ' . $source->{quantity});
516       }
517     }
518     if ($source->{ids}) {
519       my @ids = @{$source->{ids}};
520       my @id_objects = grep { $_ } map { $rs->find($_) } @ids;
521       push (@objects, @id_objects);
522     }
523     unless ($source->{quantity} || $source->{ids}) {
524       DBIx::Class::Exception->throw('must specify either quantity or ids');
525     }
526
527     # dump objects
528     foreach my $object (@objects) {
529       $source_options{set_dir} = $tmp_output_dir;
530       $self->dump_object($object, { %options, %source_options } );
531       next;
532     }
533   }
534
535   foreach my $dir ($output_dir->children) {
536     next if ($dir eq $tmp_output_dir);
537     $dir->remove || $dir->rmtree;
538   }
539
540   $self->msg("- moving temp dir to $output_dir");
541   move($_, dir($output_dir, $_->relative($_->parent)->stringify)) for $tmp_output_dir->children;
542   if (-e $output_dir) {
543     $self->msg("- clearing tmp dir $tmp_output_dir");
544     # delete existing fixture set
545     $tmp_output_dir->remove;
546   }
547
548   $self->msg("done");
549
550   return 1;
551 }
552
553 sub dump_object {
554   my ($self, $object, $params, $rr_info) = @_;  
555   my $set = $params->{set};
556   die 'no dir passed to dump_object' unless $params->{set_dir};
557   die 'no object passed to dump_object' unless $object;
558
559   my @inherited_attrs = @{$self->_inherited_attributes};
560
561   # write dir and gen filename
562   my $source_dir = dir($params->{set_dir}, lc($object->result_source->from));
563   mkdir($source_dir->stringify, 0777);
564   my $file = file($source_dir, join('-', map { $object->get_column($_) } sort $object->primary_columns) . '.fix');
565
566   # write file
567   my $exists = (-e $file->stringify) ? 1 : 0;
568   unless ($exists) {
569     $self->msg('-- dumping ' . $file->stringify, 2);
570     my %ds = $object->get_columns;
571
572     my $formatter= $object->result_source->schema->storage->datetime_parser;
573     # mess with dates if specified
574     if ($set->{datetime_relative}) {
575       unless ($@ || !$formatter) {
576         my $dt;
577         if ($set->{datetime_relative} eq 'today') {
578           $dt = DateTime->today;
579         } else {
580           $dt = $formatter->parse_datetime($set->{datetime_relative}) unless ($@);
581         }
582
583         while (my ($col, $value) = each %ds) {
584           my $col_info = $object->result_source->column_info($col);
585
586           next unless $value
587             && $col_info->{_inflate_info}
588               && uc($col_info->{data_type}) eq 'DATETIME';
589
590           $ds{$col} = $object->get_inflated_column($col)->subtract_datetime($dt);
591         }
592       } else {
593         warn "datetime_relative not supported for this db driver at the moment";
594       }
595     }
596
597     # do the actual dumping
598     my $serialized = Dump(\%ds)->Out();
599     write_file($file->stringify, $serialized);
600     my $mode = 0777; chmod $mode, $file->stringify;  
601   }
602
603   # don't bother looking at rels unless we are actually planning to dump at least one type
604   return unless ($set->{might_have}->{fetch} || $set->{belongs_to}->{fetch} || $set->{has_many}->{fetch} || $set->{fetch});
605
606   # dump rels of object
607   my $s = $object->result_source;
608   unless ($exists) {
609     foreach my $name (sort $s->relationships) {
610       my $info = $s->relationship_info($name);
611       my $r_source = $s->related_source($name);
612       # if belongs_to or might_have with might_have param set or has_many with has_many param set then
613       if (($info->{attrs}{accessor} eq 'single' && (!$info->{attrs}{join_type} || ($set->{might_have} && $set->{might_have}->{fetch}))) || $info->{attrs}{accessor} eq 'filter' || ($info->{attrs}{accessor} eq 'multi' && ($set->{has_many} && $set->{has_many}->{fetch}))) {
614         my $related_rs = $object->related_resultset($name);       
615         my $rule = $set->{rules}->{$related_rs->result_source->source_name};
616         # these parts of the rule only apply to has_many rels
617         if ($rule && $info->{attrs}{accessor} eq 'multi') {               
618           $related_rs = $related_rs->search($rule->{cond}, { join => $rule->{join} }) if ($rule->{cond});
619           $related_rs = $related_rs->search({}, { rows => $rule->{quantity} }) if ($rule->{quantity} && $rule->{quantity} ne 'all');
620           $related_rs = $related_rs->search({}, { order_by => $rule->{order_by} }) if ($rule->{order_by});                
621         }
622         if ($set->{has_many}->{quantity} && $set->{has_many}->{quantity} =~ /^\d+$/) {
623           $related_rs = $related_rs->search({}, { rows => $set->{has_many}->{quantity} });
624         }
625         my %c_params = %{$params};
626         # inherit date param
627         my %mock_set = map { $_ => $set->{$_} } grep { $set->{$_} } @inherited_attrs;
628         $c_params{set} = \%mock_set;
629         #               use Data::Dumper; print ' -- ' . Dumper($c_params{set}, $rule->{fetch}) if ($rule && $rule->{fetch});
630         $c_params{set} = merge( $c_params{set}, $rule) if ($rule && $rule->{fetch});
631         #               use Data::Dumper; print ' -- ' . Dumper(\%c_params) if ($rule && $rule->{fetch});
632         $self->dump_object($_, \%c_params) foreach $related_rs->all;      
633       } 
634     }
635   }
636   
637   return unless $set && $set->{fetch};
638   foreach my $fetch (@{$set->{fetch}}) {
639     # inherit date param
640     $fetch->{$_} = $set->{$_} foreach grep { !$fetch->{$_} && $set->{$_} } @inherited_attrs;
641     my $related_rs = $object->related_resultset($fetch->{rel});
642     my $rule = $set->{rules}->{$related_rs->result_source->source_name};
643     if ($rule) {
644       my $info = $object->result_source->relationship_info($fetch->{rel});
645       if ($info->{attrs}{accessor} eq 'multi') {
646         $fetch = merge( $fetch, $rule );
647       } elsif ($rule->{fetch}) {
648         $fetch = merge( $fetch, { fetch => $rule->{fetch} } );
649       }
650     } 
651     die "relationship " . $fetch->{rel} . " does not exist for " . $s->source_name unless ($related_rs);
652     if ($fetch->{cond} and ref $fetch->{cond} eq 'HASH') {
653       # if value starts with / assume it's meant to be passed as a scalar ref to dbic
654       # ideally this would substitute deeply
655       $fetch->{cond} = { map { $_ => ($fetch->{cond}->{$_} =~ s/^\\//) ? \$fetch->{cond}->{$_} : $fetch->{cond}->{$_} } keys %{$fetch->{cond}} };
656     }
657     $related_rs = $related_rs->search($fetch->{cond}, { join => $fetch->{join} }) if ($fetch->{cond});
658     $related_rs = $related_rs->search({}, { rows => $fetch->{quantity} }) if ($fetch->{quantity} && $fetch->{quantity} ne 'all');
659     $related_rs = $related_rs->search({}, { order_by => $fetch->{order_by} }) if ($fetch->{order_by});
660     $self->dump_object($_, { %{$params}, set => $fetch }) foreach $related_rs->all;
661   }
662 }
663
664 sub _generate_schema {
665   my $self = shift;
666   my $params = shift || {};
667   require DBI;
668   $self->msg("\ncreating schema");
669   #   die 'must pass version param to generate_schema_from_ddl' unless $params->{version};
670
671   my $schema_class = $self->schema_class || "DBIx::Class::Fixtures::Schema";
672   eval "require $schema_class";
673   die $@ if $@;
674
675   my $pre_schema;
676   my $connection_details = $params->{connection_details};
677   $namespace_counter++;
678   my $namespace = "DBIx::Class::Fixtures::GeneratedSchema_" . $namespace_counter;
679   Class::C3::Componentised->inject_base( $namespace => $schema_class );
680   $pre_schema = $namespace->connect(@{$connection_details});
681   unless( $pre_schema ) {
682     return DBIx::Class::Exception->throw('connection details not valid');
683   }
684   my @tables = map { $pre_schema->source($_)->from } $pre_schema->sources;
685   $self->msg("Tables to drop: [". join(', ', sort @tables) . "]");
686   my $dbh = $pre_schema->storage->dbh;
687
688   # clear existing db
689   $self->msg("- clearing DB of existing tables");
690   eval { $dbh->do('SET foreign_key_checks=0') };
691   foreach my $table (@tables) {
692     eval { $dbh->do('drop table ' . $table . ($params->{cascade} ? ' cascade' : '') ) };
693   }
694
695   # import new ddl file to db
696   my $ddl_file = $params->{ddl};
697   $self->msg("- deploying schema using $ddl_file");
698   my $data = _read_sql($ddl_file);
699   foreach (@$data) {
700     eval { $dbh->do($_) or warn "SQL was:\n $_"};
701           if ($@) { die "SQL was:\n $_\n$@"; }
702   }
703   $self->msg("- finished importing DDL into DB");
704
705   # load schema object from our new DB
706   $namespace_counter++;
707   my $namespace2 = "DBIx::Class::Fixtures::GeneratedSchema_" . $namespace_counter;
708   Class::C3::Componentised->inject_base( $namespace2 => $schema_class );
709   my $schema = $namespace2->connect(@{$connection_details});
710   return $schema;
711 }
712
713 sub _read_sql {
714   my $ddl_file = shift;
715   my $fh;
716   open $fh, "<$ddl_file" or die ("Can't open DDL file, $ddl_file ($!)");
717   my @data = split(/\n/, join('', <$fh>));
718   @data = grep(!/^--/, @data);
719   @data = split(/;/, join('', @data));
720   close($fh);
721   @data = grep { $_ && $_ !~ /^-- / } @data;
722   return \@data;
723 }
724
725 =head2 populate
726
727 =over 4
728
729 =item Arguments: \%$attrs
730
731 =item Return Value: 1
732
733 =back
734
735   $fixtures->populate({
736     directory => '/home/me/app/fixtures', # directory to look for fixtures in, as specified to dump
737     ddl => '/home/me/app/sql/ddl.sql', # DDL to deploy
738     connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password'], # database to clear, deploy and then populate
739     post_ddl => '/home/me/app/sql/post_ddl.sql', # DDL to deploy after populating records, ie. FK constraints
740     cascade => 1, # use CASCADE option when dropping tables
741   });
742
743 In this case the database app_dev will be cleared of all tables, then the specified DDL deployed to it,
744 then finally all fixtures found in /home/me/app/fixtures will be added to it. populate will generate
745 its own DBIx::Class schema from the DDL rather than being passed one to use. This is better as
746 custom insert methods are avoided which can to get in the way. In some cases you might not
747 have a DDL, and so this method will eventually allow a $schema object to be passed instead.
748
749 If needed, you can specify a post_ddl attribute which is a DDL to be applied after all the fixtures
750 have been added to the database. A good use of this option would be to add foreign key constraints
751 since databases like Postgresql cannot disable foreign key checks.
752
753 If your tables have foreign key constraints you may want to use the cascade attribute which will
754 make the drop table functionality cascade, ie 'DROP TABLE $table CASCADE'.
755
756 directory, dll and connection_details are all required attributes.
757
758 =cut
759
760 sub populate {
761   my $self = shift;
762   my ($params) = @_;
763   unless (ref $params eq 'HASH') {
764     return DBIx::Class::Exception->throw('first arg to populate must be hash ref');
765   }
766
767   foreach my $param (qw/directory/) {
768     unless ($params->{$param}) {
769       return DBIx::Class::Exception->throw($param . ' param not specified');
770     }
771   }
772   my $fixture_dir = dir(delete $params->{directory});
773   unless (-e $fixture_dir) {
774     return DBIx::Class::Exception->throw('fixture directory does not exist at ' . $fixture_dir);
775   }
776
777   my $ddl_file;
778   my $dbh;  
779   if ($params->{ddl} && $params->{connection_details}) {
780     $ddl_file = file(delete $params->{ddl});
781     unless (-e $ddl_file) {
782       return DBIx::Class::Exception->throw('DDL does not exist at ' . $ddl_file);
783     }
784     unless (ref $params->{connection_details} eq 'ARRAY') {
785       return DBIx::Class::Exception->throw('connection details must be an arrayref');
786     }
787   } elsif ($params->{schema}) {
788     return DBIx::Class::Exception->throw('passing a schema is not supported at the moment');
789   } else {
790     return DBIx::Class::Exception->throw('you must set the ddl and connection_details params');
791   }
792
793   my $schema = $self->_generate_schema({ ddl => $ddl_file, connection_details => delete $params->{connection_details}, %{$params} });
794   $self->msg("\nimporting fixtures");
795   my $tmp_fixture_dir = dir($fixture_dir, "-~populate~-" . $<);
796
797   my $version_file = file($fixture_dir, '_dumper_version');
798   unless (-e $version_file) {
799 #     return DBIx::Class::Exception->throw('no version file found');
800   }
801
802   if (-e $tmp_fixture_dir) {
803     $self->msg("- deleting existing temp directory $tmp_fixture_dir");
804     $tmp_fixture_dir->rmtree;
805   }
806   $self->msg("- creating temp dir");
807   dircopy(dir($fixture_dir, $schema->source($_)->from), dir($tmp_fixture_dir, $schema->source($_)->from)) for grep { -e dir($fixture_dir, $schema->source($_)->from) } $schema->sources;
808
809   eval { $schema->storage->dbh->do('SET foreign_key_checks=0') };
810
811   my $fixup_visitor;
812   my $formatter= $schema->storage->datetime_parser;
813   unless ($@ || !$formatter) {
814     my %callbacks;
815     if ($params->{datetime_relative_to}) {
816       $callbacks{'DateTime::Duration'} = sub {
817         $params->{datetime_relative_to}->clone->add_duration($_);
818       };
819     } else {
820       $callbacks{'DateTime::Duration'} = sub {
821         $formatter->format_datetime(DateTime->today->add_duration($_))
822       };
823     }
824     $callbacks{object} ||= "visit_ref"; 
825     $fixup_visitor = new Data::Visitor::Callback(%callbacks);
826   }
827   foreach my $source (sort $schema->sources) {
828     $self->msg("- adding " . $source);
829     my $rs = $schema->resultset($source);
830     my $source_dir = dir($tmp_fixture_dir, lc($rs->result_source->from));
831     next unless (-e $source_dir);
832     while (my $file = $source_dir->next) {
833       next unless ($file =~ /\.fix$/);
834       next if $file->is_dir;
835       my $contents = $file->slurp;
836       my $HASH1;
837       eval($contents);
838       $HASH1 = $fixup_visitor->visit($HASH1) if $fixup_visitor;
839       $rs->create($HASH1);
840     }
841   }
842
843   if ($params->{post_ddl}) {
844     my $data = _read_sql($params->{post_ddl});
845     foreach (@$data) {
846       eval { $schema->storage->dbh->do($_) or warn "SQL was:\n $_"};
847           if ($@) { die "SQL was:\n $_\n$@"; }
848     }
849     $self->msg("- finished importing post-populate DDL into DB");
850   }
851
852   $self->msg("- fixtures imported");
853   $self->msg("- cleaning up");
854   $tmp_fixture_dir->rmtree;
855   eval { $schema->storage->dbh->do('SET foreign_key_checks=1') };
856
857   return 1;
858 }
859
860 sub msg {
861   my $self = shift;
862   my $subject = shift || return;
863   my $level = shift || 1;
864   return unless $self->debug >= $level;
865   if (ref $subject) {
866         print Dumper($subject);
867   } else {
868         print $subject . "\n";
869   }
870 }
871
872 =head1 AUTHOR
873
874   Luke Saunders <luke@shadowcatsystems.co.uk>
875
876   Initial development sponsored by and (c) Takkle, Inc. 2007
877
878 =head1 CONTRIBUTORS
879
880   Ash Berlin <ash@shadowcatsystems.co.uk>
881   Matt S. Trout <mst@shadowcatsystems.co.uk>
882
883 =head1 LICENSE
884
885   This library is free software under the same license as perl itself
886
887 =cut
888
889 1;