1 package DBIx::Class::DeploymentHandler::DeployMethod::SQL::Translator;
4 # ABSTRACT: Manage your SQL and Perl migrations in nicely laid out directories
7 use Carp qw( carp croak );
8 use DBIx::Class::DeploymentHandler::Logger;
9 use Log::Contextual qw(:log :dlog), -package_logger =>
10 DBIx::Class::DeploymentHandler::Logger->new({
11 env_prefix => 'DBICDH'
14 use Method::Signatures::Simple;
18 require SQL::Translator::Diff;
20 require DBIx::Class::Storage; # loaded for type constraint
21 use DBIx::Class::DeploymentHandler::Types;
23 use File::Path 'mkpath';
24 use File::Spec::Functions;
26 with 'DBIx::Class::DeploymentHandler::HandlesDeploy';
35 isa => 'DBIx::Class::Schema',
41 isa => 'DBIx::Class::Storage',
46 method _build_storage {
47 my $s = $self->schema->storage;
48 $s->_determine_driver;
52 has sql_translator_args => (
55 default => sub { {} },
57 has script_directory => (
66 isa => 'DBIx::Class::DeploymentHandler::Databases',
68 default => sub { [qw( MySQL SQLite PostgreSQL )] },
77 has schema_version => (
83 # this will probably never get called as the DBICDH
84 # will be passing down a schema_version normally, which
85 # is built the same way, but we leave this in place
86 method _build_schema_version { $self->schema->schema_version }
88 method __ddl_consume_with_prefix($type, $versions, $prefix) {
89 my $base_dir = $self->script_directory;
91 my $main = catfile( $base_dir, $type );
93 catfile( $base_dir, '_common', $prefix, join q(-), @{$versions} );
97 $dir = catfile($main, $prefix, join q(-), @{$versions})
99 if ($self->ignore_ddl) {
102 croak "$main does not exist; please write/generate some SQL"
108 opendir my($dh), $dir;
110 map { $_ => "$dir/$_" }
111 grep { /\.(?:sql|pl|sql-\w+)$/ && -f "$dir/$_" }
115 die $_ unless $self->ignore_ddl;
118 opendir my($dh), $common;
119 for my $filename (grep { /\.(?:sql|pl)$/ && -f catfile($common,$_) } readdir $dh) {
120 unless ($files{$filename}) {
121 $files{$filename} = catfile($common,$filename);
127 return [@files{sort keys %files}]
130 method _ddl_initialize_consume_filenames($type, $version) {
131 $self->__ddl_consume_with_prefix($type, [ $version ], 'initialize')
134 method _ddl_schema_consume_filenames($type, $version) {
135 $self->__ddl_consume_with_prefix($type, [ $version ], 'deploy')
138 method _ddl_protoschema_upgrade_consume_filenames($versions) {
139 my $base_dir = $self->script_directory;
141 my $dir = catfile( $base_dir, '_preprocess_schema', 'upgrade', join q(-), @{$versions});
143 return [] unless -d $dir;
145 opendir my($dh), $dir;
146 my %files = map { $_ => "$dir/$_" } grep { /\.pl$/ && -f "$dir/$_" } readdir $dh;
149 return [@files{sort keys %files}]
152 method _ddl_protoschema_downgrade_consume_filenames($versions) {
153 my $base_dir = $self->script_directory;
155 my $dir = catfile( $base_dir, '_preprocess_schema', 'downgrade', join q(-), @{$versions});
157 return [] unless -d $dir;
159 opendir my($dh), $dir;
160 my %files = map { $_ => "$dir/$_" } grep { /\.pl$/ && -f "$dir/$_" } readdir $dh;
163 return [@files{sort keys %files}]
166 method _ddl_protoschema_produce_filename($version) {
167 my $dirname = catfile( $self->script_directory, '_source', 'deploy', $version );
168 mkpath($dirname) unless -d $dirname;
170 return catfile( $dirname, '001-auto.yml' );
173 method _ddl_schema_produce_filename($type, $version) {
174 my $dirname = catfile( $self->script_directory, $type, 'deploy', $version );
175 mkpath($dirname) unless -d $dirname;
177 return catfile( $dirname, '001-auto.sql' );
180 method _ddl_schema_upgrade_consume_filenames($type, $versions) {
181 $self->__ddl_consume_with_prefix($type, $versions, 'upgrade')
184 method _ddl_schema_downgrade_consume_filenames($type, $versions) {
185 $self->__ddl_consume_with_prefix($type, $versions, 'downgrade')
188 method _ddl_schema_upgrade_produce_filename($type, $versions) {
189 my $dir = $self->script_directory;
191 my $dirname = catfile( $dir, $type, 'upgrade', join q(-), @{$versions});
192 mkpath($dirname) unless -d $dirname;
194 return catfile( $dirname, '001-auto.sql' );
197 method _ddl_schema_downgrade_produce_filename($type, $versions, $dir) {
198 my $dirname = catfile( $dir, $type, 'downgrade', join q(-), @{$versions} );
199 mkpath($dirname) unless -d $dirname;
201 return catfile( $dirname, '001-auto.sql');
204 method _run_sql_array($sql) {
205 my $storage = $self->storage;
208 $_ && # remove blank lines
209 !/^(BEGIN|BEGIN TRANSACTION|COMMIT)/ # strip txn's
211 s/^\s+//; s/\s+$//; # trim whitespace
212 join '', grep { !/^--/ } split /\n/ # remove comments
215 Dlog_trace { "Running SQL $_" } $sql;
216 foreach my $line (@{$sql}) {
217 $storage->_query_start($line);
218 # the whole reason we do this is so that we can see the line that was run
220 $storage->dbh_do (sub { $_[1]->do($line) });
223 die "$_ (running line '$line')"
225 $storage->_query_end($line);
227 return join "\n", @$sql
230 method _run_sql($filename) {
231 log_debug { "Running SQL from $filename" };
232 return $self->_run_sql_array($self->_read_sql_file($filename));
235 method _run_perl($filename) {
236 log_debug { "Running Perl from $filename" };
237 my $filedata = do { local( @ARGV, $/ ) = $filename; <> };
239 no warnings 'redefine';
240 my $fn = eval "$filedata";
242 Dlog_trace { "Running Perl $_" } $fn;
245 carp "$filename failed to compile: $@";
246 } elsif (ref $fn eq 'CODE') {
249 carp "$filename should define an anonymouse sub that takes a schema but it didn't!";
253 method _run_sql_and_perl($filenames, $sql_to_run) {
254 my @files = @{$filenames};
255 my $guard = $self->schema->txn_scope_guard if $self->txn_wrap;
257 $self->_run_sql_array($sql_to_run) if $self->ignore_ddl;
259 my $sql = ($sql_to_run)?join ";\n", @$sql_to_run:'';
261 for my $filename (@files) {
262 if ($self->ignore_ddl && $filename =~ /^[^_]*-auto.*\.sql$/) {
264 } elsif ($filename =~ /\.sql$/) {
265 $sql .= $self->_run_sql($filename)
266 } elsif ( $filename =~ /\.pl$/ ) {
267 $self->_run_perl($filename)
269 croak "A file ($filename) got to deploy that wasn't sql or perl!";
273 $guard->commit if $self->txn_wrap;
280 my $version = (shift @_ || {})->{version} || $self->schema_version;
281 log_info { "deploying version $version" };
282 my $sqlt_type = $self->storage->sqlt_type;
284 if ($self->ignore_ddl) {
285 $sql = $self->_sql_from_yaml({},
286 '_ddl_protoschema_produce_filename', $sqlt_type
289 return $self->_run_sql_and_perl($self->_ddl_schema_consume_filenames(
298 my $version = $args->{version} || $self->schema_version;
299 log_info { "initializing version $version" };
300 my $storage_type = $args->{storage_type} || $self->storage->sqlt_type;
302 my @files = @{$self->_ddl_initialize_consume_filenames(
307 for my $filename (@files) {
308 # We ignore sql for now (till I figure out what to do with it)
309 if ( $filename =~ /^(.+)\.pl$/ ) {
310 my $filedata = do { local( @ARGV, $/ ) = $filename; <> };
312 no warnings 'redefine';
313 my $fn = eval "$filedata";
317 carp "$filename failed to compile: $@";
318 } elsif (ref $fn eq 'CODE') {
321 carp "$filename should define an anonymous sub but it didn't!";
324 croak "A file ($filename) got to initialize_scripts that wasn't sql or perl!";
329 method _sqldiff_from_yaml($from_version, $to_version, $db, $direction) {
330 my $dir = $self->script_directory;
333 ignore_constraint_names => 1,
334 ignore_index_names => 1,
335 %{$self->sql_translator_args}
340 my $prefilename = $self->_ddl_protoschema_produce_filename($from_version, $dir);
342 # should probably be a croak
343 carp("No previous schema file found ($prefilename)")
344 unless -e $prefilename;
346 my $t = SQL::Translator->new({
350 parser => 'SQL::Translator::Parser::YAML',
353 my $out = $t->translate( $prefilename )
356 $source_schema = $t->schema;
358 $source_schema->name( $prefilename )
359 unless $source_schema->name;
364 my $filename = $self->_ddl_protoschema_produce_filename($to_version, $dir);
366 # should probably be a croak
367 carp("No next schema file found ($filename)")
370 my $t = SQL::Translator->new({
374 parser => 'SQL::Translator::Parser::YAML',
377 my $out = $t->translate( $filename )
380 $dest_schema = $t->schema;
382 $dest_schema->name( $filename )
383 unless $dest_schema->name;
386 my $transform_files_method = "_ddl_protoschema_${direction}_consume_filenames";
387 my $transforms = $self->_coderefs_per_files(
388 $self->$transform_files_method([$from_version, $to_version])
390 $_->($source_schema, $dest_schema) for @$transforms;
392 return [SQL::Translator::Diff::schema_diff(
399 method _sql_from_yaml($sqltargs, $from_file, $db) {
400 my $schema = $self->schema;
401 my $version = $self->schema_version;
403 my $sqlt = SQL::Translator->new({
405 parser => 'SQL::Translator::Parser::YAML',
410 my $yaml_filename = $self->$from_file($version);
412 my @sql = $sqlt->translate($yaml_filename);
414 carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
420 sub _prepare_install {
422 my $sqltargs = { %{$self->sql_translator_args}, %{shift @_} };
423 my $from_file = shift;
425 my $dir = $self->script_directory;
426 my $databases = $self->databases;
427 my $version = $self->schema_version;
429 foreach my $db (@$databases) {
430 my $sql = $self->_sql_from_yaml($sqltargs, $from_file, $db ) or next;
432 my $filename = $self->$to_file($db, $version, $dir);
434 carp "Overwriting existing DDL file - $filename";
437 open my $file, q(>), $filename;
438 print {$file} join ";\n", @$sql;
443 sub _resultsource_install_filename {
444 my ($self, $source_name) = @_;
446 my ($self, $type, $version) = @_;
447 my $dirname = catfile( $self->script_directory, $type, 'deploy', $version );
448 mkpath($dirname) unless -d $dirname;
450 return catfile( $dirname, "001-auto-$source_name.sql" );
454 sub _resultsource_protoschema_filename {
455 my ($self, $source_name) = @_;
457 my ($self, $version) = @_;
458 my $dirname = catfile( $self->script_directory, '_source', 'deploy', $version );
459 mkpath($dirname) unless -d $dirname;
461 return catfile( $dirname, "001-auto-$source_name.yml" );
465 sub install_resultsource {
466 my ($self, $args) = @_;
467 my $source = $args->{result_source};
468 my $version = $args->{version};
469 log_info { 'installing_resultsource ' . $source->source_name . ", version $version" };
470 my $rs_install_file =
471 $self->_resultsource_install_filename($source->source_name);
474 $self->$rs_install_file(
475 $self->storage->sqlt_type,
479 $self->_run_sql_and_perl($files);
482 sub prepare_resultsource_install {
484 my $source = (shift @_)->{result_source};
485 log_info { 'preparing install for resultsource ' . $source->source_name };
487 my $install_filename = $self->_resultsource_install_filename($source->source_name);
488 my $proto_filename = $self->_resultsource_protoschema_filename($source->source_name);
489 $self->prepare_protoschema({
490 parser_args => { sources => [$source->source_name], }
492 $self->_prepare_install({}, $proto_filename, $install_filename);
496 log_info { 'preparing deploy' };
498 $self->prepare_protoschema({
499 # Exclude __VERSION so that it gets installed separately
500 parser_args => { sources => [grep { $_ ne '__VERSION' } $self->schema->sources], }
501 }, '_ddl_protoschema_produce_filename');
502 $self->_prepare_install({}, '_ddl_protoschema_produce_filename', '_ddl_schema_produce_filename');
505 sub prepare_upgrade {
506 my ($self, $args) = @_;
508 "preparing upgrade from $args->{from_version} to $args->{to_version}"
510 $self->_prepare_changegrade(
511 $args->{from_version}, $args->{to_version}, $args->{version_set}, 'upgrade'
515 sub prepare_downgrade {
516 my ($self, $args) = @_;
518 "preparing downgrade from $args->{from_version} to $args->{to_version}"
520 $self->_prepare_changegrade(
521 $args->{from_version}, $args->{to_version}, $args->{version_set}, 'downgrade'
525 method _coderefs_per_files($files) {
526 no warnings 'redefine';
527 [map eval do { local( @ARGV, $/ ) = $_; <> }, @$files]
530 method _prepare_changegrade($from_version, $to_version, $version_set, $direction) {
531 my $schema = $self->schema;
532 my $databases = $self->databases;
533 my $dir = $self->script_directory;
535 my $schema_version = $self->schema_version;
536 my $diff_file_method = "_ddl_schema_${direction}_produce_filename";
537 foreach my $db (@$databases) {
538 my $diff_file = $self->$diff_file_method($db, $version_set, $dir );
540 carp("Overwriting existing $direction-diff file - $diff_file");
544 open my $file, q(>), $diff_file;
545 print {$file} join ";\n", @{$self->_sqldiff_from_yaml($from_version, $to_version, $db, $direction)};
550 method _read_sql_file($file) {
553 open my $fh, '<', $file;
554 my @data = split /;\n/, join '', <$fh>;
558 $_ && # remove blank lines
559 !/^(BEGIN|BEGIN TRANSACTION|COMMIT)/ # strip txn's
561 s/^\s+//; s/\s+$//; # trim whitespace
562 join '', grep { !/^--/ } split /\n/ # remove comments
568 sub downgrade_single_step {
570 my $version_set = (shift @_)->{version_set};
571 Dlog_info { "downgrade_single_step'ing $_" } $version_set;
573 my $sqlt_type = $self->storage->sqlt_type;
575 if ($self->ignore_ddl) {
576 $sql_to_run = $self->_sqldiff_from_yaml(
577 $version_set->[0], $version_set->[1], $sqlt_type, 'downgrade',
580 my $sql = $self->_run_sql_and_perl($self->_ddl_schema_downgrade_consume_filenames(
588 sub upgrade_single_step {
590 my $version_set = (shift @_)->{version_set};
591 Dlog_info { "upgrade_single_step'ing $_" } $version_set;
593 my $sqlt_type = $self->storage->sqlt_type;
595 if ($self->ignore_ddl) {
596 $sql_to_run = $self->_sqldiff_from_yaml(
597 $version_set->[0], $version_set->[1], $sqlt_type, 'upgrade',
600 my $sql = $self->_run_sql_and_perl($self->_ddl_schema_upgrade_consume_filenames(
607 sub prepare_protoschema {
609 my $sqltargs = { %{$self->sql_translator_args}, %{shift @_} };
612 = $self->$to_file($self->schema_version);
614 # we do this because the code that uses this sets parser args,
615 # so we just need to merge in the package
616 $sqltargs->{parser_args}{package} = $self->schema;
617 my $sqlt = SQL::Translator->new({
618 parser => 'SQL::Translator::Parser::DBIx::Class',
619 producer => 'SQL::Translator::Producer::YAML',
623 my $yml = $sqlt->translate;
625 croak("Failed to translate to YAML: " . $sqlt->error)
629 carp "Overwriting existing DDL-YML file - $filename";
633 open my $file, q(>), $filename;
638 __PACKAGE__->meta->make_immutable;
642 # vim: ts=2 sw=2 expandtab
648 This class is the meat of L<DBIx::Class::DeploymentHandler>. It takes care
649 of generating serialized schemata as well as sql files to move from one
650 version of a schema to the rest. One of the hallmark features of this class
651 is that it allows for multiple sql files for deploy and upgrade, allowing
652 developers to fine tune deployment. In addition it also allows for perl
653 files to be run at any stage of the process.
655 For basic usage see L<DBIx::Class::DeploymentHandler::HandlesDeploy>. What's
656 documented here is extra fun stuff or private methods.
658 =head1 DIRECTORY LAYOUT
660 Arguably this is the best feature of L<DBIx::Class::DeploymentHandler>.
661 It's spiritually based upon L<DBIx::Migration::Directories>, but has a
662 lot of extensions and modifications, so even if you are familiar with it,
663 please read this. I feel like the best way to describe the layout is with
664 the following example:
690 | | `- 002-remove-customers.pl
693 | `- 002-generate-customers.pl
700 | |- 001-create_database.pl
701 | `- 002-create_users_and_permissions.pl
709 So basically, the code
713 on an C<SQLite> database that would simply run
714 C<$sql_migration_dir/SQLite/deploy/1/001-auto.sql>. Next,
716 $dm->upgrade_single_step([1,2])
718 would run C<$sql_migration_dir/SQLite/upgrade/1-2/001-auto.sql> followed by
719 C<$sql_migration_dir/_common/upgrade/1-2/002-generate-customers.pl>.
721 C<.pl> files don't have to be in the C<_common> directory, but most of the time
722 they should be, because perl scripts are generally database independent.
724 Note that unlike most steps in the process, C<initialize> will not run SQL, as
725 there may not even be an database at initialize time. It will run perl scripts
726 just like the other steps in the process, but nothing is passed to them.
727 Until people have used this more it will remain freeform, but a recommended use
728 of initialize is to have it prompt for username and password, and then call the
729 appropriate C<< CREATE DATABASE >> commands etc.
731 =head2 Directory Specification
733 The following subdirectories are recognized by this DeployMethod:
737 =item C<_source> This directory can contain the following directories:
741 =item C<deploy> This directory merely contains directories named after schema
742 versions, which in turn contain C<yaml> files that are serialized versions
743 of the schema at that version. These files are not for editing by hand.
747 =item C<_preprocess_schema> This directory can contain the following
752 =item C<downgrade> This directory merely contains directories named after
753 migrations, which are of the form C<$from_version-$to_version>. Inside of
754 these directories you may put Perl scripts which are to return a subref
755 that takes the arguments C<< $from_schema, $to_schema >>, which are
756 L<SQL::Translator::Schema> objects.
758 =item C<upgrade> This directory merely contains directories named after
759 migrations, which are of the form C<$from_version-$to_version>. Inside of
760 these directories you may put Perl scripts which are to return a subref
761 that takes the arguments C<< $from_schema, $to_schema >>, which are
762 L<SQL::Translator::Schema> objects.
766 =item C<$storage_type> This is a set of scripts that gets run depending on what
767 your storage type is. If you are not sure what your storage type is, take a
768 look at the producers listed for L<SQL::Translator>. Also note, C<_common>
769 is a special case. C<_common> will get merged into whatever other files you
770 already have. This directory can containt the following directories itself:
774 =item C<initialize> Gets run before the C<deploy> is C<deploy>ed. Has the
775 same structure as the C<deploy> subdirectory as well; that is, it has a
776 directory for each schema version. Unlike C<deploy>, C<upgrade>, and C<downgrade>
777 though, it can only run C<.pl> files, and the coderef in the perl files get
778 no arguments passed to them.
780 =item C<deploy> Gets run when the schema is C<deploy>ed. Structure is a
781 directory per schema version, and then files are merged with C<_common> and run
782 in filename order. C<.sql> files are merely run, as expected. C<.pl> files are
783 run according to L</PERL SCRIPTS>.
785 =item C<upgrade> Gets run when the schema is C<upgrade>d. Structure is a directory
786 per upgrade step, (for example, C<1-2> for upgrading from version 1 to version
787 2,) and then files are merged with C<_common> and run in filename order.
788 C<.sql> files are merely run, as expected. C<.pl> files are run according
791 =item C<downgrade> Gets run when the schema is C<downgrade>d. Structure is a directory
792 per downgrade step, (for example, C<2-1> for downgrading from version 2 to version
793 1,) and then files are merged with C<_common> and run in filename order.
794 C<.sql> files are merely run, as expected. C<.pl> files are run according
804 A perl script for this tool is very simple. It merely needs to contain an
805 anonymous sub that takes a L<DBIx::Class::Schema> as it's only argument.
806 A very basic perl script might look like:
816 $schema->resultset('Users')->create({
824 This attribute will, when set to true (default is false), cause the DM to use
825 L<SQL::Translator> to use the C<_source>'s serialized SQL::Translator::Schema
826 instead of any pregenerated SQL. If you have a development server this is
827 probably the best plan of action as you will not be putting as many generated
828 files in your version control. Goes well with with C<databases> of C<[]>.
832 The L<DBIx::Class::Schema> (B<required>) that is used to talk to the database
833 and generate the DDL.
837 The L<DBIx::Class::Storage> that is I<actually> used to talk to the database
838 and generate the DDL. This is automatically created with L</_build_storage>.
840 =attr sql_translator_args
842 The arguments that get passed to L<SQL::Translator> when it's used.
844 =attr script_directory
846 The directory (default C<'sql'>) that scripts are stored in
850 The types of databases (default C<< [qw( MySQL SQLite PostgreSQL )] >>) to
855 Set to true (which is the default) to wrap all upgrades and deploys in a single
860 The version the schema on your harddrive is at. Defaults to
861 C<< $self->schema->schema_version >>.