gorm-goose

gorm-goose 是一款用于 gorm 的数据库迁移工具。「gorm-goose is a database migration tool for gorm - fork of https://bitbucket.org/liamstask/goose for gorm.」

Github stars Tracking Chart

请注意:GitHub 上已经 404 了!请选择其他 gorm 迁移工具,如 Gormigrate


gorm-goose

这是 https://bitbucket.org/liamstask/goose 的复刻版,用于 gorm

gorm-goose is a database migration tool for gorm. Currently, available drivers are: "postgres", "mysql", or "sqlite3".

gorm-goose 是用于 gorm 的数据库迁移工具。目前,可用的驱动程序有 "postgres"、"mysql "或 "sqlite3"。

您可以通过创建增量 SQL 或 Go 脚本来管理数据库的演变。

安装

$ go get github.com/Altoros/gorm-goose/cmd/gorm-goose
 

这将把 gorm-goose 二进制文件安装到 $GOPATH/bin 目录中。

您还可以通过导入 github.com/Altoros/gorm-goose/lib/gorm-goose 将 gorm-goose 构建到自己的应用程序中。

用法

gorm-goose 提供了多种命令来帮助管理数据库模式。

create

创建新的 Go 迁移。

$ gorm-goose create AddSomeColumns
$ goose: created db/migrations/20130106093224_AddSomeColumns.go
 

编辑新创建的脚本,定义迁移行为。

您还可以创建 SQL 迁移:

$ gorm-goose create AddSomeColumns sql
$ goose: created db/migrations/20130106093224_AddSomeColumns.sql
 

up

应用所有可用的迁移。

$ gorm-goose up
$ goose: migrating db environment 'development', current version: 0, target: 3
$ OK    001_basics.sql
$ OK    002_next.sql
$ OK    003_and_again.go
 

option: pgschema

使用 pgschema 标志和 up 命令指定 postgres 模式。

$ gorm-goose -pgschema=my_schema_name up
$ goose: migrating db environment 'development', current version: 0, target: 3
$ OK    001_basics.sql
$ OK    002_next.sql
$ OK    003_and_again.go
 

down

从当前版本回滚一次迁移。

$ gorm-goose down
$ goose: migrating db environment 'development', current version: 3, target: 2
$ OK    003_and_again.go
 

redo

回滚最近应用的迁移,然后重新运行。

$ gorm-goose redo
$ goose: migrating db environment 'development', current version: 3, target: 2
$ OK    003_and_again.go
$ goose: migrating db environment 'development', current version: 2, target: 3
$ OK    003_and_again.go
 

status

打印所有迁移的状态:

$ gorm-goose status
$ goose: status for environment 'development'
$   Applied At                  Migration
$   =======================================
$   Sun Jan  6 11:25:03 2013 -- 001_basics.sql
$   Sun Jan  6 11:25:03 2013 -- 002_next.sql
$   Pending                  -- 003_and_again.go
 

dbversion

打印数据库的当前版本:

$ gorm-goose dbversion
$ goose: dbversion 002
 

gorm-goose -h 提供了每条命令的更多详细信息。

Migrations

gorm-goose 支持以 SQL 或 Go 语言编写的迁移--有关如何生成迁移的详情,请参阅上文的 gorm-goose 创建命令。

SQL Migrations

SQL 迁移示例如下:

-- +goose Up
CREATE TABLE post (
    id int NOT NULL,
    title text,
    body text,
    PRIMARY KEY(id)
);

-- +goose Down
DROP TABLE post;
 

注意注释中的注释。任何跟在 -- +goose Up 后面的语句都将作为前向迁移的一部分执行,而任何跟在 -- +goose Down 后面的语句都将作为回滚的一部分执行。

默认情况下,SQL 语句以分号分隔--事实上,查询语句必须以分号结束,才能被 goose 正确识别。

内含分号的更复杂语句(PL/pgSQL)必须用 -- +goose StatementBegin 和 -- +goose StatementEnd 加以注释,才能正确识别。例如:

-- +goose Up
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION histories_partition_creation( DATE, DATE )
returns void AS $$
DECLARE
  create_query text;
