generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
230 lines (190 loc) · 4.44 KB
/
database.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package sqltest
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"go.uber.org/multierr"
)
// Database is a database created for the purposes of testing.
type Database struct {
Driver Driver
Product Product
DataSource DataSource
m sync.Mutex
open bool
closers []func() error
}
// NewDatabase returns a new temporary test database for a specific pair of
// database product and SQL driver.
//
// The returned Database is an io.Closer that must be closed when the database
// is no longer needed. It is safe to close the Database even if this function
// returns an error.
func NewDatabase(
ctx context.Context,
d Driver,
p Product,
) (_ *Database, err error) {
baseDS, err := dataSource(d, p)
if err != nil {
return nil, err
}
defer baseDS.Close()
testDS := baseDS.WithDatabaseName(
generateTemporaryDatabaseName(),
)
multi, ok := p.(MultiDatabaseProduct)
if !ok {
return &Database{
Driver: d,
Product: p,
DataSource: testDS,
open: true,
}, nil
}
pool, err := openPool(p, baseDS)
if err != nil {
return nil, err
}
if err := multi.CreateDatabase(ctx, pool, testDS.DatabaseName()); err != nil {
pool.Close()
return nil, fmt.Errorf(
"unable to create a temporary %s database using the '%s' driver: %w",
p.Name(),
d.Name(),
err,
)
}
return &Database{
Driver: d,
Product: p,
DataSource: testDS,
open: true,
closers: []func() error{
pool.Close,
func() error {
// We assume that the context passed to NewDatabase() has
// already been canceled at this point. Allow an additional 3
// seconds to drop the temporary database.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return multi.DropDatabase(ctx, pool, testDS.DatabaseName())
},
},
}, nil
}
// Open returns a database pool that connects to this database.
//
// The pool is closed when db.Close() is called.
func (db *Database) Open() (*sql.DB, error) {
if db == nil {
return nil, errors.New("attempted to open a database pool for a closed database")
}
db.m.Lock()
defer db.m.Unlock()
if !db.open {
return nil, errors.New("attempted to open a database pool for a closed database")
}
pool, err := openPool(db.Product, db.DataSource)
if err != nil {
return nil, err
}
db.closers = append(db.closers, pool.Close)
return pool, nil
}
// Close releases any resources associated with the DSN.
func (db *Database) Close() error {
if db == nil {
return nil
}
db.m.Lock()
defer db.m.Unlock()
if !db.open {
return nil
}
db.open = false
closers := db.closers
db.closers = nil
var err error
for i := len(closers) - 1; i >= 0; i-- {
err = multierr.Append(err, closers[i]())
}
if db.DataSource != nil {
err = multierr.Append(err, db.DataSource.Close())
}
return err
}
// dataSource returns the data source to use for the given combination of driver
// and product.
//
// It first checks for an environment variable containing a DSN. If that is not
// present it askes the product to generate a default DSN.
func dataSource(d Driver, p Product) (DataSource, error) {
if !p.IsCompatibleWith(d) {
return nil, fmt.Errorf(
"%s is incompatible with the '%s' driver",
p.Name(),
d.Name(),
)
}
key := strings.ToUpper(fmt.Sprintf("DOGMATIQ_TEST_DSN_%s_%s", p.Name(), d.Name()))
dsn := os.Getenv(key)
if dsn != "" {
ds, err := d.ParseDSN(dsn)
if err != nil {
return nil, fmt.Errorf(
"can not parse the DSN in the %s environment variable: %w",
key,
err,
)
}
return ds, nil
}
ds, err := p.DefaultDataSource(d)
if err != nil {
return nil, fmt.Errorf(
"can not build a default %s DSN using the '%s' driver: %w",
p.Name(),
d.Name(),
err,
)
}
return ds, nil
}
var counter uint64 // atomic
// generateTemporaryDatabaseName returns a name for a temporary test database.
func generateTemporaryDatabaseName() string {
return fmt.Sprintf(
"test_%d_%d",
os.Getpid(),
atomic.AddUint64(&counter, 1),
)
}
// openPool opens a database pool for the given data source.
func openPool(p Product, ds DataSource) (_ *sql.DB, err error) {
pool, err := sql.Open(
ds.DriverName(),
ds.DSN(),
)
if err == nil {
err = pool.Ping()
if err != nil {
pool.Close()
}
}
if err != nil {
return nil, fmt.Errorf(
"unable to open a %s database pool using the '%s' driver: %w",
p.Name(),
ds.DriverName(),
err,
)
}
return pool, nil
}