登录
首页 >  Golang >  Go问答

使用 tern 迁移在 go test 容器内操作带有 postgres 数据库的任务

来源:stackoverflow

时间:2024-02-05 22:05:22 220浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《使用 tern 迁移在 go test 容器内操作带有 postgres 数据库的任务》,涉及到,有需要的可以收藏一下

问题内容

我正在尝试为我的 Postgres 数据库编写集成测试。为此,我在 Go 中使用测试容器。我已经在实际数据库中使用 tern 迁移,并将迁移放在迁移文件夹中。问题是我的一些迁移使用 .tern.conf 文件中的属性,因为这些值可能因环境而异。我为本地创建了一个类似的配置文件 local.tern.conf 并尝试设置全局变量。但由于某种原因,当我运行迁移时,这些值没有被选择。这是一个例子-

func SetupTestDatabase() *TestDatabase {
    // Set the TERN_CONFIG environment variable to the path of your local.tern.conf file
    if err := os.Setenv("TERN_CONFIG", "../local.tern.conf"); err != nil {
        // Handle error if setting the environment variable fails
        zap.S().Fatal("failed to set TERN_CONFIG", err)
    }

    // setup db container
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*60)
    defer cancel()

    container, dbInstance, dbAddr, err := createContainer(ctx)
    if err != nil {
        zap.S().Fatal("failed to setup test", err)
    }

    conn, _ := dbInstance.Acquire(ctx)
    m, err := migrate.NewMigrator(ctx, conn.Conn(), "schema_version_table")
    if err != nil {
        zap.S().Fatal("failed to setup migrator", err)
    }

    if err := m.LoadMigrations("../migrations"); err != nil {
        zap.S().Fatal("failed to load migrations", err)
        return nil
    }

    if len(m.Migrations) == 0 {
        zap.S().Fatal("no migrations found")
        return nil
    }

    if err := m.Migrate(ctx); err != nil {
        zap.S().Fatal("failed to migrate", err)
        return nil
    }

    return &TestDatabase{
        container:  container,
        DbInstance: dbInstance,
        DbAddress:  dbAddr,
    }
}

这是我的迁移的一部分 -

....
CREATE TABLE {{.version_table}} (
    version integer NOT NULL
);

alter table {{.version_table}}
    owner to {{.master_user}};
.....

这是 local.tern.conf-

[database]
 host = 
 port = 5432
 database = 
 version_table = schema_version_table

[data]
 master_user = 

正确答案


我猜配置文件必须针对 testcontainers-go 提供的随机端口,而不是 Postgres 的默认 5432 端口。您可能需要使用容器的 HostMappedPort 方法动态生成该文件,从 testcontainers-go 获取主机和随机端口。请参阅 https://golang.testcontainers.org/features/networking /#获取容器主机

ip, _ := nginxC.Host(ctx)
port, _ := nginxC.MappedPort(ctx, "80")
_, _ = http.Get(fmt.Sprintf("http://%s:%s", ip, port.Port()))

你能尝试一下吗?

另一种选择是使用“Testcontainers Desktop”,它允许定义给定服务(postgres)的端口,以透明的方式将对该端口的任何请求代理到随机端口。请参阅https://knowledge.testcontainers.cloud/fixed-ports

今天关于《使用 tern 迁移在 go test 容器内操作带有 postgres 数据库的任务》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>