GORM Playground Link

https://github.com/go-gorm/playground/pull/1

Description

old table:

CREATE TABLE `workspace_binding` (
  `toolchain_id` int NOT NULL,
  `workspace_id` int NOT NULL,
  `resource_id` int NOT NULL,
  UNIQUE KEY `tid_wid_rid_unique_index` (`toolchain_id`,`workspace_id`,`resource_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3

new talbe:

CREATE TABLE `workspace_binding_ddd` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) DEFAULT NULL,
  `updated_at` datetime(3) DEFAULT NULL,
  `toolchain_id` bigint NOT NULL,
  `workspace_id` bigint NOT NULL,
  `resource_id` bigint NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `tid_wid_rid_unique_index` (`toolchain_id`,`workspace_id`,`resource_id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb3

when auto migrate, the error is:

ALTER TABLE `workspace_binding` ADD `id` bigint AUTO_INCREMENT
Incorrect table definition; there can be only one auto column and it must be defined as a key

The statement should be: ALTER TABLEworkspace_bindingADDidbigint AUTO_INCREMENT primary key, the primary key missed is there any solution?

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: ckganesan

Hi @usernameisnull

I have raised a pull request for your issues. #129

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: ckganesan

@usernameisnull

The mentioned pull request will take some time to merge. Meanwhile, you can use the following code for a temporary fix.

package main

import (
    "fmt"
    "strings"

    driver "github.com/go-sql-driver/mysql"
    "gorm.io/gorm/clause"

    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/migrator"
)

type Migrator struct {
    mysql.Migrator
}

func (m Migrator) AddColumn(value interface{}, name string) error {
    return m.RunWithValue(value, func(stmt *gorm.Statement) error {
        // avoid using the same name field
        f := stmt.Schema.LookUpField(name)
        if f == nil {
            return fmt.Errorf("failed to look up field with name: %s", name)
        }

        if !f.IgnoreMigration {
            fieldType := m.FullDataTypeOf(f)
            columnName := clause.Column{Name: f.DBName}
            values := []interface{}{m.CurrentTable(stmt), columnName, fieldType}
            var alterSql strings.Builder
            alterSql.WriteString("ALTER TABLE ? ADD ? ?")
            if f.PrimaryKey || strings.Contains(strings.ToLower(fieldType.SQL), "auto_increment") {
                alterSql.WriteString(", ADD PRIMARY KEY (?)")
                values = append(values, columnName)
            }
            return m.DB.Exec(alterSql.String(), values...).Error
        }

        return nil
    })
}

type Dialector struct {
    mysql.Dialector
}

func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator {
    return Migrator{
        Migrator: mysql.Migrator{
            Migrator: migrator.Migrator{
                Config: migrator.Config{
                    DB:        db,
                    Dialector: dialector,
                },
            },
            Dialector: dialector.Dialector,
        },
    }
}

func Open(dsn string) gorm.Dialector {
    dsnConf, _ := driver.ParseDSN(dsn)
    return &Dialector{Dialector: mysql.Dialector{Config: &mysql.Config{DSN: dsn, DSNConfig: dsnConf}}}
}

func New(config mysql.Config) gorm.Dialector {
    switch {
    case config.DSN == "" && config.DSNConfig != nil:
        config.DSN = config.DSNConfig.FormatDSN()
    case config.DSN != "" && config.DSNConfig == nil:
        config.DSNConfig, _ = driver.ParseDSN(config.DSN)
    }
    return &Dialector{Dialector: mysql.Dialector{Config: &config}}
}

type Author struct {
    ID    uint `gorm:"primaryKey"`
    Name  string
    Email string
}

func main() {
    dsn := "root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local"
    db, err := gorm.Open(Open(dsn), &gorm.Config{})
    if err != nil {
        fmt.Println(err)
    } else {
        db.Migrator().AutoMigrate(&Author{})
    }

}

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: ckganesan

GORM Playground Link

#631

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: usernameisnull

@usernameisnull

The mentioned pull request will take some time to merge. Meanwhile, you can use the following code for a temporary fix.

``` package main

import ( "fmt" "strings"

driver "github.com/go-sql-driver/mysql" "gorm.io/gorm/clause"

"gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/migrator" )

type Migrator struct { mysql.Migrator }

func (m Migrator) AddColumn(value interface{}, name string) error { return m.RunWithValue(value, func(stmt *gorm.Statement) error { // avoid using the same name field f := stmt.Schema.LookUpField(name) if f == nil { return fmt.Errorf("failed to look up field with name: %s", name) }

  if !f.IgnoreMigration {
      fieldType := m.FullDataTypeOf(f)
      columnName := clause.Column{Name: f.DBName}
      values := []interface{}{m.CurrentTable(stmt), columnName, fieldType}
      var alterSql strings.Builder
      alterSql.WriteString("ALTER TABLE ? ADD ? ?")
      if f.PrimaryKey || strings.Contains(strings.ToLower(fieldType.SQL), "auto_increment") {
          alterSql.WriteString(", ADD PRIMARY KEY (?)")
          values = append(values, columnName)
      }
      return m.DB.Exec(alterSql.String(), values...).Error
  }

  return nil

}) }

type Dialector struct { mysql.Dialector }

func (dialector Dialector) Migrator(db *gorm.DB) gorm.Migrator { return Migrator{ Migrator: mysql.Migrator{ Migrator: migrator.Migrator{ Config: migrator.Config{ DB: db, Dialector: dialector, }, }, Dialector: dialector.Dialector, }, } }

func Open(dsn string) gorm.Dialector { dsnConf, _ := driver.ParseDSN(dsn) return &Dialector{Dialector: mysql.Dialector{Config: &mysql.Config{DSN: dsn, DSNConfig: dsnConf}}} }

func New(config mysql.Config) gorm.Dialector { switch { case config.DSN == "" && config.DSNConfig != nil: config.DSN = config.DSNConfig.FormatDSN() case config.DSN != "" && config.DSNConfig == nil: config.DSNConfig, _ = driver.ParseDSN(config.DSN) } return &Dialector{Dialector: mysql.Dialector{Config: &config}} }

type Author struct { ID uint gorm:"primaryKey" Name string Email string }

func main() { dsn := "root:root@tcp(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local" db, err := gorm.Open(Open(dsn), &gorm.Config{}) if err != nil { fmt.Println(err) } else { db.Migrator().AutoMigrate(&Author{}) }

} ```

ok, I'll try

Comment From: ckganesan

@usernameisnull

can you update gorm playground link with this url https://github.com/go-gorm/playground/pull/631

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking