Go goose
Contents
Goose
数据库版本管理
集成
package main
import (
"context"
"flag"
"log"
"os"
"github.com/pressly/goose/v3"
_ "modernc.org/sqlite"
)
var (
flags = flag.NewFlagSet("goose", flag.ExitOnError)
dir = flags.String("dir", ".", "directory with migration files")
)
func main() {
flags.Parse(os.Args[1:])
args := flags.Args()
if len(args) < 3 {
flags.Usage()
return
}
dbstring, command := args[1], args[2]
db, err := goose.OpenDBWithDriver("sqlite", dbstring)
if err != nil {
log.Fatalf("goose: failed to open DB: %v\n", err)
}
defer func() {
if err := db.Close(); err != nil {
log.Fatalf("goose: failed to close DB: %v\n", err)
}
}()
arguments := []string{}
if len(args) > 3 {
arguments = append(arguments, args[3:]...)
}
if err := goose.RunContext(context.Background(), command, db, *dir, arguments...); err != nil {
log.Fatalf("goose %v: %v", command, err)
}
}
使用
[root@Sugar goose]🐳 ./cccs sqlite3 ./foo.db status
2024/11/24 15:28:17 goose status: failed to collect migrations: no migration files found
[root@Sugar goose]🐳 ./cccs sqlite3 ./foo.db status -dir dbFile
2024/11/24 15:28:32 goose status: failed to collect migrations: no migration files found
[root@Sugar goose]🐳 ./cccs -dir dbFile sqlite3 ./foo.db status
2024/11/24 15:28:51 Applied At Migration
2024/11/24 15:28:51 =======================================
2024/11/24 15:28:51 Pending -- 20241124142616_v24_2_1_add_some_column.sql
[root@Sugar goose]🐳 ./cccs -dir dbFile sqlite3 ./foo.db up
2024/11/24 15:29:05 OK 202411xxxx2616_v24_2_1_add_some_column.sql (2.57ms)
2024/11/24 15:29:05 goose: successfully migrated database to version: 20241124142616
[root@Sugar goose]🐳 ./cccs -dir dbFile sqlite3 ./foo.db down
2024/11/24 15:31:04 OK 20241124142616_v24_2_1_add_some_column.sql (2.96ms)
[root@Sugar goose]🐳 ./cccs -dir dbFile sqlite3 ./foo.db up
2024/11/24 15:32:08 OK 20241124142616_v24_2_1_add_some_column.sql (2.77ms)
2024/11/24 15:32:08 goose: successfully migrated database to version: 20241124142616
[root@Sugar goose]🐳