BEGIN
  FOR create_query IN SELECT
      'CREATE TABLE IF NOT EXISTS histories_'
      || TO_CHAR( d, 'YYYY_MM' )
      || ' ( CHECK( created_at >= timestamp '''
      || TO_CHAR( d, 'YYYY-MM-DD 00:00:00' )
      || ''' AND created_at < timestamp '''
      || TO_CHAR( d + INTERVAL '1 month', 'YYYY-MM-DD 00:00:00' )
      || ''' ) ) inherits ( histories );'
    FROM generate_series( $1, $2, '1 month' ) AS d
  LOOP
    EXECUTE create_query;
  END LOOP;  -- LOOP END
END;         -- FUNCTION END
$$
language plpgsql;
-- +goose StatementEnd
 

Go Migrations

Go 迁移示例如下

package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
)

func Up_20130106222315(txn *gorm.DB) {
	fmt.Println("Hello from migration 20130106222315 Up!")
}

func Down_20130106222315(txn *gorm.DB) {
	fmt.Println("Hello from migration 20130106222315 Down!")
}
 

Up_20130106222315() 将作为前向迁移的一部分执行,而 Down_20130106222315() 将作为回滚的一部分执行。

函数名称(20130106222315)的数字部分必须是 migration 文件名的前导部分,如 20130106222315_descriptive_name.go。

由于 gorm-goose 还需要在同一事务中记录模式版本,因此提供的是事务而不是直接的数据库实例。每次迁移都应作为单个事务运行,以确保数据库的完整性,所以无论如何这都是个好做法。

配置

gorm-goose 希望您维护一个文件夹(通常称为 "db"),其中包含以下内容:

  • 描述要使用的数据库配置的 dbconf.yml 文件
  • 名为 "migrations" 的文件夹,其中包含实现迁移的 .sql 和/或 .go 脚本

你可以使用 -path 选项为包含配置和迁移信息的文件夹指定其他位置。

dbconf.yml 示例如下

development:
    driver: postgres
    open: user=liam dbname=tester sslmode=disable
 

在这里,development 指定环境名称,驱动程序和打开元素直接传递给 database/sql,以访问指定的数据库。

您可以随意添加多个环境,也可以使用 -env 命令行选项指定使用哪个环境。 gorm-goose 默认使用名为 development 的环境。

gorm-goose 会在开放元素中扩展环境变量。有关示例,请参阅下面的 Heroku 部分。

在 Heroku 中使用 goose

这些说明假定您使用的是 Keith Rarick's Heroku Go buildpack 构建包。首先,在项目中添加一个名为 install_goose.go(例如)的文件,以便在部署过程中触发 goose 可执行文件的构建,文件内容如下:

// use build constraints to work around http://code.google.com/p/go/issues/detail?id=4210
// +build heroku

// note: need at least one blank line after build constraint
package main

import _ "github.com/Altoros/gorm-goose/cmd/gorm-goose"
 

Set up your Heroku database(s) as usual.

然后在 dbconf.yml 中使用环境变量扩展:

production:
    driver: postgres
    open: $DATABASE_URL
 

要在生产环境中运行 gorm-goose,请使用 heroku run:

heroku run gorm-goose -env production up

 

Main metrics

Overview
Name With OwnerAltoros/gorm-goose
Primary LanguageGo
Program languageGo (Language Count: 1)
Platform
License:MIT License
所有者活动
Created At2017-08-30 11:13:09
Pushed At2023-06-30 20:43:57
Last Commit At2023-06-30 20:43:57
Release Count0
用户参与
Stargazers Count23
Watchers Count8
Fork Count10
Commits Count4
Has Issues Enabled
Issues Count5
Issue Open Count3
Pull Requests Count1
Pull Requests Open Count1
Pull Requests Close Count0
项目设置
Has Wiki Enabled
Is Archived
Is Fork
Is Locked
Is Mirror
Is Private

gorm-goose

This is a fork of https://bitbucket.org/liamstask/goose for gorm.

gorm-goose is a database migration tool for gorm.
Currently, available drivers are: "postgres", "mysql", or "sqlite3".

You can manage your database's evolution by creating incremental SQL or Go scripts.

Install

$ go get github.com/Altoros/gorm-goose/cmd/gorm-goose

This will install the gorm-goose binary to your $GOPATH/bin directory.

You can also build gorm-goose into your own applications by importing github.com/Altoros/gorm-goose/lib/gorm-goose.

Usage

gorm-goose provides several commands to help manage your database schema.

create

Create a new Go migration.

$ gorm-goose create AddSomeColumns
$ goose: created db/migrations/20130106093224_AddSomeColumns.go

Edit the newly created script to define the behavior of your migration.

You can also create an SQL migration:

$ gorm-goose create AddSomeColumns sql
$ goose: created db/migrations/20130106093224_AddSomeColumns.sql

up

Apply all available migrations.

$ gorm-goose up
$ goose: migrating db environment 'development', current version: 0, target: 3
$ OK    001_basics.sql
$ OK    002_next.sql
$ OK    003_and_again.go

option: pgschema

Use the pgschema flag with the up command specify a postgres schema.

$ gorm-goose -pgschema=my_schema_name up
$ goose: migrating db environment 'development', current version: 0, target: 3
$ OK    001_basics.sql
$ OK    002_next.sql
$ OK    003_and_again.go

down

Roll back a single migration from the current version.

$ gorm-goose down
$ goose: migrating db environment 'development', current version: 3, target: 2
$ OK    003_and_again.go

redo

Roll back the most recently applied migration, then run it again.

$ gorm-goose redo
$ goose: migrating db environment 'development', current version: 3, target: 2
$ OK    003_and_again.go
$ goose: migrating db environment 'development', current version: 2, target: 3
$ OK    003_and_again.go

status

Print the status of all migrations:

$ gorm-goose status
$ goose: status for environment 'development'
$   Applied At                  Migration
$   =======================================
$   Sun Jan  6 11:25:03 2013 -- 001_basics.sql
$   Sun Jan  6 11:25:03 2013 -- 002_next.sql
$   Pending                  -- 003_and_again.go

dbversion

Print the current version of the database:

$ gorm-goose dbversion
$ goose: dbversion 002

gorm-goose -h provides more detailed info on each command.

Migrations

gorm-goose supports migrations written in SQL or in Go - see the gorm-goose create command above for details on how to generate them.

SQL Migrations

A sample SQL migration looks like:

-- +goose Up
CREATE TABLE post (
    id int NOT NULL,
    title text,
    body text,
    PRIMARY KEY(id)
);

-- +goose Down
DROP TABLE post;

Notice the annotations in the comments. Any statements following -- +goose Up will be executed as part of a forward migration, and any statements following -- +goose Down will be executed as part of a rollback.

By default, SQL statements are delimited by semicolons - in fact, query statements must end with a semicolon to be properly recognized by goose.

More complex statements (PL/pgSQL) that have semicolons within them must be annotated with -- +goose StatementBegin and -- +goose StatementEnd to be properly recognized. For example:

-- +goose Up
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION histories_partition_creation( DATE, DATE )
returns void AS $$
DECLARE
  create_query text;
BEGIN
  FOR create_query IN SELECT
      'CREATE TABLE IF NOT EXISTS histories_'
      || TO_CHAR( d, 'YYYY_MM' )
      || ' ( CHECK( created_at >= timestamp '''
      || TO_CHAR( d, 'YYYY-MM-DD 00:00:00' )
      || ''' AND created_at < timestamp '''
      || TO_CHAR( d + INTERVAL '1 month', 'YYYY-MM-DD 00:00:00' )
      || ''' ) ) inherits ( histories );'
    FROM generate_series( $1, $2, '1 month' ) AS d
  LOOP
    EXECUTE create_query;
  END LOOP;  -- LOOP END
END;         -- FUNCTION END
$$
language plpgsql;
-- +goose StatementEnd

Go Migrations

A sample Go migration looks like:

package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
)

func Up_20130106222315(txn *gorm.DB) {
	fmt.Println("Hello from migration 20130106222315 Up!")
}

func Down_20130106222315(txn *gorm.DB) {
	fmt.Println("Hello from migration 20130106222315 Down!")
}

Up_20130106222315() will be executed as part of a forward migration, and Down_20130106222315() will be executed as part of a rollback.

The numeric portion of the function name (20130106222315) must be the leading portion of migration's filename, such as 20130106222315_descriptive_name.go. gorm-goose create does this by default.

A transaction is provided, rather than the DB instance directly, since gorm-goose also needs to record the schema version within the same transaction. Each migration should run as a single transaction to ensure DB integrity, so it's good practice anyway.

Configuration

gorm-goose expects you to maintain a folder (typically called "db"), which contains the following:

  • a dbconf.yml file that describes the database configurations you'd like to use
  • a folder called "migrations" which contains .sql and/or .go scripts that implement your migrations

You may use the -path option to specify an alternate location for the folder containing your config and migrations.

A sample dbconf.yml looks like

development:
    driver: postgres
    open: user=liam dbname=tester sslmode=disable

Here, development specifies the name of the environment, and the driver and open elements are passed directly to database/sql to access the specified database.

You may include as many environments as you like, and you can use the -env command line option to specify which one to use. gorm-goose defaults to using an environment called development.

gorm-goose will expand environment variables in the open element. For an example, see the Heroku section below.

Using goose with Heroku

These instructions assume that you're using Keith Rarick's Heroku Go buildpack. First, add a file to your project called (e.g.) install_goose.go to trigger building of the goose executable during deployment, with these contents:

// use build constraints to work around http://code.google.com/p/go/issues/detail?id=4210
// +build heroku

// note: need at least one blank line after build constraint
package main

import _ "github.com/Altoros/gorm-goose/cmd/gorm-goose"

Set up your Heroku database(s) as usual.

Then make use of environment variable expansion in your dbconf.yml:

production:
    driver: postgres
    open: $DATABASE_URL

To run gorm-goose in production, use heroku run:

heroku run gorm-goose -env production up