/
generate.go
313 lines (267 loc) · 6.72 KB
/
generate.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
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"text/template"
"unicode"
"github.com/BurntSushi/toml"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"github.com/spf13/cobra"
)
type boxType struct {
Name string
ValueType string
FormatCode string
}
type intBoxType struct {
Name string
BitSize int
}
type initData struct {
PkgName string
Version string
}
var pgToBoxTypeMap = map[string]string{
"bigint": "pgtype.Int8",
"integer": "pgtype.Int4",
"smallint": "pgtype.Int2",
"character varying": "pgtype.Varchar",
"text": "pgtype.Text",
"date": "pgtype.Date",
"timestamp with time zone": "pgtype.Timestamptz",
"inet": "pgtype.Inet",
"cidr": "pgtype.Cidr",
"bytea": "pgtype.Bytea",
}
var pgToGoTypeMap = map[string]string{
"bigint": "int64",
"integer": "int32",
"smallint": "int16",
"character varying": "string",
"text": "string",
"date": "time.Time",
"timestamp with time zone": "time.Time",
"bytea": "[]byte",
}
var acronyms = map[string]bool{
"id": true,
"ip": true,
"url": true,
}
type Config struct {
Package string
Tables []Table
}
type Column struct {
ColumnName string
DataType string
OrdinalPosition int32
FieldName string
GoBoxType string
VarName string
GoType string
}
type ColumnConfig struct {
ColumnName string `toml:"column_name"`
FieldName string `toml:"field_name"`
}
type Table struct {
TableName string `toml:"table_name"`
StructName string `toml:"struct_name"`
PrimaryKeyColumnNames []string `toml:"primary_key"`
ColumnConfigs []ColumnConfig `toml:"columns"`
Columns []Column
PrimaryKeyColumns []*Column
}
func generateCmd(cmd *cobra.Command, args []string) {
if len(args) != 0 {
fmt.Fprintln(os.Stderr, "generate does not take any arguments")
os.Exit(1)
}
var c Config
_, err := toml.DecodeFile("config.toml", &c)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
conn, err := pgx.Connect(context.Background(), "")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
err = inspectDatabase(conn, c.Tables)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
templates := loadTemplates()
supportData := initData{
PkgName: c.Package,
Version: VERSION,
}
supportFiles := []struct {
path string
tmpl *template.Template
}{
{"pgxdata_db.go", templates.Lookup("db")},
}
for _, f := range supportFiles {
err := writeSupportFile(f.path, f.tmpl, supportData)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
for _, t := range c.Tables {
file, err := os.Create("pgxdata_" + goCaseToFileCase(t.StructName) + ".go")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
err = writeTableCrud(file, templates, c.Package, t)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
file.Close()
}
}
type Queryer interface {
Query(ctx context.Context, sql string, args ...interface{}) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row
Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
}
func writeTableCrud(w io.Writer, templates *template.Template, pkgName string, table Table) error {
return templates.ExecuteTemplate(w, "row", struct {
PkgName string
TableName string
StructName string
Columns []Column
PrimaryKeyColumns []*Column
}{
PkgName: pkgName,
TableName: table.TableName,
StructName: table.StructName,
Columns: table.Columns,
PrimaryKeyColumns: table.PrimaryKeyColumns,
})
}
func inspectDatabase(db Queryer, tables []Table) error {
for i := range tables {
rows, err := db.Query(context.Background(), `select column_name, data_type, ordinal_position from information_schema.columns where table_name=$1`, tables[i].TableName)
if err != nil {
return err
}
var columns []Column
for rows.Next() {
var c Column
rows.Scan(&c.ColumnName, &c.DataType, &c.OrdinalPosition)
c.FieldName = pgCaseToGoPublicCase(c.ColumnName)
c.GoBoxType = pgTypeToGoBoxType(c.DataType)
c.VarName = pgCaseToGoPrivateCase(c.ColumnName)
c.GoType = pgTypeToGoType(c.DataType)
columns = append(columns, c)
}
if rows.Err() != nil {
return err
}
tables[i].Columns = columns
if len(tables[i].PrimaryKeyColumnNames) == 0 {
tables[i].PrimaryKeyColumnNames = []string{"id"}
}
for _, columnName := range tables[i].PrimaryKeyColumnNames {
var found bool
for j := range tables[i].Columns {
if tables[i].Columns[j].ColumnName == columnName {
tables[i].PrimaryKeyColumns = append(tables[i].PrimaryKeyColumns, &tables[i].Columns[j])
found = true
break
}
}
if !found {
return fmt.Errorf("table %s primary_key column %s not found", tables[i].TableName, columnName)
}
}
for _, cc := range tables[i].ColumnConfigs {
var found bool
for j := range tables[i].Columns {
if tables[i].Columns[j].ColumnName == cc.ColumnName {
if cc.FieldName != "" {
tables[i].Columns[j].FieldName = cc.FieldName
}
found = true
break
}
}
if !found {
return fmt.Errorf("table %s column %s not found", tables[i].TableName, cc.ColumnName)
}
}
}
return nil
}
func pgCaseToGoPublicCase(pg string) string {
parts := strings.Split(pg, "_")
buf := &bytes.Buffer{}
for _, s := range parts {
if acronyms[s] {
s = strings.ToUpper(s)
} else {
s = strings.Title(s)
}
buf.WriteString(s)
}
return buf.String()
}
func pgCaseToGoPrivateCase(pg string) string {
parts := strings.Split(pg, "_")
buf := &bytes.Buffer{}
for i, s := range parts {
if i == 0 {
s = strings.ToLower(s)
} else if acronyms[s] {
s = strings.ToUpper(s)
} else {
s = strings.Title(s)
}
buf.WriteString(s)
}
return buf.String()
}
func goCaseToFileCase(g string) string {
buf := &bytes.Buffer{}
for i, r := range g {
if unicode.IsUpper(r) && i != 0 {
buf.WriteRune('_')
}
buf.WriteRune(unicode.ToLower(r))
}
return buf.String()
}
func pgTypeToGoBoxType(pg string) string {
if t, ok := pgToBoxTypeMap[pg]; ok {
return t
} else {
return "pgtype.Varchar"
}
}
func pgTypeToGoType(pg string) string {
if t, ok := pgToGoTypeMap[pg]; ok {
return t
} else {
return "string"
}
}
func writeSupportFile(path string, tmpl *template.Template, data initData) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return tmpl.Execute(file, data)
}