You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在执行Goose数据库迁移时指定环境(test、prod)及上下文?

在Goose中实现环境特定迁移与环境配置

一、实现类似Liquibase上下文的环境特定插入操作

Goose支持通过条件注释实现仅在指定环境执行的迁移代码,替代Liquibase的context功能,具体用法如下:

单环境生效代码

用-- +goose if env=<环境名>和-- +goose end包裹仅对应环境执行的SQL:

-- +goose Up
-- 所有环境都会执行的通用操作
CREATE TABLE IF NOT EXISTS app_configs (id INT PRIMARY KEY, key VARCHAR(255), value TEXT);

-- 仅test环境执行的插入
-- +goose if env=test
INSERT INTO app_configs (id, key, value) VALUES (1, 'env_type', 'test');
-- +goose end

-- 仅dev环境执行的插入
-- +goose if env=dev
INSERT INTO app_configs (id, key, value) VALUES (2, 'env_type', 'dev');
-- +goose end

-- +goose Down
DROP TABLE IF EXISTS app_configs;

多环境共享代码

如果一段代码需要在多个环境生效,用||连接环境名:

-- +goose if env=test||env=dev
-- test和dev环境都会执行这段插入
INSERT INTO app_configs (id, key, value) VALUES (3, 'debug_mode', 'true');
-- +goose end

二、执行迁移时指定数据库环境

有两种常用方式区分不同环境的数据库:

1. 用GOOSE_ENV环境变量指定环境

执行迁移前设置GOOSE_ENV变量,Goose会自动识别条件注释中的环境标识:

# 针对test环境执行迁移
GOOSE_ENV=test goose up

# 针对dev环境执行迁移
GOOSE_ENV=dev goose up

# 针对prod环境执行迁移
GOOSE_ENV=prod goose up

2. 用独立配置文件区分环境

为每个环境创建单独的Goose配置文件(比如goose-test.yaml、goose-prod.yaml),配置对应环境的数据库连接信息:

# goose-test.yaml示例
driver: postgres
dbname: test_app_db
host: localhost
user: test_user
password: test_pass
sslmode: disable

执行时通过-config参数指定配置文件:

# 使用test环境配置执行迁移
goose -config ./goose-test.yaml up

# 使用prod环境配置执行迁移
goose -config ./goose-prod.yaml up

也可以在配置文件中使用环境变量占位符,实现更灵活的配置:

# goose.yaml通用配置
driver: postgres
dbname: ${DB_NAME}
host: ${DB_HOST}
user: ${DB_USER}
password: ${DB_PASSWORD}
sslmode: ${DB_SSLMODE}

执行前设置对应环境的变量:

# 启动test环境迁移
export DB_NAME=test_app_db DB_HOST=localhost DB_USER=test_user DB_PASSWORD=test_pass DB_SSLMODE=disable
goose up

# 启动prod环境迁移
export DB_NAME=prod_app_db DB_HOST=prod-db.example.com DB_USER=prod_user DB_PASSWORD=prod_pass DB_SSLMODE=require
goose up

内容的提问来源于stack exchange,提问作者sdkdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:13:37