-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (84 loc) · 2.29 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"os"
"github.com/HeadHunter483/go-tg-bot/internal/config"
_ "github.com/HeadHunter483/go-tg-bot/migrations"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"github.com/pressly/goose/v3"
)
const dialect = "postgres"
var (
flags = flag.NewFlagSet("migrate", flag.ExitOnError)
dir = flags.String("dir", "migrations", "directory with migration files")
)
func main() {
flags.Usage = usage
flags.Parse(os.Args[1:])
args := flags.Args()
if len(args) == 0 || args[0] == "-h" || args[0] == "--help" {
flags.Usage()
return
}
command := args[0]
switch command {
case "create":
if err := goose.Run("create", nil, *dir, args[1:]...); err != nil {
log.Fatalf("migrate run: %v", err)
}
return
case "fix":
if err := goose.Run("fix", nil, *dir); err != nil {
log.Fatalf("migrate run: %v", err)
}
return
}
if err := godotenv.Load(); err != nil {
log.Print(".env file not found")
}
conf := config.New()
dbInfo := fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=%s",
conf.DB.Host, conf.DB.Port, conf.DB.User, conf.DB.Pass, conf.DB.Name)
appDb, err := sql.Open("postgres", dbInfo)
if err != nil {
log.Fatalf(err.Error())
}
defer appDb.Close()
if err := goose.SetDialect(dialect); err != nil {
log.Fatal(err)
}
if err := goose.Run(command, appDb, *dir, args[1:]...); err != nil {
log.Fatalf("migrate run: %v", err)
}
}
func usage() {
fmt.Println(usagePrefix)
flags.PrintDefaults()
fmt.Println(usageCommands)
}
var (
usagePrefix = `Usage: migrate [OPTIONS] COMMAND
Examples:
migrate status
Options:
`
usageCommands = `
Commands:
up Migrate the DB to the most recent version available
up-by-one Migrate the DB up by 1
up-to VERSION Migrate the DB to a specific VERSION
down Roll back the version by 1
down-to VERSION Roll back to a specific VERSION
redo Re-run the latest migration
reset Roll back all migrations
status Dump the migration status for the current DB
version Print the current version of the database
create NAME [sql|go] Creates new migration file with the current timestamp
fix Apply sequential ordering to migrations
`
)