-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbtypegen.go
239 lines (204 loc) · 5.19 KB
/
dbtypegen.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
package dbtypegen
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"strings"
"github.com/iancoleman/strcase"
"github.com/k0kubun/sqldef/sqlparser"
"golang.org/x/tools/imports"
)
// Option is option for generator.
type Option func(*config)
type config struct {
pkg string
jsonType string
uuidType string
typeSuffix string
typePrefix string
tag string
}
// WithPackage returns an option that sets package name.
func WithPackage(pkg string) Option {
return func(cfg *config) {
cfg.pkg = pkg
}
}
// WithJSONType returns an option that sets json type.
func WithJSONType(jsonType string) Option {
return func(cfg *config) {
cfg.jsonType = jsonType
}
}
// WithUUIDType returns an option that sets uuid type.
func WithUUIDType(uuidType string) Option {
return func(cfg *config) {
cfg.uuidType = uuidType
}
}
// WithTypePrefix returns an option that sets type prefix.
func WithTypePrefix(typePrefix string) Option {
return func(cfg *config) {
cfg.typePrefix = typePrefix
}
}
// WithTypeSuffix returns an option that sets type suffix.
func WithTypeSuffix(typeSuffix string) Option {
return func(cfg *config) {
cfg.typeSuffix = typeSuffix
}
}
// WithTag returns an option that sets struct tag.
func WithTag(tag string) Option {
return func(cfg *config) {
cfg.tag = tag
}
}
func defaults() []Option {
return []Option{
WithPackage("dbtype"),
WithJSONType("json.RawMessage"),
WithUUIDType("string"),
WithTypePrefix(""),
WithTypeSuffix(""),
WithTag("db"),
}
}
type generator struct {
*config
}
// Generate generates go source code and returns the data.
func Generate(ctx context.Context, r io.Reader, opts ...Option) ([]byte, error) {
cfg := new(config)
opts = append(defaults(), opts...)
for _, opt := range opts {
opt(cfg)
}
g := &generator{config: cfg}
b := new(bytes.Buffer)
fp(b, "// Code generated by dbtypegen. DO NOT EDIT.")
fp(b, "\n")
fp(b, "package %s", g.pkg)
tokens := sqlparser.NewTokenizer(r)
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
stmt, err := sqlparser.ParseNext(tokens)
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, err
}
ddl, ok := stmt.(*sqlparser.DDL)
if !ok {
continue
}
if ddl.Action == "create" {
if err := g.generate(b, ddl); err != nil {
return nil, err
}
}
}
out, err := imports.Process("", b.Bytes(), nil)
if err != nil {
return nil, err
}
return out, nil
}
func (g *generator) generate(w io.Writer, ddl *sqlparser.DDL) error {
tableName := ddl.NewName.Name.String()
structName := g.typePrefix + toCamel(tableName) + g.typeSuffix
fp(w, "// %s is the type that represents table `%s`.", structName, tableName)
fp(w, "type %s struct {", structName)
if ddl.TableSpec == nil {
return nil
}
columns := make([]string, 0, len(ddl.TableSpec.Columns))
fields := make([]string, 0, len(ddl.TableSpec.Columns))
for _, c := range ddl.TableSpec.Columns {
var length int
if c.Type.Length != nil {
length = int(c.Type.Length.Type)
}
var typ string
switch strings.ToLower(c.Type.Type) {
case "varchar", "char", "text":
typ = "string"
case "int", "integer", "decimal", "numeric", "number", "smallint", "real":
typ = "int"
case "bigint", "timestamp":
typ = "int64"
case "tinyint":
if length == 1 {
typ = "bool"
} else {
typ = "int"
}
case "float", "double":
typ = "float64"
case "datetime", "date", "time", "year":
typ = "time.Time"
case "bool", "boolean":
typ = "bool"
case "json":
typ = g.jsonType
case "blob":
typ = "[]byte"
case "bit":
typ = "uint32"
case "uuid":
typ = g.uuidType
default:
return fmt.Errorf("unsupported type %s", c.Type.Type)
}
if c.Type.NotNull != nil && !*c.Type.NotNull {
typ = fmt.Sprintf("sql.Null%s", toCamel(typ))
}
columnName := c.Name.String()
fieldName := toCamel(columnName)
columns = append(columns, columnName)
fields = append(fields, fieldName)
fp(w, "%s %s `%s:\"%s\"`", fieldName, typ, g.tag, c.Name)
}
fp(w, "}")
fp(w, "\n")
columnsString := strings.Join(columns, ",")
fp(w, "// Columns returns all columns as joined string")
fp(w, "func (t *%s) Columns() string {", structName)
fp(w, "return \"%s\"", columnsString)
fp(w, "}")
fp(w, "\n")
fp(w, "// ColumnList returns all columns as slice of string.")
fp(w, "func (t *%s) ColumnList() []string {", structName)
fp(w, "return []string{\"%s\"}", strings.Join(columns, "\",\""))
fp(w, "}")
fp(w, "\n")
fp(w, "// TableName returns the name of table.")
fp(w, "func (t *%s) TableName() string {", structName)
fp(w, "return \"%s\"", tableName)
fp(w, "}")
fp(w, "\n")
fp(w, "// SelectAll returns a part of query like `SELECT id,name FROM people`.")
fp(w, "func (t *%s) SelectAll() string {", structName)
fp(w, "return \"SELECT %s FROM %s\"", columnsString, tableName)
fp(w, "}")
fp(w, "\n")
fp(w, "// ScanAll returns field's pointers for row.Scan.")
fp(w, "func (t *%s) ScanAll() []interface{} {", structName)
fp(w, "return []interface{}{&t.%s}", strings.Join(fields, ",&t."))
fp(w, "}")
fp(w, "\n")
return nil
}
func fp(w io.Writer, format string, args ...interface{}) {
fmt.Fprintf(w, "\n"+format, args...)
}
func toCamel(s string) string {
return strcase.ToCamel(s)
}