forked from pressly/goose
/
ydb.go
148 lines (137 loc) · 3.55 KB
/
ydb.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package testdb
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/ory/dockertest/v3"
"github.com/ory/dockertest/v3/docker"
"github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/balancers"
ydbLog "github.com/ydb-platform/ydb-go-sdk/v3/log"
"github.com/ydb-platform/ydb-go-sdk/v3/trace"
)
const (
YDB_IMAGE = "ghcr.io/ydb-platform/local-ydb"
YDB_VERSION = "23.3"
YDB_PORT = "2136"
YDB_UI_PORT = "8765"
YDB_DATABASE = "local"
)
func newYdb(opts ...OptionsFunc) (*sql.DB, func(), error) {
option := &options{}
for _, f := range opts {
f(option)
}
// Uses a sensible default on windows (tcp/http) and linux/osx (socket).
pool, err := dockertest.NewPool("")
if err != nil {
return nil, nil, err
}
runOptions := &dockertest.RunOptions{
Repository: YDB_IMAGE,
Tag: YDB_VERSION,
Env: []string{
"YDB_USE_IN_MEMORY_PDISKS=true",
"YDB_LOCAL_SURVIVE_RESTART=true",
"GRPC_PORT=" + YDB_PORT,
"MON_PORT=" + YDB_UI_PORT,
},
Labels: map[string]string{"goose_test": "1"},
PortBindings: map[docker.Port][]docker.PortBinding{},
Mounts: []string{os.TempDir() + ":/ydb_certs"},
Hostname: "localhost",
}
if option.debug {
runOptions.Env = append(runOptions.Env, "YDB_DEFAULT_LOG_LEVEL=NOTICE")
} else {
runOptions.Env = append(runOptions.Env, "YDB_DEFAULT_LOG_LEVEL=ERROR")
}
if option.bindPort > 0 {
runOptions.PortBindings[YDB_PORT+"/tcp"] = []docker.PortBinding{
{HostPort: strconv.Itoa(option.bindPort)},
}
}
container, err := pool.RunWithOptions(
runOptions,
func(config *docker.HostConfig) {
// Set AutoRemove to true so that stopped container goes away by itself.
config.AutoRemove = true
config.RestartPolicy = docker.RestartPolicy{Name: "no"}
config.Init = true
},
)
if err != nil {
return nil, nil, err
}
cleanup := func() {
if option.debug {
// User must manually delete the Docker container.
return
}
if err := pool.Purge(container); err != nil {
log.Printf("failed to purge resource: %v", err)
}
}
// Fetch port assigned to container
dsn := fmt.Sprintf("grpc://%s:%s/%s",
"localhost",
container.GetPort(YDB_PORT+"/tcp"),
YDB_DATABASE,
)
var db *sql.DB
// Exponential backoff-retry, because the application in the container
// might not be ready to accept connections yet.
if err := pool.Retry(func() (err error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := containerWaitHealthy(ctx, pool, container.Container.ID); err != nil {
return err
}
opts := []ydb.Option{
ydb.WithBalancer(balancers.SingleConn()),
}
if option.debug {
opts = append(opts, ydb.WithLogger(ydbLog.Default(os.Stdout), trace.DetailsAll, ydbLog.WithLogQuery()))
}
nativeDriver, err := ydb.Open(ctx, dsn, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
_ = nativeDriver.Close(context.Background())
}
}()
connector, err := ydb.Connector(nativeDriver,
ydb.WithDefaultQueryMode(ydb.ScriptingQueryMode),
ydb.WithFakeTx(ydb.ScriptingQueryMode),
ydb.WithAutoDeclare(),
ydb.WithNumericArgs(),
)
if err != nil {
return err
}
defer func() {
if err != nil {
_ = connector.Close()
}
}()
db = sql.OpenDB(connector)
db.SetMaxIdleConns(5)
db.SetMaxOpenConns(10)
db.SetConnMaxLifetime(time.Hour)
err = db.Ping()
if err != nil {
return err
}
return nil
}); err != nil {
cleanup()
return nil, nil, fmt.Errorf("could not connect to docker database: %w", err)
}
return db, cleanup, nil
}