forked from zlyuancn/zstr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsql_template.go
631 lines (579 loc) · 16.1 KB
/
sql_template.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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/7/18
Description :
-------------------------------------------------
*/
package zstr
import (
"bytes"
"fmt"
"reflect"
"strconv"
"strings"
)
const defaultSqlCompareFlag = "="
var (
// 操作符
sqlTemplateOperationMapp = map[int32]struct{}{
'&': {},
'|': {},
'#': {},
'@': {},
}
// 标记
sqlTemplateFlagMapp = map[string]struct{}{
">": {},
">=": {},
"<": {},
"<=": {},
"!=": {},
"<>": {},
"=": {},
"in": {},
"notin": {},
"not_in": {},
"like": {},
"likestart": {},
"like_start": {},
"likeend": {},
"like_end": {},
}
// 选项
sqlTemplateOptsMapp = map[int32]struct{}{
'a': {}, // attention, 不会忽略参数值为该类型的零值
'd': {}, // direct, 直接将值写入sql语句
'm': {}, // must, 必填
}
)
type sqlTemplate struct {
data map[string]interface{}
names []string
values []interface{}
keyCounter *counter // key计数器
sub int // 下标计数器
}
func newSqlTemplate(values []interface{}) *sqlTemplate {
return &sqlTemplate{
data: makeMapOfValues(values),
keyCounter: newCounter(-1),
}
}
func (m *sqlTemplate) calculateTemplate(ss []rune, start int) (int, int, bool, bool) {
var crust, has, ok bool
// 查找开头
for i := start; i < len(ss); i++ {
if ss[i] == '{' {
start, crust, has = i, true, true
break
}
if _, ok = sqlTemplateOperationMapp[ss[i]]; ok {
start, crust, has = i, false, true
break
}
}
if !has {
return 0, 0, false, false
}
// 预检
if crust && (len(ss)-start < 4) || (len(ss)-start < 2) {
return 0, 0, false, false
}
if !crust {
for i := start + 1; i < len(ss); i++ {
_, ok = templateVariableNameMap[ss[i]]
if !ok {
if i-start < 2 {
return m.calculateTemplate(ss, i)
}
return start, i, false, true
}
}
return start, len(ss), false, len(ss)-start >= 2
}
if crust {
for i := start + 1; i < len(ss); i++ {
if ss[i] != '}' {
continue
}
return start, i + 1, true, true
}
}
return 0, 0, false, false
}
func (m *sqlTemplate) replaceAllFunc(s string, fn func(s string, crust bool) string) string {
ss := []rune(s)
var buff bytes.Buffer
for offset := 0; offset < len(ss); {
start, end, crust, has := m.calculateTemplate(ss, offset)
if !has {
buff.WriteString(string(ss[offset:]))
break
}
buff.WriteString(string(ss[offset:start]))
buff.WriteString(fn(string(ss[start:end]), crust))
offset = end
}
return buff.String()
}
func (m *sqlTemplate) addValue(name string, value interface{}) {
m.names = append(m.names, name)
m.values = append(m.values, value)
}
func (m *sqlTemplate) Parse(sql_template string) (sql_str string, names []string, args []interface{}) {
sql_str = m.replaceAllFunc(sql_template, func(s string, crust bool) string {
if crust {
s = s[1 : len(s)-1]
}
operation, name, flag, opts, err := m.sqlTemplateSyntaxParse(s)
if err != nil {
panic(err)
}
return m.translate(operation, name, flag, opts)
})
return m.repairSql(sql_str), m.names, m.values
}
func (m *sqlTemplate) translate(operation, name, flag string, opts string) string {
// 选项检查
var attention_opt, direct_opt, must_opt bool
for _, o := range opts {
switch o {
case 'a':
attention_opt = true
case 'd':
direct_opt = true
case 'm':
must_opt = true
default:
panic(fmt.Sprintf(`syntax error, non-supported option "%s"`, string(o)))
}
}
switch operation {
case "#":
attention_opt = true
case "@":
attention_opt = false
direct_opt = true
}
vName := name + "[" + strconv.Itoa(m.keyCounter.Incr(name)) + "]"
value, has := m.data[vName]
if !has {
vName = name
value, has = m.data[name]
}
if !has {
vName = "*[" + strconv.Itoa(m.sub) + "]"
value, has = m.data[vName]
}
m.sub++ // 每次一定+1
// 无值返回空sql语句
if !has {
if must_opt {
panic(fmt.Sprintf(`"%s" must have a value`, name))
}
return ""
}
// 非注意模式且值为零值返回空sql语句
if !attention_opt && IsZero(value) {
return ""
}
// 操作检查
switch operation {
case "&":
operation = "and"
case "|":
operation = "or"
case "#":
// nil改为null
if value == nil {
return "null"
}
if direct_opt {
return anyToSqlString(value, true)
}
m.addValue(vName, value)
return "?"
case "@": // !attention_opt + direct
return anyToSqlString(value, false)
default:
panic(fmt.Errorf(`syntax error, non-supported operation "%s"`, operation))
}
// nil 修改语句
if value == nil {
switch flag {
case "!=", "<>", "notin", "not_in", ">", "<":
return fmt.Sprintf(`%s %s is not null`, operation, name)
case "=", "like", "likestart", "like_start", "likeend", "like_end":
return fmt.Sprintf(`%s %s is null`, operation, name)
case "in", ">=", "<=":
return ""
}
}
var makeSqlStr func() string
var directWrite func() string
// 标记
switch flag {
case ">", ">=", "<", "<=", "!=", "<>", "=":
makeSqlStr = func() string {
m.addValue(vName, value)
return fmt.Sprintf(`%s %s %s ?`, operation, name, flag)
}
directWrite = func() string {
return fmt.Sprintf(`%s %s %s %s`, operation, name, flag, anyToSqlString(value, true))
}
case "in":
values := m.parseToSlice(value)
if len(values) == 0 {
return ""
}
makeSqlStr = func() string {
if len(values) == 1 {
m.addValue(vName, values[0])
return fmt.Sprintf(`%s %s = ?`, operation, name)
}
fs := make([]string, len(values))
for i, s := range values {
m.addValue(fmt.Sprintf("%s.in(%d)", vName, i), s)
fs[i] = "?"
}
return fmt.Sprintf(`%s %s in (%s)`, operation, name, strings.Join(fs, ","))
}
directWrite = func() string {
if len(values) == 1 {
return fmt.Sprintf(`%s %s = %s`, operation, name, anyToSqlString(values[0], true))
}
return fmt.Sprintf(`%s %s in %s`, operation, name, anyToSqlString(value, true))
}
case "notin", "not_in":
values := m.parseToSlice(value)
if len(values) == 0 {
return ""
}
makeSqlStr = func() string {
if len(values) == 1 {
m.addValue(vName, values[0])
return fmt.Sprintf(`%s %s != ?`, operation, name)
}
fs := make([]string, len(values))
for i, s := range values {
m.addValue(fmt.Sprintf("%s.not_in(%d)", vName, i), s)
fs[i] = "?"
}
return fmt.Sprintf(`%s %s not in (%s)`, operation, name, strings.Join(fs, ","))
}
directWrite = func() string {
if len(values) == 1 {
return fmt.Sprintf(`%s %s != %s`, operation, name, anyToSqlString(values[0], true))
}
return fmt.Sprintf(`%s %s not in %s`, operation, name, anyToSqlString(value, true))
}
case "like": // 包含xx
makeSqlStr = func() string {
m.addValue(vName, "%"+anyToSqlString(value, false)+"%")
return fmt.Sprintf(`%s %s like ?`, operation, name)
}
directWrite = func() string {
return fmt.Sprintf(`%s %s like '%%%s%%'`, operation, name, anyToSqlString(value, false))
}
case "likestart", "like_start": // 以xx开始
makeSqlStr = func() string {
m.addValue(vName, anyToSqlString(value, false)+"%")
return fmt.Sprintf(`%s %s like ?`, operation, name)
}
directWrite = func() string {
return fmt.Sprintf(`%s %s like '%s%%'`, operation, name, anyToSqlString(value, false))
}
case "likeend", "like_end": // 以xx结束
makeSqlStr = func() string {
m.addValue(vName, "%"+anyToSqlString(value, false))
return fmt.Sprintf(`%s %s like ?`, operation, name)
}
directWrite = func() string {
return fmt.Sprintf(`%s %s like '%%%s'`, operation, name, anyToSqlString(value, false))
}
default:
panic(fmt.Errorf(`syntax error, non-supported flag "%s"`, flag))
}
// 直接模式, 将值写入sql语句
if direct_opt {
return directWrite()
}
return makeSqlStr()
}
func (m *sqlTemplate) Render(sql_template string) string {
result := m.replaceAllFunc(sql_template, func(s string, crust bool) string {
if crust {
s = s[1 : len(s)-1]
}
operation, name, flag, opts, err := m.sqlTemplateSyntaxParse(s)
if err != nil {
panic(err)
}
return m.sqlTranslate(operation, name, flag, opts)
})
return m.repairSql(result)
}
func (m *sqlTemplate) sqlTranslate(operation, name, flag string, opts string) string {
// 选项检查
var attention_opt, must_opt bool
for _, o := range opts {
switch o {
case 'a':
attention_opt = true
case 'd':
case 'm':
must_opt = true
default:
panic(fmt.Sprintf(`syntax error, non-supported option "%s"`, string(o)))
}
}
switch operation {
case "#":
attention_opt = true
case "@":
attention_opt = false
}
value, has := m.data[name+"["+strconv.Itoa(m.keyCounter.Incr(name))+"]"]
if !has {
value, has = m.data[name]
}
if !has {
value, has = m.data["*["+strconv.Itoa(m.sub)+"]"]
}
m.sub++ // 每次一定+1
// 无值返回空sql语句
if !has {
if must_opt {
panic(fmt.Sprintf(`"%s" must have a value`, name))
}
return ""
}
// 非注意模式, 零值返回空sql语句
if !attention_opt && IsZero(value) {
return ""
}
switch operation {
case "&":
operation = "and"
case "|":
operation = "or"
case "#":
// nil改为null
if value == nil {
return "null"
}
return anyToSqlString(value, true)
case "@":
return anyToSqlString(value, false)
default:
panic(fmt.Errorf(`syntax error, non-supported operation "%s"`, operation))
}
// nil 修改语句
if value == nil {
switch flag {
case "!=", "<>", "notin", "not_in", ">", "<":
return fmt.Sprintf(`%s %s is not null`, operation, name)
case "=", "like", "likestart", "like_start", "likeend", "like_end":
return fmt.Sprintf(`%s %s is null`, operation, name)
case "in", ">=", "<=":
return ""
}
}
var sql_str string
switch flag {
case ">", ">=", "<", "<=", "!=", "<>", "=":
sql_str = fmt.Sprintf(`%s %s %s %s`, operation, name, flag, anyToSqlString(value, true))
case "in":
values := m.parseToSlice(value)
if len(values) == 0 {
return ""
}
if len(values) == 1 {
return fmt.Sprintf(`%s %s = %s`, operation, name, anyToSqlString(values[0], true))
}
sql_str = fmt.Sprintf(`%s %s in %s`, operation, name, anyToSqlString(value, true))
case "notin", "not_in":
values := m.parseToSlice(value)
if len(values) == 0 {
return ""
}
if len(values) == 1 {
return fmt.Sprintf(`%s %s != %s`, operation, name, anyToSqlString(values[0], true))
}
sql_str = fmt.Sprintf(`%s %s not in %s`, operation, name, anyToSqlString(value, true))
case "like": // 包含xx
sql_str = fmt.Sprintf(`%s %s like '%%%s%%'`, operation, name, anyToSqlString(value, false))
case "likestart", "like_start": // 以xx开始
sql_str = fmt.Sprintf(`%s %s like '%s%%'`, operation, name, anyToSqlString(value, false))
case "likeend", "like_end": // 以xx结束
sql_str = fmt.Sprintf(`%s %s like '%%%s'`, operation, name, anyToSqlString(value, false))
default:
panic(fmt.Errorf(`syntax error, non-supported flag "%s"`, flag))
}
return sql_str
}
// 将数据解析为切片
func (m *sqlTemplate) parseToSlice(a interface{}) []interface{} {
switch v := a.(type) {
case nil:
return []interface{}{"null"}
case string, []byte, bool,
int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64,
float32, float64:
return []interface{}{v}
}
r_v := reflect.Indirect(reflect.ValueOf(a))
if r_v.Kind() != reflect.Slice && r_v.Kind() != reflect.Array {
return []interface{}{fmt.Sprint(a)}
}
l := r_v.Len()
out := make([]interface{}, 0, l)
for i := 0; i < l; i++ {
v := reflect.Indirect(r_v.Index(i)).Interface()
out = append(out, m.parseToSlice(v)...)
}
return out
}
// sql模板语法解析
//
// 语法格式: (操作符)(name)
// 语法格式: {(操作符)(name)}
// 语法格式: {(操作符)(name) (标志)}
// 语法格式: {(操作符)(name) (标志) (选项)}
// 语法格式: {(操作符)(name) (选项)}
//
// 操作符:
// &: 转为 and name flag value
// |: 转为 or name flag value
// #: 转为 value, 自带 attention 选项, 仅支持以下格式
// (操作符)(name)
// {(操作符)(name)}
// {(操作符)(name) (选项)}
// @: attention 选项无效且自带 direct 选项, 且不会为字符串加上引号, 仅支持以下格式, 一般用于写入一条语句
// (操作符)(name)
// {(操作符)(name)}
// {(操作符)(name) (选项)}
//
//
// name: 示例: a a2 a_2 a_2.b a_2.b_2
//
// 标志: > >= < <= != <> = in notin not_in like likestart like_start likeend like_end
//
// 选项:
// a: attention, 不会忽略参数值为该类型的零值
// d: direct, 直接将值写入sql语句中
// m: must, 必须传值, 值可以为零值
//
// 输入的values必须为:map[string]string, map[string]interface{},或按顺序传入值
//
// 寻值优先级:
// 匹配名下标 > 匹配名 > *下标
// 如: a[0] > a > *[0]
//
// 注意:
// 一般情况下如果name没有传参或为该类型的零值, 则替换为空字符串
// 如果name的值为nil, 不同的标志会转为不同的语句
// 我们不会去检查name是否完全符合变量名标志, 因为这是无意义且消耗资源的
// 变量名首位可以为数字, 变量中间可以连续出现多个小数点, 如 0..a 是合法的
//
// 示例:
// s := SqlRender("select * from t where &a {&b} {&c !=} {&d in} {|e} limit 1", map[string]interface{}{
// "a": 1,
// "b[0]": "2",
// "*[2]": 3.3,
// "d": []string{"4"},
// "e": nil,
// })
func (m *sqlTemplate) sqlTemplateSyntaxParse(text string) (operation, name, flag, opts string, err error) {
// 去头去尾
temp := strings.TrimSpace(text)
// 空数据
if temp == "" {
err = fmt.Errorf("syntax error, {%s}, empty data", text)
return
}
// 分离操作符
operation, temp = temp[:1], temp[1:]
// 缩进空格
temp = m.retractAllSpace(temp)
// 分离数据
texts := strings.SplitN(temp, " ", 4) // 4为考虑尾部可能有空格
if len(texts) >= 1 {
name = texts[0]
}
if len(texts) >= 2 {
flag = texts[1]
} else {
flag = defaultSqlCompareFlag
}
if len(texts) >= 3 {
opts = texts[2]
}
if len(texts) >= 4 && texts[3] != " " {
err = fmt.Errorf("syntax error, {%s}, redundant data", text)
return
}
// 检查操作符
if _, ok := sqlTemplateOperationMapp[int32(operation[0])]; !ok {
err = fmt.Errorf(`syntax error, {%s}, non-supported operation "%s"`, text, operation)
return
}
// 检查变量名
if name == "" {
err = fmt.Errorf("syntax error, {%s}, no variable name", text)
return
}
if name[0] == '.' || name[len(name)-1] == '.' {
err = fmt.Errorf("syntax error, {%s}, Invalid variable name", text)
return
}
for _, v := range []rune(name) {
if _, ok := templateVariableNameMap[v]; !ok {
err = fmt.Errorf("syntax error, {%s}, Invalid variable name", text)
return
}
}
// 检查标记
if _, ok := sqlTemplateFlagMapp[flag]; !ok {
if opts != "" {
err = fmt.Errorf(`syntax error, {%s}, non-supported flag "%s"`, text, flag)
return
}
flag, opts = defaultSqlCompareFlag, flag
}
// 检查选项
os := make(map[int32]struct{})
for _, o := range opts {
if _, ok := sqlTemplateOptsMapp[o]; !ok {
err = fmt.Errorf(`syntax error, {%s}, non-supported option "%s"`, text, string(o))
return
}
// 重复选项
if _, ok := os[o]; ok {
err = fmt.Errorf(`syntax error, {%s}, repetitive option "%s"`, text, string(o))
return
}
os[o] = struct{}{}
}
return
}
// sql模板解析
func SqlTemplateParse(sql_template string, values ...interface{}) (sql_str string, names []string, args []interface{}) {
return newSqlTemplate(values).Parse(sql_template)
}
// sql模板解析, 和SqlTemplateParse一样, 只是简短了函数名
func SqlParse(sql_template string, values ...interface{}) (sql_str string, names []string, args []interface{}) {
return newSqlTemplate(values).Parse(sql_template)
}
// sql模板渲染
//
// 值会直接写入sql语句中, 不支持sql注入检查
func SqlTemplateRender(sql_template string, values ...interface{}) string {
return newSqlTemplate(values).Render(sql_template)
}
// sql模板渲染, 和SqlTemplateRender一样, 只是简短了函数名
func SqlRender(sql_template string, values ...interface{}) string {
return newSqlTemplate(values).Render(sql_template)
}