-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
677 lines (640 loc) · 15.8 KB
/
util.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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
/*
Nging is a toolbox for webmasters
Copyright (C) 2018-present Wenhui Shen <swh@admpub.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package mysql
import (
"bytes"
"database/sql"
"fmt"
"io"
"math"
"regexp"
"sort"
"strconv"
"strings"
"github.com/webx-top/com"
"github.com/webx-top/db/lib/factory"
"github.com/webx-top/echo"
)
func (m *mySQL) kvVal(sqlStr string) ([]map[string]string, error) {
r := []map[string]string{}
rows, err := m.newParam().SetCollection(sqlStr).Query()
if err != nil {
return r, err
}
defer rows.Close()
for rows.Next() {
var k sql.NullString
var v sql.NullString
err = rows.Scan(&k, &v)
if err != nil {
break
}
r = append(r, map[string]string{
"k": k.String,
"v": v.String,
})
}
return r, err
}
func (m *mySQL) newParam(dbfactory ...*factory.Factory) *factory.Param {
if len(dbfactory) > 0 && dbfactory[0] != nil {
return factory.NewParam(dbfactory[0])
}
return factory.NewParam(m.db)
}
func (m *mySQL) ok(msg string) {
m.SetOk(msg)
}
func (m *mySQL) checkErr(err error) interface{} {
return m.CheckErr(err)
}
func (m *mySQL) fail(msg string) {
m.SetFail(msg)
}
func (m *mySQL) getScopeGrant(object string) *Grant {
g := &Grant{Value: object}
if object == `*.*` {
g.Scope = `all`
return g
}
if strings.Contains(object, `@`) {
g.Scope = `proxy`
return g
}
strs := strings.SplitN(object, `.`, 2) // dbName.* / dbName.tableName / `dbName`.`tableName`
for i, v := range strs {
v = strings.Trim(v, "`") // dbName.*
switch i {
case 0:
v = strings.Replace(v, `\`, ``, -1)
g.Database = v
case 1:
if v == `*` { // dbName.*
g.Scope = `database`
} else if strings.HasSuffix(v, `)`) { // `dbName`.`tableName`(`colName`,`colName`)
vs := strings.SplitN(v, `(`, 2)
switch len(vs) {
case 2:
g.Table = strings.TrimSpace(vs[0])
g.Table = strings.TrimSuffix(g.Table, "`")
g.Columns = strings.TrimSuffix(vs[1], `)`)
g.Scope = `column`
}
} else { // `dbName`.`tableName`
g.Table = strings.TrimSpace(v)
g.Table = strings.TrimSuffix(g.Table, "`")
g.Scope = `table`
}
}
}
return g
}
func quoteCol(col string) string {
return "`" + strings.Replace(com.AddSlashes(col), "`", "``", -1) + "`"
}
func quoteVal(val string, otherChars ...rune) string {
return "'" + com.AddSlashes(val, otherChars...) + "'"
}
func convertFields(columns []string, fields map[string]*Field, selects []string) string {
var r string
l := len(selects)
for _, colName := range columns {
quotedName := quoteCol(colName)
if l > 0 {
found := false
for _, val := range selects {
if quotedName == val {
found = true
break
}
}
if !found {
continue
}
}
field, ok := fields[colName]
if !ok {
continue
}
as := convertField(field)
if len(as) > 0 {
r += ", " + as + " AS " + quotedName
}
}
return r
}
/** Convert field in select and edit
* @param array one element from fields()
* @return string
*/
func convertField(field *Field) string {
if strings.Contains(field.Type, "binary") {
return "HEX(" + quoteCol(field.Field) + ")"
}
if field.Type == "bit" {
return "BIN(" + quoteCol(field.Field) + " + 0)" // + 0 is required outside MySQLnd
}
switch {
case strings.Contains(field.Type, "geometry"),
strings.Contains(field.Type, "point"),
strings.Contains(field.Type, "linestring"),
strings.Contains(field.Type, "polygon"):
return "AsWKT(" + quoteCol(field.Field) + ")"
}
return ``
}
/** Convert value in edit after applying functions back
* @param array one element from fields()
* @param string
* @return string
*/
func unconvertField(field *Field, ret string) string {
if strings.Contains(field.Type, "binary") {
return "UNHEX(" + ret + ")"
}
if field.Type == "bit" {
return "CONV(" + ret + ", 2, 10) + 0"
}
switch {
case strings.Contains(field.Type, "geometry"),
strings.Contains(field.Type, "point"),
strings.Contains(field.Type, "linestring"),
strings.Contains(field.Type, "polygon"):
return "GeomFromText(" + ret + ")"
}
return ret
}
/** Process edit input field
* @param one field from fields()
* @return string or false to leave the original value
*/
func (m *mySQL) processInputFieldValue(field *Field) (string, bool) {
idf := bracketEscape(field.Field, false)
if field.Type == "set" {
total := 0
for _, v := range m.FormValues("value[" + idf + "][]") {
i, _ := strconv.Atoi(v)
total += i
}
return strconv.Itoa(total), true
}
value := m.Form("value[" + idf + "]")
if field.Type == "enum" {
i, _ := strconv.Atoi(value)
if i == -1 {
return ``, false
}
if len(value) == 0 {
return "NULL", true
}
return strconv.Itoa(i), true
}
if field.AutoIncrement.Valid && len(value) == 0 {
return ``, false
}
function := m.Form("function[" + idf + "]")
switch function {
case "orig":
if field.On_update == "CURRENT_TIMESTAMP" {
return quoteCol(field.Field), true
}
return ``, false
case "NULL":
return "NULL", true
case "json":
return value, true
}
if reFieldTypeBlob.MatchString(field.Type) {
buf := new(bytes.Buffer)
_, e := m.SaveUploadedFileToWriter("value["+idf+"]", buf)
if e != nil {
return ``, false
}
return quoteVal(buf.String()), true
}
return processInput(field, value, function), true
}
func processInput(field *Field, value string, function string) string {
switch function {
case `SQL`:
return value // SQL injection
case `now`, `getdate`, `uuid`:
return function + `()`
case `current_date`, `current_timestamp`:
return function + `()`
case `unix_timestamp(now)`: // 秒数字
return `unix_timestamp(now())`
case `unix_timestamp_ms(now)`: // 毫秒数字
return `REPLACE(unix_timestamp(current_timestamp(3)),'.','')`
case `addtime`, `subtime`, `concat`:
return function + `(` + quoteCol(field.Field) + `,` + quoteVal(value) + `)`
case `md5`, `sha1`, `password`, `encrypt`:
return function + `(` + quoteVal(value) + `)`
default:
ret := quoteVal(value)
if reFunctionAddOrSubOr.MatchString(function) {
ret = quoteCol(field.Field) + ` ` + function + ` ` + ret
} else if reFunctionInterval.MatchString(function) {
ret2 := ret
ret = quoteCol(field.Field) + ` ` + function + ` `
if reSQLValue.MatchString(value) {
ret += value
} else {
ret += ret2
}
}
return unconvertField(field, ret)
}
}
func getCharset(version string) string {
if com.VersionCompare(version, `5.5.3`) >= 0 {
return "utf8mb4"
}
return "utf8" // SHOW CHARSET would require an extra query
}
func applySQLFunction(function, column string) string {
if len(function) == 0 {
return column
}
switch function {
case `unixepoch`:
return `DATETIME(` + column + `, '` + function + `')`
case `count distinct`:
return `COUNT(DISTINCT ` + column + `)`
default:
return strings.ToUpper(function) + `(` + column + `)`
}
}
/** Find unique identifier of a row
* @param array
* @param array result of indexes()
* @return array or null if there is no unique identifier
*/
func uniqueArray(row map[string]*sql.NullString, indexes map[string]*Indexes) map[string]*sql.NullString {
ret := map[string]*sql.NullString{}
var hasPrimary bool
var hasUnique bool
for _, index := range indexes {
if index.Type == `PRIMARY` {
for _, key := range index.Columns {
v, y := row[key]
if !y {
hasPrimary = false
ret = map[string]*sql.NullString{}
break
}
hasPrimary = true
ret[key] = v
}
if hasPrimary {
return ret
}
} else {
if !hasUnique && index.Type == `UNIQUE` {
hasUnique = true
}
}
}
if len(ret) > 0 {
ret = map[string]*sql.NullString{}
}
if !hasUnique {
return ret
}
for _, index := range indexes {
if index.Type != `UNIQUE` {
continue
}
hasUnique = false
for _, key := range index.Columns {
v, y := row[key]
if !y {
hasUnique = false
ret = map[string]*sql.NullString{}
break
}
hasUnique = true
ret[key] = v
}
if hasUnique {
return ret
}
}
return ret
}
/** Escape or unescape string to use inside form []
* @param string
* @param bool
* @return string
*/
func bracketEscape(idf string, back bool) string {
// escape brackets inside name="x[]"
if back {
for k, v := range trans {
idf = strings.Replace(idf, v, k, -1)
}
return idf
}
for k, v := range trans {
idf = strings.Replace(idf, k, v, -1)
}
return idf
}
/** Escape column key used in where()
* @param string
* @return string
*/
func escapeKey(key string) string {
if match := reFieldName.FindAllString(key, 1); len(match) > 3 {
return match[1] + quoteCol(match[2]) + match[3] //! SQL injection
}
return quoteCol(key)
}
func (m *mySQL) editFunctions(field *Field) []string {
var r []string
if field.AutoIncrement.Valid {
r = append(r, m.T(`自动增量`))
} else {
if field.Null {
r = append(r, "NULL")
}
r = append(r, ``)
for key, functions := range editFunctions {
if key == 0 {
for pattern, values := range functions {
if len(pattern) == 0 {
r = append(r, values...)
} else {
re, err := regexp.Compile(pattern)
if err != nil {
m.Logger().Error(err)
continue
}
if !re.MatchString(field.Type) {
continue
}
r = append(r, values...)
}
}
continue
}
switch field.Type {
case `set`, `enum`:
default:
if !reFieldTypeBlob.MatchString(field.Type) {
r = append(r, `SQL`)
}
}
}
}
return r
}
func (m *mySQL) whereByMapx(where *echo.Mapx, null *echo.Mapx, fields map[string]*Field) string {
wheres := map[string]*echo.Mapx{}
nulls := map[string]*echo.Mapx{}
if where != nil {
wheres = where.Map
}
if null != nil {
nulls = null.Map
}
return m.where(wheres, nulls, fields)
}
func (m *mySQL) where(wheres map[string]*echo.Mapx, nulls map[string]*echo.Mapx, fields map[string]*Field) string {
r := []string{}
for key, mapx := range wheres {
if mapx == nil {
continue
}
key = bracketEscape(key, true)
column := escapeKey(key)
field, ok := fields[key]
if !ok {
continue
}
val := mapx.Value()
if (m.DbAuth.Driver == `mssql`) || (m.supportSQL && reOnlyFloatOrEmpty.MatchString(val)) {
r = append(r, column+" LIKE "+quoteVal(val, '%', '_'))
} else {
r = append(r, column+"="+unconvertField(field, quoteVal(val)))
}
/*
if m.supportSQL &&
(strings.Contains(field.Type, `char`) || strings.Contains(field.Type, `text`)) &&
reNotSpaceOrDashOrAt.MatchString(val) {
r = append(r, column+"="+quoteVal(val)+" COLLATE "+getCharset(m.getVersion())+"_bin")
}
*/
}
for key, mapx := range nulls {
if mapx == nil {
continue
}
key = mapx.Value()
r = append(r, escapeKey(key)+" IS NULL")
}
return strings.Join(r, " AND ")
}
func enumValues(field *Field) []*Enum {
r := make([]*Enum, len(field.Options))
for index, option := range field.Options {
r[index] = &Enum{
Int: index + 1,
String: option,
}
}
return r
}
func typeSetValues(field *Field) []*Enum {
r := make([]*Enum, len(field.Options))
for index, option := range field.Options {
r[index] = &Enum{
Int: typeSetNumber(index),
String: option,
}
}
return r
}
func typeSetNumber(i int) int {
return 1 << uint64(math.Abs(float64(i)))
}
/** Print CSV row
* @param array
* @return null
*/
func dumpCSV(isHeader bool, fields map[string]*Field, cols []string, row map[string]*sql.NullString, format string, writer io.Writer) {
var sep string
switch format {
case `csv`:
sep = `,`
case `tsv`:
sep = "\t"
default:
sep = ";"
}
vals := make([]string, len(cols))
if isHeader {
for idx, col := range cols {
if len(col) == 0 || reCSVText.MatchString(col) {
vals[idx] = `"` + strings.Replace(col, `"`, `""`, -1) + `"`
} else {
vals[idx] = col
}
}
} else {
for idx, col := range cols {
val := row[col]
v := val.String
field, ok := fields[col]
if ok {
v = field.Format(v)
}
if len(v) == 0 || reCSVText.MatchString(v) {
vals[idx] = `"` + strings.Replace(v, `"`, `""`, -1) + `"`
} else {
vals[idx] = v
}
}
}
writer.Write(com.Str2bytes(strings.Join(vals, sep) + "\r\n"))
}
func friendlyURL(v string) string {
return reFriendlyName.ReplaceAllString(v, `-`)
}
func safeScan(rows *sql.Rows, colNum int, recv ...interface{}) error {
if len(recv) <= colNum {
return rows.Scan(recv...)
}
return rows.Scan(recv[0:colNum]...)
}
type indexForm struct {
Indexes map[string]*Indexes
}
func diffIndexes(c echo.Context, formData map[string][]string, indexes map[string]*Indexes, indexTypes []string) ([]*indexItems, error) {
recv := &indexForm{
Indexes: map[string]*Indexes{},
}
err := c.MapData(recv, formData)
if err != nil {
return nil, err
}
alter := []*indexItems{}
keys := make([]int, 0, len(recv.Indexes))
for key := range recv.Indexes {
i, e := strconv.Atoi(key)
if e != nil {
continue
}
keys = append(keys, i)
}
sort.Ints(keys)
for _, i := range keys {
indexSet, ok := recv.Indexes[strconv.Itoa(i)]
if !ok {
continue
}
indexSet.Name = strings.TrimSpace(indexSet.Name)
indexSet.Type = strings.TrimSpace(indexSet.Type)
indexSet.With = strings.TrimSpace(indexSet.With)
item := &indexItems{
Indexes: indexSet,
Set: []string{},
}
if !com.InSlice(item.Type, indexTypes) {
continue
}
lenSize := len(item.Lengths)
descSize := len(item.Descs)
expSize := len(item.Expressions)
columns := []string{}
lengths := []string{}
descs := []string{}
expressions := []string{}
for key, col := range item.Columns {
if len(col) == 0 {
continue
}
var length, desc, exp, set string
if col == `$` {
if key < expSize {
exp = item.Expressions[key]
}
if len(exp) == 0 {
continue
}
set = `((` + exp + `))`
} else {
set = quoteCol(col)
if key < lenSize {
length = item.Lengths[key]
}
if len(length) > 0 {
set += `(` + length + `)`
}
if key < descSize {
desc = item.Descs[key]
}
if len(desc) > 0 {
switch desc {
case `DESC`:
set += ` DESC`
case `ASC`:
set += ` ASC`
}
}
}
item.Set = append(item.Set, set)
columns = append(columns, col)
lengths = append(lengths, length)
descs = append(descs, desc)
expressions = append(expressions, exp)
}
if len(columns) < 1 {
continue
}
if existing, ok := indexes[item.Name]; ok {
/*
fmt.Println(item.Type, `==`, existing.Type)
fmt.Printf(`columns:%#v`+" == %#v\n", columns, existing.Columns)
fmt.Printf(`lengths:%#v`+" == %#v\n", lengths, existing.Lengths)
fmt.Printf(`descs:%#v`+" == %#v\n", descs, existing.Descs)
// */
if len(item.With) > 0 && len(existing.With) > 0 && !strings.Contains(item.With, "`") {
existing.With = strings.ReplaceAll(existing.With, "`", "")
}
if item.Type == existing.Type &&
fmt.Sprintf(`%#v`, columns) == fmt.Sprintf(`%#v`, existing.Columns) &&
fmt.Sprintf(`%#v`, lengths) == fmt.Sprintf(`%#v`, existing.Lengths) &&
fmt.Sprintf(`%#v`, descs) == fmt.Sprintf(`%#v`, existing.Descs) &&
item.With == existing.With &&
fmt.Sprintf(`%#v`, expressions) == fmt.Sprintf(`%#v`, existing.Expressions) {
delete(indexes, item.Name)
continue
}
}
alter = append(alter, item)
}
for name, existing := range indexes {
alter = append(alter, &indexItems{
Indexes: &Indexes{
Name: name,
Type: existing.Type,
},
Set: []string{},
Operation: `DROP`,
})
}
return alter, err
}