silverdirk's initial progress callback
[dbsrgits/DBIx-Class-DeploymentHandler.git] / lib / DBIx / Class / DeploymentHandler / DeployMethod / SQL / Translator.pm
index c065916..f65cf70 100644 (file)
@@ -6,7 +6,7 @@ use Moose;
 use autodie;
 use Carp qw( carp croak );
 use DBIx::Class::DeploymentHandler::Logger;
-use Log::Contextual qw(:log :dlog), -default_logger =>
+use Log::Contextual qw(:log :dlog), -package_logger =>
   DBIx::Class::DeploymentHandler::Logger->new({
     env_prefix => 'DBICDH'
   });
@@ -31,6 +31,12 @@ has ignore_ddl => (
   default  => undef,
 );
 
+has force_overwrite => (
+  isa      => 'Bool',
+  is       => 'ro',
+  default  => undef,
+);
+
 has schema => (
   isa      => 'DBIx::Class::Schema',
   is       => 'ro',
@@ -43,6 +49,11 @@ has storage => (
   lazy_build => 1,
 );
 
+has progress_callback => (
+  is => 'rw',
+  isa => 'Maybe[CodeRef]',
+);
+
 method _build_storage {
   my $s = $self->schema->storage;
   $s->_determine_driver;
@@ -92,6 +103,9 @@ method __ddl_consume_with_prefix($type, $versions, $prefix) {
   my $common  =
     catfile( $base_dir, '_common', $prefix, join q(-), @{$versions} );
 
+  my $common_any  =
+    catfile( $base_dir, '_common', $prefix, '_any' );
+
   my $dir;
   if (-d $main) {
     $dir = catfile($main, $prefix, join q(-), @{$versions})
@@ -102,6 +116,7 @@ method __ddl_consume_with_prefix($type, $versions, $prefix) {
       croak "$main does not exist; please write/generate some SQL"
     }
   }
+  my $dir_any = catfile($main, $prefix, '_any');
 
   my %files;
   try {
@@ -114,11 +129,11 @@ method __ddl_consume_with_prefix($type, $versions, $prefix) {
   } catch {
     die $_ unless $self->ignore_ddl;
   };
-  if (-d $common) {
-    opendir my($dh), $common;
-    for my $filename (grep { /\.(?:sql|pl)$/ && -f catfile($common,$_) } readdir $dh) {
+  for my $dirname (grep { -d $_ } $common, $common_any, $dir_any) {
+    opendir my($dh), $dirname;
+    for my $filename (grep { /\.(?:sql|pl)$/ && -f catfile($dirname,$_) } readdir $dh) {
       unless ($files{$filename}) {
-        $files{$filename} = catfile($common,$filename);
+        $files{$filename} = catfile($dirname,$filename);
       }
     }
     closedir $dh;
@@ -135,6 +150,19 @@ method _ddl_schema_consume_filenames($type, $version) {
   $self->__ddl_consume_with_prefix($type, [ $version ], 'deploy')
 }
 
+method _ddl_protoschema_deploy_consume_filenames($version) {
+  my $base_dir = $self->script_directory;
+
+  my $dir = catfile( $base_dir, '_source', 'deploy', $version);
+  return [] unless -d $dir;
+
+  opendir my($dh), $dir;
+  my %files = map { $_ => "$dir/$_" } grep { /\.yml$/ && -f "$dir/$_" } readdir $dh;
+  closedir $dh;
+
+  return [@files{sort keys %files}]
+}
+
 method _ddl_protoschema_upgrade_consume_filenames($versions) {
   my $base_dir = $self->script_directory;
 
@@ -221,7 +249,7 @@ method _run_sql_array($sql) {
     }
     catch {
       die "$_ (running line '$line')"
-    }
+    };
     $storage->_query_end($line);
   }
   return join "\n", @$sql
@@ -232,7 +260,7 @@ method _run_sql($filename) {
   return $self->_run_sql_array($self->_read_sql_file($filename));
 }
 
-method _run_perl($filename) {
+method _run_perl($filename, $versions) {
   log_debug { "Running Perl from $filename" };
   my $filedata = do { local( @ARGV, $/ ) = $filename; <> };
 
@@ -242,29 +270,34 @@ method _run_perl($filename) {
   Dlog_trace { "Running Perl $_" } $fn;
 
   if ($@) {
-    carp "$filename failed to compile: $@";
+    croak "$filename failed to compile: $@";
   } elsif (ref $fn eq 'CODE') {
-    $fn->($self->schema)
+    $fn->($self->schema, $versions)
   } else {
-    carp "$filename should define an anonymouse sub that takes a schema but it didn't!";
+    croak "$filename should define an anonymouse sub that takes a schema but it didn't!";
   }
 }
 
-method _run_sql_and_perl($filenames, $sql_to_run) {
+method _run_sql_and_perl($filenames, $sql_to_run, $versions) {
   my @files   = @{$filenames};
   my $guard   = $self->schema->txn_scope_guard if $self->txn_wrap;
 
   $self->_run_sql_array($sql_to_run) if $self->ignore_ddl;
 
   my $sql = ($sql_to_run)?join ";\n", @$sql_to_run:'';
+  my $i= -1;
   FILENAME:
   for my $filename (@files) {
+    $i++;
     if ($self->ignore_ddl && $filename =~ /^[^_]*-auto.*\.sql$/) {
+      $self->progress_callback and $self->progress_callback->($i, scalar(@files), 'skip', $filename);
       next FILENAME
     } elsif ($filename =~ /\.sql$/) {
-       $sql .= $self->_run_sql($filename)
+      $self->progress_callback and $self->progress_callback->($i, scalar(@files), 'sql', $filename);
+      $sql .= $self->_run_sql($filename)
     } elsif ( $filename =~ /\.pl$/ ) {
-       $self->_run_perl($filename)
+      $self->progress_callback and $self->progress_callback->($i, scalar(@files), 'perl', $filename);
+      $self->_run_perl($filename, $versions)
     } else {
       croak "A file ($filename) got to deploy that wasn't sql or perl!";
     }
@@ -283,13 +316,13 @@ sub deploy {
   my $sql;
   if ($self->ignore_ddl) {
      $sql = $self->_sql_from_yaml({},
-       '_ddl_protoschema_produce_filename', $sqlt_type
+       '_ddl_protoschema_deploy_consume_filenames', $sqlt_type
      );
   }
   return $self->_run_sql_and_perl($self->_ddl_schema_consume_filenames(
     $sqlt_type,
     $version,
-  ), $sql);
+  ), $sql, [$version]);
 }
 
 sub initialize {
@@ -314,11 +347,11 @@ sub initialize {
       use warnings;
 
       if ($@) {
-        carp "$filename failed to compile: $@";
+        croak "$filename failed to compile: $@";
       } elsif (ref $fn eq 'CODE') {
         $fn->()
       } else {
-        carp "$filename should define an anonymous sub but it didn't!";
+        croak "$filename should define an anonymous sub but it didn't!";
       }
     } else {
       croak "A file ($filename) got to initialize_scripts that wasn't sql or perl!";
@@ -400,19 +433,25 @@ method _sql_from_yaml($sqltargs, $from_file, $db) {
   my $schema    = $self->schema;
   my $version   = $self->schema_version;
 
-  my $sqlt = SQL::Translator->new({
-    add_drop_table          => 0,
-    parser                  => 'SQL::Translator::Parser::YAML',
-    %{$sqltargs},
-    producer => $db,
-  });
+  my @sql;
 
-  my $yaml_filename = $self->$from_file($version);
-
-  my @sql = $sqlt->translate($yaml_filename);
-  if(!@sql) {
-    carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
-    return undef;
+  my $actual_file = $self->$from_file($version);
+  for my $yaml_filename (@{
+     DlogS_trace { "generating SQL from Serialized SQL Files: $_" }
+        (ref $actual_file?$actual_file:[$actual_file])
+  }) {
+     my $sqlt = SQL::Translator->new({
+       add_drop_table          => 0,
+       parser                  => 'SQL::Translator::Parser::YAML',
+       %{$sqltargs},
+       producer => $db,
+     });
+
+     push @sql, $sqlt->translate($yaml_filename);
+     if(!@sql) {
+       carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
+       return undef;
+     }
   }
   return \@sql;
 }
@@ -431,8 +470,12 @@ sub _prepare_install {
 
     my $filename = $self->$to_file($db, $version, $dir);
     if (-e $filename ) {
-      carp "Overwriting existing DDL file - $filename";
-      unlink $filename;
+      if ($self->force_overwrite) {
+         carp "Overwriting existing DDL file - $filename";
+         unlink $filename;
+      } else {
+         die "Cannot overwrite '$filename', either enable force_overwrite or delete it"
+      }
     }
     open my $file, q(>), $filename;
     print {$file} join ";\n", @$sql;
@@ -455,7 +498,7 @@ sub _resultsource_protoschema_filename {
   my ($self, $source_name) = @_;
   return sub {
     my ($self, $version) = @_;
-    my $dirname = catfile( $self->script_directory, '_source', $version );
+    my $dirname = catfile( $self->script_directory, '_source', 'deploy', $version );
     mkpath($dirname) unless -d $dirname;
 
     return catfile( $dirname, "001-auto-$source_name.yml" );
@@ -464,8 +507,10 @@ sub _resultsource_protoschema_filename {
 
 sub install_resultsource {
   my ($self, $args) = @_;
-  my $source          = $args->{result_source};
-  my $version         = $args->{version};
+  my $source          = $args->{result_source}
+    or die 'result_source must be passed to install_resultsource';
+  my $version         = $args->{version}
+    or die 'version must be passed to install_resultsource';
   log_info { 'installing_resultsource ' . $source->source_name . ", version $version" };
   my $rs_install_file =
     $self->_resultsource_install_filename($source->source_name);
@@ -476,7 +521,7 @@ sub install_resultsource {
       $version,
     )
   ];
-  $self->_run_sql_and_perl($files);
+  $self->_run_sql_and_perl($files, '', [$version]);
 }
 
 sub prepare_resultsource_install {
@@ -495,7 +540,10 @@ sub prepare_resultsource_install {
 sub prepare_deploy {
   log_info { 'preparing deploy' };
   my $self = shift;
-  $self->prepare_protoschema({}, '_ddl_protoschema_produce_filename');
+  $self->prepare_protoschema({
+      # Exclude __VERSION so that it gets installed separately
+      parser_args => { sources => [grep { $_ ne '__VERSION' } $self->schema->sources], }
+  }, '_ddl_protoschema_produce_filename');
   $self->_prepare_install({}, '_ddl_protoschema_produce_filename', '_ddl_schema_produce_filename');
 }
 
@@ -534,8 +582,12 @@ method _prepare_changegrade($from_version, $to_version, $version_set, $direction
   foreach my $db (@$databases) {
     my $diff_file = $self->$diff_file_method($db, $version_set, $dir );
     if(-e $diff_file) {
-      carp("Overwriting existing $direction-diff file - $diff_file");
-      unlink $diff_file;
+      if ($self->force_overwrite) {
+         carp("Overwriting existing $direction-diff file - $diff_file");
+         unlink $diff_file;
+      } else {
+         die "Cannot overwrite '$diff_file', either enable force_overwrite or delete it"
+      }
     }
 
     open my $file, q(>), $diff_file;
@@ -577,7 +629,7 @@ sub downgrade_single_step {
   my $sql = $self->_run_sql_and_perl($self->_ddl_schema_downgrade_consume_filenames(
     $sqlt_type,
     $version_set,
-  ), $sql_to_run);
+  ), $sql_to_run, $version_set);
 
   return ['', $sql];
 }
@@ -597,7 +649,7 @@ sub upgrade_single_step {
   my $sql = $self->_run_sql_and_perl($self->_ddl_schema_upgrade_consume_filenames(
     $sqlt_type,
     $version_set,
-  ), $sql_to_run);
+  ), $sql_to_run, $version_set);
   return ['', $sql];
 }
 
@@ -623,8 +675,12 @@ sub prepare_protoschema {
     unless $yml;
 
   if (-e $filename ) {
-    carp "Overwriting existing DDL-YML file - $filename";
-    unlink $filename;
+    if ($self->force_overwrite) {
+       carp "Overwriting existing DDL-YML file - $filename";
+       unlink $filename;
+    } else {
+       die "Cannot overwrite '$filename', either enable force_overwrite or delete it"
+    }
   }
 
   open my $file, q(>), $filename;
@@ -687,7 +743,9 @@ the following example:
  |  |     `- 002-remove-customers.pl
  |  `- upgrade
  |     `- 1-2
- |        `- 002-generate-customers.pl
+ |     |  `- 002-generate-customers.pl
+ |     `- _any
+ |        `- 999-bump-action.pl
  `- MySQL
     |- downgrade
     |  `- 2-1
@@ -713,7 +771,9 @@ C<$sql_migration_dir/SQLite/deploy/1/001-auto.sql>.  Next,
  $dm->upgrade_single_step([1,2])
 
 would run C<$sql_migration_dir/SQLite/upgrade/1-2/001-auto.sql> followed by
-C<$sql_migration_dir/_common/upgrade/1-2/002-generate-customers.pl>.
+C<$sql_migration_dir/_common/upgrade/1-2/002-generate-customers.pl>, and
+finally punctuated by
+C<$sql_migration_dir/_common/upgrade/_any/999-bump-action.pl>.
 
 C<.pl> files don't have to be in the C<_common> directory, but most of the time
 they should be, because perl scripts are generally database independent.
@@ -764,7 +824,7 @@ L<SQL::Translator::Schema> objects.
 your storage type is.  If you are not sure what your storage type is, take a
 look at the producers listed for L<SQL::Translator>.  Also note, C<_common>
 is a special case.  C<_common> will get merged into whatever other files you
-already have.  This directory can containt the following directories itself:
+already have.  This directory can contain the following directories itself:
 
 =over 2
 
@@ -796,10 +856,17 @@ to L</PERL SCRIPTS>.
 
 =back
 
+Note that there can be an C<_any> in the place of any of the versions (like
+C<1-2> or C<1>), which means those scripts will be run B<every> time.  So if
+you have an C<_any> in C<_common/upgrade>, that script will get run for every
+upgrade.
+
 =head1 PERL SCRIPTS
 
 A perl script for this tool is very simple.  It merely needs to contain an
-anonymous sub that takes a L<DBIx::Class::Schema> as it's only argument.
+anonymous sub that takes a L<DBIx::Class::Schema> and the version set as it's
+arguments.
+
 A very basic perl script might look like:
 
  #!perl
@@ -810,6 +877,9 @@ A very basic perl script might look like:
  sub {
    my $schema = shift;
 
+   # [1] for deploy, [1,2] for upgrade or downgrade, probably used with _any
+   my $versions = shift;
+
    $schema->resultset('Users')->create({
      name => 'root',
      password => 'root',
@@ -824,6 +894,12 @@ instead of any pregenerated SQL.  If you have a development server this is
 probably the best plan of action as you will not be putting as many generated
 files in your version control.  Goes well with with C<databases> of C<[]>.
 
+=attr force_overwrite
+
+When this attribute is true generated files will be overwritten when the
+methods which create such files are run again.  The default is false, in which
+case the program will die with a message saying which file needs to be deleted.
+
 =attr schema
 
 The L<DBIx::Class::Schema> (B<required>) that is used to talk to the database