我有一个使用PostgreSQL的小型Go Web应用程序.

我的数据库驱动程序是pgx.现在,我希望在应用程序启动时自动运行migrations.我为此找到了goose个.

然而,我很难在pgx车手上使用goose.

当我运行我的代码时,我将得到:

Opening DB
2023/08/09 09:39:28 sql: unknown driver "pgx" (forgotten import?)

以下是主干道的缩写.开始:

package main

import (
"context"
"flag"
"fmt"
"log"
"os"

    _ "github.com/jackc/pgx/v5"
    "github.com/pressly/goose/v3"

)

func main() {

    // DSN is the PostgreSQL Data Source Name, Database Source Name.
    // Often the same as connection string.
    dsn := flag.String("dsn", "postgres://postgres:password@localhost:5555/plazet", "PostgreSQL data source name")
    flag.Parse()
    
    db, err := openDbConnectionPool(*dsn)
    if err != nil {
        fmt.Printf("Unable to connect to database: %v\n", err)
        os.Exit(1)
    }
    
    // Ping the database to check if the connection is working
    connection, err := db.Acquire(context.Background())
    if err != nil {
        fmt.Printf("Unable to acquire connection: %v\n", err)
        os.Exit(1)
    }
    
    println("Opening DB")
    
    sql, err := goose.OpenDBWithDriver("pgx", *dsn)
    if err != nil {
        log.Fatalf(err.Error())
    }
    
    println("Migrating")
    
    err = goose.Up(sql, "./migrations")
    if err != nil {
        log.Fatalf(err.Error())
    }
    
    defer connection.Release()
    
    defer db.Close()
    
    // Code for router and stuff...

}

我判断了OpenDBWithDriver,而PGx是一个预期值.在这种情况下,我遗漏了什么?

推荐答案

驱动程序pgxgithub.com/jackc/pgx/v5/stdlib包(source code)注册:

package stdlib

// ...

func init() {
    pgxDriver = &Driver{
        configs: make(map[string]*pgx.ConnConfig),
    }

    // if pgx driver was already registered by different pgx major version then we
    // skip registration under the default name.
    if !contains(sql.Drivers(), "pgx") {
        sql.Register("pgx", pgxDriver)
    }
    sql.Register("pgx/v5", pgxDriver)
    // ...

请try 导入该程序包:

import (
    _ "github.com/jackc/pgx/v5/stdlib"
    "github.com/pressly/goose/v3"
)

Go相关问答推荐

如何获得与cksum相同的CRC 32?

为什么在GO中打印变量会导致堆栈溢出?

向API网关终结点发出POST请求时出现AWS Lambda With Go:";Rune me.InvalidEntrypoint";错误

如何给杜松子wine 的路由加上一个名字,比如Laravel ?

Golang使用Run()执行的命令没有返回

使用Golang的Lambda自定义al2运行时,初始化阶段超时

如何获取集群外go Kubernetes客户端的当前命名空间?

我应该先解锁然后再广播吗?

使用Cookie身份验证的Gorilla Golang Websocket优化

Neptune 在连接到启用 IAM 的 Neptune 实例时抛出握手错误错误

如何模仿联合类型

如何使用 go-playground/validator 编写 snake case 绑定标签?

Golang Gin 绑定请求正文 XML 到 Slice

处理程序后访问 HTTP 请求上下文

使用go doc命令查看示例函数?

出于某种原因,Golang (Go) AES CBC 密文被填充了 16 个 0x00 字节

从 Go struct 中提取标签作为 reflect.Value

如何正确判断 io.Reader 是否为零?

正则表达式处理数字签名的多个条目

空接口与泛型接口有何不同?