/
generator.go
232 lines (209 loc) · 6.03 KB
/
generator.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
// Copyright (c) 2018-present Anbillon Team (anbillonteam@gmail.com).
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package main
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/gobuffalo/packr"
"github.com/iancoleman/strcase"
"golang.org/x/tools/imports"
)
const (
sqlbrickTemplate = "sqlbrick.tpl"
brickTemplate = "brick.tpl"
ddlTemplate = "ddl.tpl"
insertTemplate = "insert.tpl"
deleteTemplate = "delete.tpl"
updateTemplate = "update.tpl"
selectTemplate = "select.tpl"
)
var templates = map[QueryType]string{
QueryTypeCreate: ddlTemplate,
QueryTypeInsert: insertTemplate,
QueryTypeDelete: deleteTemplate,
QueryTypeUpdate: updateTemplate,
QueryTypeSelect: selectTemplate,
}
// Type definition for sqlbrick generator.
type Generator struct {
buf bytes.Buffer
box packr.Box
outputDir string
packageName string
}
// Type definition for sql functions used to generate sql func.
type SqlFunc struct {
BrickName string
FuncName string
Segments []string
Conditions []Condition
RemoveComma bool
IndexOfWhere int
Mapper MapperType
IsTx bool
ArgName string
Args []string
TotalArgs int
Comment string
}
// NewGenerator create a new Generator with output dir and package name.
func NewGenerator(outputDir string, packageName string) *Generator {
g := &Generator{
box: packr.NewBox("./templates"),
outputDir: outputDir,
packageName: packageName,
}
return g
}
// header add common headers in output files.
func (g *Generator) header(source string) {
g.Printf("// Code generated by github.com/anbillon/sqlbrick. DO NOT EDIT IT.")
g.NewLine()
g.NewLine()
if len(source) != 0 {
g.Printf(fmt.Sprintf("// This file is generated from: %v", source))
g.NewLine()
g.NewLine()
}
g.Printf("package " + g.packageName)
g.NewLine()
}
// Printf will add one line into the generator buffer.
func (g *Generator) Printf(format string, args ...interface{}) {
_, _ = fmt.Fprintf(&g.buf, format, args...)
}
// NewLine will add a new line to the generator buffer.
func (g *Generator) NewLine() {
g.Printf("\n")
}
// applyTemplate will apply data into template
func (g *Generator) applyTemplate(tplName string, data interface{}) error {
tplFuncMap := make(template.FuncMap)
cache := make(map[string]interface{})
tplFuncMap["ToSnake"] = strcase.ToSnake
tplFuncMap["Add"] = func(a, b int) int {
return a + b
}
tplFuncMap["CacheSet"] = func(key string, value interface{}) string {
cache[key] = value
return ""
}
tplFuncMap["CacheGet"] = func(key string) interface{} {
return cache[key]
}
tplContent, err := g.box.FindString(tplName)
if err != nil {
return err
}
tpl, err := template.New("").Funcs(tplFuncMap).Parse(tplContent)
if err != nil {
return err
}
return tpl.Execute(&g.buf, data)
}
// GenerateSqlBrick will add sql brick definition into the generator buffer.
func (g *Generator) GenerateSqlBrick(bricks []string, txMap map[string]bool) {
if err := g.applyTemplate(sqlbrickTemplate, struct {
Bricks []string
TxMap map[string]bool
}{
Bricks: bricks,
TxMap: txMap,
}); err != nil {
log.Printf("error: %v", err)
}
}
// CheckTx check if given statements has transaction.
func (g *Generator) CheckTx(statements []Statement) bool {
var hasTxStatement bool
for _, v := range statements {
if v.Definition.IsTx {
hasTxStatement = true
break
}
}
return hasTxStatement
}
// GenerateBrick will add brick definition into the generator buffer.
func (g *Generator) GenerateBrick(sourceFilename string, brick string,
syntaxes []Syntax, statements []Statement) {
hasTxStatement := g.CheckTx(statements)
if err := g.applyTemplate(brickTemplate, struct {
SourceFilename string
BrickName string
HasTx bool
Syntaxes []Syntax
}{
SourceFilename: sourceFilename,
BrickName: brick,
HasTx: hasTxStatement,
Syntaxes: syntaxes,
}); err != nil {
log.Printf("error: %v", err)
}
}
// Generate will add func into the generator buffer.
func (g *Generator) Generate(brickName string, statement Statement) {
dynamicQuery := statement.Query
definition := statement.Definition
queryType := dynamicQuery.QueryType
tpl, found := templates[queryType]
if !found {
log.Printf("no template found for given query:\n %v", dynamicQuery.Segments)
return
}
var argName = "args"
argsLen := dynamicQuery.Args
if len(argsLen) == 1 {
argName = dynamicQuery.Args[0]
}
if err := g.applyTemplate(tpl, SqlFunc{
BrickName: brickName,
FuncName: definition.Name,
Segments: dynamicQuery.Segments,
Conditions: dynamicQuery.Conditions,
IndexOfWhere: dynamicQuery.IndexOfWhere,
RemoveComma: dynamicQuery.RemoveLastComma,
Mapper: definition.Mapper,
IsTx: definition.IsTx,
Args: dynamicQuery.Args,
ArgName: argName,
TotalArgs: len(dynamicQuery.Args),
Comment: statement.Comment,
}); err != nil {
log.Printf("error: %v", err)
}
g.NewLine()
}
// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format(outputFilename string) []byte {
src, err := format.Source(g.buf.Bytes())
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: internal error: invalid Go generated: %s", err)
log.Printf("warning: compile the package to analyze the error")
return g.buf.Bytes()
}
importedSrc, err := imports.Process(outputFilename, src, nil)
if err != nil {
log.Printf("warning: internal error: invalid Go generated: %s", err)
}
return importedSrc
}
// Output will create a source code file and write all code.
func (g *Generator) Output(filename string) error {
if err := os.MkdirAll(g.outputDir, os.ModePerm); err != nil {
return err
}
outputFilename := filepath.Join(g.outputDir, strings.ToLower(filename))
return ioutil.WriteFile(outputFilename, g.format(outputFilename), 0644)
}