forked from pingcap/go-randgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tables.go
133 lines (110 loc) · 2.42 KB
/
tables.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
package gendata
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/yuin/gopher-lua"
)
type Tables struct {
*options
}
var tablesTmpl = mustParse("tables", "create table {{.tname}} (\n"+
"`pk` int primary key%s\n"+
") {{.charsets}} {{.partitions}}")
// support vars
var tablesVars = []*varWithDefault{
{
"rows",
[]string{"0", "1", "2", "10", "100"},
},
{
"charsets",
[]string{"undef"},
},
{
"partitions",
[]string{"undef"},
},
}
// process function
var tableFuncs = map[string]func(string, *tableStmt) (string, error){
"rows": func(text string, stmt *tableStmt) (s string, e error) {
rows, err := strconv.Atoi(text)
if err != nil {
return "", err
}
stmt.rowNum = rows
return "", nil
},
"charsets": func(text string, stmt *tableStmt) (s string, e error) {
if text == "undef" {
return "", nil
}
return fmt.Sprintf("character set %s", text), nil
},
"partitions": func(text string, stmt *tableStmt) (s string, e error) {
if text == "undef" {
return "", nil
}
num, err := strconv.Atoi(text)
if err != nil {
return "", err
}
return fmt.Sprintf("\npartition by hash(pk)\npartitions %d", num), nil
},
}
func newTables(l *lua.LState) (*Tables, error) {
o, err := newOptions(tablesTmpl, l, "tables", tablesVars)
if err != nil {
return nil, err
}
return &Tables{o}, nil
}
func (t *Tables) gen() ([]*tableStmt, error) {
tnamePrefix := "table"
buf := &bytes.Buffer{}
m := make(map[string]string)
stmts := make([]*tableStmt, 0, t.numbers)
err := t.traverse(func(cur []string) error {
buf.Reset()
buf.WriteString(tnamePrefix)
stmt := &tableStmt{}
for i := range cur {
// current field name: fields[i]
// current field value: curr[i]
field := t.fields[i]
buf.WriteString("_" + cur[i])
target, err := tableFuncs[field](cur[i], stmt)
if err != nil {
return err
}
m[field] = target
}
tname := buf.String()
stmt.name = tname
m["tname"] = tname
stmt.format = t.format(m)
stmts = append(stmts, stmt)
return nil
})
if err != nil {
return nil, err
}
return stmts, nil
}
type tableStmt struct {
// create statement without field part
format string
// table name
name string
rowNum int
// generate by wrapInTable
ddl string
}
func (t *tableStmt) wrapInTable(fieldStmts []string) {
buf := &bytes.Buffer{}
buf.WriteString(",\n")
buf.WriteString(strings.Join(fieldStmts, ",\n"))
t.ddl = fmt.Sprintf(t.format, buf.String())
}