-
Notifications
You must be signed in to change notification settings - Fork 75
/
sql.go
55 lines (45 loc) · 1.53 KB
/
sql.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
// Copyright (c) 2022 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"context"
"database/sql"
"time"
"github.com/pkg/errors"
)
const (
// timeoutOp is the timeout for a single database operation.
timeoutOp = 1 * time.Minute
// timeoutTx is the timeout for a database transaction.
timeoutTx = 3 * time.Minute
)
// beginTx returns a database transactions and a cancel function for the
// transaction.
//
// The cancel function can be used up until the tx is committed or manually
// rolled back. Invoking the cancel function rolls the tx back and releases all
// resources associated with it. This allows the caller to defer the cancel
// function in order to rollback the tx on unexpected errors. Once the tx is
// successfully committed the deferred invocation of the cancel function does
// nothing.
func (p *politeiawww) beginTx() (*sql.Tx, func(), error) {
ctx, cancel := ctxForTx()
opts := &sql.TxOptions{
Isolation: sql.LevelDefault,
}
tx, err := p.db.BeginTx(ctx, opts)
if err != nil {
return nil, nil, errors.WithStack(err)
}
return tx, cancel, nil
}
// ctxForOp returns a context and cancel function for a single database
// operation.
func ctxForOp() (context.Context, func()) {
return context.WithTimeout(context.Background(), timeoutOp)
}
// ctxForTx returns a context and a cancel function for a database transaction.
func ctxForTx() (context.Context, func()) {
return context.WithTimeout(context.Background(), timeoutTx)
}