-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmigrations.go
More file actions
66 lines (51 loc) · 1.52 KB
/
Copy pathmigrations.go
File metadata and controls
66 lines (51 loc) · 1.52 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
package floxy
import (
"context"
"embed"
"errors"
"fmt"
"net/url"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/iofs"
_ "github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/jackc/pgx/v5/pgxpool"
_ "github.com/lib/pq"
)
const dbSchema = "workflows"
//go:embed migrations/*.sql
var migrationFiles embed.FS
// RunMigrations executes all migration files in order
func RunMigrations(ctx context.Context, pool *pgxpool.Pool) error {
fmt.Println("[floxy] up migrations...")
_, err := pool.Exec(ctx, "CREATE SCHEMA IF NOT EXISTS "+dbSchema)
if err != nil {
return err
}
connString := pool.Config().ConnString()
connStringURL, err := url.Parse(connString)
if err != nil {
return fmt.Errorf("parsing connection string: %w", err)
}
values := connStringURL.Query()
values.Set("search_path", dbSchema) // set db schema
connStringURL.RawQuery = values.Encode()
connString = connStringURL.String()
driver, err := iofs.New(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("open migration files: %w", err)
}
migrator, err := migrate.NewWithSourceInstance("iofs", driver, connString)
if err != nil {
return fmt.Errorf("init migrator: %w", err)
}
if err := migrator.Up(); err != nil {
if errors.Is(err, migrate.ErrNoChange) {
fmt.Println("[floxy] up migrations: no changes")
return nil
}
return fmt.Errorf("run migrations: %w", err)
}
fmt.Println("[floxy] up migrations done")
return nil
}