1 package DBIx::Class::Fixtures;
6 use DBIx::Class::Exception;
7 use Class::Accessor::Grouped;
8 use Path::Class qw(dir file);
10 use Config::Any::JSON;
11 use Data::Dump::Streamer;
12 use Data::Visitor::Callback;
14 use File::Copy::Recursive qw/dircopy/;
15 use File::Copy qw/move/;
16 use Hash::Merge qw( merge );
18 use Class::C3::Componentised;
20 use base qw(Class::Accessor::Grouped);
22 our $namespace_counter = 0;
24 __PACKAGE__->mk_group_accessors( 'simple' => qw/config_dir _inherited_attributes debug schema_class/);
32 our $VERSION = '1.000';
40 use DBIx::Class::Fixtures;
44 my $fixtures = DBIx::Class::Fixtures->new({ config_dir => '/home/me/app/fixture_configs' });
47 config => 'set_config.json',
48 schema => $source_dbic_schema,
49 directory => '/home/me/app/fixtures'
53 directory => '/home/me/app/fixtures',
54 ddl => '/home/me/app/sql/ddl.sql',
55 connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password']
60 Dump fixtures from source database to filesystem then import to another database (with same schema)
61 at any time. Use as a constant dataset for running tests against or for populating development databases
62 when impractical to use production clones. Describe fixture set using relations and conditions based
63 on your DBIx::Class schema.
65 =head1 DEFINE YOUR FIXTURE SET
67 Fixture sets are currently defined in .json files which must reside in your config_dir
68 (e.g. /home/me/app/fixture_configs/a_fixture_set.json). They describe which data to pull and dump
69 from the source database.
87 This will fetch artists with primary keys 1 and 3, the producer with primary key 5 and two of producer 5's
88 artists where 'artists' is a has_many DBIx::Class rel from Producer to Artist.
90 The top level attributes are as follows:
94 Sets must be an array of hashes, as in the example given above. Each set defines a set of objects to be
95 included in the fixtures. For details on valid set attributes see L</SET ATTRIBUTES> below.
99 Rules place general conditions on classes. For example if whenever an artist was dumped you also wanted all
100 of their cds dumped too, then you could use a rule to specify this. For example:
124 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
125 has_many DBIx::Class relation from Artist to CD. This is eqivalent to:
149 rules must be a hash keyed by class name.
153 =head2 datetime_relative
155 Only available for MySQL and PostgreSQL at the moment, must be a value that DateTime::Format::*
156 can parse. For example:
160 class: 'RecentItems',
163 datetime_relative : "2007-10-30 00:00:00"
166 This will work when dumping from a MySQL database and will cause any datetime fields (where datatype => 'datetime'
167 in the column def of the schema class) to be dumped as a DateTime::Duration object relative to the date specified in
168 the datetime_relative value. For example if the RecentItem object had a date field set to 2007-10-25, then when the
169 fixture is imported the field will be set to 5 days in the past relative to the current time.
173 Specifies whether to automatically dump might_have relationships. Should be a hash with one attribute - fetch. Set fetch to 1 or 0.
188 Note: belongs_to rels are automatically dumped whether you like it or not, this is to avoid FKs to nowhere when importing.
189 General rules on has_many rels are not accepted at this top level, but you can turn them on for individual
190 sets - see L</SET ATTRIBUTES>.
192 =head1 SET ATTRIBUTES
196 Required attribute. Specifies the DBIx::Class object class you wish to dump.
200 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
201 just won't get dumped, no warnings or death.
205 Must be either an integer or the string 'all'. Specifying an integer will effectively set the 'rows' attribute on the resultset clause,
206 specifying 'all' will cause the rows attribute to be left off and for all matching rows to be dumped. There's no randomising
207 here, it's just the first x rows.
211 A hash specifying the conditions dumped objects must match. Essentially this is a JSON representation of a DBIx::Class search clause. For example:
217 cond: { name: 'Dave' }
221 This will dump all artists whose name is 'dave'. Essentially $artist_rs->search({ name => 'Dave' })->all.
223 Sometimes in a search clause it's useful to use scalar refs to do things like:
225 $artist_rs->search({ no1_singles => \'> no1_albums' })
227 This could be specified in the cond hash like so:
233 cond: { no1_singles: '\> no1_albums' }
237 So if the value starts with a backslash the value is made a scalar ref before being passed to search.
241 An array of relationships to be used in the cond clause.
247 cond: { 'cds.position': { '>': 4 } },
252 Fetch all artists who have cds with position greater than 4.
256 Must be an array of hashes. Specifies which rels to also dump. For example:
265 cond: { position: '2' }
270 Will cause the cds of artists 1 and 3 to be dumped where the cd position is 2.
272 Valid attributes are: 'rel', 'quantity', 'cond', 'has_many', 'might_have' and 'join'. rel is the name of the DBIx::Class
273 rel to follow, the rest are the same as in the set attributes. quantity is necessary for has_many relationships,
274 but not if using for belongs_to or might_have relationships.
278 Specifies whether to fetch has_many rels for this set. Must be a hash containing keys fetch and quantity.
280 Set fetch to 1 if you want to fetch them, and quantity to either 'all' or an integer.
282 Be careful here, dumping has_many rels can lead to a lot of data being dumped.
286 As with has_many but for might_have relationships. Quantity doesn't do anything in this case.
288 This value will be inherited by all fetches in this set. This is not true for the has_many attribute.
290 =head1 RULE ATTRIBUTES
294 Same as with L</SET ATTRIBUTES>
298 Same as with L</SET ATTRIBUTES>
302 Same as with L</SET ATTRIBUTES>
306 Same as with L</SET ATTRIBUTES>
310 Same as with L</SET ATTRIBUTES>
318 =item Arguments: \%$attrs
320 =item Return Value: $fixture_object
324 Returns a new DBIx::Class::Fixture object. %attrs has only two valid keys at the
325 moment - 'debug' which determines whether to be verbose and 'config_dir' which is required and much contain a valid path to
326 the directory in which your .json configs reside.
328 my $fixtures = DBIx::Class::Fixtures->new({ config_dir => '/home/me/app/fixture_configs' });
336 unless (ref $params eq 'HASH') {
337 return DBIx::Class::Exception->throw('first arg to DBIx::Class::Fixtures->new() must be hash ref');
340 unless ($params->{config_dir}) {
341 return DBIx::Class::Exception->throw('config_dir param not specified');
344 my $config_dir = dir($params->{config_dir});
345 unless (-e $params->{config_dir}) {
346 return DBIx::Class::Exception->throw('config_dir directory doesn\'t exist');
350 config_dir => $config_dir,
351 _inherited_attributes => [qw/datetime_relative might_have rules/],
352 debug => $params->{debug}
364 =item Arguments: \%$attrs
366 =item Return Value: 1
371 config => 'set_config.json', # config file to use. must be in the config directory specified in the constructor
372 schema => $source_dbic_schema,
373 directory => '/home/me/app/fixtures' # output directory
376 In this case objects will be dumped to subdirectories in the specified directory. For example:
378 /home/me/app/fixtures/artist/1.fix
379 /home/me/app/fixtures/artist/3.fix
380 /home/me/app/fixtures/producer/5.fix
382 config, schema and directory are all required attributes.
390 unless (ref $params eq 'HASH') {
391 return DBIx::Class::Exception->throw('first arg to dump must be hash ref');
394 foreach my $param (qw/config schema directory/) {
395 unless ($params->{$param}) {
396 return DBIx::Class::Exception->throw($param . ' param not specified');
400 my $config_file = file($self->config_dir, $params->{config});
401 unless (-e $config_file) {
402 return DBIx::Class::Exception->throw('config does not exist at ' . $config_file);
405 my $config = Config::Any::JSON->load($config_file);
406 unless ($config && $config->{sets} && ref $config->{sets} eq 'ARRAY' && scalar(@{$config->{sets}})) {
407 return DBIx::Class::Exception->throw('config has no sets');
410 my $output_dir = dir($params->{directory});
411 unless (-e $output_dir) {
412 return DBIx::Class::Exception->throw('output directory does not exist at ' . $output_dir);
415 my $schema = $params->{schema};
417 $self->msg("generating fixtures");
418 my $tmp_output_dir = dir($output_dir, '-~dump~-');
420 if (-e $tmp_output_dir) {
421 $self->msg("- clearing existing $tmp_output_dir");
422 $tmp_output_dir->rmtree;
424 $self->msg("- creating $tmp_output_dir");
425 $tmp_output_dir->mkpath;
427 # write version file (for the potential benefit of populate)
428 my $version_file = file($tmp_output_dir, '_dumper_version');
429 write_file($version_file->stringify, $VERSION);
431 $config->{rules} ||= {};
432 my @sources = sort { $a->{class} cmp $b->{class} } @{delete $config->{sets}};
433 my %options = ( is_root => 1 );
434 foreach my $source (@sources) {
435 # apply rule to set if specified
436 my $rule = $config->{rules}->{$source->{class}};
437 $source = merge( $source, $rule ) if ($rule);
440 my $rs = $schema->resultset($source->{class});
441 $rs = $rs->search($source->{cond}, { join => $source->{join} }) if ($source->{cond});
442 $self->msg("- dumping $source->{class}");
444 my %source_options = ( set => { %{$config}, %{$source} } );
445 if ($source->{quantity}) {
446 $rs = $rs->search({}, { order_by => $source->{order_by} }) if ($source->{order_by});
447 if ($source->{quantity} eq 'all') {
448 push (@objects, $rs->all);
449 } elsif ($source->{quantity} =~ /^\d+$/) {
450 push (@objects, $rs->search({}, { rows => $source->{quantity} }));
452 DBIx::Class::Exception->throw('invalid value for quantity - ' . $source->{quantity});
455 if ($source->{ids}) {
456 my @ids = @{$source->{ids}};
457 my @id_objects = grep { $_ } map { $rs->find($_) } @ids;
458 push (@objects, @id_objects);
460 unless ($source->{quantity} || $source->{ids}) {
461 DBIx::Class::Exception->throw('must specify either quantity or ids');
465 foreach my $object (@objects) {
466 $source_options{set_dir} = $tmp_output_dir;
467 $self->dump_object($object, { %options, %source_options } );
472 foreach my $dir ($output_dir->children) {
473 next if ($dir eq $tmp_output_dir);
474 $dir->remove || $dir->rmtree;
477 $self->msg("- moving temp dir to $output_dir");
478 move($_, dir($output_dir, $_->relative($_->parent)->stringify)) for $tmp_output_dir->children;
479 if (-e $output_dir) {
480 $self->msg("- clearing tmp dir $tmp_output_dir");
481 # delete existing fixture set
482 $tmp_output_dir->remove;
491 my ($self, $object, $params, $rr_info) = @_;
492 my $set = $params->{set};
493 die 'no dir passed to dump_object' unless $params->{set_dir};
494 die 'no object passed to dump_object' unless $object;
496 my @inherited_attrs = @{$self->_inherited_attributes};
498 # write dir and gen filename
499 my $source_dir = dir($params->{set_dir}, lc($object->result_source->from));
500 mkdir($source_dir->stringify, 0777);
501 my $file = file($source_dir, join('-', map { $object->get_column($_) } sort $object->primary_columns) . '.fix');
504 my $exists = (-e $file->stringify) ? 1 : 0;
506 $self->msg('-- dumping ' . $file->stringify, 2);
507 my %ds = $object->get_columns;
509 my $formatter= $object->result_source->schema->storage->datetime_parser;
510 # mess with dates if specified
511 if ($set->{datetime_relative}) {
512 unless ($@ || !$formatter) {
514 if ($set->{datetime_relative} eq 'today') {
515 $dt = DateTime->today;
517 $dt = $formatter->parse_datetime($set->{datetime_relative}) unless ($@);
520 while (my ($col, $value) = each %ds) {
521 my $col_info = $object->result_source->column_info($col);
524 && $col_info->{_inflate_info}
525 && uc($col_info->{data_type}) eq 'DATETIME';
527 $ds{$col} = $object->get_inflated_column($col)->subtract_datetime($dt);
530 warn "datetime_relative not supported for this db driver at the moment";
534 # do the actual dumping
535 my $serialized = Dump(\%ds)->Out();
536 write_file($file->stringify, $serialized);
537 my $mode = 0777; chmod $mode, $file->stringify;
540 # dump rels of object
541 my $s = $object->result_source;
543 foreach my $name (sort $s->relationships) {
544 my $info = $s->relationship_info($name);
545 my $r_source = $s->related_source($name);
546 # if belongs_to or might_have with might_have param set or has_many with has_many param set then
547 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}))) {
548 my $related_rs = $object->related_resultset($name);
549 my $rule = $set->{rules}->{$related_rs->result_source->source_name};
550 # these parts of the rule only apply to has_many rels
551 if ($rule && $info->{attrs}{accessor} eq 'multi') {
552 $related_rs = $related_rs->search($rule->{cond}, { join => $rule->{join} }) if ($rule->{cond});
553 $related_rs = $related_rs->search({}, { rows => $rule->{quantity} }) if ($rule->{quantity} && $rule->{quantity} ne 'all');
554 $related_rs = $related_rs->search({}, { order_by => $rule->{order_by} }) if ($rule->{order_by});
556 if ($set->{has_many}->{quantity} && $set->{has_many}->{quantity} =~ /^\d+$/) {
557 $related_rs = $related_rs->search({}, { rows => $set->{has_many}->{quantity} });
559 my %c_params = %{$params};
561 my %mock_set = map { $_ => $set->{$_} } grep { $set->{$_} } @inherited_attrs;
562 $c_params{set} = \%mock_set;
563 # use Data::Dumper; print ' -- ' . Dumper($c_params{set}, $rule->{fetch}) if ($rule && $rule->{fetch});
564 $c_params{set} = merge( $c_params{set}, $rule) if ($rule && $rule->{fetch});
565 # use Data::Dumper; print ' -- ' . Dumper(\%c_params) if ($rule && $rule->{fetch});
566 $self->dump_object($_, \%c_params) foreach $related_rs->all;
571 return unless $set && $set->{fetch};
572 foreach my $fetch (@{$set->{fetch}}) {
574 $fetch->{$_} = $set->{$_} foreach grep { !$fetch->{$_} && $set->{$_} } @inherited_attrs;
575 my $related_rs = $object->related_resultset($fetch->{rel});
576 my $rule = $set->{rules}->{$related_rs->result_source->source_name};
578 my $info = $object->result_source->relationship_info($fetch->{rel});
579 if ($info->{attrs}{accessor} eq 'multi') {
580 $fetch = merge( $fetch, $rule );
581 } elsif ($rule->{fetch}) {
582 $fetch = merge( $fetch, { fetch => $rule->{fetch} } );
585 die "relationship " . $fetch->{rel} . " does not exist for " . $s->source_name unless ($related_rs);
586 if ($fetch->{cond} and ref $fetch->{cond} eq 'HASH') {
587 # if value starts with / assume it's meant to be passed as a scalar ref to dbic
588 # ideally this would substitute deeply
589 $fetch->{cond} = { map { $_ => ($fetch->{cond}->{$_} =~ s/^\\//) ? \$fetch->{cond}->{$_} : $fetch->{cond}->{$_} } keys %{$fetch->{cond}} };
591 $related_rs = $related_rs->search($fetch->{cond}, { join => $fetch->{join} }) if ($fetch->{cond});
592 $related_rs = $related_rs->search({}, { rows => $fetch->{quantity} }) if ($fetch->{quantity} && $fetch->{quantity} ne 'all');
593 $related_rs = $related_rs->search({}, { order_by => $fetch->{order_by} }) if ($fetch->{order_by});
594 $self->dump_object($_, { %{$params}, set => $fetch }) foreach $related_rs->all;
598 sub _generate_schema {
600 my $params = shift || {};
602 $self->msg("\ncreating schema");
603 # die 'must pass version param to generate_schema_from_ddl' unless $params->{version};
605 my $schema_class = $self->schema_class || "DBIx::Class::Fixtures::Schema";
606 eval "require $schema_class";
610 my $connection_details = $params->{connection_details};
611 $namespace_counter++;
612 my $namespace = "DBIx::Class::Fixtures::GeneratedSchema_" . $namespace_counter;
613 Class::C3::Componentised->inject_base( $namespace => $schema_class );
614 $pre_schema = $namespace->connect(@{$connection_details});
615 unless( $pre_schema ) {
616 return DBIx::Class::Exception->throw('connection details not valid');
618 my @tables = map { $pre_schema->source($_)->from } $pre_schema->sources;
619 my $dbh = $pre_schema->storage->dbh;
622 $self->msg("- clearing DB of existing tables");
623 eval { $dbh->do('SET foreign_key_checks=0') };
624 $dbh->do('drop table ' . $_) for (@tables);
626 # import new ddl file to db
627 my $ddl_file = $params->{ddl};
628 $self->msg("- deploying schema using $ddl_file");
630 open $fh, "<$ddl_file" or die ("Can't open DDL file, $ddl_file ($!)");
631 my @data = split(/\n/, join('', <$fh>));
632 @data = grep(!/^--/, @data);
633 @data = split(/;/, join('', @data));
635 @data = grep { $_ && $_ !~ /^-- / } @data;
637 eval { $dbh->do($_) or warn "SQL was:\n $_"};
638 if ($@) { die "SQL was:\n $_\n$@"; }
640 $self->msg("- finished importing DDL into DB");
642 # load schema object from our new DB
643 $self->msg("- loading fresh DBIC object from DB");
644 my $schema = $namespace->connect(@{$connection_details});
653 =item Arguments: \%$attrs
655 =item Return Value: 1
659 $fixtures->populate({
660 directory => '/home/me/app/fixtures', # directory to look for fixtures in, as specified to dump
661 ddl => '/home/me/app/sql/ddl.sql', # DDL to deploy
662 connection_details => ['dbi:mysql:dbname=app_dev', 'me', 'password'] # database to clear, deploy and then populate
665 In this case the database app_dev will be cleared of all tables, then the specified DDL deployed to it,
666 then finally all fixtures found in /home/me/app/fixtures will be added to it. populate will generate
667 its own DBIx::Class schema from the DDL rather than being passed one to use. This is better as
668 custom insert methods are avoided which can to get in the way. In some cases you might not
669 have a DDL, and so this method will eventually allow a $schema object to be passed instead.
671 directory, dll and connection_details are all required attributes.
678 unless (ref $params eq 'HASH') {
679 return DBIx::Class::Exception->throw('first arg to populate must be hash ref');
682 foreach my $param (qw/directory/) {
683 unless ($params->{$param}) {
684 return DBIx::Class::Exception->throw($param . ' param not specified');
687 my $fixture_dir = dir(delete $params->{directory});
688 unless (-e $fixture_dir) {
689 return DBIx::Class::Exception->throw('fixture directory does not exist at ' . $fixture_dir);
694 if ($params->{ddl} && $params->{connection_details}) {
695 $ddl_file = file(delete $params->{ddl});
696 unless (-e $ddl_file) {
697 return DBIx::Class::Exception->throw('DDL does not exist at ' . $ddl_file);
699 unless (ref $params->{connection_details} eq 'ARRAY') {
700 return DBIx::Class::Exception->throw('connection details must be an arrayref');
702 } elsif ($params->{schema}) {
703 return DBIx::Class::Exception->throw('passing a schema is not supported at the moment');
705 return DBIx::Class::Exception->throw('you must set the ddl and connection_details params');
708 my $schema = $self->_generate_schema({ ddl => $ddl_file, connection_details => delete $params->{connection_details}, %{$params} });
709 $self->msg("\nimporting fixtures");
710 my $tmp_fixture_dir = dir($fixture_dir, "-~populate~-" . $<);
712 my $version_file = file($fixture_dir, '_dumper_version');
713 unless (-e $version_file) {
714 # return DBIx::Class::Exception->throw('no version file found');
717 if (-e $tmp_fixture_dir) {
718 $self->msg("- deleting existing temp directory $tmp_fixture_dir");
719 $tmp_fixture_dir->rmtree;
721 $self->msg("- creating temp dir");
722 dircopy(dir($fixture_dir, $schema->source($_)->from), dir($tmp_fixture_dir, $schema->source($_)->from)) for $schema->sources;
724 eval { $schema->storage->dbh->do('SET foreign_key_checks=0') };
727 my $formatter= $schema->storage->datetime_parser;
728 unless ($@ || !$formatter) {
730 if ($params->{datetime_relative_to}) {
731 $callbacks{'DateTime::Duration'} = sub {
732 $params->{datetime_relative_to}->clone->add_duration($_);
735 $callbacks{'DateTime::Duration'} = sub {
736 $formatter->format_datetime(DateTime->today->add_duration($_))
739 $callbacks{object} ||= "visit_ref";
740 $fixup_visitor = new Data::Visitor::Callback(%callbacks);
742 foreach my $source (sort $schema->sources) {
743 $self->msg("- adding " . $source);
744 my $rs = $schema->resultset($source);
745 my $source_dir = dir($tmp_fixture_dir, lc($rs->result_source->from));
746 next unless (-e $source_dir);
747 while (my $file = $source_dir->next) {
748 next unless ($file =~ /\.fix$/);
749 next if $file->is_dir;
750 my $contents = $file->slurp;
753 $HASH1 = $fixup_visitor->visit($HASH1) if $fixup_visitor;
758 $self->msg("- fixtures imported");
759 $self->msg("- cleaning up");
760 $tmp_fixture_dir->rmtree;
761 eval { $schema->storage->dbh->do('SET foreign_key_checks=1') };
768 my $subject = shift || return;
769 my $level = shift || 1;
771 return unless $self->debug >= $level;
773 print Dumper($subject);
775 print $subject . "\n";
781 Luke Saunders <luke@shadowcatsystems.co.uk>
785 Ash Berlin <ash@shadowcatsystems.co.uk>
786 Matt S. Trout <mst@shadowcatsystems.co.uk>