Repository navigation
Expand file tree
/
Copy pathdao.go
More file actions
417 lines (320 loc) · 10.3 KB
/
Copy pathdao.go
File metadata and controls
417 lines (320 loc) · 10.3 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright 2023 by Blank-Xu. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sqladapter
import (
"bytes"
"context"
"database/sql"
"fmt"
"strconv"
"strings"
)
func newDao(db *sql.DB, driverNameIndex adapterDriverNameIndex, tableName string) dao {
d := dao{
db: db,
tableName: tableName,
placeHolder: defaultPlaceholder,
sqlCreateTable: fmt.Sprintf(sqlCreateTable, tableName),
sqlTableExist: fmt.Sprintf(sqlTableExist, tableName),
sqlInsertRow: fmt.Sprintf(sqlInsertRow, tableName),
sqlUpdateRow: fmt.Sprintf(sqlUpdateRow, tableName),
sqlDeleteAll: fmt.Sprintf(sqlDeleteAll, tableName),
sqlDeleteRow: fmt.Sprintf(sqlDeleteRow, tableName),
sqlDeleteByArgs: fmt.Sprintf(sqlDeleteByArgs, tableName),
sqlSelectAll: fmt.Sprintf(sqlSelectAll, tableName),
sqlSelectWhere: fmt.Sprintf(sqlSelectWhere, tableName),
}
switch driverNameIndex {
case _SQLite:
d.sqlCreateTable = fmt.Sprintf(sqlCreateTableSQLite3, tableName)
case _MySQL:
d.sqlCreateTable = fmt.Sprintf(sqlCreateTableMySQL, tableName)
case _PostgreSQL:
d.placeHolder = sqlPlaceholderPostgreSQL
d.sqlCreateTable = fmt.Sprintf(sqlCreateTablePostgreSQL, tableName)
d.sqlInsertRow = fmt.Sprintf(sqlInsertRowPostgreSQL, tableName)
d.sqlUpdateRow = fmt.Sprintf(sqlUpdateRowPostgreSQL, tableName)
d.sqlDeleteRow = fmt.Sprintf(sqlDeleteRowPostgreSQL, tableName)
case _SQLServer:
d.placeHolder = sqlPlaceholderSQLServer
d.sqlCreateTable = fmt.Sprintf(sqlCreateTableSQLServer, tableName)
d.sqlInsertRow = fmt.Sprintf(sqlInsertRowSQLServer, tableName)
d.sqlUpdateRow = fmt.Sprintf(sqlUpdateRowSQLServer, tableName)
d.sqlDeleteRow = fmt.Sprintf(sqlDeleteRowSQLServer, tableName)
}
return d
}
type dao struct {
db *sql.DB
tableName string
placeHolder string
sqlCreateTable string
sqlTableExist string
sqlSelectAll string
sqlSelectWhere string
sqlInsertRow string
sqlUpdateRow string
sqlDeleteAll string
sqlDeleteRow string
sqlDeleteByArgs string
}
// rebindSQL rebind SQL by different database.
func (d dao) rebindSQL(query string) string {
if d.placeHolder == defaultPlaceholder {
return query
}
var idx, num int
result := make([]byte, 0, len(query)+10)
for {
idx = strings.Index(query, defaultPlaceholder)
if idx == -1 {
break
}
num++
result = append(result, query[:idx]...)
result = append(result, d.placeHolder...)
result = strconv.AppendInt(result, int64(num), 10)
query = query[idx+1:]
}
return string(append(result, query...))
}
// querySQL query data by sql.
func (d dao) querySQL(ctx context.Context, query string, args ...interface{}) ([]rule, error) {
rows, err := d.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
rules := make([]rule, 0, 128)
for rows.Next() {
var rule rule
err = rows.Scan(&rule.PType, &rule.V0, &rule.V1, &rule.V2, &rule.V3, &rule.V4, &rule.V5)
if err != nil {
return nil, err
}
rules = append(rules, rule)
}
if err = rows.Err(); err != nil {
return nil, err
}
return rules, nil
}
// execSQL exec sql.
func (d dao) execSQL(ctx context.Context, query string, args ...interface{}) error {
_, err := d.db.ExecContext(ctx, query, args...)
return err
}
type txData struct {
step string
query string
args []interface{}
}
// execTxSQL exec transaction sql rows.
func (d dao) execTxSQL(ctx context.Context, beforeTxData, afterTxData txData, query string, args [][]interface{}) error {
tx, err := d.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx err: %w", err)
}
var (
step string
stmt *sql.Stmt
)
if beforeTxData.query != "" {
if _, err = tx.ExecContext(ctx, beforeTxData.query, beforeTxData.args...); err != nil {
step = beforeTxData.step + " before prepare"
goto ROLLBACK
}
}
if stmt, err = tx.PrepareContext(ctx, query); err != nil {
step = "prepare context"
goto ROLLBACK
}
for _, arg := range args {
if _, err = stmt.ExecContext(ctx, arg...); err != nil {
step = "stmt exec context"
goto ROLLBACK
}
}
if err = stmt.Close(); err != nil {
step = "stmt close"
goto ROLLBACK
}
if afterTxData.query != "" {
if _, err = tx.ExecContext(ctx, afterTxData.query, afterTxData.args...); err != nil {
step = afterTxData.step + " after stmt"
goto ROLLBACK
}
}
if err = tx.Commit(); err != nil {
step = "commit"
goto ROLLBACK
}
return nil
ROLLBACK:
if err1 := tx.Rollback(); err1 != nil {
return fmt.Errorf("%s err: %w, rollback err: %w", step, err, err1)
}
return fmt.Errorf("%s err: %w", step, err)
}
// CreateTable create a table.
func (d dao) CreateTable(ctx context.Context) error {
return d.execSQL(ctx, d.sqlCreateTable)
}
// IsTableExist check the table exists.
func (d dao) IsTableExist(ctx context.Context) bool {
return d.execSQL(ctx, d.sqlTableExist) == nil
}
// SelectAll select all data from the table.
func (d dao) SelectAll(ctx context.Context) ([]rule, error) {
return d.querySQL(ctx, d.sqlSelectAll)
}
// SelectRows select eligible data by args from the table.
func (d dao) SelectRows(ctx context.Context, query string, args ...interface{}) ([]rule, error) {
if len(args) == 0 {
return d.querySQL(ctx, query)
}
query = d.rebindSQL(query)
return d.querySQL(ctx, query, args...)
}
// SelectByCondition .
func (d dao) SelectByCondition(ctx context.Context, whereCondition string, args ...interface{}) ([]rule, error) {
var buf bytes.Buffer
buf.Grow(128)
buf.WriteString(d.sqlSelectWhere)
// this is for reuse the SQL
buf.WriteString("p_type=?")
buf.WriteString(whereCondition)
query := d.rebindSQL(buf.String())
return d.querySQL(ctx, query, args...)
}
// SelectByFilter select eligible data by Filter from the table.
func (d dao) SelectByFilter(ctx context.Context, filterData [maxParameterCount]filterData) (lines []rule, err error) {
var (
sqlBuf bytes.Buffer
buf bytes.Buffer
)
sqlBuf.Grow(64)
sqlBuf.WriteString(d.sqlSelectWhere)
args := make([]string, 0, maxParameterCount)
for _, col := range filterData {
l := len(col.arg)
if l == 0 {
continue
}
switch sqlBuf.Bytes()[sqlBuf.Len()-1] {
case '?', ')':
sqlBuf.WriteString(" AND ")
}
sqlBuf.WriteString(col.fieldName)
if l == 1 {
sqlBuf.WriteString("=?")
args = append(args, col.arg[0])
} else {
buf.Grow(l * 2)
for i := 0; i < l; i++ {
buf.WriteString("?,")
}
buf.Truncate(buf.Len() - 1)
sqlBuf.WriteString(" IN (")
sqlBuf.Write(buf.Bytes())
sqlBuf.WriteByte(')')
args = append(args, col.arg...)
buf.Reset()
}
}
params := make([]interface{}, len(args))
for idx := range args {
params[idx] = args[idx]
}
return d.SelectRows(ctx, sqlBuf.String(), params...)
}
// InsertRow insert one row to the table.
func (d dao) InsertRow(ctx context.Context, args ...interface{}) error {
return d.execSQL(ctx, d.sqlInsertRow, args...)
}
// InsertRows insert multiple rows to the table by transaction.
func (d dao) InsertRows(ctx context.Context, args [][]interface{}) error {
return d.execTxSQL(ctx, txData{}, txData{}, d.sqlInsertRow, args)
}
// UpdateRow update one row to the table.
func (d dao) UpdateRow(ctx context.Context, args ...interface{}) error {
return d.execSQL(ctx, d.sqlUpdateRow, args...)
}
// UpdateRows update multiple rows to the table by transaction.
func (d dao) UpdateRows(ctx context.Context, args [][]interface{}) error {
return d.execTxSQL(ctx, txData{}, txData{}, d.sqlUpdateRow, args)
}
// UpdateFilteredRows .
func (d dao) UpdateFilteredRows(ctx context.Context, deleteCondition string, deleteArgs []interface{}, updateArgs [][]interface{}) error {
deleteQuery := d.sqlDeleteByArgs + deleteCondition
deleteQuery = d.rebindSQL(deleteQuery)
return d.execTxSQL(ctx, txData{step: "delete rows", query: deleteQuery, args: deleteArgs}, txData{step: "after tx exec"}, d.sqlInsertRow, updateArgs)
}
// DeleteAll clear the table.
// func (d dao) DeleteAll(ctx context.Context) error {
// return d.execSQL(ctx, d.sqlDeleteAll)
// }
// DeleteRows delete eligible data.
func (d dao) DeleteRows(ctx context.Context, args [][]interface{}) error {
return d.execTxSQL(ctx, txData{}, txData{}, d.sqlDeleteRow, args)
}
// DeleteAllAndInsertRows clear table and insert new rows.
func (d dao) DeleteAllAndInsertRows(ctx context.Context, rules [][]interface{}) error {
return d.execTxSQL(ctx, txData{step: "delete all", query: d.sqlDeleteAll}, txData{}, d.sqlInsertRow, rules)
}
// DeleteByArgs delete eligible data.
func (d dao) DeleteByArgs(ctx context.Context, ptype string, rule []string) error {
var sqlBuf bytes.Buffer
sqlBuf.Grow(128)
sqlBuf.WriteString(d.sqlDeleteByArgs)
args := make([]interface{}, 0, maxParameterCount)
args = append(args, ptype)
for idx, arg := range rule {
if arg != "" {
sqlBuf.WriteString(" AND v")
sqlBuf.WriteString(strconv.Itoa(idx))
sqlBuf.WriteString("=?")
args = append(args, arg)
}
}
query := d.rebindSQL(sqlBuf.String())
return d.execSQL(ctx, query, args...)
}
// DeleteByCondition .
func (d dao) DeleteByCondition(ctx context.Context, condition string, args ...interface{}) error {
deleteQuery := d.sqlDeleteByArgs + condition
deleteQuery = d.rebindSQL(deleteQuery)
return d.execSQL(ctx, deleteQuery, args...)
}
// GenFilteredCondition .
func (d dao) GenFilteredCondition(ptype string, fieldIndex int, fieldValues ...string) (string, []interface{}) {
var whereConditionBuf bytes.Buffer
whereConditionBuf.Grow(64)
args := make([]interface{}, 0, maxParameterCount)
args = append(args, ptype)
var value string
l := fieldIndex + len(fieldValues)
for idx := 0; idx < maxParameterCount-1; idx++ {
if fieldIndex <= idx && idx < l {
value = fieldValues[idx-fieldIndex]
if value != "" {
whereConditionBuf.WriteString(" AND v")
whereConditionBuf.WriteString(strconv.Itoa(idx))
whereConditionBuf.WriteString("=?")
args = append(args, value)
}
}
}
return whereConditionBuf.String(), args
}