From f0884b23e829b139a83cd9c00b792e254a014d0a Mon Sep 17 00:00:00 2001 From: libvoid <135131094+libvoid@users.noreply.github.com> Date: Wed, 19 Aug 2026 17:47:59 +0200 Subject: [PATCH] fix(migrator): drop duplicate PRIMARY KEY clause in AlterColumn AlterColumn rewrites a column's definition using FullDataTypeOf, which inlines "PRIMARY KEY AUTOINCREMENT" for autoincrement fields. If the table's DDL already declared that column's primary key as a separate "PRIMARY KEY (`col`)" table constraint, that clause was never removed producing a CREATE TABLE with two primary key definitions and failing with "table ... has more than one primary key". We need to look for a matching standalone PRIMARY KEY clause referencing that column alone and drop it. Composite primary keys are left untouched, since they parse to more than one column. This commit fixes a regression introduced since 139bd307e5272318b407f578ed99ecc726cab544 (v1.5.4) --- migrator.go | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/migrator.go b/migrator.go index 563a8a3..cfa7fe8 100644 --- a/migrator.go +++ b/migrator.go @@ -89,7 +89,18 @@ func (m Migrator) AlterColumn(value interface{}, name string) error { for i, f := range ddl.fields { if matches := columnRegexp.FindStringSubmatch(f); len(matches) > 1 && matches[1] == field.DBName { ddl.fields[i] = fmt.Sprintf("`%v` ?", field.DBName) - sqlArgs = []interface{}{m.FullDataTypeOf(field)} + dataType := m.FullDataTypeOf(field) + sqlArgs = []interface{}{dataType} + if strings.Contains(strings.ToUpper(dataType.SQL), "PRIMARY KEY") { + for j, g := range ddl.fields { + if strings.HasPrefix(strings.ToUpper(g), "PRIMARY KEY") { + if cols, err := parseAllColumns(g); err == nil && len(cols) == 1 && cols[0] == field.DBName { + ddl.fields = append(ddl.fields[:j], ddl.fields[j+1:]...) + break + } + } + } + } // table created by old version might look like `CREATE TABLE ? (? varchar(10) UNIQUE)`. // FullDataTypeOf doesn't contain UNIQUE, so we need to add unique constraint. if strings.Contains(strings.ToUpper(matches[3]), " UNIQUE") {