bump required versions
[dbsrgits/SQL-Translator-2.0-ish.git] / lib / SQL / Translator / Producer / SQL / MySQL.pm
CommitLineData
24e6a53a 1use MooseX::Declare;
2role SQL::Translator::Producer::SQL::MySQL {
3 use SQL::Translator::Constants qw(:sqlt_types :sqlt_constants);
4 use SQL::Translator::Types qw(Column Constraint Index Table View);
5 my $DEFAULT_MAX_ID_LENGTH = 64;
6 my %used_names;
7
8 #
9 # Use only lowercase for the keys (e.g. "long" and not "LONG")
10 #
11 my %translate = (
12 #
13 # Oracle types
14 #
15 varchar2 => 'varchar',
16 long => 'text',
17 clob => 'longtext',
18
19 #
20 # Sybase types
21 #
22 int => 'integer',
23 money => 'float',
24 real => 'double',
25 comment => 'text',
26 bit => 'tinyint',
27
28 #
29 # Access types
30 #
31 'long integer' => 'integer',
32 'text' => 'text',
33 'datetime' => 'datetime',
34
35 #
36 # PostgreSQL types
37 #
38 bytea => 'BLOB',
39 );
40
41 #
42 # Column types that do not support lenth attribute
43 #
44 my @no_length_attr = qw/ date time timestamp datetime year /;
45
46 method preprocess_schema($schema) {
47# my ($schema) = @_;
48
49 # extra->{mysql_table_type} used to be the type. It belongs in options, so
50 # move it if we find it. Return Engine type if found in extra or options
51 # Similarly for mysql_charset and mysql_collate
52 my $extra_to_options = sub {
53 my ($table, $extra_name, $opt_name) = @_;
54
55 my $extra = $table->extra;
56
57 my $extra_type = delete $extra->{$extra_name};
58
59 # Now just to find if there is already an Engine or Type option...
60 # and lets normalize it to ENGINE since:
61 #
62 # The ENGINE table option specifies the storage engine for the table.
63 # TYPE is a synonym, but ENGINE is the preferred option name.
64 #
65
66 # We have to use the hash directly here since otherwise there is no way
67 # to remove options.
68 my $options = ( $table->{options} ||= []);
69
70 # If multiple option names, normalize to the first one
71 if (ref $opt_name) {
72 OPT_NAME: for ( @$opt_name[1..$#$opt_name] ) {
73 for my $idx ( 0..$#{$options} ) {
74 my ($key, $value) = %{ $options->[$idx] };
75
76 if (uc $key eq $_) {
77 $options->[$idx] = { $opt_name->[0] => $value };
78 last OPT_NAME;
79 }
80 }
81 }
82 $opt_name = $opt_name->[0];
83
84 }
85
86
87 # This assumes that there isn't both a Type and an Engine option.
88 OPTION:
89 for my $idx ( 0..$#{$options} ) {
90 my ($key, $value) = %{ $options->[$idx] };
91
92 next unless uc $key eq $opt_name;
93
94 # make sure case is right on option name
95 delete $options->[$idx]{$key};
96 return $options->[$idx]{$opt_name} = $value || $extra_type;
97
98 }
99
100 if ($extra_type) {
101 push @$options, { $opt_name => $extra_type };
102 return $extra_type;
103 }
104
105 };
106
107 # Names are only specific to a given schema
108 my %used_names = ();
109
110 #
111 # Work out which tables need to be InnoDB to support foreign key
112 # constraints. We do this first as we need InnoDB at both ends.
113 #
114 foreach my $table ( $schema->get_tables ) {
115
116 $extra_to_options->($table, 'mysql_table_type', ['ENGINE', 'TYPE'] );
117 $extra_to_options->($table, 'mysql_charset', 'CHARACTER SET' );
118 $extra_to_options->($table, 'mysql_collate', 'COLLATE' );
119
120 foreach my $c ( $table->get_constraints ) {
121 next unless $c->type eq FOREIGN_KEY;
122
123 # Normalize constraint names here.
124 my $c_name = $c->name;
125 # Give the constraint a name if it doesn't have one, so it doens't feel
126 # left out
127 $c_name = $table->name . '_fk' unless length $c_name;
128
129 $c->name( $self->next_unused_name($c_name) );
130
131 for my $meth (qw/table reference_table/) {
132 my $table = $schema->get_table($c->$meth) || next;
133 # This normalizes the types to ENGINE and returns the value if its there
134 next if $extra_to_options->($table, 'mysql_table_type', ['ENGINE', 'TYPE']);
94f42333 135 $table->options({ 'ENGINE' => 'InnoDB' });
24e6a53a 136 }
137 } # foreach constraints
138
139 my %map = ( mysql_collate => 'collate', mysql_charset => 'character set');
140 foreach my $f ( $table->get_fields ) {
141 my $extra = $f->extra;
142 for (keys %map) {
143 $extra->{$map{$_}} = delete $extra->{$_} if exists $extra->{$_};
144 }
145
146 my @size = $f->size;
147 if ( !$size[0] && $f->data_type =~ /char$/ ) {
148 $f->size( (255) );
149 }
150 }
151
152 }
153 }
154
94f42333 155 method produce {
24e6a53a 156 my $translator = $self->translator;
157 my $DEBUG = 0;# = $translator->debug;
158 #local %used_names;
159 my $no_comments = $translator->no_comments;
160 my $add_drop_table = $translator->add_drop_table;
161 my $schema = $translator->schema;
162 my $show_warnings = $translator->show_warnings || 0;
163 my $producer_args = $translator->producer_args;
f48e6f55 164 my $mysql_version = $translator->engine_version ($producer_args->{mysql_version}, 'perl') || 0;
24e6a53a 165 my $max_id_length = $producer_args->{mysql_max_id_length} || $DEFAULT_MAX_ID_LENGTH;
166
167 my ($qt, $qf, $qc) = ('','', '');
168 $qt = '`' if $translator->quote_table_names;
169 $qf = '`' if $translator->quote_field_names;
170
171 #debug("PKG: Beginning production\n");
172 %used_names = ();
173 my $create = '';
174 $create .= $self->header_comment unless ($no_comments);
175 # \todo Don't set if MySQL 3.x is set on command line
176 my @create = "SET foreign_key_checks=0";
177
178 $self->preprocess_schema($schema);
179
180 #
181 # Generate sql
182 #
183 my @table_defs =();
184
185 for my $table ( $schema->get_tables ) {
186 # print $table->name, "\n";
187 push @table_defs, $self->create_table($table,
188 { add_drop_table => $add_drop_table,
189 show_warnings => $show_warnings,
190 no_comments => $no_comments,
191 quote_table_names => $qt,
192 quote_field_names => $qf,
193 max_id_length => $max_id_length,
194 mysql_version => $mysql_version
195 });
196 }
197
198 if ($mysql_version >= 5.000001) {
199 for my $view ( $schema->get_views ) {
200 push @table_defs, $self->create_view($view,
201 { add_replace_view => $add_drop_table,
202 show_warnings => $show_warnings,
203 no_comments => $no_comments,
204 quote_table_names => $qt,
205 quote_field_names => $qf,
206 max_id_length => $max_id_length,
207 mysql_version => $mysql_version
208 });
209 }
210 }
211
212
94f42333 213 #warn "@table_defs\n";
24e6a53a 214 push @table_defs, "SET foreign_key_checks=1";
24e6a53a 215 return wantarray ? ($create ? $create : (), @create, @table_defs) : ($create . join('', map { $_ ? "$_;\n\n" : () } (@create, @table_defs)));
216 }
217
218 method create_view($view, $options) {
24e6a53a 219 my $qt = $options->{quote_table_names} || '';
220 my $qf = $options->{quote_field_names} || '';
221
222 my $view_name = $view->name;
223 #debug("PKG: Looking at view '${view_name}'\n");
224
225 # Header. Should this look like what mysqldump produces?
226 my $create = '';
227 $create .= "--\n-- View: ${qt}${view_name}${qt}\n--\n" unless $options->{no_comments};
228 $create .= 'CREATE';
229 $create .= ' OR REPLACE' if $options->{add_replace_view};
230 $create .= "\n";
231
232 my $extra = $view->extra;
233 # ALGORITHM
234 if( exists($extra->{mysql_algorithm}) && defined(my $algorithm = $extra->{mysql_algorithm}) ){
235 $create .= " ALGORITHM = ${algorithm}\n" if $algorithm =~ /(?:UNDEFINED|MERGE|TEMPTABLE)/i;
236 }
237 # DEFINER
238 if( exists($extra->{mysql_definer}) && defined(my $user = $extra->{mysql_definer}) ){
239 $create .= " DEFINER = ${user}\n";
240 }
241 # SECURITY
242 if( exists($extra->{mysql_security}) && defined(my $security = $extra->{mysql_security}) ){
243 $create .= " SQL SECURITY ${security}\n" if $security =~ /(?:DEFINER|INVOKER)/i;
244 }
245
246 #Header, cont.
247 $create .= " VIEW ${qt}${view_name}${qt}";
248
249 if( my @fields = $view->fields ){
250 my $list = join ', ', map { "${qf}${_}${qf}"} @fields;
251 $create .= " ( ${list} )";
252 }
253 if( my $sql = $view->sql ){
254 $create .= " AS (\n ${sql}\n )";
255 }
256 # $create .= "";
257 return $create;
258 }
259
260 method create_table($table, $options) {
261# my ($table, $options) = @_;
262
263 my $qt = $options->{quote_table_names} || '';
264 my $qf = $options->{quote_field_names} || '';
265
266 my $table_name = $self->quote_table_name($table->name, $qt);
267 #debug("PKG: Looking at table '$table_name'\n");
268
269 #
270 # Header. Should this look like what mysqldump produces?
271 #
272 my $create = '';
273 my $drop;
274 $create .= "--\n-- Table: $table_name\n--\n" unless $options->{no_comments};
275 $drop = qq[DROP TABLE IF EXISTS $table_name] if $options->{add_drop_table};
276 $create .= "CREATE TABLE $table_name (\n";
277
278 #
279 # Fields
280 #
281 my @field_defs;
282 for my $field ( $table->get_fields ) {
283 push @field_defs, $self->create_field($field, $options);
284 }
285
286 #
287 # Indices
288 #
289 my @index_defs;
290 my %indexed_fields;
291 for my $index ( $table->get_indices ) {
292 push @index_defs, $self->create_index($index, $options);
293 $indexed_fields{ $_ } = 1 for $index->fields;
294 }
295
296 #
297 # Constraints -- need to handle more than just FK. -ky
298 #
299 my @constraint_defs;
300 my @constraints = $table->get_constraints;
301 for my $c ( @constraints ) {
94f42333 302 my $constr = $self->create_constraint($c, $options);
303 push @constraint_defs, $constr if($constr); #use Data::Dumper; warn Dumper($c->columns) if $constr =~ /^CONSTRAINT/; # unless $c->fields;
24e6a53a 304 next unless $c->fields;
94f42333 305
24e6a53a 306 unless ( $indexed_fields{ ($c->fields())[0] } || $c->type ne FOREIGN_KEY ) {
307 push @index_defs, "INDEX ($qf" . ($c->fields())[0] . "$qf)";
308 $indexed_fields{ ($c->fields())[0] } = 1;
309 }
310 }
94f42333 311
24e6a53a 312 $create .= join(",\n", map { " $_" }
313 @field_defs, @index_defs, @constraint_defs
314 );
94f42333 315
24e6a53a 316 #
317 # Footer
318 #
319 $create .= "\n)";
320 $create .= $self->generate_table_options($table, $options) || '';
321 # $create .= ";\n\n";
322
323 return $drop ? ($drop,$create) : $create;
324 }
325
326 method quote_table_name(Str $table_name, Str $qt) {
327 $table_name =~ s/\./$qt.$qt/g;
328
329 return "$qt$table_name$qt";
330 }
331
332 method generate_table_options(Table $table, $options?) {
333 my $create;
334
335 my $table_type_defined = 0;
336 my $qf = $options->{quote_field_names} ||= '';
337 my $charset = $table->extra->{'mysql_charset'};
338 my $collate = $table->extra->{'mysql_collate'};
339 my $union = undef;
94f42333 340
341 for my $t1_option_ref ($table->_options) {
24e6a53a 342 my($key, $value) = %{$t1_option_ref};
343 $table_type_defined = 1
344 if uc $key eq 'ENGINE' or uc $key eq 'TYPE';
345 if (uc $key eq 'CHARACTER SET') {
346 $charset = $value;
347 next;
348 } elsif (uc $key eq 'COLLATE') {
349 $collate = $value;
350 next;
351 } elsif (uc $key eq 'UNION') {
352 $union = "($qf". join("$qf, $qf", @$value) ."$qf)";
353 next;
354 }
355 $create .= " $key=$value";
356 }
357
358 my $mysql_table_type = $table->extra->{'mysql_table_type'};
359 $create .= " ENGINE=$mysql_table_type"
360 if $mysql_table_type && !$table_type_defined;
361 my $comments = $table->comments;
362
363 $create .= " DEFAULT CHARACTER SET $charset" if $charset;
364 $create .= " COLLATE $collate" if $collate;
365 $create .= " UNION=$union" if $union;
366 $create .= qq[ comment='$comments'] if $comments;
367 return $create;
368 }
369
370 method create_field($field, $options?) {
371 my $qf = $options->{quote_field_names} ||= '';
372
373 my $field_name = $field->name;
374 #debug("PKG: Looking at field '$field_name'\n");
375 my $field_def = "$qf$field_name$qf";
376
377 # data type and size
378 my $data_type = $field->data_type;
379 my @size = $field->size;
380 my %extra = $field->extra;
381 my $list = $extra{'list'} || [];
382 # \todo deal with embedded quotes
383 my $commalist = join( ', ', map { qq['$_'] } @$list );
384 my $charset = $extra{'mysql_charset'};
385 my $collate = $extra{'mysql_collate'};
386
387 my $mysql_version = $options->{mysql_version} || 0;
388 #
389 # Oracle "number" type -- figure best MySQL type
390 #
391 if ( lc $data_type eq 'number' ) {
392 # not an integer
393 if ( scalar @size > 1 ) {
394 $data_type = 'double';
395 }
396 elsif ( $size[0] && $size[0] >= 12 ) {
397 $data_type = 'bigint';
398 }
399 elsif ( $size[0] && $size[0] <= 1 ) {
400 $data_type = 'tinyint';
401 }
402 else {
403 $data_type = 'int';
404 }
405 }
406 #
407 # Convert a large Oracle varchar to "text"
408 # (not necessary as of 5.0.3 http://dev.mysql.com/doc/refman/5.0/en/char.html)
409 #
410 elsif ( $data_type =~ /char/i && $size[0] > 255 ) {
411 unless ($size[0] <= 65535 && $mysql_version >= 5.000003 ) {
412 $data_type = 'text';
413 @size = ();
414 }
415 }
416 elsif ( $data_type =~ /boolean/i ) {
417 if ($mysql_version >= 4) {
418 $data_type = 'boolean';
419 } else {
420 $data_type = 'enum';
421 $commalist = "'0','1'";
422 }
423 }
424# elsif ( exists $translate{ lc $data_type } ) {
425# $data_type = $translate{ lc $data_type };
426# }
427
428 @size = () if $data_type =~ /(text|blob)/i;
429
430 if ( $data_type =~ /(double|float)/ && scalar @size == 1 ) {
431 push @size, '0';
432 }
433
434 $field_def .= " $data_type";
435
436 if ( lc($data_type) eq 'enum' || lc($data_type) eq 'set') {
437 $field_def .= '(' . $commalist . ')';
438 }
439 elsif (
440 defined $size[0] && $size[0] > 0
441 &&
442 ! grep lc($data_type) eq $_, @no_length_attr
443 ) {
444 $field_def .= '(' . join( ', ', @size ) . ')';
445 }
446
447 # char sets
448 $field_def .= " CHARACTER SET $charset" if $charset;
449 $field_def .= " COLLATE $collate" if $collate;
450
451 # MySQL qualifiers
452 for my $qual ( qw[ binary unsigned zerofill ] ) {
453 my $val = $extra{ $qual } || $extra{ uc $qual } or next;
454 $field_def .= " $qual";
455 }
456 for my $qual ( 'character set', 'collate', 'on update' ) {
457 my $val = $extra{ $qual } || $extra{ uc $qual } or next;
458 $field_def .= " $qual $val";
459 }
460
461 # Null?
462 $field_def .= ' NOT NULL' unless $field->is_nullable;
463
464 # Default? XXX Need better quoting!
465 my $default = $field->default_value;
466=cut
467 if ( defined $default ) {
468 SQL::Translator::Producer->_apply_default_value(
469 \$field_def,
470 $default,
471 [
472 'NULL' => \'NULL',
473 ],
474 );
475 }
476=cut
477
478 if ( my $comments = $field->comments ) {
479 $field_def .= qq[ comment '$comments'];
480 }
481
482 # auto_increment?
483 $field_def .= " auto_increment" if $field->is_auto_increment;
484
485 return $field_def;
486 }
487
488 method alter_create_index(Index $index, $options?) {
489 my $qt = $options->{quote_table_names} || '';
490 my $qf = $options->{quote_field_names} || '';
491
492 return join( ' ',
493 'ALTER TABLE',
494 $qt.$index->table->name.$qt,
495 'ADD',
496 create_index(@_)
497 );
498 }
499
500 method create_index($index, $options?) {
501# my ( $index, $options ) = @_;
502
503 my $qf = $options->{quote_field_names} || '';
504
505 return join(
506 ' ',
507 map { $_ || () }
508 lc $index->type eq 'normal' ? 'INDEX' : $index->type . ' INDEX',
509 $index->name
510 ? (
511 $self->truncate_id_uniquely(
512 $index->name,
513 $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH
514 )
515 )
516 : '',
517 '(' . $qf . join( "$qf, $qf", $index->fields ) . $qf . ')'
518 );
519 }
520
521 method alter_drop_index(Index $index, $options?) {
522 my $qt = $options->{quote_table_names} || '';
523 my $qf = $options->{quote_field_names} || '';
524
525 return join( ' ',
526 'ALTER TABLE',
527 $qt.$index->table->name.$qt,
528 'DROP',
529 'INDEX',
530 $index->name || $index->fields
531 );
532
533 }
534
535 method alter_drop_constraint(Constraint $c, $options?) {
536 my $qt = $options->{quote_table_names} || '';
537 my $qc = $options->{quote_field_names} || '';
538
539 my $out = sprintf('ALTER TABLE %s DROP %s %s',
540 $qt . $c->table->name . $qt,
541 $c->type eq FOREIGN_KEY ? $c->type : "INDEX",
542 $qc . $c->name . $qc );
543
544 return $out;
545 }
546
547 method alter_create_constraint($index, $options?) {
548 my $qt = $options->{quote_table_names} || '';
549 return join( ' ',
550 'ALTER TABLE',
551 $qt.$index->table->name.$qt,
552 'ADD',
553 $self->create_constraint(@_) );
554 }
555
556 method create_constraint(Constraint $c, $options?) {
557 my $qf = $options->{quote_field_names} || '';
558 my $qt = $options->{quote_table_names} || '';
559 my $leave_name = $options->{leave_name} || undef;
560
561 my @fields = $c->fields or return;
562
563 if ( $c->type eq PRIMARY_KEY ) {
564 return 'PRIMARY KEY (' . $qf . join("$qf, $qf", @fields). $qf . ')';
565 }
566 elsif ( $c->type eq UNIQUE ) {
567 return
568 'UNIQUE '.
569 (defined $c->name ? $qf.$self->truncate_id_uniquely( $c->name, $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH ).$qf.' ' : '').
570 '(' . $qf . join("$qf, $qf", @fields). $qf . ')';
571 }
572 elsif ( $c->type eq FOREIGN_KEY ) {
573 #
574 # Make sure FK field is indexed or MySQL complains.
575 #
24e6a53a 576 my $table = $c->table;
577 my $c_name = $self->truncate_id_uniquely( $c->name, $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH );
578
579 my $def = join(' ',
580 map { $_ || () }
581 'CONSTRAINT',
582 $qf . $c_name . $qf,
583 'FOREIGN KEY'
584 );
585
586
587 $def .= ' ('.$qf . join( "$qf, $qf", @fields ) . $qf . ')';
94f42333 588
24e6a53a 589 $def .= ' REFERENCES ' . $qt . $c->reference_table . $qt;
24e6a53a 590 my @rfields = map { $_ || () } $c->reference_fields;
94f42333 591
24e6a53a 592 unless ( @rfields ) {
593 my $rtable_name = $c->reference_table;
594 if ( my $ref_table = $table->schema->get_table( $rtable_name ) ) {
595 push @rfields, $ref_table->primary_key;
596 }
597 else {
598 warn "Can't find reference table '$rtable_name' " .
599 "in schema\n" if $options->{show_warnings};
600 }
601 }
602
603 if ( @rfields ) {
604 $def .= ' (' . $qf . join( "$qf, $qf", @rfields ) . $qf . ')';
605 }
606 else {
607 warn "FK constraint on " . $table->name . '.' .
608 join('', @fields) . " has no reference fields\n"
609 if $options->{show_warnings};
610 }
611
612 if ( $c->match_type ) {
94f42333 613 $def .= ' MATCH ';
614 $def .= ( $c->match_type =~ /full/i ) ? 'FULL' : 'PARTIAL';
24e6a53a 615 }
94f42333 616# if ( $c->on_delete ) {
617# $def .= ' ON DELETE '.join( ' ', $c->on_delete );
618# }
24e6a53a 619
94f42333 620# if ( $c->on_update ) {
621# $def .= ' ON UPDATE '.join( ' ', $c->on_update );
622# }
24e6a53a 623 return $def;
624 }
625
626 return undef;
627 }
628
629 method alter_table(Str $to_table, $options?) {
630 my $qt = $options->{quote_table_names} || '';
631
632 my $table_options = $self->generate_table_options($to_table, $options) || '';
633 my $out = sprintf('ALTER TABLE %s%s',
634 $qt . $to_table->name . $qt,
635 $table_options);
636
637 return $out;
638 }
639
640 method rename_field(@args) { alter_field(@args) }
641 method alter_field(Str $from_field, Str $to_field, $options?) {
642 my $qf = $options->{quote_field_names} || '';
643 my $qt = $options->{quote_table_names} || '';
644
645 my $out = sprintf('ALTER TABLE %s CHANGE COLUMN %s %s',
646 $qt . $to_field->table->name . $qt,
647 $qf . $from_field->name . $qf,
648 $self->create_field($to_field, $options));
649
650 return $out;
651 }
652
653 method add_field(Str $new_field, $options?) {
654 my $qt = $options->{quote_table_names} || '';
655
656 my $out = sprintf('ALTER TABLE %s ADD COLUMN %s',
657 $qt . $new_field->table->name . $qt,
658 create_field($new_field, $options));
659
660 return $out;
661
662 }
663
664 method drop_field(Str $old_field, $options?) {
665 my $qf = $options->{quote_field_names} || '';
666 my $qt = $options->{quote_table_names} || '';
667
668 my $out = sprintf('ALTER TABLE %s DROP COLUMN %s',
669 $qt . $old_field->table->name . $qt,
670 $qf . $old_field->name . $qf);
671
672 return $out;
673
674 }
675
676 method batch_alter_table($table, $diff_hash, $options?) {
677 # InnoDB has an issue with dropping and re-adding a FK constraint under the
678 # name in a single alter statment, see: http://bugs.mysql.com/bug.php?id=13741
679 #
680 # We have to work round this.
681
682 my %fks_to_alter;
683 my %fks_to_drop = map {
684 $_->type eq FOREIGN_KEY
685 ? ( $_->name => $_ )
686 : ( )
687 } @{$diff_hash->{alter_drop_constraint} };
688
689 my %fks_to_create = map {
690 if ( $_->type eq FOREIGN_KEY) {
691 $fks_to_alter{$_->name} = $fks_to_drop{$_->name} if $fks_to_drop{$_->name};
692 ( $_->name => $_ );
693 } else { ( ) }
694 } @{$diff_hash->{alter_create_constraint} };
695
696 my @drop_stmt;
697 if (scalar keys %fks_to_alter) {
698 $diff_hash->{alter_drop_constraint} = [
699 grep { !$fks_to_alter{$_->name} } @{ $diff_hash->{alter_drop_constraint} }
700 ];
701
702 @drop_stmt = batch_alter_table($table, { alter_drop_constraint => [ values %fks_to_alter ] }, $options);
703
704 }
705
706 my @stmts = map {
707 if (@{ $diff_hash->{$_} || [] }) {
708 my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_";
709 map { $meth->( (ref $_ eq 'ARRAY' ? @$_ : $_), $options ) } @{ $diff_hash->{$_} }
710 } else { () }
711 } qw/rename_table
712 alter_drop_constraint
713 alter_drop_index
714 drop_field
715 add_field
716 alter_field
717 rename_field
718 alter_create_index
719 alter_create_constraint
720 alter_table/;
721
722 # rename_table makes things a bit more complex
723 my $renamed_from = "";
724 $renamed_from = $diff_hash->{rename_table}[0][0]->name
725 if $diff_hash->{rename_table} && @{$diff_hash->{rename_table}};
726
727 return unless @stmts;
728 # Just zero or one stmts. return now
729 return (@drop_stmt,@stmts) unless @stmts > 1;
730
731 # Now strip off the 'ALTER TABLE xyz' of all but the first one
732
733 my $qt = $options->{quote_table_names} || '';
734 my $table_name = $qt . $table->name . $qt;
735
736
737 my $re = $renamed_from
738 ? qr/^ALTER TABLE (?:\Q$table_name\E|\Q$qt$renamed_from$qt\E) /
739 : qr/^ALTER TABLE \Q$table_name\E /;
740
741 my $first = shift @stmts;
742 my ($alter_table) = $first =~ /($re)/;
743
744 my $padd = " " x length($alter_table);
745
746 return @drop_stmt, join( ",\n", $first, map { s/$re//; $padd . $_ } @stmts);
747
748 }
749
750 method drop_table(Str $table, $options?) {
751 my $qt = $options->{quote_table_names} || '';
752
753 # Drop (foreign key) constraints so table drops cleanly
754 my @sql = batch_alter_table($table, { alter_drop_constraint => [ grep { $_->type eq 'FOREIGN KEY' } $table->get_constraints ] }, $options);
755
756 return (@sql, "DROP TABLE $qt$table$qt");
757 # return join("\n", @sql, "DROP TABLE $qt$table$qt");
758
759 }
760
761 method rename_table(Str $old_table, Str $new_table, $options?) {
762 my $qt = $options->{quote_table_names} || '';
763
764 return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt";
765 }
766
767 method next_unused_name($name?) {
768# my $name = shift || '';
769 if ( !defined($used_names{$name}) ) {
770 $used_names{$name} = $name;
771 return $name;
772 }
773
774 my $i = 1;
775 while ( defined($used_names{$name . '_' . $i}) ) {
776 ++$i;
777 }
778 $name .= '_' . $i;
779 $used_names{$name} = $name;
780 return $name;
781 }
782
783 method header_comment($producer?, $comment_char?) {
784 $producer ||= caller;
785 my $now = scalar localtime;
786 my $DEFAULT_COMMENT = '-- ';
787
788 $comment_char = $DEFAULT_COMMENT
789 unless defined $comment_char;
790
791 my $header_comment =<<"HEADER_COMMENT";
792 ${comment_char}
793 ${comment_char}Created by $producer
794 ${comment_char}Created on $now
795 ${comment_char}
796HEADER_COMMENT
797
798 # Any additional stuff passed in
799 for my $additional_comment (@_) {
800 $header_comment .= "${comment_char}${additional_comment}\n";
801 }
802
803 return $header_comment;
804 }
805
f48e6f55 806 use constant COLLISION_TAG_LENGTH => 8;
24e6a53a 807
f48e6f55 808 method truncate_id_uniquely(Str $desired_name, Int $max_symbol_length) {
809 return $desired_name
810 unless defined $desired_name && length $desired_name > $max_symbol_length;
24e6a53a 811
f48e6f55 812 my $truncated_name = substr $desired_name, 0,
813 $max_symbol_length - COLLISION_TAG_LENGTH - 1;
24e6a53a 814
f48e6f55 815 # Hex isn't the most space-efficient, but it skirts around allowed
816 # charset issues
817 my $digest = sha1_hex($desired_name);
818 my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH;
24e6a53a 819
f48e6f55 820 return $truncated_name
821 . '_'
822 . $collision_tag;
24e6a53a 823 }
24e6a53a 824}