Commit | Line | Data |
24e6a53a |
1 | use MooseX::Declare; |
2 | role 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 |
5590bc43 |
134 | next if $extra_to_options->($table, 'mysql_table_type', ['ENGINE', 'TYPE']); |
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 | } |
7c0c8240 |
211 | |
24e6a53a |
212 | push @table_defs, "SET foreign_key_checks=1"; |
24e6a53a |
213 | return wantarray ? ($create ? $create : (), @create, @table_defs) : ($create . join('', map { $_ ? "$_;\n\n" : () } (@create, @table_defs))); |
214 | } |
215 | |
216 | method create_view($view, $options) { |
24e6a53a |
217 | my $qt = $options->{quote_table_names} || ''; |
218 | my $qf = $options->{quote_field_names} || ''; |
219 | |
220 | my $view_name = $view->name; |
221 | #debug("PKG: Looking at view '${view_name}'\n"); |
222 | |
223 | # Header. Should this look like what mysqldump produces? |
224 | my $create = ''; |
225 | $create .= "--\n-- View: ${qt}${view_name}${qt}\n--\n" unless $options->{no_comments}; |
226 | $create .= 'CREATE'; |
227 | $create .= ' OR REPLACE' if $options->{add_replace_view}; |
228 | $create .= "\n"; |
229 | |
230 | my $extra = $view->extra; |
231 | # ALGORITHM |
232 | if( exists($extra->{mysql_algorithm}) && defined(my $algorithm = $extra->{mysql_algorithm}) ){ |
233 | $create .= " ALGORITHM = ${algorithm}\n" if $algorithm =~ /(?:UNDEFINED|MERGE|TEMPTABLE)/i; |
234 | } |
235 | # DEFINER |
236 | if( exists($extra->{mysql_definer}) && defined(my $user = $extra->{mysql_definer}) ){ |
237 | $create .= " DEFINER = ${user}\n"; |
238 | } |
239 | # SECURITY |
240 | if( exists($extra->{mysql_security}) && defined(my $security = $extra->{mysql_security}) ){ |
241 | $create .= " SQL SECURITY ${security}\n" if $security =~ /(?:DEFINER|INVOKER)/i; |
242 | } |
243 | |
244 | #Header, cont. |
245 | $create .= " VIEW ${qt}${view_name}${qt}"; |
246 | |
247 | if( my @fields = $view->fields ){ |
248 | my $list = join ', ', map { "${qf}${_}${qf}"} @fields; |
249 | $create .= " ( ${list} )"; |
250 | } |
251 | if( my $sql = $view->sql ){ |
252 | $create .= " AS (\n ${sql}\n )"; |
253 | } |
24e6a53a |
254 | return $create; |
255 | } |
256 | |
257 | method create_table($table, $options) { |
24e6a53a |
258 | my $qt = $options->{quote_table_names} || ''; |
259 | my $qf = $options->{quote_field_names} || ''; |
260 | |
261 | my $table_name = $self->quote_table_name($table->name, $qt); |
262 | #debug("PKG: Looking at table '$table_name'\n"); |
263 | |
264 | # |
265 | # Header. Should this look like what mysqldump produces? |
266 | # |
267 | my $create = ''; |
268 | my $drop; |
269 | $create .= "--\n-- Table: $table_name\n--\n" unless $options->{no_comments}; |
270 | $drop = qq[DROP TABLE IF EXISTS $table_name] if $options->{add_drop_table}; |
271 | $create .= "CREATE TABLE $table_name (\n"; |
272 | |
273 | # |
274 | # Fields |
275 | # |
276 | my @field_defs; |
277 | for my $field ( $table->get_fields ) { |
278 | push @field_defs, $self->create_field($field, $options); |
279 | } |
280 | |
281 | # |
282 | # Indices |
283 | # |
284 | my @index_defs; |
285 | my %indexed_fields; |
286 | for my $index ( $table->get_indices ) { |
287 | push @index_defs, $self->create_index($index, $options); |
288 | $indexed_fields{ $_ } = 1 for $index->fields; |
289 | } |
290 | |
291 | # |
292 | # Constraints -- need to handle more than just FK. -ky |
293 | # |
294 | my @constraint_defs; |
295 | my @constraints = $table->get_constraints; |
296 | for my $c ( @constraints ) { |
94f42333 |
297 | my $constr = $self->create_constraint($c, $options); |
298 | push @constraint_defs, $constr if($constr); #use Data::Dumper; warn Dumper($c->columns) if $constr =~ /^CONSTRAINT/; # unless $c->fields; |
24e6a53a |
299 | next unless $c->fields; |
94f42333 |
300 | |
24e6a53a |
301 | unless ( $indexed_fields{ ($c->fields())[0] } || $c->type ne FOREIGN_KEY ) { |
302 | push @index_defs, "INDEX ($qf" . ($c->fields())[0] . "$qf)"; |
303 | $indexed_fields{ ($c->fields())[0] } = 1; |
304 | } |
305 | } |
94f42333 |
306 | |
24e6a53a |
307 | $create .= join(",\n", map { " $_" } |
308 | @field_defs, @index_defs, @constraint_defs |
309 | ); |
94f42333 |
310 | |
24e6a53a |
311 | # |
312 | # Footer |
313 | # |
314 | $create .= "\n)"; |
315 | $create .= $self->generate_table_options($table, $options) || ''; |
316 | # $create .= ";\n\n"; |
317 | |
318 | return $drop ? ($drop,$create) : $create; |
319 | } |
320 | |
321 | method quote_table_name(Str $table_name, Str $qt) { |
322 | $table_name =~ s/\./$qt.$qt/g; |
323 | |
324 | return "$qt$table_name$qt"; |
325 | } |
326 | |
327 | method generate_table_options(Table $table, $options?) { |
328 | my $create; |
329 | |
330 | my $table_type_defined = 0; |
331 | my $qf = $options->{quote_field_names} ||= ''; |
332 | my $charset = $table->extra->{'mysql_charset'}; |
333 | my $collate = $table->extra->{'mysql_collate'}; |
334 | my $union = undef; |
94f42333 |
335 | |
5590bc43 |
336 | for my $t1_option_ref ($table->options) { |
24e6a53a |
337 | my($key, $value) = %{$t1_option_ref}; |
338 | $table_type_defined = 1 |
339 | if uc $key eq 'ENGINE' or uc $key eq 'TYPE'; |
340 | if (uc $key eq 'CHARACTER SET') { |
341 | $charset = $value; |
342 | next; |
343 | } elsif (uc $key eq 'COLLATE') { |
344 | $collate = $value; |
345 | next; |
346 | } elsif (uc $key eq 'UNION') { |
347 | $union = "($qf". join("$qf, $qf", @$value) ."$qf)"; |
348 | next; |
349 | } |
350 | $create .= " $key=$value"; |
351 | } |
352 | |
353 | my $mysql_table_type = $table->extra->{'mysql_table_type'}; |
354 | $create .= " ENGINE=$mysql_table_type" |
355 | if $mysql_table_type && !$table_type_defined; |
356 | my $comments = $table->comments; |
357 | |
358 | $create .= " DEFAULT CHARACTER SET $charset" if $charset; |
359 | $create .= " COLLATE $collate" if $collate; |
360 | $create .= " UNION=$union" if $union; |
361 | $create .= qq[ comment='$comments'] if $comments; |
362 | return $create; |
363 | } |
364 | |
365 | method create_field($field, $options?) { |
366 | my $qf = $options->{quote_field_names} ||= ''; |
367 | |
368 | my $field_name = $field->name; |
369 | #debug("PKG: Looking at field '$field_name'\n"); |
370 | my $field_def = "$qf$field_name$qf"; |
371 | |
372 | # data type and size |
373 | my $data_type = $field->data_type; |
374 | my @size = $field->size; |
375 | my %extra = $field->extra; |
376 | my $list = $extra{'list'} || []; |
377 | # \todo deal with embedded quotes |
378 | my $commalist = join( ', ', map { qq['$_'] } @$list ); |
379 | my $charset = $extra{'mysql_charset'}; |
380 | my $collate = $extra{'mysql_collate'}; |
381 | |
382 | my $mysql_version = $options->{mysql_version} || 0; |
383 | # |
384 | # Oracle "number" type -- figure best MySQL type |
385 | # |
386 | if ( lc $data_type eq 'number' ) { |
387 | # not an integer |
388 | if ( scalar @size > 1 ) { |
389 | $data_type = 'double'; |
390 | } |
391 | elsif ( $size[0] && $size[0] >= 12 ) { |
392 | $data_type = 'bigint'; |
393 | } |
394 | elsif ( $size[0] && $size[0] <= 1 ) { |
395 | $data_type = 'tinyint'; |
396 | } |
397 | else { |
398 | $data_type = 'int'; |
399 | } |
400 | } |
401 | # |
402 | # Convert a large Oracle varchar to "text" |
403 | # (not necessary as of 5.0.3 http://dev.mysql.com/doc/refman/5.0/en/char.html) |
404 | # |
405 | elsif ( $data_type =~ /char/i && $size[0] > 255 ) { |
406 | unless ($size[0] <= 65535 && $mysql_version >= 5.000003 ) { |
407 | $data_type = 'text'; |
408 | @size = (); |
409 | } |
410 | } |
411 | elsif ( $data_type =~ /boolean/i ) { |
412 | if ($mysql_version >= 4) { |
413 | $data_type = 'boolean'; |
414 | } else { |
415 | $data_type = 'enum'; |
416 | $commalist = "'0','1'"; |
417 | } |
418 | } |
419 | # elsif ( exists $translate{ lc $data_type } ) { |
420 | # $data_type = $translate{ lc $data_type }; |
421 | # } |
422 | |
423 | @size = () if $data_type =~ /(text|blob)/i; |
424 | |
425 | if ( $data_type =~ /(double|float)/ && scalar @size == 1 ) { |
426 | push @size, '0'; |
427 | } |
428 | |
429 | $field_def .= " $data_type"; |
430 | |
431 | if ( lc($data_type) eq 'enum' || lc($data_type) eq 'set') { |
432 | $field_def .= '(' . $commalist . ')'; |
433 | } |
434 | elsif ( |
435 | defined $size[0] && $size[0] > 0 |
436 | && |
437 | ! grep lc($data_type) eq $_, @no_length_attr |
438 | ) { |
439 | $field_def .= '(' . join( ', ', @size ) . ')'; |
440 | } |
441 | |
442 | # char sets |
443 | $field_def .= " CHARACTER SET $charset" if $charset; |
444 | $field_def .= " COLLATE $collate" if $collate; |
445 | |
446 | # MySQL qualifiers |
447 | for my $qual ( qw[ binary unsigned zerofill ] ) { |
448 | my $val = $extra{ $qual } || $extra{ uc $qual } or next; |
449 | $field_def .= " $qual"; |
450 | } |
451 | for my $qual ( 'character set', 'collate', 'on update' ) { |
452 | my $val = $extra{ $qual } || $extra{ uc $qual } or next; |
453 | $field_def .= " $qual $val"; |
454 | } |
455 | |
456 | # Null? |
457 | $field_def .= ' NOT NULL' unless $field->is_nullable; |
458 | |
459 | # Default? XXX Need better quoting! |
460 | my $default = $field->default_value; |
e20b43c1 |
461 | |
462 | # if ( defined $default ) { |
463 | # SQL::Translator::Producer->_apply_default_value( |
464 | # \$field_def, |
465 | # $default, |
466 | # [ |
467 | # 'NULL' => \'NULL', |
468 | # ], |
469 | # ); |
470 | # } |
24e6a53a |
471 | |
472 | if ( my $comments = $field->comments ) { |
473 | $field_def .= qq[ comment '$comments']; |
474 | } |
475 | |
476 | # auto_increment? |
477 | $field_def .= " auto_increment" if $field->is_auto_increment; |
478 | |
479 | return $field_def; |
480 | } |
481 | |
482 | method alter_create_index(Index $index, $options?) { |
483 | my $qt = $options->{quote_table_names} || ''; |
484 | my $qf = $options->{quote_field_names} || ''; |
485 | |
486 | return join( ' ', |
487 | 'ALTER TABLE', |
488 | $qt.$index->table->name.$qt, |
489 | 'ADD', |
490 | create_index(@_) |
491 | ); |
492 | } |
493 | |
494 | method create_index($index, $options?) { |
495 | # my ( $index, $options ) = @_; |
496 | |
497 | my $qf = $options->{quote_field_names} || ''; |
498 | |
499 | return join( |
500 | ' ', |
501 | map { $_ || () } |
502 | lc $index->type eq 'normal' ? 'INDEX' : $index->type . ' INDEX', |
503 | $index->name |
504 | ? ( |
505 | $self->truncate_id_uniquely( |
506 | $index->name, |
507 | $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH |
508 | ) |
509 | ) |
510 | : '', |
511 | '(' . $qf . join( "$qf, $qf", $index->fields ) . $qf . ')' |
512 | ); |
513 | } |
514 | |
515 | method alter_drop_index(Index $index, $options?) { |
516 | my $qt = $options->{quote_table_names} || ''; |
517 | my $qf = $options->{quote_field_names} || ''; |
518 | |
519 | return join( ' ', |
520 | 'ALTER TABLE', |
521 | $qt.$index->table->name.$qt, |
522 | 'DROP', |
523 | 'INDEX', |
524 | $index->name || $index->fields |
525 | ); |
526 | |
527 | } |
528 | |
529 | method alter_drop_constraint(Constraint $c, $options?) { |
530 | my $qt = $options->{quote_table_names} || ''; |
531 | my $qc = $options->{quote_field_names} || ''; |
532 | |
533 | my $out = sprintf('ALTER TABLE %s DROP %s %s', |
534 | $qt . $c->table->name . $qt, |
535 | $c->type eq FOREIGN_KEY ? $c->type : "INDEX", |
536 | $qc . $c->name . $qc ); |
537 | |
538 | return $out; |
539 | } |
540 | |
541 | method alter_create_constraint($index, $options?) { |
542 | my $qt = $options->{quote_table_names} || ''; |
543 | return join( ' ', |
544 | 'ALTER TABLE', |
545 | $qt.$index->table->name.$qt, |
546 | 'ADD', |
547 | $self->create_constraint(@_) ); |
548 | } |
549 | |
550 | method create_constraint(Constraint $c, $options?) { |
551 | my $qf = $options->{quote_field_names} || ''; |
552 | my $qt = $options->{quote_table_names} || ''; |
553 | my $leave_name = $options->{leave_name} || undef; |
554 | |
555 | my @fields = $c->fields or return; |
556 | |
557 | if ( $c->type eq PRIMARY_KEY ) { |
558 | return 'PRIMARY KEY (' . $qf . join("$qf, $qf", @fields). $qf . ')'; |
559 | } |
560 | elsif ( $c->type eq UNIQUE ) { |
561 | return |
562 | 'UNIQUE '. |
563 | (defined $c->name ? $qf.$self->truncate_id_uniquely( $c->name, $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH ).$qf.' ' : ''). |
564 | '(' . $qf . join("$qf, $qf", @fields). $qf . ')'; |
565 | } |
566 | elsif ( $c->type eq FOREIGN_KEY ) { |
567 | # |
568 | # Make sure FK field is indexed or MySQL complains. |
569 | # |
24e6a53a |
570 | my $table = $c->table; |
571 | my $c_name = $self->truncate_id_uniquely( $c->name, $options->{max_id_length} || $DEFAULT_MAX_ID_LENGTH ); |
572 | |
573 | my $def = join(' ', |
574 | map { $_ || () } |
575 | 'CONSTRAINT', |
576 | $qf . $c_name . $qf, |
577 | 'FOREIGN KEY' |
578 | ); |
579 | |
580 | |
581 | $def .= ' ('.$qf . join( "$qf, $qf", @fields ) . $qf . ')'; |
94f42333 |
582 | |
24e6a53a |
583 | $def .= ' REFERENCES ' . $qt . $c->reference_table . $qt; |
24e6a53a |
584 | my @rfields = map { $_ || () } $c->reference_fields; |
94f42333 |
585 | |
24e6a53a |
586 | unless ( @rfields ) { |
587 | my $rtable_name = $c->reference_table; |
588 | if ( my $ref_table = $table->schema->get_table( $rtable_name ) ) { |
589 | push @rfields, $ref_table->primary_key; |
590 | } |
591 | else { |
592 | warn "Can't find reference table '$rtable_name' " . |
593 | "in schema\n" if $options->{show_warnings}; |
594 | } |
595 | } |
596 | |
597 | if ( @rfields ) { |
598 | $def .= ' (' . $qf . join( "$qf, $qf", @rfields ) . $qf . ')'; |
599 | } |
600 | else { |
601 | warn "FK constraint on " . $table->name . '.' . |
602 | join('', @fields) . " has no reference fields\n" |
603 | if $options->{show_warnings}; |
604 | } |
605 | |
606 | if ( $c->match_type ) { |
94f42333 |
607 | $def .= ' MATCH '; |
608 | $def .= ( $c->match_type =~ /full/i ) ? 'FULL' : 'PARTIAL'; |
24e6a53a |
609 | } |
94f42333 |
610 | # if ( $c->on_delete ) { |
611 | # $def .= ' ON DELETE '.join( ' ', $c->on_delete ); |
612 | # } |
24e6a53a |
613 | |
94f42333 |
614 | # if ( $c->on_update ) { |
615 | # $def .= ' ON UPDATE '.join( ' ', $c->on_update ); |
616 | # } |
24e6a53a |
617 | return $def; |
618 | } |
619 | |
620 | return undef; |
621 | } |
622 | |
623 | method alter_table(Str $to_table, $options?) { |
624 | my $qt = $options->{quote_table_names} || ''; |
625 | |
626 | my $table_options = $self->generate_table_options($to_table, $options) || ''; |
627 | my $out = sprintf('ALTER TABLE %s%s', |
628 | $qt . $to_table->name . $qt, |
629 | $table_options); |
630 | |
631 | return $out; |
632 | } |
633 | |
634 | method rename_field(@args) { alter_field(@args) } |
635 | method alter_field(Str $from_field, Str $to_field, $options?) { |
636 | my $qf = $options->{quote_field_names} || ''; |
637 | my $qt = $options->{quote_table_names} || ''; |
638 | |
639 | my $out = sprintf('ALTER TABLE %s CHANGE COLUMN %s %s', |
640 | $qt . $to_field->table->name . $qt, |
641 | $qf . $from_field->name . $qf, |
642 | $self->create_field($to_field, $options)); |
643 | |
644 | return $out; |
645 | } |
646 | |
647 | method add_field(Str $new_field, $options?) { |
648 | my $qt = $options->{quote_table_names} || ''; |
649 | |
650 | my $out = sprintf('ALTER TABLE %s ADD COLUMN %s', |
651 | $qt . $new_field->table->name . $qt, |
652 | create_field($new_field, $options)); |
653 | |
654 | return $out; |
655 | |
656 | } |
657 | |
658 | method drop_field(Str $old_field, $options?) { |
659 | my $qf = $options->{quote_field_names} || ''; |
660 | my $qt = $options->{quote_table_names} || ''; |
661 | |
662 | my $out = sprintf('ALTER TABLE %s DROP COLUMN %s', |
663 | $qt . $old_field->table->name . $qt, |
664 | $qf . $old_field->name . $qf); |
665 | |
666 | return $out; |
667 | |
668 | } |
669 | |
670 | method batch_alter_table($table, $diff_hash, $options?) { |
671 | # InnoDB has an issue with dropping and re-adding a FK constraint under the |
672 | # name in a single alter statment, see: http://bugs.mysql.com/bug.php?id=13741 |
673 | # |
674 | # We have to work round this. |
675 | |
676 | my %fks_to_alter; |
677 | my %fks_to_drop = map { |
678 | $_->type eq FOREIGN_KEY |
679 | ? ( $_->name => $_ ) |
680 | : ( ) |
681 | } @{$diff_hash->{alter_drop_constraint} }; |
682 | |
683 | my %fks_to_create = map { |
684 | if ( $_->type eq FOREIGN_KEY) { |
685 | $fks_to_alter{$_->name} = $fks_to_drop{$_->name} if $fks_to_drop{$_->name}; |
686 | ( $_->name => $_ ); |
687 | } else { ( ) } |
688 | } @{$diff_hash->{alter_create_constraint} }; |
689 | |
690 | my @drop_stmt; |
691 | if (scalar keys %fks_to_alter) { |
692 | $diff_hash->{alter_drop_constraint} = [ |
693 | grep { !$fks_to_alter{$_->name} } @{ $diff_hash->{alter_drop_constraint} } |
694 | ]; |
695 | |
696 | @drop_stmt = batch_alter_table($table, { alter_drop_constraint => [ values %fks_to_alter ] }, $options); |
697 | |
698 | } |
699 | |
700 | my @stmts = map { |
701 | if (@{ $diff_hash->{$_} || [] }) { |
702 | my $meth = __PACKAGE__->can($_) or die __PACKAGE__ . " cant $_"; |
703 | map { $meth->( (ref $_ eq 'ARRAY' ? @$_ : $_), $options ) } @{ $diff_hash->{$_} } |
704 | } else { () } |
705 | } qw/rename_table |
706 | alter_drop_constraint |
707 | alter_drop_index |
708 | drop_field |
709 | add_field |
710 | alter_field |
711 | rename_field |
712 | alter_create_index |
713 | alter_create_constraint |
714 | alter_table/; |
715 | |
716 | # rename_table makes things a bit more complex |
717 | my $renamed_from = ""; |
718 | $renamed_from = $diff_hash->{rename_table}[0][0]->name |
719 | if $diff_hash->{rename_table} && @{$diff_hash->{rename_table}}; |
720 | |
721 | return unless @stmts; |
722 | # Just zero or one stmts. return now |
723 | return (@drop_stmt,@stmts) unless @stmts > 1; |
724 | |
725 | # Now strip off the 'ALTER TABLE xyz' of all but the first one |
726 | |
727 | my $qt = $options->{quote_table_names} || ''; |
728 | my $table_name = $qt . $table->name . $qt; |
729 | |
730 | |
731 | my $re = $renamed_from |
732 | ? qr/^ALTER TABLE (?:\Q$table_name\E|\Q$qt$renamed_from$qt\E) / |
733 | : qr/^ALTER TABLE \Q$table_name\E /; |
734 | |
735 | my $first = shift @stmts; |
736 | my ($alter_table) = $first =~ /($re)/; |
737 | |
738 | my $padd = " " x length($alter_table); |
739 | |
740 | return @drop_stmt, join( ",\n", $first, map { s/$re//; $padd . $_ } @stmts); |
741 | |
742 | } |
743 | |
744 | method drop_table(Str $table, $options?) { |
745 | my $qt = $options->{quote_table_names} || ''; |
746 | |
747 | # Drop (foreign key) constraints so table drops cleanly |
748 | my @sql = batch_alter_table($table, { alter_drop_constraint => [ grep { $_->type eq 'FOREIGN KEY' } $table->get_constraints ] }, $options); |
749 | |
750 | return (@sql, "DROP TABLE $qt$table$qt"); |
751 | # return join("\n", @sql, "DROP TABLE $qt$table$qt"); |
752 | |
753 | } |
754 | |
755 | method rename_table(Str $old_table, Str $new_table, $options?) { |
756 | my $qt = $options->{quote_table_names} || ''; |
757 | |
758 | return "ALTER TABLE $qt$old_table$qt RENAME TO $qt$new_table$qt"; |
759 | } |
760 | |
761 | method next_unused_name($name?) { |
762 | # my $name = shift || ''; |
763 | if ( !defined($used_names{$name}) ) { |
764 | $used_names{$name} = $name; |
765 | return $name; |
766 | } |
767 | |
768 | my $i = 1; |
769 | while ( defined($used_names{$name . '_' . $i}) ) { |
770 | ++$i; |
771 | } |
772 | $name .= '_' . $i; |
773 | $used_names{$name} = $name; |
774 | return $name; |
775 | } |
776 | |
777 | method header_comment($producer?, $comment_char?) { |
778 | $producer ||= caller; |
779 | my $now = scalar localtime; |
780 | my $DEFAULT_COMMENT = '-- '; |
781 | |
782 | $comment_char = $DEFAULT_COMMENT |
783 | unless defined $comment_char; |
784 | |
785 | my $header_comment =<<"HEADER_COMMENT"; |
786 | ${comment_char} |
787 | ${comment_char}Created by $producer |
788 | ${comment_char}Created on $now |
789 | ${comment_char} |
790 | HEADER_COMMENT |
791 | |
792 | # Any additional stuff passed in |
793 | for my $additional_comment (@_) { |
794 | $header_comment .= "${comment_char}${additional_comment}\n"; |
795 | } |
796 | |
797 | return $header_comment; |
798 | } |
799 | |
f48e6f55 |
800 | use constant COLLISION_TAG_LENGTH => 8; |
24e6a53a |
801 | |
f48e6f55 |
802 | method truncate_id_uniquely(Str $desired_name, Int $max_symbol_length) { |
f77b076a |
803 | use Digest::SHA1 qw(sha1_hex); |
f48e6f55 |
804 | return $desired_name |
805 | unless defined $desired_name && length $desired_name > $max_symbol_length; |
24e6a53a |
806 | |
f48e6f55 |
807 | my $truncated_name = substr $desired_name, 0, |
808 | $max_symbol_length - COLLISION_TAG_LENGTH - 1; |
24e6a53a |
809 | |
f48e6f55 |
810 | # Hex isn't the most space-efficient, but it skirts around allowed |
811 | # charset issues |
812 | my $digest = sha1_hex($desired_name); |
813 | my $collision_tag = substr $digest, 0, COLLISION_TAG_LENGTH; |
24e6a53a |
814 | |
f48e6f55 |
815 | return $truncated_name |
816 | . '_' |
817 | . $collision_tag; |
24e6a53a |
818 | } |
24e6a53a |
819 | } |