-
Notifications
You must be signed in to change notification settings - Fork 18
/
clickhouse_orm_generator.go
348 lines (303 loc) · 12.1 KB
/
clickhouse_orm_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
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package Ch
import (
"bytes"
"fmt"
"os"
"sort"
"strings"
"github.com/kokizzu/gotro/I"
"github.com/kokizzu/gotro/L"
"github.com/kokizzu/gotro/S"
"github.com/kokizzu/gotro/X"
)
// quote import
func qi(importPath string) string {
return `
` + "`" + importPath + "`"
}
// backquote
func bq(importPath string) string {
return "`" + importPath + "`"
}
// double quote
//func dq(str string) string {
// return `"` + str + `"`
//}
var typeTranslator = map[DataType]string{
//Uuid: `string`,
UInt64: `uint64`,
Float64: `float64`,
String: `string`,
Int64: `int64`,
IPv4: `net.IP`,
IPv6: `net.IP`,
DateTime: `time.Time`,
DateTime64: `time.Time`,
Int8: `int8`,
Int16: `int16`,
Int32: `int32`,
UInt8: `uint8`,
UInt16: `uint16`,
UInt32: `uint32`,
Float32: `float32`,
}
//var typeConverter = map[DataType]string{
// UInt64: `X.ToU`,
// Float64: `X.ToF`,
// String: `X.ToS`,
// Int64: `X.ToI`,
// Int8: `X.ToByte`,
//}
const connStruct = `Ch.Adapter`
const connImport = "\n\n\t_ `github.com/ClickHouse/clickhouse-go/v2`"
const buffImport = "\n\tchBuffer `github.com/kokizzu/ch-timed-buffer`"
const warning = "// DO NOT EDIT, will be overwritten by github.com/kokizzu/Ch/clickhouse_orm_generator.go\n\n"
func GenerateOrm(tables map[TableName]*TableProp) {
ci := L.CallerInfo(2)
this := L.CallerInfo()
pkgName := S.RightOfLast(ci.PackageName, `/`)
saPkgName := `sa` + pkgName[1:] // write/command (mutator)
L.Print(saPkgName)
mPkgName := `m` + pkgName[1:]
// generate
apBuf := bytes.Buffer{}
SA := func(str string) {
_, err := apBuf.WriteString(str)
L.PanicIf(err, `failed apBuf.WriteString`)
}
// sort by table name to keep the order when regenerating structs
tableNames := make([]string, 0, len(tables))
for k := range tables {
tableNames = append(tableNames, string(k))
}
sort.Strings(tableNames)
// check have IP
haveIp := false
for _, tableName := range tableNames {
props := tables[TableName(tableName)]
for _, prop := range props.Fields {
if prop.Type == IPv4 || prop.Type == IPv6 {
haveIp = true
break
}
}
}
//SA(`// generated: ` + time.Now().String() + "\n")
SA(`package ` + saPkgName)
SA("\n\n")
SA(warning)
SA(`import (`)
// import reader
SA(qi(`database/sql`))
if haveIp {
SA(qi(`net`))
}
SA(qi(`time`))
SA("\n")
SA(qi(ci.PackageName)) // /models/m*
SA(connImport)
SA(buffImport)
SA("\n")
SA(qi(`github.com/kokizzu/gotro/A`))
SA(qi(this.PackageName)) // github.com/kokizzu/gotro/D/Ch
SA(qi(`github.com/kokizzu/gotro/L`))
//SA(qi(`github.com/kokizzu/gotro/X`))
SA(`
)` + "\n\n")
SA(`//go:generate gomodifytags -all -add-tags json,form,query,long,msg -transform camelcase --skip-unexported -w -file ` + saPkgName + "__ORM.GEN.go\n")
SA(`//go:generate replacer -afterprefix "Id\" form" "Id,string\" form" type ` + saPkgName + "__ORM.GEN.go\n")
SA(`//go:generate replacer -afterprefix "json:\"id\"" "json:\"id,string\"" type ` + saPkgName + "__ORM.GEN.go\n")
SA(`//go:generate replacer -afterprefix "By\" form" "By,string\" form" type ` + saPkgName + "__ORM.GEN.go\n")
SA(`// go:generate msgp -tests=false -file ` + saPkgName + `__ORM.GEN.go -o ` + saPkgName + `__MSG.GEN.go` + "\n\n")
for _, tableName := range tableNames {
SA(`var ` + tableName + `Dummy = ` + S.PascalCase(tableName) + "{}\n")
}
SA("var Preparators = map[Ch.TableName]chBuffer.Preparator{\n")
for _, tableName := range tableNames {
SA(` ` + mPkgName + `.Table` + S.PascalCase(tableName) + `: func(tx *sql.Tx) *sql.Stmt {
query := ` + tableName + `Dummy.SqlInsert()
stmt, err := tx.Prepare(query)
L.IsError(err, ` + "`failed to tx.Prepare: `+query" + `)
return stmt
},
`)
}
SA("}\n")
// for each table generate in order
for _, tableName := range tableNames {
props := tables[TableName(tableName)]
structName := S.PascalCase(tableName)
maxLen := 1
for _, prop := range props.Fields {
l := len(prop.Name) + 1
if maxLen < l {
maxLen = l
}
}
// reader struct
SA(`type ` + structName + " struct {\n")
SA(" Adapter *" + connStruct + " `json:" + `"-"` + " msg:" + `"-"` + " query:" + `"-"` + " form:" + `"-"` + "`\n")
for _, prop := range props.Fields {
camel := S.PascalCase(prop.Name)
SA(" " + camel + strings.Repeat(` `, maxLen-len(camel)) + typeTranslator[prop.Type] + "\n")
}
SA("}\n\n")
// reader struct constructor
SA(`func New` + structName + `(adapter *` + connStruct + `) *` + structName + " {\n")
SA(` return &` + structName + "{Adapter: adapter}\n")
SA("}\n\n")
// field type map
SA("// " + structName + "FieldTypeMap returns key value of field name and key\n")
SA("var " + structName + "FieldTypeMap = map[string]Ch.DataType { //nolint:dupl false positive\n")
for _, field := range props.Fields {
SA(" " + S.BT(field.Name) + `:` + strings.Repeat(` `, maxLen-len(field.Name)) + TypeToConst[field.Type] + ",\n")
}
SA("}\n\n")
// table name
receiverName := strings.ToLower(string(structName[0]))
SA(`func (` + receiverName + ` *` + structName + ") TableName() Ch.TableName { //nolint:dupl false positive\n")
SA(" return " + mPkgName + `.Table` + structName + "\n")
SA("}\n\n")
// Sql table name
SA(`func (` + receiverName + ` *` + structName + ") SqlTableName() string { //nolint:dupl false positive\n")
SA(" return `" + `"` + tableName + `"` + "`\n")
SA("}\n\n")
// ScanRowAllColumns
SA(`func (` + receiverName + ` *` + structName + ") ScanRowAllCols(rows *sql.Rows) (err error) { //nolint:dupl false positive\n")
SA(" return rows.Scan(\n")
for _, prop := range props.Fields {
SA(" &" + receiverName + "." + S.PascalCase(prop.Name) + ",\n")
}
SA(" )\n")
SA("}\n\n")
// ScanRowsAllColumns
SA(`func (` + receiverName + ` *` + structName + ") ScanRowsAllCols(rows *sql.Rows, estimateRows int) (res []" + structName + ", err error) { //nolint:dupl false positive\n")
SA(" res = make([]" + structName + ", 0, estimateRows)\n")
SA(" defer rows.Close()\n")
SA(" for rows.Next() {\n")
SA(" var row " + structName + "\n")
SA(" err = row.ScanRowAllCols(rows)\n")
SA(" if err != nil {\n")
SA(" return\n")
SA(" }\n")
SA(" res = append(res, row)\n")
SA(" }\n")
SA(" return\n")
SA("}\n\n")
// insert, error if exists
SA("// insert, error if exists\n")
SA(`func (` + receiverName + ` *` + structName + ") SqlInsert() string { //nolint:dupl false positive\n")
qMark := S.Repeat(`,?`, len(props.Fields))[1:]
SA(" return `INSERT INTO ` + " + receiverName + ".SqlTableName() + ` (` + " + receiverName + ".SqlAllFields() + `) VALUES (" + qMark + ")`\n")
SA("}\n\n")
// total records
SA(`func (` + receiverName + ` *` + structName + ") SqlCount() string { //nolint:dupl false positive\n")
SA(" return `SELECT COUNT(*) FROM ` + " + receiverName + ".SqlTableName()\n")
SA("}\n\n")
// Sql select all fields, used when need to mutate or show every fields
SA(`func (` + receiverName + ` *` + structName + ") SqlSelectAllFields() string { //nolint:dupl false positive\n")
sqlFields := ``
for _, prop := range props.Fields {
sqlFields += `, ` + (prop.Name) + "\n\t"
}
SA(` return ` + bq(sqlFields[1:]) + "\n")
SA("}\n\n")
SA(`func (` + receiverName + ` *` + structName + ") SqlAllFields() string { //nolint:dupl false positive\n")
sqlFields = ``
for _, prop := range props.Fields {
sqlFields += `, ` + prop.Name + ""
}
SA(` return ` + bq(sqlFields[2:]) + "\n")
SA("}\n\n")
// to Insert parameter
SA(`func (` + receiverName + ` ` + structName + ") SqlInsertParam() []any { //nolint:dupl false positive\n")
SA(" return []any{\n")
for idx, prop := range props.Fields {
SA(" " + receiverName + "." + S.PascalCase(prop.Name) + ", // " + I.ToStr(idx) + " \n")
}
SA(" }\n")
SA("}\n\n")
for idx, prop := range props.Fields {
propName := S.PascalCase(prop.Name)
// index functions
SA(`func (` + receiverName + ` *` + structName + ") Idx" + propName + "() int { //nolint:dupl false positive\n")
SA(" return " + X.ToS(idx) + "\n")
SA("}\n\n")
// column name functions
//SA(`func (` + receiverName + ` *` + structName + ") col" + propName + "() string { //nolint:dupl false positive\n")
//SA(" return `" + prop.Name + "`\n")
//SA("}\n\n")
// Sql column name functions
SA(`func (` + receiverName + ` *` + structName + ") Sql" + propName + "() string { //nolint:dupl false positive\n")
SA(" return `" + prop.Name + "`\n")
SA("}\n\n")
}
// to AX
SA(`func (` + receiverName + ` *` + structName + ") ToArray() A.X { //nolint:dupl false positive\n")
SA(" return A.X{\n")
for idx, prop := range props.Fields {
camel := S.PascalCase(prop.Name)
SA(" " + receiverName + "." + camel + `,` + strings.Repeat(` `, maxLen-len(camel)) + `// ` + X.ToS(idx) + "\n")
}
SA(" }\n")
SA("}\n\n")
//// from AX
//SA(`func (` + receiverName + ` *` + structName + `) FromArray(a A.X) *` + structName + " { //nolint:dupl false positive\n")
//for idx, prop := range props.Fields {
// SA(" " + receiverName + "." + S.PascalCase(prop.Name) + ` = ` + typeConverter[prop.Type] + "(a[" + X.ToS(idx) + "])\n")
//}
//SA(" return " + receiverName + "\n")
//SA("}\n\n")
SA(warning)
}
err := os.MkdirAll(`./`+saPkgName, os.ModePerm)
if L.IsError(err, `os.MkDir failed: `+saPkgName) {
return
}
apFname := fmt.Sprintf(`./%s/%s__ORM.GEN.go`, saPkgName, saPkgName)
err = os.WriteFile(apFname, apBuf.Bytes(), os.ModePerm)
if L.IsError(err, `os.WriteFile failed: `+apFname) {
return
}
}
//func generateMutationByUniqueIndexumns(uniqueCamel, structProp, receiverName, structName string, AP, WC func(str string)) {
//
// //// primary fields
// //AP(`func (` + receiverName + ` *` + structName + ") PrimaryIndex() A.X { //nolint:dupl false positive\n")
// //AP(` return A.X{` + structProp + "}\n")
// //AP("}\n\n")
//
// // find by unique, used when need to mutate the object
// AP(`func (` + receiverName + ` *` + structName + `) FindBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
// //AP(" res, err := " + receiverName + ".Adapter.Select(" + receiverName + ".SpaceName(), " + receiverName + `.UniqueIndex` + uniqueCamel + `(), 0, 1, ` + iterEq + ", A.X{" + structProp + "})\n")
// AP(" if L.IsError(err, `" + structName + `.FindBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName()) {\n")
// AP(" return false\n")
// AP(" }\n")
// AP(" rows := res.Tuples()\n")
// AP(" if len(rows) == 1 {\n")
// AP(" " + receiverName + ".FromArray(rows[0])\n")
// AP(" return true\n")
// AP(" }\n")
// AP(" return false\n")
// AP("}\n\n")
//
// // Overwrite all columns, error if not exists
// WC("// Overwrite all columns, error if not exists\n")
// WC(`func (` + receiverName + ` *` + structName + `Mutator) DoOverwriteBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
// WC(" _, err := " + receiverName + `.Adapter.Update(` + receiverName + ".SpaceName(), " + receiverName + `.UniqueIndex` + uniqueCamel + "(), A.X{" + structProp + "}, " + receiverName + ".ToUpdateArray())\n")
// WC(" return !L.IsError(err, `" + structName + `.DoOverwriteBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
// WC("}\n\n")
//
// // Update only mutated, error if not exists
// WC("// Update only mutated, error if not exists, use Find* and Set* methods instead of direct assignment\n")
// WC(`func (` + receiverName + ` *` + structName + `Mutator) DoUpdateBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
// WC(" _, err := " + receiverName + `.Adapter.Update(` + receiverName + ".SpaceName(), " + receiverName + `.UniqueIndex` + uniqueCamel + "(), A.X{" + structProp + "}, " + receiverName + ".mutations)\n")
// WC(" return !L.IsError(err, `" + structName + `.DoUpdateBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
// WC("}\n\n")
//
// // permanent delete
// WC(`func (` + receiverName + ` *` + structName + `Mutator) DoDeletePermanentBy` + uniqueCamel + "() bool { //nolint:dupl false positive\n")
// WC(" _, err := " + receiverName + ".Adapter.Delete(" + receiverName + ".SpaceName(), " + receiverName + `.UniqueIndex` + uniqueCamel + `(), A.X{` + structProp + "})\n")
// WC(" return !L.IsError(err, `" + structName + `.DoDeletePermanentBy` + uniqueCamel + " failed: `+" + receiverName + ".SpaceName())\n")
// WC("}\n\n")
//}