-
Notifications
You must be signed in to change notification settings - Fork 7
/
db.go
65 lines (50 loc) · 1.58 KB
/
db.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
package db
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/upsert --feature sql/modifier --feature sql/upsert --feature sql/versioned-migration ./schema --target ./model
import (
"context"
"database/sql"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/schema"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/pkg/errors"
"go.uber.org/fx"
"github.com/Southclaws/storyden/internal/config"
"github.com/Southclaws/storyden/internal/infrastructure/db/model"
)
func Build() fx.Option {
return fx.Provide(newDB)
}
func newDB(lc fx.Lifecycle, cfg config.Config) (*model.Client, *sql.DB, error) {
wctx, cancel := context.WithCancel(context.Background())
client, db, err := connect(wctx, cfg.DatabaseURL)
if err != nil {
cancel()
return nil, nil, err
}
lc.Append(fx.Hook{
OnStop: func(_ context.Context) error {
defer cancel()
return client.Close()
},
})
return client, db, nil
}
func connect(ctx context.Context, url string) (*model.Client, *sql.DB, error) {
driver, err := sql.Open("pgx", url)
if err != nil {
return nil, nil, errors.Wrap(err, "failed to connect to database")
}
client := model.NewClient(model.Driver(entsql.OpenDB(dialect.Postgres, driver)))
opts := []schema.MigrateOption{
schema.WithAtlas(true),
}
// We don't do versioned migrations currently.
opts = append(opts, schema.WithDropColumn(true))
opts = append(opts, schema.WithDropIndex(true))
// Run only additive migrations
if err := client.Schema.Create(ctx, opts...); err != nil {
return nil, nil, err
}
return client, driver, nil
}