16f97cd39b93c1b6dae306cb4e0ad62245275d3f
[dbsrgits/DBIx-Class-DeploymentHandler.git] / lib / DBIx / Class / DeploymentHandler / DeployMethod / SQL / Translator.pm
1 package DBIx::Class::DeploymentHandler::DeployMethod::SQL::Translator;
2 use Moose;
3
4 # ABSTRACT: Manage your SQL and Perl migrations in nicely laid out directories
5
6 use autodie;
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'
12   });
13 use Context::Preserve;
14
15 use Try::Tiny;
16
17 use SQL::Translator;
18 require SQL::Translator::Diff;
19
20 require DBIx::Class::Storage;   # loaded for type constraint
21 use DBIx::Class::DeploymentHandler::Types;
22
23 use File::Path 'mkpath';
24 use File::Spec::Functions;
25
26 with 'DBIx::Class::DeploymentHandler::HandlesDeploy';
27
28 has ignore_ddl => (
29   isa      => 'Bool',
30   is       => 'ro',
31   default  => undef,
32 );
33
34 has force_overwrite => (
35   isa      => 'Bool',
36   is       => 'ro',
37   default  => undef,
38 );
39
40 has schema => (
41   isa      => 'DBIx::Class::Schema',
42   is       => 'ro',
43   required => 1,
44 );
45
46 has storage => (
47   isa        => 'DBIx::Class::Storage',
48   is         => 'ro',
49   lazy_build => 1,
50 );
51
52 sub _build_storage {
53   my $self = shift;
54   my $s = $self->schema->storage;
55   $s->_determine_driver;
56   $s
57 }
58
59 has sql_translator_args => (
60   isa => 'HashRef',
61   is  => 'ro',
62   default => sub { {} },
63 );
64 has script_directory => (
65   isa      => 'Str',
66   is       => 'ro',
67   required => 1,
68   default  => 'sql',
69 );
70
71 has databases => (
72   coerce  => 1,
73   isa     => 'DBIx::Class::DeploymentHandler::Databases',
74   is      => 'ro',
75   default => sub { [qw( MySQL SQLite PostgreSQL )] },
76 );
77
78 has txn_wrap => (
79   is => 'ro',
80   isa => 'Bool',
81   default => 1,
82 );
83
84 has schema_version => (
85   is => 'ro',
86   isa => 'Str',
87   lazy_build => 1,
88 );
89
90 # this will probably never get called as the DBICDH
91 # will be passing down a schema_version normally, which
92 # is built the same way, but we leave this in place
93 sub _build_schema_version {
94   my $self = shift;
95   $self->schema->schema_version
96 }
97
98 sub __ddl_consume_with_prefix {
99   my ($self, $type, $versions, $prefix) = @_;
100   my $base_dir = $self->script_directory;
101
102   my $main    = catfile( $base_dir, $type      );
103   my $common  =
104     catfile( $base_dir, '_common', $prefix, join q(-), @{$versions} );
105
106   my $common_any  =
107     catfile( $base_dir, '_common', $prefix, '_any' );
108
109   my $dir;
110   if (-d $main) {
111     $dir = catfile($main, $prefix, join q(-), @{$versions})
112   } else {
113     if ($self->ignore_ddl) {
114       return []
115     } else {
116       croak "$main does not exist; please write/generate some SQL"
117     }
118   }
119   my $dir_any = catfile($main, $prefix, '_any');
120
121   my %files;
122   try {
123      opendir my($dh), $dir;
124      %files =
125        map { $_ => "$dir/$_" }
126        grep { /\.(?:sql|pl|sql-\w+)$/ && -f "$dir/$_" }
127        readdir $dh;
128      closedir $dh;
129   } catch {
130     die $_ unless $self->ignore_ddl;
131   };
132   for my $dirname (grep { -d $_ } $common, $common_any, $dir_any) {
133     opendir my($dh), $dirname;
134     for my $filename (grep { /\.(?:sql|pl)$/ && -f catfile($dirname,$_) } readdir $dh) {
135       unless ($files{$filename}) {
136         $files{$filename} = catfile($dirname,$filename);
137       }
138     }
139     closedir $dh;
140   }
141
142   return [@files{sort keys %files}]
143 }
144
145 sub _ddl_initialize_consume_filenames {
146   my ($self, $type, $version) = @_;
147   $self->__ddl_consume_with_prefix($type, [ $version ], 'initialize')
148 }
149
150 sub _ddl_schema_consume_filenames {
151   my ($self, $type, $version) = @_;
152   $self->__ddl_consume_with_prefix($type, [ $version ], 'deploy')
153 }
154
155 sub _ddl_protoschema_deploy_consume_filenames {
156   my ($self, $version) = @_;
157   my $base_dir = $self->script_directory;
158
159   my $dir = catfile( $base_dir, '_source', 'deploy', $version);
160   return [] unless -d $dir;
161
162   opendir my($dh), $dir;
163   my %files = map { $_ => "$dir/$_" } grep { /\.yml$/ && -f "$dir/$_" } readdir $dh;
164   closedir $dh;
165
166   return [@files{sort keys %files}]
167 }
168
169 sub _ddl_protoschema_upgrade_consume_filenames {
170   my ($self, $versions) = @_;
171   my $base_dir = $self->script_directory;
172
173   my $dir = catfile( $base_dir, '_preprocess_schema', 'upgrade', join q(-), @{$versions});
174
175   return [] unless -d $dir;
176
177   opendir my($dh), $dir;
178   my %files = map { $_ => "$dir/$_" } grep { /\.pl$/ && -f "$dir/$_" } readdir $dh;
179   closedir $dh;
180
181   return [@files{sort keys %files}]
182 }
183
184 sub _ddl_protoschema_downgrade_consume_filenames {
185   my ($self, $versions) = @_;
186   my $base_dir = $self->script_directory;
187
188   my $dir = catfile( $base_dir, '_preprocess_schema', 'downgrade', join q(-), @{$versions});
189
190   return [] unless -d $dir;
191
192   opendir my($dh), $dir;
193   my %files = map { $_ => "$dir/$_" } grep { /\.pl$/ && -f "$dir/$_" } readdir $dh;
194   closedir $dh;
195
196   return [@files{sort keys %files}]
197 }
198
199 sub _ddl_protoschema_produce_filename {
200   my ($self, $version) = @_;
201   my $dirname = catfile( $self->script_directory, '_source', 'deploy',  $version );
202   mkpath($dirname) unless -d $dirname;
203
204   return catfile( $dirname, '001-auto.yml' );
205 }
206
207 sub _ddl_schema_produce_filename {
208   my ($self, $type, $version) = @_;
209   my $dirname = catfile( $self->script_directory, $type, 'deploy', $version );
210   mkpath($dirname) unless -d $dirname;
211
212   return catfile( $dirname, '001-auto.sql' );
213 }
214
215 sub _ddl_schema_upgrade_consume_filenames {
216   my ($self, $type, $versions) = @_;
217   $self->__ddl_consume_with_prefix($type, $versions, 'upgrade')
218 }
219
220 sub _ddl_schema_downgrade_consume_filenames {
221   my ($self, $type, $versions) = @_;
222   $self->__ddl_consume_with_prefix($type, $versions, 'downgrade')
223 }
224
225 sub _ddl_schema_upgrade_produce_filename {
226   my ($self, $type, $versions) = @_;
227   my $dir = $self->script_directory;
228
229   my $dirname = catfile( $dir, $type, 'upgrade', join q(-), @{$versions});
230   mkpath($dirname) unless -d $dirname;
231
232   return catfile( $dirname, '001-auto.sql' );
233 }
234
235 sub _ddl_schema_downgrade_produce_filename {
236   my ($self, $type, $versions, $dir) = @_;
237   my $dirname = catfile( $dir, $type, 'downgrade', join q(-), @{$versions} );
238   mkpath($dirname) unless -d $dirname;
239
240   return catfile( $dirname, '001-auto.sql');
241 }
242
243 sub _run_sql_array {
244   my ($self, $sql) = @_;
245   my $storage = $self->storage;
246
247   $sql = [ _split_sql_chunk( @$sql ) ];
248
249   Dlog_trace { "Running SQL $_" } $sql;
250   foreach my $line (@{$sql}) {
251     $storage->_query_start($line);
252     # the whole reason we do this is so that we can see the line that was run
253     try {
254       $storage->dbh_do (sub { $_[1]->do($line) });
255     }
256     catch {
257       die "$_ (running line '$line')"
258     };
259     $storage->_query_end($line);
260   }
261   return join "\n", @$sql
262 }
263
264 # split a chunk o' SQL into statements
265 sub _split_sql_chunk {
266     my @sql = map { split /;\n/, $_ } @_;
267
268     for ( @sql ) {
269         # strip transactions
270         s/^(?:BEGIN|BEGIN TRANSACTION|COMMIT).*//mgi;
271
272         # trim whitespaces
273         s/^\s+|\s+$//mg;
274
275         # remove comments
276         s/^--.*//gm;
277
278         # remove blank lines
279         s/^\n//mg;
280
281         # put on single line
282         s/\n/ /g;
283     }
284
285     return @sql;
286 }
287
288 sub _run_sql {
289   my ($self, $filename) = @_;
290   log_debug { "Running SQL from $filename" };
291   return $self->_run_sql_array($self->_read_sql_file($filename));
292 }
293
294 # stolen from Plack::Util::_load_sandbox
295 sub _load_sandbox {
296   my $_file = shift;
297
298   my $_package = $_file;
299   $_package =~ s/([^A-Za-z0-9_])/sprintf("_%2x", unpack("C", $1))/eg;
300
301   local $0 = $_file; # so FindBin etc. works
302
303   return eval sprintf <<'END_EVAL', $_package;
304 package DBICDH::Sandbox::%s;
305 {
306   my $app = do $_file;
307   if ( !$app && ( my $error = $@ || $! )) { die $error; }
308   $app;
309 }
310 END_EVAL
311 }
312
313 sub _run_perl {
314   my ($self, $filename, $versions) = @_;
315   log_debug { "Running Perl from $filename" };
316   my $filedata = do { local( @ARGV, $/ ) = $filename; <> };
317
318   my $fn = _load_sandbox($filename);
319
320   Dlog_trace { "Running Perl $_" } $fn;
321
322   if (ref $fn eq 'CODE') {
323     $fn->($self->schema, $versions)
324   } else {
325     croak "$filename should define an anonymouse sub that takes a schema but it didn't!";
326   }
327 }
328
329 sub txn_do {
330    my ( $self, $code ) = @_;
331    return $code->() unless $self->txn_wrap;
332
333    my $guard = $self->schema->txn_scope_guard;
334
335    return preserve_context { $code->() } after => sub { $guard->commit };
336 }
337
338 sub _run_sql_and_perl {
339   my ($self, $filenames, $sql_to_run, $versions) = @_;
340   my @files   = @{$filenames};
341   $self->txn_do(sub {
342      $self->_run_sql_array($sql_to_run) if $self->ignore_ddl;
343
344      my $sql = ($sql_to_run)?join ";\n", @$sql_to_run:'';
345      FILENAME:
346      for my $filename (@files) {
347        if ($self->ignore_ddl && $filename =~ /^[^_]*-auto.*\.sql$/) {
348          next FILENAME
349        } elsif ($filename =~ /\.sql$/) {
350           $sql .= $self->_run_sql($filename)
351        } elsif ( $filename =~ /\.pl$/ ) {
352           $self->_run_perl($filename, $versions)
353        } else {
354          croak "A file ($filename) got to deploy that wasn't sql or perl!";
355        }
356      }
357
358      return $sql;
359   });
360 }
361
362 sub deploy {
363   my $self = shift;
364   my $version = (shift @_ || {})->{version} || $self->schema_version;
365   log_info { "deploying version $version" };
366   my $sqlt_type = $self->storage->sqlt_type;
367   my $sql;
368   if ($self->ignore_ddl) {
369      $sql = $self->_sql_from_yaml({},
370        '_ddl_protoschema_deploy_consume_filenames', $sqlt_type
371      );
372   }
373   return $self->_run_sql_and_perl($self->_ddl_schema_consume_filenames(
374     $sqlt_type,
375     $version,
376   ), $sql, [$version]);
377 }
378
379 sub initialize {
380   my $self         = shift;
381   my $args         = shift;
382   my $version      = $args->{version}      || $self->schema_version;
383   log_info { "initializing version $version" };
384   my $storage_type = $args->{storage_type} || $self->storage->sqlt_type;
385
386   my @files = @{$self->_ddl_initialize_consume_filenames(
387     $storage_type,
388     $version,
389   )};
390
391   for my $filename (@files) {
392     # We ignore sql for now (till I figure out what to do with it)
393     if ( $filename =~ /^(.+)\.pl$/ ) {
394       my $filedata = do { local( @ARGV, $/ ) = $filename; <> };
395
396       no warnings 'redefine';
397       my $fn = eval "$filedata";
398       use warnings;
399
400       if ($@) {
401         croak "$filename failed to compile: $@";
402       } elsif (ref $fn eq 'CODE') {
403         $fn->()
404       } else {
405         croak "$filename should define an anonymous sub but it didn't!";
406       }
407     } else {
408       croak "A file ($filename) got to initialize_scripts that wasn't sql or perl!";
409     }
410   }
411 }
412
413 sub _sqldiff_from_yaml {
414   my ($self, $from_version, $to_version, $db, $direction) = @_;
415   my $dir       = $self->script_directory;
416   my $sqltargs = {
417     add_drop_table => 1,
418     ignore_constraint_names => 1,
419     ignore_index_names => 1,
420     %{$self->sql_translator_args}
421   };
422
423   my $source_schema;
424   {
425     my $prefilename = $self->_ddl_protoschema_produce_filename($from_version, $dir);
426
427     # should probably be a croak
428     carp("No previous schema file found ($prefilename)")
429        unless -e $prefilename;
430
431     my $t = SQL::Translator->new({
432        %{$sqltargs},
433        debug => 0,
434        trace => 0,
435        parser => 'SQL::Translator::Parser::YAML',
436     });
437
438     my $out = $t->translate( $prefilename )
439       or croak($t->error);
440
441     $source_schema = $t->schema;
442
443     $source_schema->name( $prefilename )
444       unless  $source_schema->name;
445   }
446
447   my $dest_schema;
448   {
449     my $filename = $self->_ddl_protoschema_produce_filename($to_version, $dir);
450
451     # should probably be a croak
452     carp("No next schema file found ($filename)")
453        unless -e $filename;
454
455     my $t = SQL::Translator->new({
456        %{$sqltargs},
457        debug => 0,
458        trace => 0,
459        parser => 'SQL::Translator::Parser::YAML',
460     });
461
462     my $out = $t->translate( $filename )
463       or croak($t->error);
464
465     $dest_schema = $t->schema;
466
467     $dest_schema->name( $filename )
468       unless $dest_schema->name;
469   }
470
471   my $transform_files_method =  "_ddl_protoschema_${direction}_consume_filenames";
472   my $transforms = $self->_coderefs_per_files(
473     $self->$transform_files_method([$from_version, $to_version])
474   );
475   $_->($source_schema, $dest_schema) for @$transforms;
476
477   return [SQL::Translator::Diff::schema_diff(
478      $source_schema, $db,
479      $dest_schema,   $db,
480      $sqltargs
481   )];
482 }
483
484 sub _sql_from_yaml {
485   my ($self, $sqltargs, $from_file, $db) = @_;
486   my $schema    = $self->schema;
487   my $version   = $self->schema_version;
488
489   my @sql;
490
491   my $actual_file = $self->$from_file($version);
492   for my $yaml_filename (@{
493      DlogS_trace { "generating SQL from Serialized SQL Files: $_" }
494         (ref $actual_file?$actual_file:[$actual_file])
495   }) {
496      my $sqlt = SQL::Translator->new({
497        add_drop_table          => 0,
498        parser                  => 'SQL::Translator::Parser::YAML',
499        %{$sqltargs},
500        producer => $db,
501      });
502
503      push @sql, $sqlt->translate($yaml_filename);
504      if(!@sql) {
505        carp("Failed to translate to $db, skipping. (" . $sqlt->error . ")");
506        return undef;
507      }
508   }
509   return \@sql;
510 }
511
512 sub _prepare_install {
513   my $self      = shift;
514   my $sqltargs  = { %{$self->sql_translator_args}, %{shift @_} };
515   my $from_file = shift;
516   my $to_file   = shift;
517   my $dir       = $self->script_directory;
518   my $databases = $self->databases;
519   my $version   = $self->schema_version;
520
521   foreach my $db (@$databases) {
522     my $sql = $self->_sql_from_yaml($sqltargs, $from_file, $db ) or next;
523
524     my $filename = $self->$to_file($db, $version, $dir);
525     if (-e $filename ) {
526       if ($self->force_overwrite) {
527          carp "Overwriting existing DDL file - $filename";
528          unlink $filename;
529       } else {
530          die "Cannot overwrite '$filename', either enable force_overwrite or delete it"
531       }
532     }
533     open my $file, q(>), $filename;
534     print {$file} join ";\n", @$sql;
535     close $file;
536   }
537 }
538
539 sub _resultsource_install_filename {
540   my ($self, $source_name) = @_;
541   return sub {
542     my ($self, $type, $version) = @_;
543     my $dirname = catfile( $self->script_directory, $type, 'deploy', $version );
544     mkpath($dirname) unless -d $dirname;
545
546     return catfile( $dirname, "001-auto-$source_name.sql" );
547   }
548 }
549
550 sub _resultsource_protoschema_filename {
551   my ($self, $source_name) = @_;
552   return sub {
553     my ($self, $version) = @_;
554     my $dirname = catfile( $self->script_directory, '_source', 'deploy', $version );
555     mkpath($dirname) unless -d $dirname;
556
557     return catfile( $dirname, "001-auto-$source_name.yml" );
558   }
559 }
560
561 sub install_resultsource {
562   my ($self, $args) = @_;
563   my $source          = $args->{result_source}
564     or die 'result_source must be passed to install_resultsource';
565   my $version         = $args->{version}
566     or die 'version must be passed to install_resultsource';
567   log_info { 'installing_resultsource ' . $source->source_name . ", version $version" };
568   my $rs_install_file =
569     $self->_resultsource_install_filename($source->source_name);
570
571   my $files = [
572      $self->$rs_install_file(
573       $self->storage->sqlt_type,
574       $version,
575     )
576   ];
577   $self->_run_sql_and_perl($files, '', [$version]);
578 }
579
580 sub prepare_resultsource_install {
581   my $self = shift;
582   my $source = (shift @_)->{result_source};
583   log_info { 'preparing install for resultsource ' . $source->source_name };
584
585   my $install_filename = $self->_resultsource_install_filename($source->source_name);
586   my $proto_filename = $self->_resultsource_protoschema_filename($source->source_name);
587   $self->prepare_protoschema({
588       parser_args => { sources => [$source->source_name], }
589   }, $proto_filename);
590   $self->_prepare_install({}, $proto_filename, $install_filename);
591 }
592
593 sub prepare_deploy {
594   log_info { 'preparing deploy' };
595   my $self = shift;
596   $self->prepare_protoschema({
597       # Exclude __VERSION so that it gets installed separately
598       parser_args => { sources => [grep { $_ ne '__VERSION' } $self->schema->sources], }
599   }, '_ddl_protoschema_produce_filename');
600   $self->_prepare_install({}, '_ddl_protoschema_produce_filename', '_ddl_schema_produce_filename');
601 }
602
603 sub prepare_upgrade {
604   my ($self, $args) = @_;
605   log_info {
606      "preparing upgrade from $args->{from_version} to $args->{to_version}"
607   };
608   $self->_prepare_changegrade(
609     $args->{from_version}, $args->{to_version}, $args->{version_set}, 'upgrade'
610   );
611 }
612
613 sub prepare_downgrade {
614   my ($self, $args) = @_;
615   log_info {
616      "preparing downgrade from $args->{from_version} to $args->{to_version}"
617   };
618   $self->_prepare_changegrade(
619     $args->{from_version}, $args->{to_version}, $args->{version_set}, 'downgrade'
620   );
621 }
622
623 sub _coderefs_per_files {
624   my ($self, $files) = @_;
625   no warnings 'redefine';
626   [map eval do { local( @ARGV, $/ ) = $_; <> }, @$files]
627 }
628
629 sub _prepare_changegrade {
630   my ($self, $from_version, $to_version, $version_set, $direction) = @_;
631   my $schema    = $self->schema;
632   my $databases = $self->databases;
633   my $dir       = $self->script_directory;
634
635   my $schema_version = $self->schema_version;
636   my $diff_file_method = "_ddl_schema_${direction}_produce_filename";
637   foreach my $db (@$databases) {
638     my $diff_file = $self->$diff_file_method($db, $version_set, $dir );
639     if(-e $diff_file) {
640       if ($self->force_overwrite) {
641          carp("Overwriting existing $direction-diff file - $diff_file");
642          unlink $diff_file;
643       } else {
644          die "Cannot overwrite '$diff_file', either enable force_overwrite or delete it"
645       }
646     }
647
648     open my $file, q(>), $diff_file;
649     print {$file} join ";\n", @{$self->_sqldiff_from_yaml($from_version, $to_version, $db, $direction)};
650     close $file;
651   }
652 }
653
654 sub _read_sql_file {
655   my ($self, $file)  = @_;
656   return unless $file;
657
658    local $/ = undef;  #sluuuuuurp
659
660   open my $fh, '<', $file;
661   return [ _split_sql_chunk( <$fh> ) ];
662 }
663
664 sub downgrade_single_step {
665   my $self = shift;
666   my $version_set = (shift @_)->{version_set};
667   Dlog_info { "downgrade_single_step'ing $_" } $version_set;
668
669   my $sqlt_type = $self->storage->sqlt_type;
670   my $sql_to_run;
671   if ($self->ignore_ddl) {
672      $sql_to_run = $self->_sqldiff_from_yaml(
673        $version_set->[0], $version_set->[1], $sqlt_type, 'downgrade',
674      );
675   }
676   my $sql = $self->_run_sql_and_perl($self->_ddl_schema_downgrade_consume_filenames(
677     $sqlt_type,
678     $version_set,
679   ), $sql_to_run, $version_set);
680
681   return ['', $sql];
682 }
683
684 sub upgrade_single_step {
685   my $self = shift;
686   my $version_set = (shift @_)->{version_set};
687   Dlog_info { "upgrade_single_step'ing $_" } $version_set;
688
689   my $sqlt_type = $self->storage->sqlt_type;
690   my $sql_to_run;
691   if ($self->ignore_ddl) {
692      $sql_to_run = $self->_sqldiff_from_yaml(
693        $version_set->[0], $version_set->[1], $sqlt_type, 'upgrade',
694      );
695   }
696   my $sql = $self->_run_sql_and_perl($self->_ddl_schema_upgrade_consume_filenames(
697     $sqlt_type,
698     $version_set,
699   ), $sql_to_run, $version_set);
700   return ['', $sql];
701 }
702
703 sub prepare_protoschema {
704   my $self      = shift;
705   my $sqltargs  = { %{$self->sql_translator_args}, %{shift @_} };
706   my $to_file   = shift;
707   my $filename
708     = $self->$to_file($self->schema_version);
709
710   # we do this because the code that uses this sets parser args,
711   # so we just need to merge in the package
712   $sqltargs->{parser_args}{package} = $self->schema;
713   my $sqlt = SQL::Translator->new({
714     parser                  => 'SQL::Translator::Parser::DBIx::Class',
715     producer                => 'SQL::Translator::Producer::YAML',
716     %{ $sqltargs },
717   });
718
719   my $yml = $sqlt->translate;
720
721   croak("Failed to translate to YAML: " . $sqlt->error)
722     unless $yml;
723
724   if (-e $filename ) {
725     if ($self->force_overwrite) {
726        carp "Overwriting existing DDL-YML file - $filename";
727        unlink $filename;
728     } else {
729        die "Cannot overwrite '$filename', either enable force_overwrite or delete it"
730     }
731   }
732
733   open my $file, q(>), $filename;
734   print {$file} $yml;
735   close $file;
736 }
737
738 __PACKAGE__->meta->make_immutable;
739
740 1;
741
742 # vim: ts=2 sw=2 expandtab
743
744 __END__
745
746 =head1 DESCRIPTION
747
748 This class is the meat of L<DBIx::Class::DeploymentHandler>.  It takes care
749 of generating serialized schemata  as well as sql files to move from one
750 version of a schema to the rest.  One of the hallmark features of this class
751 is that it allows for multiple sql files for deploy and upgrade, allowing
752 developers to fine tune deployment.  In addition it also allows for perl
753 files to be run at any stage of the process.
754
755 For basic usage see L<DBIx::Class::DeploymentHandler::HandlesDeploy>.  What's
756 documented here is extra fun stuff or private methods.
757
758 =head1 DIRECTORY LAYOUT
759
760 Arguably this is the best feature of L<DBIx::Class::DeploymentHandler>.
761 It's spiritually based upon L<DBIx::Migration::Directories>, but has a
762 lot of extensions and modifications, so even if you are familiar with it,
763 please read this.  I feel like the best way to describe the layout is with
764 the following example:
765
766  $sql_migration_dir
767  |- _source
768  |  |- deploy
769  |     |- 1
770  |     |  `- 001-auto.yml
771  |     |- 2
772  |     |  `- 001-auto.yml
773  |     `- 3
774  |        `- 001-auto.yml
775  |- SQLite
776  |  |- downgrade
777  |  |  `- 2-1
778  |  |     `- 001-auto.sql
779  |  |- deploy
780  |  |  `- 1
781  |  |     `- 001-auto.sql
782  |  `- upgrade
783  |     |- 1-2
784  |     |  `- 001-auto.sql
785  |     `- 2-3
786  |        `- 001-auto.sql
787  |- _common
788  |  |- downgrade
789  |  |  `- 2-1
790  |  |     `- 002-remove-customers.pl
791  |  `- upgrade
792  |     `- 1-2
793  |     |  `- 002-generate-customers.pl
794  |     `- _any
795  |        `- 999-bump-action.pl
796  `- MySQL
797     |- downgrade
798     |  `- 2-1
799     |     `- 001-auto.sql
800     |- initialize
801     |  `- 1
802     |     |- 001-create_database.pl
803     |     `- 002-create_users_and_permissions.pl
804     |- deploy
805     |  `- 1
806     |     `- 001-auto.sql
807     `- upgrade
808        `- 1-2
809           `- 001-auto.sql
810
811 So basically, the code
812
813  $dm->deploy(1)
814
815 on an C<SQLite> database that would simply run
816 C<$sql_migration_dir/SQLite/deploy/1/001-auto.sql>.  Next,
817
818  $dm->upgrade_single_step([1,2])
819
820 would run C<$sql_migration_dir/SQLite/upgrade/1-2/001-auto.sql> followed by
821 C<$sql_migration_dir/_common/upgrade/1-2/002-generate-customers.pl>, and
822 finally punctuated by
823 C<$sql_migration_dir/_common/upgrade/_any/999-bump-action.pl>.
824
825 C<.pl> files don't have to be in the C<_common> directory, but most of the time
826 they should be, because perl scripts are generally database independent.
827
828 Note that unlike most steps in the process, C<initialize> will not run SQL, as
829 there may not even be an database at initialize time.  It will run perl scripts
830 just like the other steps in the process, but nothing is passed to them.
831 Until people have used this more it will remain freeform, but a recommended use
832 of initialize is to have it prompt for username and password, and then call the
833 appropriate C<< CREATE DATABASE >> commands etc.
834
835 =head2 Directory Specification
836
837 The following subdirectories are recognized by this DeployMethod:
838
839 =over 2
840
841 =item C<_source> This directory can contain the following directories:
842
843 =over 2
844
845 =item C<deploy> This directory merely contains directories named after schema
846 versions, which in turn contain C<yaml> files that are serialized versions
847 of the schema at that version.  These files are not for editing by hand.
848
849 =back
850
851 =item C<_preprocess_schema> This directory can contain the following
852 directories:
853
854 =over 2
855
856 =item C<downgrade> This directory merely contains directories named after
857 migrations, which are of the form C<$from_version-$to_version>.  Inside of
858 these directories you may put Perl scripts which are to return a subref
859 that takes the arguments C<< $from_schema, $to_schema >>, which are
860 L<SQL::Translator::Schema> objects.
861
862 =item C<upgrade> This directory merely contains directories named after
863 migrations, which are of the form C<$from_version-$to_version>.  Inside of
864 these directories you may put Perl scripts which are to return a subref
865 that takes the arguments C<< $from_schema, $to_schema >>, which are
866 L<SQL::Translator::Schema> objects.
867
868 =back
869
870 =item C<$storage_type> This is a set of scripts that gets run depending on what
871 your storage type is.  If you are not sure what your storage type is, take a
872 look at the producers listed for L<SQL::Translator>.  Also note, C<_common>
873 is a special case.  C<_common> will get merged into whatever other files you
874 already have.  This directory can contain the following directories itself:
875
876 =over 2
877
878 =item C<initialize> Gets run before the C<deploy> is C<deploy>ed.  Has the
879 same structure as the C<deploy> subdirectory as well; that is, it has a
880 directory for each schema version.  Unlike C<deploy>, C<upgrade>, and C<downgrade>
881 though, it can only run C<.pl> files, and the coderef in the perl files get
882 no arguments passed to them.
883
884 =item C<deploy> Gets run when the schema is C<deploy>ed.  Structure is a
885 directory per schema version, and then files are merged with C<_common> and run
886 in filename order.  C<.sql> files are merely run, as expected.  C<.pl> files are
887 run according to L</PERL SCRIPTS>.
888
889 =item C<upgrade> Gets run when the schema is C<upgrade>d.  Structure is a directory
890 per upgrade step, (for example, C<1-2> for upgrading from version 1 to version
891 2,) and then files are merged with C<_common> and run in filename order.
892 C<.sql> files are merely run, as expected.  C<.pl> files are run according
893 to L</PERL SCRIPTS>.
894
895 =item C<downgrade> Gets run when the schema is C<downgrade>d.  Structure is a directory
896 per downgrade step, (for example, C<2-1> for downgrading from version 2 to version
897 1,) and then files are merged with C<_common> and run in filename order.
898 C<.sql> files are merely run, as expected.  C<.pl> files are run according
899 to L</PERL SCRIPTS>.
900
901
902 =back
903
904 =back
905
906 Note that there can be an C<_any> in the place of any of the versions (like
907 C<1-2> or C<1>), which means those scripts will be run B<every> time.  So if
908 you have an C<_any> in C<_common/upgrade>, that script will get run for every
909 upgrade.
910
911 =head1 PERL SCRIPTS
912
913 A perl script for this tool is very simple.  It merely needs to contain an
914 anonymous sub that takes a L<DBIx::Class::Schema> and the version set as it's
915 arguments.
916
917 A very basic perl script might look like:
918
919  #!perl
920
921  use strict;
922  use warnings;
923
924  use DBIx::Class::DeploymentHandler::DeployMethod::SQL::Translator::ScriptHelpers
925     'schema_from_schema_loader';
926
927  schema_from_schema_loader({ naming => 'v4' }, sub {
928    my $schema = shift;
929
930    # [1] for deploy, [1,2] for upgrade or downgrade, probably used with _any
931    my $versions = shift;
932
933    $schema->resultset('Users')->create({
934      name => 'root',
935      password => 'root',
936    })
937  })
938
939 Note that the above uses
940 L<DBIx::Class::DeploymentHanlder::DeployMethod::SQL::Translator::ScriptHelpers/schema_from_schema_loader>.
941 Using a raw coderef is strongly discouraged as it is likely to break as you
942 modify your schema.
943
944 =attr ignore_ddl
945
946 This attribute will, when set to true (default is false), cause the DM to use
947 L<SQL::Translator> to use the C<_source>'s serialized SQL::Translator::Schema
948 instead of any pregenerated SQL.  If you have a development server this is
949 probably the best plan of action as you will not be putting as many generated
950 files in your version control.  Goes well with with C<databases> of C<[]>.
951
952 =attr force_overwrite
953
954 When this attribute is true generated files will be overwritten when the
955 methods which create such files are run again.  The default is false, in which
956 case the program will die with a message saying which file needs to be deleted.
957
958 =attr schema
959
960 The L<DBIx::Class::Schema> (B<required>) that is used to talk to the database
961 and generate the DDL.
962
963 =attr storage
964
965 The L<DBIx::Class::Storage> that is I<actually> used to talk to the database
966 and generate the DDL.  This is automatically created with L</_build_storage>.
967
968 =attr sql_translator_args
969
970 The arguments that get passed to L<SQL::Translator> when it's used.
971
972 =attr script_directory
973
974 The directory (default C<'sql'>) that scripts are stored in
975
976 =attr databases
977
978 The types of databases (default C<< [qw( MySQL SQLite PostgreSQL )] >>) to
979 generate files for
980
981 =attr txn_wrap
982
983 Set to true (which is the default) to wrap all upgrades and deploys in a single
984 transaction.
985
986 =attr schema_version
987
988 The version the schema on your harddrive is at.  Defaults to
989 C<< $self->schema->schema_version >>.