/
sqlprepare.go
74 lines (61 loc) · 1.45 KB
/
sqlprepare.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
package util
import (
"context"
"database/sql"
"github.com/pkg/errors"
"github.com/target/goalert/util/sqlutil"
)
type ContextPreparer interface {
PrepareContext(context.Context, string) (*sql.Stmt, error)
}
type PrepareStmt struct {
*sql.Stmt
q string
}
func (p *PrepareStmt) PrepareFor(ctx context.Context, cp ContextPreparer) (*sql.Stmt, error) {
return cp.PrepareContext(ctx, p.q)
}
type Preparer interface {
PrepareContext(context.Context, string) (*sql.Stmt, error)
}
// Prepare is used to prepare SQL statements.
//
// If Ctx is specified, it will be used to prepare all statements.
// Only the first error is recorded. Subsequent calls to `P` are
// ignored after a failure.
type Prepare struct {
DB Preparer
Ctx context.Context
Err error
}
type queryErr struct {
q string
err *sqlutil.Error
}
type QueryError interface {
Query() string
Cause() *sqlutil.Error
}
func (q *queryErr) Query() string { return q.q }
func (q *queryErr) Cause() *sqlutil.Error { return q.err }
func (q *queryErr) Error() string { return q.err.Error() }
func (p *Prepare) P(query string) (s *sql.Stmt) {
if p.Err != nil {
return nil
}
if p.Ctx != nil {
s, p.Err = p.DB.PrepareContext(p.Ctx, query)
} else {
s, p.Err = p.DB.PrepareContext(context.Background(), query)
}
if p.Err != nil {
if e := sqlutil.MapError(p.Err); e != nil {
p.Err = &queryErr{
err: e,
q: query,
}
}
p.Err = errors.WithStack(p.Err)
}
return s
}