forked from peterldowns/pgmigrate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
108 lines (98 loc) · 3.14 KB
/
Copy pathmain.go
File metadata and controls
108 lines (98 loc) · 3.14 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"context"
"database/sql"
"embed"
"fmt"
"os"
"time"
"github.com/charmbracelet/log"
_ "github.com/lib/pq"
"github.com/geckoboard/pgmigrate"
)
// This is a simplified example of an application that will run a web server.
// Like any application using pgmigrate, it starts by connecting to the
// database and running pgmigrate.Migrate. If this fails, it exits. If it
// succeeds, it continues to running the server.
//
// You do not need to run migrations directly in your application -- for
// instance, you could use a kubernetes init container, or some other kind of
// initialization step to run the migrations via Docker or CLI before starting
// your web server. This is just one way to do it.
func main() {
ctx := context.Background()
logger := log.NewWithOptions(os.Stdout, log.Options{Formatter: log.TextFormatter})
logger.Info("connecting to the database")
db, err := sql.Open("postgres", "postgres://appuser:verysecret@localhost:5435/exampleapp?sslmode=disable")
if err != nil {
panic(err)
}
logger.Info("applying migrations")
err = applyMigrations(ctx, db, logger)
if err != nil {
panic(err)
}
logger.Info("running the web server")
runServer(ctx, db, logger)
}
// The migrations directory will be embedded into the application
// at build time. You can also ship your migration files next to the
// application and have it read them from disk. For more information,
// read the docs for pgmigrate.Load.
//
//go:embed migrations/*.sql
var migrationsFS embed.FS
// Does what it says!
func applyMigrations(ctx context.Context, db *sql.DB, logger *log.Logger) error {
verrs, err := pgmigrate.Migrate(ctx, db, migrationsFS, logAdapter{logger})
if err != nil {
return err
}
for _, verr := range verrs {
var vals []any
for key, val := range verr.Fields {
vals = append(vals, key, val)
}
logger.Warn(verr.Message, vals...)
}
return nil
}
// This is a fake, it just pretends to start a web server. It actually does
// nothing because this is just an example application to show off how
// migrations work.
func runServer(_ context.Context, _ *sql.DB, logger *log.Logger) {
fmt.Println("hello, world")
fmt.Println("(this isn't actually a working application but please pretend it is)")
for { // infinite loop, cancellable with ctrl-c
time.Sleep(5 * time.Second)
logger.Info("tick")
}
}
// This is an unavoidable annoyance -- in order to make pgmigrate work with
// various different logging libraries (zap, slog, logrus, etc.) it requires
// you to adapt your logger to its interface. This wraps the charm/log logger
// so that we can see the pgmigrate logs when the app starts up.
type logAdapter struct {
*log.Logger
}
func (l logAdapter) Log(
_ context.Context,
level pgmigrate.LogLevel,
msg string,
fields ...pgmigrate.LogField,
) {
args := make([]any, 0, 2*len(fields))
for _, field := range fields {
args = append(args, field.Key, field.Value)
}
switch level {
case pgmigrate.LogLevelDebug:
l.Logger.Debug(msg, args...)
case pgmigrate.LogLevelInfo:
l.Logger.Info(msg, args...)
case pgmigrate.LogLevelError:
l.Logger.Error(msg, args...)
case pgmigrate.LogLevelWarning:
l.Logger.Warn(msg, args...)
}
}