我有一个简单的应用程序,使用golang-migrate/migrate with postgresql数据库。然而,当我调用Migration函数时,我想我会收到一个错误,因为我在migrate.New()中的sourceURL或databaseURL是无效的内存地址或空指针。
但我不确定为什么我的sourceURL或databaseURL会导致错误-我将sourceURL存储为file:///database/migration,这是我的sql文件存储的目录,将databaseURL存储为在Makefile中定义的postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable。
我的Makefile是这样的
migrate:
migrate -source file://database/migration \
-database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable up
rollback:
migrate -source file://database/migration \
-database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable down
drop:
migrate -source file://database/migration \
-database postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable drop
migration:
migrate create -ext sql -dir database/migration go_graphql
run:
go run main.go然后,我的main.go如下所示。
func main() {
ctx := context.Background()
config := config.New()
db := pg.New(ctx, config)
println("HEL")
if err := db.Migration(); err != nil {
log.Fatal(err)
}
fmt.Println("Server started")
}在main.go中调用db.Migration时出现错误
func (db *DB) Migration() error {
m, err := migrate.New("file:///database/migration/", "postgres://postgres:postgres@127.0.0.1:5432/go_graphql?sslmode=disable"))
println(m)
if err != nil {
// **I get error here!!**
return fmt.Errorf("error happened when migration")
}
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
return fmt.Errorf("error when migration up: %v", err)
}
log.Println("migration completed!")
return err
}这是我的config.go。DATABASE_URL与postgres URL相同
type database struct {
URL string
}
type Config struct {
Database database
}
func New() *Config {
godotenv.Load()
return &Config{
Database: database{
URL: os.Getenv("DATABASE_URL"),
},
}
}发布于 2021-09-05 08:48:44
通过您在评论error happened when migration source driver: unknown driver 'file' (forgotten import?)中发布的错误,我可以告诉您,如前所述,您忘记了导入file
import (
....
_ "github.com/golang-migrate/migrate/v4/source/file"
)您可以在Want to use an existing database client?一节中查看https://github.com/golang-migrate/migrate#use-in-your-go-project中的示例
https://stackoverflow.com/questions/69054061
复制相似问题