GORM Playground Link
https://github.com/go-gorm/playground/pull/647
Description
I've been trying to work around SQLite's limitation of not being able to modify columns by creating a new table with AutoMigrate and copying the contents of the original table over before deleting the original table and renaming the new one to the name of the origin one.
Like so:
db.Table("foo_temp").AutoMigrate(&Foo{})
Unfortunately this triggers a panic for my type Foo. The playground link contains a minimal example that reproduces the issue.
Expected behaviour would be a more meaningful error in case what I'm trying to do is illegal.
Stacktrace:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x104f4a2f4]
goroutine 5 [running]:
testing.tRunner.func1.2({0x105670380, 0x105b9f9b0})
/opt/homebrew/Cellar/go/1.21.0/libexec/src/testing/testing.go:1545 +0x274
testing.tRunner.func1()
/opt/homebrew/Cellar/go/1.21.0/libexec/src/testing/testing.go:1548 +0x448
panic({0x105670380?, 0x105b9f9b0?})
/opt/homebrew/Cellar/go/1.21.0/libexec/src/runtime/panic.go:920 +0x26c
gorm.io/gorm/migrator.Migrator.ReorderModels({{0x8?, 0xc0004f9e60?, {0x105741c68?, 0xc0004f9e90?}}}, {0xc0005e6700, 0x1, 0xc000194c18?}, 0x1)
/Users/cschinnerl/go/src/github.com/ChrisSchinnerl/playground/gorm/migrator/migrator.go:939 +0x644
gorm.io/gorm/migrator.Migrator.AutoMigrate({{0x80?, 0xc0004f9e60?, {0x105741c68?, 0xc0004f9e90?}}}, {0xc0005e6700, 0x1, 0x1})
/Users/cschinnerl/go/src/github.com/ChrisSchinnerl/playground/gorm/migrator/migrator.go:113 +0x74
gorm.io/gorm.(*DB).AutoMigrate(0xc000194e78?, {0xc0005e6700, 0x1, 0x1})
/Users/cschinnerl/go/src/github.com/ChrisSchinnerl/playground/gorm/migrator.go:24 +0x54
gorm.io/playground.TestGORM(0x0?)
/Users/cschinnerl/go/src/github.com/ChrisSchinnerl/playground/main_test.go:22 +0xdc
testing.tRunner(0xc00048eb60, 0x105733e38)
/opt/homebrew/Cellar/go/1.21.0/libexec/src/testing/testing.go:1595 +0x198
created by testing.(*T).Run in goroutine 1
/opt/homebrew/Cellar/go/1.21.0/libexec/src/testing/testing.go:1648 +0x5dc
FAIL gorm.io/playground 0.235s
Comment From: LicketySpliket
What if you change primarykey to primaryKey? I wonder if the capitalization prevents finding a key for the JOIN table.
Comment From: ninepointsvn
To use custom table name with AutoMigrate() you should make the struct implement Tabler interface like this:
func (f Foo) TableName() string {
return "foo_temp"
}
Then
db.AutoMigrate(&Bar{}, &Foo{})