diff --git a/lib/SQL/Translator/Producer/MySQL.pm b/lib/SQL/Translator/Producer/MySQL.pm index 5106dfb3e..f4518c766 100644 --- a/lib/SQL/Translator/Producer/MySQL.pm +++ b/lib/SQL/Translator/Producer/MySQL.pm @@ -460,6 +460,16 @@ sub create_table # my @constraint_defs; my @constraints = $table->get_constraints; + + # Mark fields which are first in a UNIQUE constraint as indexed if the + # constraint name is the same as the field. This is to prevent a duplicate + # index being created to support foreign keys. + for my $c ( @constraints ) { + if ($c->type eq UNIQUE && $c->name eq ($c->fields())[0]) { + $indexed_fields{ ($c->fields())[0] } = 1; + } + } + for my $c ( @constraints ) { my $constr = create_constraint($c, $options); push @constraint_defs, $constr if($constr); diff --git a/t/38-mysql-producer.t b/t/38-mysql-producer.t index b3c3bf88c..ef35b7719 100644 --- a/t/38-mysql-producer.t +++ b/t/38-mysql-producer.t @@ -194,6 +194,41 @@ schema: type: FOREIGN_KEY fields: foo2 name: fk_thing + + thing4: + name: thing4 + extra: + order: 4 + fields: + id: + name: id + data_type: int + is_primary_key: 0 + order: 1 + is_foreign_key: 1 + foo: + name: foo + data_type: int + order: 2 + is_not_null: 1 + foo2: + name: foo2 + data_type: int + order: 3 + is_not_null: 1 + constraints: + - type: UNIQUE + fields: + - foo + - foo2 + name: foo + - type: PRIMARY_KEY + fields: + - id + - reference_table: thing + type: FOREIGN_KEY + fields: foo + name: foo EOSCHEMA my @stmts = ( @@ -240,6 +275,16 @@ my @stmts = ( CONSTRAINT `fk_thing_3` FOREIGN KEY (`foo2`) REFERENCES `some`.`thing2` (`id`, `foo`) ) ENGINE=InnoDB", +"DROP TABLE IF EXISTS `thing4`", +"CREATE TABLE `thing4` ( + `id` integer NOT NULL, + `foo` integer NULL, + `foo2` integer NULL, + UNIQUE `foo` (`foo`, `foo2`), + PRIMARY KEY (`id`), + CONSTRAINT `foo` FOREIGN KEY (`foo`) REFERENCES `thing` (`id`) +) ENGINE=InnoDB", + "SET foreign_key_checks=1", );