Your Question
is there a way to add additional methods to gorm.DB? i want to make some wrappers for existing gorm.DB methods and the usual way of defining a new type seems to panic.
The document you expected this should be explained
the main docs, most likely.
Expected answer
something like this:
type DB struct {
gorm.DB
}
func GetDatabase() (*DB, err) {
db, err := gorm.Open(/* ... */)
return &DB{*db}
}
func (db *DB) Migrate() {
db.AutoMigrate(&User{})
}
func main() {
db, _ := GetDatabase()
db.Migrate()
}
alas, when i run it, it panics:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x888798]
goroutine 1 [running]:
gorm.io/gorm.(*DB).getInstance(0x40f46a?)
/home/sfr/.local/share/go/pkg/mod/gorm.io/gorm@v1.25.1/gorm.go:390 +0x18
gorm.io/gorm.(*DB).Migrator(0x40f847?)
/home/sfr/.local/share/go/pkg/mod/gorm.io/gorm@v1.25.1/migrator.go:12 +0x19
gorm.io/gorm.(*DB).AutoMigrate(0xc000207880?, {0xc0002d4250, 0x1, 0x1})
/home/sfr/.local/share/go/pkg/mod/gorm.io/gorm@v1.25.1/migrator.go:24 +0x28
git.sr.ht/~sfr/celatum/database.(*DB).Migrate(...)
/home/sfr/src/celatum/database/database.go:44
main.main()
/home/sfr/src/celatum/main.go:35 +0x1e5
exit status 2
Comment From: black-06
It works:
type DB struct {
*gorm.DB
}
func GetDatabase() *DB {
db, _ := gorm.Open(/* ... */)
return &DB{DB: db}
}
func (db *DB) Migrate() {
type User struct {
ID int
Name string
}
db.Debug().AutoMigrate(&User{})
}
func TestMyDB(t *testing.T) {
database := GetDatabase()
database.Migrate()
}
Maybe you should create a playground pr