-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
79 lines (64 loc) · 1.84 KB
/
common.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
package bun
import (
"context"
"github.com/tyrm/megabot"
"github.com/tyrm/megabot/internal/db"
"github.com/tyrm/megabot/internal/db/bun/migrations"
"github.com/tyrm/megabot/internal/models"
"github.com/uptrace/bun/dbfixture"
"github.com/uptrace/bun/migrate"
)
type commonDB struct {
bun *Bun
}
// Close closes the bun db connection
func (c *commonDB) Close(ctx context.Context) db.Error {
l := logger.WithField("func", "Close")
l.Info("closing db connection")
return c.bun.Close()
}
// Create inserts an object into the database
func (c *commonDB) Create(ctx context.Context, i any) db.Error {
_, err := c.bun.NewInsert().Model(i).Exec(ctx)
if err != nil {
logger.WithField("func", "Create").Errorf("db: %s", err.Error())
}
return c.bun.ProcessError(err)
}
// DoMigration runs schema migrations on the database
func (c *commonDB) DoMigration(ctx context.Context) db.Error {
l := logger.WithField("func", "DoMigration")
migrator := migrate.NewMigrator(c.bun.DB, migrations.Migrations)
if err := migrator.Init(ctx); err != nil {
return err
}
group, err := migrator.Migrate(ctx)
if err != nil {
if err.Error() == "migrate: there are no any migrations" {
return nil
}
return err
}
if group.ID == 0 {
l.Info("there are no new migrations to run")
return nil
}
l.Infof("migrated database to %s", group)
return nil
}
func (c *commonDB) LoadTestData(ctx context.Context) db.Error {
l := logger.WithField("func", "DoMigration")
// Register models before loading fixtures.
c.bun.RegisterModel(
(*models.User)(nil),
(*models.GroupMembership)(nil),
)
// Automatically create tables.
fixture := dbfixture.New(c.bun.DB, dbfixture.WithTruncateTables())
// Load fixtures.
if err := fixture.Load(ctx, megabot.Files, "test/fixture.yml"); err != nil {
l.Errorf("loading test data: %s", err.Error())
return err
}
return nil
}