-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbuilder.go
More file actions
632 lines (518 loc) · 16.5 KB
/
builder.go
File metadata and controls
632 lines (518 loc) · 16.5 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
package sqlbuilder
import (
"database/sql"
"fmt"
"maps"
"reflect"
"regexp"
"strings"
"time"
"github.com/sunary/sqlize/sqltemplates"
"github.com/sunary/sqlize/utils"
)
// Tag prefixes
const (
SqlTagDefault = "sql"
prefixColumn = "column:" // set column name, eg: 'column:column_name'
prefixEmbedded = "embedded_prefix:" // set embed prefix for flatten struct, eg: 'embedded_prefix:base_'
prefixPreviousName = ",previous:" // mark previous name-field, eg: 'column:column_name,previous:old_name'
prefixType = "type:" // set field type, eg: 'type:VARCHAR(64)'
prefixDefault = "default:" // set default value, eg: 'default:0'
prefixComment = "comment:" // comment field, eg: 'comment:sth you want to comment'
)
// Special tags
const (
tagIsSquash = "squash"
tagIsEmbedded = "embedded"
tagEnum = "enum" // type:ENUM('open','close')
)
// Null and key constraints
const (
tagIsNull = "null"
tagIsNotNull = "not_null"
tagIsAutoIncrement = "auto_increment"
tagIsPrimaryKey = "primary_key" // this field is primary key, eg: 'primary_key'
)
// Index related
const (
tagIsIndex = "index" // indexing this field, eg: 'index' (=> idx_column_name)
tagIsUniqueIndex = "unique" // unique indexing this field, eg: 'unique' (=> idx_column_name)
prefixIndex = "index:" // indexing with name, eg: 'index:idx_name'
prefixUniqueIndex = "unique:" // unique indexing with name, eg: 'unique:idx_name'
prefixIndexColumns = "index_columns:" // indexing these fields, eg: 'index_columns:col1,col2' (=> idx_col1_col2)
prefixIndexType = "index_type:" // indexing with type, eg: 'index_type:btree' (default) or 'index_type:hash'
)
// Foreign key related
const (
prefixForeignKey = "foreign_key:" // 'foreign_key:'
prefixFkReferences = "references:" // 'references:'
prefixFkConstraint = "constraint:" // 'constraint:'
)
// Function names
const (
funcTableName = "TableName"
)
var (
reflectValueFields = map[string]struct{}{
"typ": {},
"ptr": {},
"flag": {},
}
ignoredFieldComment = map[string]struct{}{
"id": {},
"created_at": {},
"updated_at": {},
"deleted_at": {},
}
compileKeepEnumChar = regexp.MustCompile(`[^0-9A-Za-z,\\-_]+`)
)
// SqlBuilder ...
type SqlBuilder struct {
sql *sqltemplates.Sql
sqlTag string
dialect sqltemplates.SqlDialect
generateComment bool
pluralTableName bool
tables map[string]string
}
// NewSqlBuilder ...
func NewSqlBuilder(opts ...SqlBuilderOption) *SqlBuilder {
o := sqlBuilderOptions{
dialect: sqltemplates.MysqlDialect,
lowercase: false,
pluralTableName: false,
sqlTag: SqlTagDefault,
}
for i := range opts {
opts[i].apply(&o)
}
return &SqlBuilder{
sql: sqltemplates.NewSql(o.dialect, o.lowercase),
dialect: o.dialect,
sqlTag: o.sqlTag,
pluralTableName: o.pluralTableName,
generateComment: o.generateComment,
tables: map[string]string{},
}
}
// MappingTables ...
func (s *SqlBuilder) MappingTables(m map[string]string) {
maps.Copy(s.tables, m)
}
// AddTable ...
func (s SqlBuilder) AddTable(obj interface{}) string {
_, tableName := s.GetTableName(obj)
columns, columnsHistory, indexes := s.parseStruct(tableName, "", obj)
sqlPrimaryKey := s.sql.PrimaryOption()
for i := range columns {
if strings.Index(columns[i], sqlPrimaryKey) > 0 {
columns[0], columns[i] = columns[i], columns[0]
break
}
}
tableComment := ""
comments := []string{}
if s.generateComment {
switch s.dialect {
case sqltemplates.PostgresDialect:
comments = append(comments, fmt.Sprintf(s.sql.TableComment(), s.sql.EscapeSqlName(tableName), tableName))
default:
tableComment = " " + fmt.Sprintf(s.sql.TableComment(), tableName)
}
}
sqls := []string{fmt.Sprintf(s.sql.CreateTableStm(),
s.sql.EscapeSqlName(tableName),
strings.Join(columns, ",\n"), tableComment)}
for _, h := range columnsHistory {
sqls = append(sqls,
fmt.Sprintf(s.sql.AlterTableRenameColumnStm(),
s.sql.EscapeSqlName(tableName),
s.sql.EscapeSqlName(h[0]),
s.sql.EscapeSqlName(h[1])))
}
sqls = append(sqls, append(comments, indexes...)...)
return strings.Join(sqls, "\n")
}
type attrs struct {
// Basic attributes
Name string
Prefix string
Type string
Value string
Comment string
// Key and constraint attributes
IsPk bool
IsUnique bool
IsNull bool
IsNotNull bool
IsAutoIncr bool
// Foreign key
ForeignKey *fkAttrs
// Index attributes
Index string
IndexType string
IndexColumns string
// Special attribute
IsEmbedded bool
}
type fkAttrs struct {
Name string
Table string
Column string
RefTable string
RefColumn string
Constraint string
}
// parseStruct return columns, columnsHistory, indexes
func (s SqlBuilder) parseStruct(tableName, prefix string, obj interface{}) ([]string, [][2]string, []string) {
maxLen := 0
rawCols := make([][]string, 0)
embedColumns := make([]string, 0)
embedColumnsHistory := make([][2]string, 0)
embedIndexes := make([]string, 0)
columns := make([]string, 0)
columnsHistory := make([][2]string, 0)
comments := make([]string, 0)
indexes := make([]string, 0)
var pkFields []string
v := reflect.ValueOf(obj)
t := reflect.TypeOf(obj)
for j := 0; j < t.NumField(); j++ {
field := t.Field(j)
stag := field.Tag.Get(s.sqlTag)
if stag == "-" {
continue
}
at := attrs{
Name: prefix + utils.ToSnakeCase(field.Name),
}
xstag := strings.Split(stag, ";")
for _, ot := range xstag {
// normalize tag, convert `primaryKey` => `primary_key`
normTag := utils.ToSnakeCase(ot)
switch {
case strings.HasPrefix(normTag, prefixColumn):
columnNames := strings.Split(trimPrefix(ot, prefixColumn), prefixPreviousName)
if len(columnNames) == 1 {
at.Name = columnNames[0]
} else {
columnsHistory = append(columnsHistory, [2]string{columnNames[1], columnNames[0]})
at.Name = columnNames[1]
}
at.Name = prefix + at.Name
case strings.HasPrefix(normTag, prefixEmbedded):
at.Prefix = trimPrefix(ot, prefixEmbedded)
at.IsEmbedded = true
case strings.HasPrefix(normTag, prefixForeignKey):
if at.ForeignKey == nil {
at.ForeignKey = &fkAttrs{
Table: tableName,
RefColumn: trimPrefix(ot, prefixForeignKey),
}
}
objectNames := strings.Split(field.Type.String(), ".")
obName := objectNames[len(objectNames)-1]
if rt, ok := s.tables[obName]; ok {
at.ForeignKey.RefTable = rt
} else {
at.ForeignKey.RefTable = utils.ToSnakeCase(obName)
}
at.ForeignKey.Name = fmt.Sprintf("fk_%s_%s", at.ForeignKey.RefTable, tableName) // default
if at.ForeignKey.Column == "" {
at.ForeignKey.Column = at.ForeignKey.RefColumn // default, override by tag `references`
}
case strings.HasPrefix(normTag, prefixFkReferences):
if at.ForeignKey == nil {
at.ForeignKey = &fkAttrs{
Table: tableName,
}
}
at.ForeignKey.Column = trimPrefix(ot, prefixFkReferences)
case strings.HasPrefix(normTag, prefixFkConstraint):
if at.ForeignKey == nil {
at.ForeignKey = &fkAttrs{
Table: tableName,
}
}
at.ForeignKey.Constraint = trimPrefix(ot, prefixFkConstraint)
case strings.HasPrefix(normTag, prefixType):
at.Type = trimPrefix(ot, prefixType)
if s.generateComment && at.Comment == "" && strings.HasPrefix(strings.ToLower(at.Type), tagEnum) {
enumRaw := ot[len(prefixType)+len(tagEnum):] // this tag is safe, remove prefix: "type:ENUM"
enumStr := compileKeepEnumChar.ReplaceAllString(enumRaw, "")
at.Comment = createCommentFromEnum(strings.Split(enumStr, ","))
}
case strings.HasPrefix(normTag, prefixDefault):
at.Value = fmt.Sprintf(s.sql.DefaultOption(), trimPrefix(ot, (prefixDefault)))
case strings.HasPrefix(normTag, prefixComment):
at.Comment = trimPrefix(ot, prefixComment)
case normTag == tagIsPrimaryKey:
at.IsPk = true
case normTag == tagIsIndex:
at.Index = getWhenEmpty(at.Index, createIndexName("", nil, at.Name))
at.IndexColumns = s.sql.EscapeSqlName(at.Name)
case normTag == tagIsUniqueIndex:
at.IsUnique = true
at.Index = getWhenEmpty(at.Index, createIndexName("", nil, at.Name))
if at.IndexColumns == "" {
at.IndexColumns = s.sql.EscapeSqlName(at.Name)
}
case strings.HasPrefix(normTag, prefixIndex):
idxFields := strings.Split(trimPrefix(ot, prefixIndex), ",")
at.Index = createIndexName(prefix, idxFields, at.Name)
if len(idxFields) > 1 {
at.IndexColumns = strings.Join(s.sql.EscapeSqlNames(idxFields), ", ")
} else {
at.IndexColumns = s.sql.EscapeSqlName(at.Name)
}
case strings.HasPrefix(normTag, prefixUniqueIndex):
at.IsUnique = true
at.Index = createIndexName(prefix, []string{trimPrefix(ot, prefixUniqueIndex)}, at.Name)
at.IndexColumns = s.sql.EscapeSqlName(at.Name)
case strings.HasPrefix(normTag, prefixIndexColumns):
idxFields := strings.Split(trimPrefix(ot, prefixIndexColumns), ",")
if at.IsPk {
pkFields = idxFields
}
at.Index = createIndexName(prefix, idxFields, at.Name)
at.IndexColumns = strings.Join(s.sql.EscapeSqlNames(idxFields), ", ")
case strings.HasPrefix(normTag, prefixIndexType):
at.Index = getWhenEmpty(at.Index, createIndexName(prefix, nil, at.Name))
if len(at.IndexColumns) == 0 {
at.IndexColumns = strings.Join(s.sql.EscapeSqlNames([]string{at.Name}), ", ")
}
at.IndexType = trimPrefix(ot, prefixIndexType)
case normTag == tagIsNull:
at.IsNotNull = true
case normTag == tagIsNotNull:
at.IsNotNull = true
case normTag == tagIsAutoIncrement:
at.IsAutoIncr = true
case normTag == tagIsSquash, normTag == tagIsEmbedded:
at.IsEmbedded = true
}
}
if at.ForeignKey != nil {
indexes = append(indexes, fmt.Sprintf(s.sql.CreateForeignKeyStm(),
s.sql.EscapeSqlName(at.ForeignKey.Table), s.sql.EscapeSqlName(at.ForeignKey.Name), s.sql.EscapeSqlName(at.ForeignKey.Column),
s.sql.EscapeSqlName(at.ForeignKey.RefTable), s.sql.EscapeSqlName(at.ForeignKey.RefColumn)))
continue
}
if at.IsPk {
// create primary key multiple field as constraint
if len(pkFields) > 1 {
primaryKey := strings.Join(s.sql.EscapeSqlNames(pkFields), ", ")
indexes = append(indexes, fmt.Sprintf(s.sql.CreatePrimaryKeyStm(), tableName, primaryKey))
}
} else if at.Index != "" {
var strIndex string
if at.IsUnique {
strIndex = fmt.Sprintf(s.sql.CreateUniqueIndexStm(at.IndexType),
s.sql.EscapeSqlName(at.Index),
s.sql.EscapeSqlName(tableName), at.IndexColumns)
} else {
strIndex = fmt.Sprintf(s.sql.CreateIndexStm(at.IndexType),
s.sql.EscapeSqlName(at.Index),
s.sql.EscapeSqlName(tableName), at.IndexColumns)
}
indexes = append(indexes, strIndex)
}
if len(at.Name) > maxLen {
maxLen = len(at.Name)
}
col := []string{at.Name}
if at.Type != "" {
col = append(col, at.Type)
} else {
if _, ok := reflectValueFields[t.Field(j).Name]; ok {
continue
}
strType, isEmbedded := s.sqlType(v.Field(j).Interface(), "")
if isEmbedded && (at.IsEmbedded || len(at.Prefix) > 0) {
_columns, _columnsHistory, _indexes := s.parseStruct(tableName, prefix+at.Prefix, v.Field(j).Interface())
embedColumns = append(embedColumns, _columns...)
embedColumnsHistory = append(embedColumnsHistory, _columnsHistory...)
embedIndexes = append(embedIndexes, _indexes...)
continue
} else {
if isEmbedded { // default type for struct is "TEXT"
strType = s.sql.TextType()
}
col = append(col, strType)
}
}
if at.IsNotNull {
col = append(col, s.sql.NotNullValue())
} else if at.IsNull {
col = append(col, s.sql.NullValue())
}
if at.Value != "" {
col = append(col, at.Value)
}
if at.IsAutoIncr {
col = append(col, s.sql.AutoIncrementOption())
}
// primary key attribute appended after field
if at.IsPk && len(pkFields) <= 1 {
col = append(col, s.sql.PrimaryOption())
}
if s.generateComment && at.Comment == "" {
at.Comment = createCommentFromFieldName(at.Name)
}
if at.Comment != "" {
switch s.dialect {
case sqltemplates.PostgresDialect:
comments = append(comments,
fmt.Sprintf(s.sql.ColumnComment(), s.sql.EscapeSqlName(tableName), s.sql.EscapeSqlName(at.Name), at.Comment))
default:
col = append(col, fmt.Sprintf(s.sql.ColumnComment(), at.Comment))
}
}
rawCols = append(rawCols, col)
}
for _, f := range rawCols {
columns = append(columns,
fmt.Sprintf(" %s%s%s", s.sql.EscapeSqlName(f[0]), strings.Repeat(" ", maxLen-len(f[0])+1), strings.Join(f[1:], " ")))
}
return append(columns, embedColumns...),
append(columnsHistory, embedColumnsHistory...),
append(comments, append(indexes, embedIndexes...)...)
}
func getWhenEmpty(s, s2 string) string {
if s == "" {
return s2
}
return s
}
// because tag is norm
func trimPrefix(ot, prefix string) string {
if strings.HasPrefix(ot, prefix) {
return ot[len(prefix):]
}
// all prefix tag is end with `:`
return ot[strings.Index(ot, ":")+1:]
}
// RemoveTable ...
func (s SqlBuilder) RemoveTable(tb interface{}) string {
_, table := s.GetTableName(tb)
return fmt.Sprintf(s.sql.DropTableStm(), s.sql.EscapeSqlName(table))
}
// createIndexName format idx_field_names
func createIndexName(prefix string, indexColumns []string, column string) string {
cols := make([]string, len(indexColumns))
for i := range indexColumns {
cols[i] = prefix + indexColumns[i]
}
if len(indexColumns) == 1 && indexColumns[0] != column {
return indexColumns[0]
}
if len(indexColumns) == 0 {
indexColumns = []string{column}
}
return fmt.Sprintf("idx_%s", strings.Join(indexColumns, "_"))
}
// createCommentFromEnum by enum values or field name
func createCommentFromEnum(enums []string) string {
if len(enums) > 0 {
return fmt.Sprintf("enum values: %s", strings.Join(enums, ", "))
}
return ""
}
// createCommentFromFieldName by enum values or field name
func createCommentFromFieldName(column string) string {
if _, ok := ignoredFieldComment[column]; ok {
return ""
}
return strings.Replace(column, "_", " ", -1)
}
// prefix return sqlType, isEmbedded
func (s SqlBuilder) sqlType(v interface{}, suffix string) (string, bool) {
if t, ok := s.sqlNullType(v, s.sql.NullValue()); ok {
return t, false
}
switch reflect.ValueOf(v).Kind() {
case reflect.Ptr:
vv := reflect.Indirect(reflect.ValueOf(v))
if reflect.ValueOf(v).Pointer() == 0 || vv.IsZero() {
return s.sql.PointerType(), false
}
return s.sqlType(vv.Interface(), s.sql.NullValue())
case reflect.Struct:
if _, ok := v.(time.Time); ok {
break
}
return "", true
}
return s.sqlPrimitiveType(v, suffix), false
}
// sqlNullType return sqlNullType, isPrimitiveType
func (s SqlBuilder) sqlNullType(v interface{}, suffix string) (string, bool) {
if suffix != "" {
suffix = " " + suffix
}
switch v.(type) {
case sql.NullBool:
return s.sql.BooleanType() + suffix, true
case sql.NullInt32:
return s.sql.IntType() + suffix, true
case sql.NullInt64:
return s.sql.BigIntType() + suffix, true
case sql.NullFloat64:
return s.sql.DoubleType() + suffix, true
case sql.NullString:
return s.sql.TextType() + suffix, true
case sql.NullTime:
return s.sql.DatetimeType() + suffix, true
default:
return "", false
}
}
// sqlPrimitiveType ...
func (s SqlBuilder) sqlPrimitiveType(v interface{}, suffix string) string {
if suffix != "" {
suffix = " " + suffix
}
switch v.(type) {
case bool:
return s.sql.BooleanType() + suffix
case int8, uint8:
return s.sql.TinyIntType() + suffix
case int16, uint16:
return s.sql.SmallIntType() + suffix
case int, int32, uint32:
return s.sql.IntType() + suffix
case int64, uint64:
return s.sql.BigIntType() + suffix
case float32:
return s.sql.FloatType() + suffix
case float64:
return s.sql.DoubleType() + suffix
case string:
return s.sql.TextType() + suffix
case time.Time:
return s.sql.DatetimeType() + suffix
default:
return s.sql.UnspecificType()
}
}
// GetTableName read from TableNameFn or parse table name from model as snake_case
// return object name and table name
func (s SqlBuilder) GetTableName(t interface{}) (string, string) {
name := ""
if t := reflect.TypeOf(t); t.Kind() == reflect.Ptr {
name = t.Elem().Name()
} else {
name = t.Name()
}
st := reflect.TypeOf(t)
if _, ok := st.MethodByName(funcTableName); ok {
v := reflect.ValueOf(t).MethodByName(funcTableName).Call(nil)
if len(v) > 0 {
return name, v[0].String()
}
}
if s.pluralTableName {
name = name + "s"
}
return name, utils.ToSnakeCase(name)
}