generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
migrate.go
41 lines (35 loc) · 932 Bytes
/
migrate.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
package sql
import (
"context"
"database/sql"
"embed"
"fmt"
"net/url"
"github.com/amacneil/dbmate/v2/pkg/dbmate"
_ "github.com/amacneil/dbmate/v2/pkg/driver/postgres"
_ "github.com/jackc/pgx/v5/stdlib" // SQL driver
"github.com/TBD54566975/ftl/internal/log"
)
//go:embed schema
var migrationSchema embed.FS
// Migrate the database.
func Migrate(ctx context.Context, dsn string) error {
u, err := url.Parse(dsn)
if err != nil {
return fmt.Errorf("%s: %w", "invalid DSN", err)
}
conn, err := sql.Open("pgx", dsn)
if err != nil {
return fmt.Errorf("%s: %w", "failed to connect to database", err)
}
defer conn.Close()
db := dbmate.New(u)
db.FS = migrationSchema
db.Log = log.FromContext(ctx).Scope("migrate").WriterAt(log.Debug)
db.MigrationsDir = []string{"schema"}
err = db.CreateAndMigrate()
if err != nil {
return fmt.Errorf("%s: %w", "failed to create and migrate database", err)
}
return nil
}