-
-
Notifications
You must be signed in to change notification settings - Fork 242
/
connection.go
323 lines (280 loc) · 8.42 KB
/
connection.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package pop
import (
"context"
"database/sql"
"errors"
"fmt"
"math/rand"
"strings"
"sync/atomic"
"time"
"github.com/gobuffalo/pop/v6/internal/defaults"
"github.com/gobuffalo/pop/v6/internal/randx"
"github.com/gobuffalo/pop/v6/logging"
)
// Connections contains all available connections
var Connections = map[string]*Connection{}
// Connection represents all necessary details to talk with a datastore
type Connection struct {
ID string
Store store
Dialect dialect
Elapsed int64
TX *Tx
eager bool
eagerFields []string
}
func (c *Connection) String() string {
return c.URL()
}
// URL returns the datasource connection string
func (c *Connection) URL() string {
return c.Dialect.URL()
}
// Context returns the connection's context set by "Context()" or context.TODO()
// if no context is set.
func (c *Connection) Context() context.Context {
if c, ok := c.Store.(interface{ Context() context.Context }); ok {
return c.Context()
}
return context.TODO()
}
// MigrationURL returns the datasource connection string used for running the migrations
func (c *Connection) MigrationURL() string {
return c.Dialect.MigrationURL()
}
// MigrationTableName returns the name of the table to track migrations
func (c *Connection) MigrationTableName() string {
return c.Dialect.Details().MigrationTableName()
}
// NewConnection creates a new connection, and sets it's `Dialect`
// appropriately based on the `ConnectionDetails` passed into it.
func NewConnection(deets *ConnectionDetails) (*Connection, error) {
err := deets.Finalize()
if err != nil {
return nil, err
}
c := &Connection{}
c.setID()
if nc, ok := newConnection[deets.Dialect]; ok {
c.Dialect, err = nc(deets)
if err != nil {
return c, fmt.Errorf("could not create new connection: %w", err)
}
return c, nil
}
return nil, fmt.Errorf("could not found connection creator for %v", deets.Dialect)
}
// Connect takes the name of a connection, default is "development", and will
// return that connection from the available `Connections`. If a connection with
// that name can not be found an error will be returned. If a connection is
// found, and it has yet to open a connection with its underlying datastore,
// a connection to that store will be opened.
func Connect(e string) (*Connection, error) {
if len(Connections) == 0 {
err := LoadConfigFile()
if err != nil {
return nil, err
}
}
e = defaults.String(e, "development")
c := Connections[e]
if c == nil {
return c, fmt.Errorf("could not find connection named %s", e)
}
if err := c.Open(); err != nil {
return c, fmt.Errorf("couldn't open connection for %s: %w", e, err)
}
return c, nil
}
// Open creates a new datasource connection
func (c *Connection) Open() error {
if c.Store != nil {
return nil
}
if c.Dialect == nil {
return errors.New("invalid connection instance")
}
details := c.Dialect.Details()
db, err := openPotentiallyInstrumentedConnection(c.Dialect, c.Dialect.URL())
if err != nil {
return err
}
db.SetMaxOpenConns(details.Pool)
if details.IdlePool != 0 {
db.SetMaxIdleConns(details.IdlePool)
}
if details.ConnMaxLifetime > 0 {
db.SetConnMaxLifetime(details.ConnMaxLifetime)
}
if details.ConnMaxIdleTime > 0 {
db.SetConnMaxIdleTime(details.ConnMaxIdleTime)
}
if details.Unsafe {
db = db.Unsafe()
}
c.Store = &dB{db}
if d, ok := c.Dialect.(afterOpenable); ok {
if err := d.AfterOpen(c); err != nil {
c.Store = nil
return fmt.Errorf("could not open database connection: %w", err)
}
}
return nil
}
// Close destroys an active datasource connection
func (c *Connection) Close() error {
if err := c.Store.Close(); err != nil {
return fmt.Errorf("couldn't close connection: %w", err)
}
c.Store = nil
return nil
}
// Transaction will start a new transaction on the connection. If the inner function
// returns an error then the transaction will be rolled back, otherwise the transaction
// will automatically commit at the end.
func (c *Connection) Transaction(fn func(tx *Connection) error) error {
return c.Dialect.Lock(func() (err error) {
var dberr error
cn, err := c.NewTransaction()
if err != nil {
return err
}
txlog(logging.SQL, cn, "BEGIN Transaction ---")
defer func() {
if ex := recover(); ex != nil {
txlog(logging.SQL, cn, "ROLLBACK Transaction (inner function panic) ---")
dberr = cn.TX.Rollback()
if dberr != nil {
txlog(logging.Error, cn, "database error while inner panic rollback: %w", dberr)
}
panic(ex)
}
}()
err = fn(cn)
if err != nil {
txlog(logging.SQL, cn, "ROLLBACK Transaction ---")
dberr = cn.TX.Rollback()
} else {
txlog(logging.SQL, cn, "END Transaction ---")
dberr = cn.TX.Commit()
}
if dberr != nil {
return fmt.Errorf("database error on committing or rolling back transaction: %w", dberr)
}
return err
})
}
// Rollback will open a new transaction and automatically rollback that transaction
// when the inner function returns, regardless. This can be useful for tests, etc...
func (c *Connection) Rollback(fn func(tx *Connection)) error {
// TODO: the name of the method could be changed to express it better.
cn, err := c.NewTransaction()
if err != nil {
return err
}
txlog(logging.SQL, cn, "BEGIN Transaction for Rollback ---")
fn(cn)
txlog(logging.SQL, cn, "ROLLBACK Transaction as planned ---")
return cn.TX.Rollback()
}
// NewTransaction starts a new transaction on the connection
func (c *Connection) NewTransaction() (*Connection, error) {
return c.NewTransactionContextOptions(c.Context(), nil)
}
// NewTransactionContext starts a new transaction on the connection using the provided context
func (c *Connection) NewTransactionContext(ctx context.Context) (*Connection, error) {
return c.NewTransactionContextOptions(ctx, nil)
}
// NewTransactionContextOptions starts a new transaction on the connection using the provided context and transaction options
func (c *Connection) NewTransactionContextOptions(ctx context.Context, options *sql.TxOptions) (*Connection, error) {
var cn *Connection
if c.TX == nil {
tx, err := c.Store.TransactionContextOptions(ctx, options)
if err != nil {
return cn, fmt.Errorf("couldn't start a new transaction: %w", err)
}
cn = &Connection{
Store: contextStore{store: tx, ctx: ctx},
Dialect: c.Dialect,
TX: tx,
}
cn.setID()
} else {
cn = c
}
return cn, nil
}
// WithContext returns a copy of the connection, wrapped with a context.
func (c *Connection) WithContext(ctx context.Context) *Connection {
cn := c.copy()
cn.Store = contextStore{
store: cn.Store,
ctx: ctx,
}
return cn
}
func (c *Connection) copy() *Connection {
// TODO: checkme. it copies and creates a new Connection (and a new ID)
// with the same TX which could make confusions and complexity in usage.
// related PRs: #72/#73, #79/#80, and #497
cn := &Connection{
Store: c.Store,
Dialect: c.Dialect,
TX: c.TX,
}
cn.setID(c.ID) // ID of the source as a seed
return cn
}
// Q creates a new "empty" query for the current connection.
func (c *Connection) Q() *Query {
return Q(c)
}
// disableEager disables eager mode for current connection.
func (c *Connection) disableEager() {
// The check technically is not required, because (*Connection).Eager() creates a (shallow) copy.
// When not reusing eager connections, this should be safe.
// However, this write triggers the go race detector.
if c.eager {
c.eager = false
c.eagerFields = []string{}
}
}
// TruncateAll truncates all data from the datasource
func (c *Connection) TruncateAll() error {
return c.Dialect.TruncateAll(c)
}
func (c *Connection) timeFunc(name string, fn func() error) error {
start := time.Now()
err := fn()
atomic.AddInt64(&c.Elapsed, int64(time.Since(start)))
if err != nil {
return err
}
return nil
}
// setID sets a unique ID for a Connection in a specific format indicating the
// Connection type, TX.ID, and optionally a copy ID. It makes it easy to trace
// related queries for a single request.
//
// examples: "conn-7881415437117811350", "tx-4924907692359316530", "tx-831769923571164863-ytzxZa"
func (c *Connection) setID(id ...string) {
if len(id) == 1 {
idElems := strings.Split(id[0], "-")
l := 2
if len(idElems) < 2 {
l = len(idElems)
}
prefix := strings.Join(idElems[0:l], "-")
body := randx.String(6)
c.ID = fmt.Sprintf("%s-%s", prefix, body)
} else {
prefix := "conn"
body := rand.Int()
if c.TX != nil {
prefix = "tx"
body = c.TX.ID
}
c.ID = fmt.Sprintf("%s-%d", prefix, body)
}
}