/
SQL.go
305 lines (255 loc) · 7.82 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
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
package sdk
import (
"context"
"database/sql"
"errors"
"fmt"
"io"
"strings"
)
var (
ErrInvalidTransaction = errors.New("Invalid transaction")
ErrInvalidArgumentsScan = errors.New("Invalid arguments for scan")
ErrNoColumnsReturned = errors.New("No columns returned")
ErrInvalidDatabase = errors.New("Invalid database")
)
type (
BeginTx interface {
BeginTx(ctx context.Context, opts *sql.TxOptions) (tx *sql.Tx, err error)
}
ExecContext interface {
ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error)
}
PingContext interface {
PingContext(ctx context.Context) (err error)
}
PrepareContext interface {
PrepareContext(ctx context.Context, query string) (stmt *sql.Stmt, err error)
}
QueryContext interface {
QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)
}
QueryRowContext interface {
QueryRowContext(ctx context.Context, query string, args ...interface{}) (row *sql.Row)
}
)
// SQLConn is a common interface of *sql.DB and *sql.Conn.
type SQLConn interface {
BeginTx
io.Closer
PingContext
SQLTxConn
}
// SQLTxConn is a common interface of *sql.DB, *sql.Conn, and *sql.Tx.
type SQLTxConn interface {
ExecContext
PrepareContext
QueryContext
QueryRowContext
}
var (
_ SQLConn = (*sql.Conn)(nil)
_ SQLConn = (*sql.DB)(nil)
_ SQLTxConn = (*sql.Tx)(nil)
)
const (
_SELECT = "SELECT"
_INSERT = "INSERT"
_UPDATE = "UPDATE"
_DELETE = "DELETE"
_CREATE = "CREATE"
_ALTER = "ALTER"
_DROP = "DROP"
_USE = "USE"
_ADD = "ADD"
_EXEC = "EXEC"
_TRUNCATE = "TRUNCATE"
)
func SQLNoScan() interface{} { return new([]byte) }
type SQL struct{}
// BoxExec will wrap `ExecContext` so that we can Scan later
//
// BoxExec(cmd.ExecContext(ctx, "..."))
//
// Scan the result of ExecContext that usually return numbers of rowsAffected
// and lastInsertID.
func (SQL) BoxExec(sqlResult sql.Result, err error) BoxExec { return boxExec{sqlResult, err} }
type BoxExec interface {
Scan(rowsAffected *int, lastInsertID *int) (err error)
}
// BoxQuery will wrap `QueryContext` so that we can Scan later
//
// BoxQuery(cmd.QueryContext(ctx, "..."))
//
// Scan all the rows and map it into []map[string]interface{} using column name
// as key in the map and then parse it into json format, after that unmarshal
// into designated dest.
func (SQL) BoxQuery(sqlRows *sql.Rows, err error) BoxQuery { return boxQuery{sqlRows, err} }
type BoxQuery interface {
// Scan accept do, a func that accept `i int` as index and returns a List
// of pointer.
// List == nil // break the loop
// len(List) < 1 // skip the current loop
// len(List) > 0 // assign the pointer, must be same as the length of columns
Scan(row func(i int) List) (err error)
}
// EndTx will end transaction with provided *sql.Tx and error. The tx argument
// should be valid, and then will check the err, if any error occurred, will
// commencing the ROLLBACK else will COMMIT the transaction.
//
// txc := XSQLTxConn(db) // shared between *sql.Tx, *sql.DB and *sql.Conn
// if tx, err := db.BeginTx(ctx, nil); err == nil && tx != nil {
// defer func() { err = xsql.EndTx(tx, err) }()
// txc = tx
// }
func (SQL) EndTx(tx *sql.Tx, err error) error {
if tx == nil {
return fmt.Errorf("database: %w", ErrInvalidTransaction)
}
// if any error occurred, we try to rollback
if msg := "rollback"; err != nil {
if errR := tx.Rollback(); errR != nil {
msg = fmt.Sprintf("%s failed: (%s)", msg, errR.Error())
}
return fmt.Errorf("database: %s because: %w", msg, err)
}
// we try to commit here
if err = tx.Commit(); err != nil {
return fmt.Errorf("database: %w", err)
}
return nil
}
type boxExec struct {
sqlResult sql.Result
err error
}
func (x boxExec) Scan(rowsAffected *int, lastInsertID *int) (err error) {
err = x.err
if err != nil {
return fmt.Errorf("database: BoxExec: %w", err)
}
if x.sqlResult == nil {
return fmt.Errorf("database: BoxExec: %w", ErrInvalidArgumentsScan)
}
if rowsAffected != nil {
if n, err := x.sqlResult.RowsAffected(); err == nil {
if n < 1 {
return fmt.Errorf("database: BoxExec: %w", sql.ErrNoRows)
}
*rowsAffected = int(n)
}
}
if lastInsertID != nil {
if n, err := x.sqlResult.LastInsertId(); err == nil {
*lastInsertID = int(n)
}
}
return err
}
type boxQuery struct {
sqlRows *sql.Rows
err error
}
func (x boxQuery) Scan(row func(i int) List) (err error) {
err = x.err
if err != nil {
return err
} else if x.sqlRows == nil {
return fmt.Errorf("database: boxQuery: %w", sql.ErrNoRows)
} else if err = x.sqlRows.Err(); err != nil {
return err
}
defer x.sqlRows.Close()
cols, err := x.sqlRows.Columns()
if err != nil {
return fmt.Errorf("database: boxQuery: %w", err)
} else if len(cols) < 1 {
return fmt.Errorf("database: boxQuery: %w", ErrNoColumnsReturned)
}
for i := 0; x.sqlRows.Next(); i++ {
err = x.sqlRows.Err()
if err != nil {
return fmt.Errorf("database: boxQuery: %w", err)
}
dest := row(i)
if dest == nil { // nil dest
break
} else if len(dest) < 1 { // empty dest
continue
} else if len(dest) != len(cols) { // diff dest & cols
return fmt.Errorf("database: boxQuery: %w: [%d] columns on [%d] destinations", ErrInvalidArgumentsScan, len(cols), len(dest))
}
err = x.sqlRows.Scan(dest...) // scan into pointers
if err != nil {
return fmt.Errorf("database: boxQuery: %w", err)
}
}
return err
}
// RemoveComment from sql command.
func (SQL) RemoveComment(query string) (query_ string) {
commentStartIdx, replaces := -1, []string{}
for i := range query {
// we found sql comment
if i-1 >= 0 && i+1 < len(query) && query[i] == '-' && query[i+1] == '-' && query[i-1] != '-' {
commentStartIdx = i
continue
}
if commentStartIdx > -1 && query[i] == '\n' {
replaces = append(replaces, query[commentStartIdx:i])
}
}
for _, v := range replaces {
query = strings.Replace(query, v, "", 1)
}
return strings.TrimSpace(query)
}
// IsMultipleCommand is a naive implementation of checking multiple sql command.
func (SQL) IsMultipleCommand(query string) (ok bool) {
validCount := 0
for _, query := range strings.Split(query, ";") {
query = strings.ToUpper(strings.TrimSpace(SQL{}.RemoveComment(query)))
if (SQL{}).IsValidCommand(query) {
validCount++
}
}
return validCount > 1
}
// IsSELECTCommand only valid if starts with SELECT.
func (SQL) IsSELECTCommand(query string) (ok bool) {
query = strings.ToUpper(strings.TrimSpace(SQL{}.RemoveComment(query)))
for _, s := range []string{_SELECT} {
ok = ok || strings.HasPrefix(query, s) || strings.Contains(query, s)
}
return ok
}
// IsDMLCommand only valid if starts with INSERT, UPDATE, DELETE.
func (SQL) IsDMLCommand(query string) (ok bool) {
query = strings.ToUpper(strings.TrimSpace(SQL{}.RemoveComment(query)))
for _, s := range []string{_INSERT, _UPDATE, _DELETE} {
ok = ok || strings.HasPrefix(query, s)
}
return ok
}
// IsDDLCommand only valid if starts with CREATE, ALTER, DROP, USE, ADD, EXEC, TRUNCATE.
func (SQL) IsDDLCommand(query string) (ok bool) {
query = strings.ToUpper(strings.TrimSpace(SQL{}.RemoveComment(query)))
for _, s := range []string{_CREATE, _ALTER, _DROP, _USE, _ADD, _EXEC, _TRUNCATE} {
ok = ok || strings.HasPrefix(query, s)
}
return ok
}
func (SQL) IsValidCommand(query string) (ok bool) {
return SQL{}.IsSELECTCommand(query) || SQL{}.IsDMLCommand(query) || SQL{}.IsDDLCommand(query)
}
// SetupOrTeardown will execute multiple queries and useful in SETUP/TEARDOWN
// phase of Behavior Driven Development (BDD). BDD approach is useful to make sure
// that the SQL Query should satisfied the syntax and reduce integration issues.
func (SQL) SetupOrTeardown(ctx context.Context, conn ExecContext, queries ...string) error {
for _, q := range queries {
if _, err := conn.ExecContext(ctx, q); err != nil {
return err
}
}
return nil
}