mysql icon indicating copy to clipboard operation
mysql copied to clipboard

Unique key columns duplicated with MariaDB

Open muety opened this issue 2 years ago • 1 comments

I came across the following bug. Sorry for skipping the playground, but the following code should be sufficient for reproducing the bug.

  • Gorm version: 1.23.5
  • Driver version: 1.3.3
  • MariaDB version: 10.7.3

Consider this script:

package main

import (
  "gorm.io/gorm"
  "gorm.io/driver/mysql"
)

type Product struct {
  gorm.Model
  Name string `gorm:"unique"`
}

func main() {
  db, err := gorm.Open(mysql.New(mysql.Config{
  	DriverName: "mysql",
  	DSN: "root:shhh@tcp(127.0.0.1:3306)/gormbug?charset=utf8mb4&parseTime=true&loc=Local&sql_mode=ANSI_QUOTES",
  	DontSupportRenameIndex:  true,
  	DontSupportRenameColumn: true,
 	SkipInitializeWithVersion: false,
  }), &gorm.Config{})
  if err != nil {
    panic("failed to connect database")
  }

  db.AutoMigrate(&Product{})
}

Steps to reproduce

  1. Run script (go run main.go)
  2. Check DDL (show create table products;)
CREATE TABLE `products` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) DEFAULT NULL,
  `updated_at` datetime(3) DEFAULT NULL,
  `deleted_at` datetime(3) DEFAULT NULL,
  `name` varchar(191) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `idx_products_deleted_at` (`deleted_at`)
  1. Run script again
  2. Check DDL again
CREATE TABLE `products` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) DEFAULT NULL,
  `updated_at` datetime(3) DEFAULT NULL,
  `deleted_at` datetime(3) DEFAULT NULL,
  `name` varchar(191) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `name_2` (`name`),
  KEY `idx_products_deleted_at` (`deleted_at`)

As you can see, each time the auto migration runs, a new name_* key statement is added.

muety avatar May 07 '22 07:05 muety

Did some digging and traced the issue back to this line. Looks like this is a general MariaDB issue, as running

alter table users modify column api_key varchar(191) unique;

manually results in a duplicated index as well, alongside the following warning message:

+-------+------+---------------------------------------------------------------------------------------------+
| Level | Code | Message                                                                                     |
+-------+------+---------------------------------------------------------------------------------------------+
| Note  | 1831 | Duplicate index `api_key_25`. This is deprecated and will be disallowed in a future release |
+-------+------+---------------------------------------------------------------------------------------------+

GORM's driver should nevertheless come up with some workaround to this.

EDIT: MySQL behaves the same.

muety avatar May 07 '22 20:05 muety

Latest version should fixed the issue.

jinzhu avatar Oct 08 '22 12:10 jinzhu