-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdml_sql.go
74 lines (67 loc) · 1.75 KB
/
dml_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
package sqlsmith
import (
"errors"
"fmt"
"strings"
"github.com/you06/sqlsmith-go/builtin"
"github.com/you06/sqlsmith-go/types"
"github.com/you06/sqlsmith-go/util"
)
// SelectStmt make random select statement SQL
func (s *SQLSmith) SelectStmt(depth int) (string, error) {
tree := s.selectStmt(depth)
return s.Walk(tree)
}
// UpdateStmt make random update statement SQL
func (s *SQLSmith) UpdateStmt() (string, error) {
tree := s.updateStmt()
return s.Walk(tree)
}
// InsertStmtAST implement insert statement from AST
func (s *SQLSmith) InsertStmtAST() (string, error) {
tree := s.insertStmt()
return s.Walk(tree)
}
// InsertStmt make random insert statement SQL
func (s *SQLSmith) InsertStmt(fn bool) (string, error) {
if s.currDB == "" {
return "", errors.New("no table selected")
}
var table *types.Table
rdTableIndex := s.rd(len(s.Databases[s.currDB].Tables))
tableIndex := 0
for _, t := range s.Databases[s.currDB].Tables {
if rdTableIndex == tableIndex {
table = t
break
}
tableIndex++
}
var columns []*types.Column
var columnNames []string
for _, column := range table.Columns {
if column.Column == "id" {
continue
}
columns = append(columns, column)
columnNames = append(columnNames, fmt.Sprintf("`%s`", column.Column))
}
var vals []string
for _, column := range columns {
if fn && s.rdFloat64() < 0.5 {
builtinFn := builtin.GenerateFuncCallExpr(nil, s.rd(3), s.stable)
builtinStr, err := util.BufferOut(builtinFn)
if err != nil {
return "", err
}
vals = append(vals, builtinStr)
} else {
vals = append(vals, s.generateDataItem(column.DataType))
}
}
sql := fmt.Sprintf("INSERT INTO %s(%s) VALUES(%s)",
table.Table,
strings.Join(columnNames, ", "),
strings.Join(vals, ", "))
return sql, nil
}