使用库进行数据库迁移

huangapple go评论96阅读模式
英文:

Database Migration using library

问题

我正在尝试使用以下代码将数据库架构迁移到POSTGRESQL,但是它不起作用,返回了一个错误:

> "source driver: unknown driver file (forgotten import?)"

而使用CLI工具时它可以正常工作。

Up.sqldown.sql文件位于dbMigration文件夹中。

package main

import (
	"log"
	"github.com/golang-migrate/migrate"
)

func main() {
	mg, err := migrate.New(
		"file://dbMigration",
		"postgres://username:localhost:5432/databasename?sslmode=disable",
	)
	if err != nil {
		log.Fatal(err)
	}
	if err = mg.Up; err != nil {
		log.Fatal(err)
	}
}
英文:

I was trying to migrate database schema to POSTGRESQL using the code below
BUT it does not work, it returned an error

> "source driver: unknown driver file (forgotten import?)"

And it worked well using CLI

Up.sql and down.sql files are in dbMigration folder

package main

import (
	"log"
	"github.com/golang-migrate/migrate"
)

func main() {
	mg, err := migrate.New(
		"file://dbMigration",
		"postgres://username:localhost:5432/databasename?sslmode=disable",
	)
	if err != nil {
		log.Fatal(err)
	}
	if err = mg.Up; err != nil {
		log.Fatal(err)
	}
}

答案1

得分: 3

如果你在Go语言中使用数据库包,通常需要单独导入驱动程序。

这也是错误信息试图告诉你的。

source driver: unknown driver file (forgotten import?)

在golang-migrate中,你可以从他们的存储库中导入驱动程序。

import (
    "github.com/golang-migrate/migrate/v4"
    _ "github.com/golang-migrate/migrate/v4/database/postgres"
    _ "github.com/golang-migrate/migrate/v4/source/github"
)

这也在他们的readme中有记录。

英文:

If you use database packages in go, you usually need to import the driver separately.

That's also what the error is trying to tell you.

source driver: unknown driver file (forgotten import?)

In golang-migrate, you can import the driver from their repository.

import (
    "github.com/golang-migrate/migrate/v4"
    _ "github.com/golang-migrate/migrate/v4/database/postgres"
    _ "github.com/golang-migrate/migrate/v4/source/github"
)

This is also documented in their readme.

huangapple
  • 本文由 发表于 2022年1月23日 20:09:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/70821878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定