I created a Postgres database in superbase.com and wanted to connect it to my Golang project using GORM. But when I try to migrate the table, it throws an error.
#database.go
package initializers
import (
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var DB *gorm.DB
func ConnectToDB() {
var err error
dsn := os.Getenv("DB_URL")
DB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(DB, "Failed to connect to database")
} else {
fmt.Println(DB, "Database connection established successfully")
}
}
#migrate.go
package main
import (
"GinGorm/initializers"
"GinGorm/models"
)
func init() {
initializers.LoadEnvVariables()
initializers.ConnectToDB()
}
func main() {
post := &models.Post{}
initializers.DB.Debug().AutoMigrate(post)
}
Error thrown on command: go run migrate/migrate.go
&{0xc0001ce480 0 0xc00005f6c0 1} Database connection established successfully panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x28 pc=0xc19372]
goroutine 1 [running]: gorm.io/gorm.(*DB).getInstance(0x70?) C:/Users/harsh/go/pkg/mod/gorm.io/gorm@v1.25.12/gorm.go:406 +0x12 gorm.io/gorm.(*DB).Debug(0x0) C:/Users/harsh/go/pkg/mod/gorm.io/gorm@v1.25.12/gorm.go:329 +0x18 main.main() D:/Code/Go/gin/GinGorm/migrate/migrate.go:15 +0x2e exit status 2
The failure is in the Debug
call. initializers.DB
is invalid. It was never initialized.
The problem is here...
DB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
DB, err :=
declares local DB
and err
variables. This local DB
is masking your global var DB *gorm.DB
.
Instead, declare just the err
and use =
var err error
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
Here's a demonstration of the difference.