/
db.go
247 lines (224 loc) · 5.34 KB
/
db.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
package sql
import (
"bytes"
"database/sql"
"errors"
"hash/crc32"
"strings"
"sync"
"gnd.la/internal"
"gnd.la/orm/driver"
)
var (
ErrNoRows = sql.ErrNoRows
ErrFuncNotSupported = errors.New("function not supported")
)
type Queryier interface {
Query(query string, args ...interface{}) (*sql.Rows, error)
QueryRow(query string, args ...interface{}) *sql.Row
}
type Executor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
type queryExecutor interface {
Queryier
Executor
}
type cacheEntry struct {
sql string
stmt *sql.Stmt
}
type DB struct {
// database/sql.DB
sqlDb *sql.DB
// non-nil only when in transaction
tx *sql.Tx
txDone bool
// might be eithr sqlDb or tx, depending on
// if we're inside a transaction or not.
conn queryExecutor
driver *Driver
replacesPlaceholders bool
mu sync.RWMutex
cache map[uint32]cacheEntry
}
func (d *DB) replacePlaceholders(query string) string {
var buf bytes.Buffer
var inQuote, inDoubleQuote bool
p := 0
placeholder := d.driver.backend.Placeholder
written := 0
last := len(query) - 1
for ii, ch := range query {
switch ch {
case '\'':
if ii == last || query[ii+1] != '\'' {
inQuote = !inQuote
}
case '"':
inDoubleQuote = !inDoubleQuote
case '?':
if !inQuote && !inDoubleQuote {
buf.WriteString(query[written:ii])
buf.WriteString(placeholder(p))
p++
written = ii + 1
}
}
}
if written == 0 {
return query
}
buf.WriteString(query[written:])
return buf.String()
}
func (d *DB) Exec(query string, args ...interface{}) (sql.Result, error) {
if d.replacesPlaceholders {
query = d.replacePlaceholders(query)
}
d.driver.debugq(query, args)
if len(args) > 0 {
if stmt := d.preparedStmt(query); stmt != nil {
return stmt.Exec(args...)
}
}
return d.conn.Exec(query, args...)
}
func (d *DB) Query(query string, args ...interface{}) (*sql.Rows, error) {
if d.replacesPlaceholders {
query = d.replacePlaceholders(query)
}
d.driver.debugq(query, args)
if len(args) > 0 {
if stmt := d.preparedStmt(query); stmt != nil {
return stmt.Query(args...)
}
}
return d.conn.Query(query, args...)
}
func (d *DB) QueryRow(query string, args ...interface{}) *sql.Row {
if d.replacesPlaceholders {
query = d.replacePlaceholders(query)
}
query = d.replacePlaceholders(query)
d.driver.debugq(query, args)
if len(args) > 0 {
if stmt := d.preparedStmt(query); stmt != nil {
return stmt.QueryRow(args...)
}
}
return d.conn.QueryRow(query, args...)
}
func (d *DB) Begin() (*DB, error) {
if d.tx != nil {
return nil, driver.ErrInTransaction
}
tx, err := d.sqlDb.Begin()
if err != nil {
return nil, err
}
return &DB{
sqlDb: d.sqlDb,
tx: tx,
conn: tx,
driver: d.driver,
replacesPlaceholders: d.replacesPlaceholders,
}, nil
}
func (d *DB) Commit() error {
if d.tx == nil {
return driver.ErrNotInTransaction
}
d.txDone = true
return d.tx.Commit()
}
func (d *DB) Rollback() error {
if d.tx == nil {
return driver.ErrNotInTransaction
}
d.txDone = true
return d.tx.Rollback()
}
func (d *DB) Close() error {
if d.tx != nil {
if !d.txDone {
return d.tx.Rollback()
}
return nil
}
return d.sqlDb.Close()
}
func (d *DB) QuoteString(s string) string {
return d.quoteWith(s, d.driver.backend.StringQuote())
}
func (d *DB) QuoteIdentifier(s string) string {
return d.quoteWith(s, d.driver.backend.IdentifierQuote())
}
func (d *DB) quoteWith(s string, q byte) string {
qu := string(q)
var escaped string
if q == '\'' {
escaped = strings.Replace(s, "'", "''", -1)
} else {
escaped = strings.Replace(s, qu, "\\"+qu, -1)
}
return qu + escaped + qu
}
func (d *DB) preparedStmt(s string) *sql.Stmt {
// Don't bother making a prepared statement if
// the transaction is non-nil, since the current
// implementation of d.tx.Stmt() (as of Go 1.8 freeze)
// will end up parsing the query string again. Given
// that tx prepared statements won't be valid once
// the transaction goes away, we'll most likely end
// up parsing twice for one execution.
//
// XXX: Also, sqlite has some issues with prepared stmts
// and transactions. TestMigrations in gnd.la/orm wouldn't
// pass because the connection which created the 1st
// "migration "table was incorrectly in a transaction and when
// creating the table for the 1st migration (BadMigration1),
// the inspection would return that no table was present.
// Eventually, the table would appear and some other part
// of the test would fail.
//
// TLDR: Make sure the sqlite tests pass if you remove the following
// check
if d.tx != nil {
return nil
}
key := crc32.ChecksumIEEE(internal.StringToBytes(s))
d.mu.RLock()
cached, ok := d.cache[key]
d.mu.RUnlock()
if ok && cached.sql == s {
if d.tx != nil {
return d.tx.Stmt(cached.stmt)
}
return cached.stmt
}
stmt, _ := d.sqlDb.Prepare(s)
if stmt == nil {
// Let the non-prepared method report the error
return nil
}
d.mu.Lock()
if d.cache == nil {
d.cache = make(map[uint32]cacheEntry)
}
d.cache[key] = cacheEntry{sql: s, stmt: stmt}
d.mu.Unlock()
if d.tx != nil {
return d.tx.Stmt(stmt)
}
return stmt
}
func (d *DB) DB() *sql.DB {
return d.sqlDb
}
func (d *DB) Driver() *Driver {
return d.driver
}
func (d *DB) Backend() Backend {
return d.driver.backend
}