forked from uptrace/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (66 loc) · 1.66 KB
/
main.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
80
81
82
83
84
package main
import (
"context"
"database/sql"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
"github.com/uptrace/bun/extra/bundebug"
)
func main() {
ctx := context.Background()
sqlite, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
if err != nil {
panic(err)
}
sqlite.SetMaxOpenConns(1)
db := bun.NewDB(sqlite, sqlitedialect.New())
db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))
if err := db.ResetModel(ctx, (*User)(nil)); err != nil {
panic(err)
}
user := new(User)
if _, err := db.NewInsert().Model(user).Exec(ctx); err != nil {
panic(err)
}
if _, err := db.NewUpdate().
Model(user).
WherePK().
Exec(ctx); err != nil {
panic(err)
}
if err := db.NewSelect().Model(user).WherePK().Scan(ctx); err != nil {
panic(err)
}
spew.Dump(user)
}
type User struct {
ID int64 `bun:",pk,autoincrement"`
Password string
CreatedAt time.Time `bun:",nullzero"`
UpdatedAt time.Time `bun:",nullzero"`
}
var _ bun.BeforeAppendModelHook = (*User)(nil)
func (u *User) BeforeAppendModel(ctx context.Context, query bun.Query) error {
switch query.(type) {
case *bun.InsertQuery:
u.Password = "[encrypted]"
u.CreatedAt = time.Now()
case *bun.UpdateQuery:
u.UpdatedAt = time.Now()
}
return nil
}
var _ bun.BeforeScanRowHook = (*User)(nil)
func (u *User) BeforeScanRow(ctx context.Context) error {
// Do some initialization.
u.Password = ""
return nil
}
var _ bun.AfterScanRowHook = (*User)(nil)
func (u *User) AfterScanRow(ctx context.Context) error {
u.Password = "[decrypted]"
return nil
}