Repository navigation
Expand file tree
/
Copy pathgenerate.go
More file actions
719 lines (674 loc) · 23.6 KB
/
Copy pathgenerate.go
File metadata and controls
719 lines (674 loc) · 23.6 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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package definitionc
import "webtyp.com/model"
import (
"os"
"path/filepath"
"sort"
"strings"
"webtyp.com/fmt"
)
// hasExcludedField reports whether the Definition drops any field from the
// generated struct. Only then does the output carry a filtered _schemaX literal:
// otherwise Schema() returns XModel.Fields and no field literal is re-emitted.
func hasExcludedField(fields []FieldInfo) bool {
for _, f := range fields {
if f.Exclude {
return true
}
}
return false
}
// GenerateForFile writes ORM implementations for all infos into one file.
func (o *Generator) GenerateForFile(infos []StructInfo, sourceFile string) error {
if len(infos) == 0 {
return nil
}
for _, info := range infos {
for _, f := range info.Fields {
if f.Item != model.ItemNone {
switch f.Type {
case model.FieldStruct, model.FieldStructSlice, model.FieldBlob, model.FieldIntSlice:
return fmt.Err(fmt.Sprintf("field %s: only scalar fields can be shown in a list item", f.ColumnName))
}
}
}
}
defs, err := o.packageDefinitions(filepath.Dir(sourceFile))
if err != nil {
return err
}
code, err := o.moduleCode(infos, sourceFile)
if err != nil {
return err
}
buf := fmt.Convert()
// File Header
buf.Write(GeneratedHeader + "\n\n")
buf.Write(fmt.Sprintf("package %s\n\n", infos[0].PackageName))
hasORM := false
// kindImports collects the packages that non-model kind constructors
// (webtyp/input kinds, project-custom kinds) live in, keyed by import path.
kindImports := make(map[string]string) // path -> alias used in the scanned source
for _, info := range infos {
if !info.NoDB {
hasORM = true
} else {
// Check if it has scalar FKs (SchemaExt)
for _, f := range info.Fields {
if f.Ref != "" && f.Type != model.FieldStruct && f.Type != model.FieldStructSlice {
hasORM = true
break
}
}
}
// Kind constructors (input.Email(), custom kinds) are only WRITTEN into the
// output inside the _schemaX literal, which exists only when a field is
// excluded — otherwise Schema() returns XModel.Fields and the generated file
// never names a kind. Importing them unconditionally emits an unused import,
// and the generated file does not compile.
if !hasExcludedField(info.Fields) {
continue
}
for _, f := range info.Fields {
if f.KindImportPath != "" {
kindImports[f.KindImportPath] = f.KindImportAlias
}
}
}
for _, info := range infos {
for _, f := range info.Fields {
if isInstant(f.GoType) {
kindImports[timeImportPath] = ""
}
}
hasItemLabel := false
for _, f := range info.Fields {
if f.Item == model.ItemLabel {
hasItemLabel = true
break
}
}
if hasItemLabel {
for _, f := range info.Fields {
if (f.Item != model.ItemNone || f.PK) && f.GoType != "string" {
kindImports["webtyp.com/fmt"] = ""
}
}
}
}
for path, alias := range code.imports {
kindImports[path] = alias
}
buf.Write("import (\n")
buf.Write("\t\"webtyp.com/model\"\n")
if hasORM {
buf.Write("\t\"webtyp.com/orm\"\n")
}
if len(kindImports) > 0 {
paths := make([]string, 0, len(kindImports))
for path := range kindImports {
paths = append(paths, path)
}
sort.Strings(paths)
for _, path := range paths {
alias := kindImports[path]
defaultAlias := path
if idx := strings.LastIndex(path, "/"); idx != -1 {
defaultAlias = path[idx+1:]
}
if alias != "" && alias != defaultAlias {
buf.Write(fmt.Sprintf("\t%s \"%s\"\n", alias, path))
} else {
buf.Write(fmt.Sprintf("\t\"%s\"\n", path))
}
}
}
buf.Write(")\n\n")
for _, info := range infos {
// Struct definition
buf.Write(fmt.Sprintf("type %s struct {\n", info.Name))
for _, f := range info.Fields {
buf.Write(fmt.Sprintf("\t%s %s\n", f.Name, f.GoType))
}
buf.Write("}\n\n")
// Model Interface Methods
buf.Write(fmt.Sprintf("func (m *%s) ModelName() string { return \"%s\" }\n\n", info.Name, info.ModelName))
if info.Wire {
// model.Wirer: a transport format; form.New refuses it.
buf.Write(fmt.Sprintf("func (m *%s) Wire() bool { return true }\n\n", info.Name))
}
for _, call := range info.ExternalCalls {
callTypeName := info.Name + fmt.Convert(call.Name).CamelUp().String()
buf.Write(fmt.Sprintf("// %s is the ExternalCall type for %s.%s.\n", callTypeName, info.ModelName, call.Name))
buf.Write(fmt.Sprintf("type %s struct{}\n\n", callTypeName))
buf.Write(fmt.Sprintf("func (%s) ModelName() string { return %q }\n\n", callTypeName, info.ModelName+"."+call.Name))
}
if hasExcludedField(info.Fields) {
buf.Write(fmt.Sprintf("var _schema%s = []model.Field{\n", info.Name))
for _, f := range info.Fields {
if f.Exclude {
continue
}
buf.Write(fmt.Sprintf("\t\t{Name: \"%s\", Type: %s", f.ColumnName, f.KindConstructor))
if !info.NoDB && (f.PK || f.Unique || f.AutoInc || f.Revision) {
buf.Write(", DB: &model.FieldDB{")
var parts []string
if f.PK {
parts = append(parts, "PK: true")
}
if f.Unique {
parts = append(parts, "Unique: true")
}
if f.AutoInc {
parts = append(parts, "AutoInc: true")
}
if f.Revision {
parts = append(parts, "Revision: true")
}
buf.Write(fmt.Convert(parts).Join(", ").String())
buf.Write("}")
}
if f.NotNull {
buf.Write(", NotNull: true")
}
if f.OmitEmpty {
buf.Write(", OmitEmpty: true")
}
writePermittedFields(buf, f)
buf.Write("},\n")
}
buf.Write("\t}\n\n")
buf.Write(fmt.Sprintf("func (m *%s) Schema() []model.Field { return _schema%s }\n\n", info.Name, info.Name))
} else {
buf.Write(fmt.Sprintf("func (m *%s) Schema() []model.Field { return %sModel.Fields }\n\n", info.Name, info.Name))
}
buf.Write(fmt.Sprintf("func (m *%s) Pointers() []any { return []any{", info.Name))
first := true
for _, f := range info.Fields {
if f.Exclude {
continue
}
if !first {
buf.Write(", ")
}
if isInstant(f.GoType) {
// Storage, codecs and forms read integers through *int64; a typed instant has int64 as its
// underlying type, so its address converts without copying.
buf.Write(fmt.Sprintf("(*int64)(&m.%s)", f.Name))
} else {
buf.Write(fmt.Sprintf("&m.%s", f.Name))
}
first = false
}
buf.Write("} }\n\n")
buf.Write(fmt.Sprintf("func (m *%s) IsNil() bool { return m == nil }\n\n", info.Name))
buf.Write(fmt.Sprintf("func (m *%s) EncodeFields(w model.FieldWriter) {\n", info.Name))
for _, f := range info.Fields {
if f.Exclude {
continue
}
var line string
switch f.Type {
case model.FieldText:
line = fmt.Sprintf("w.String(\"%s\", m.%s)", f.ColumnName, f.Name)
case model.FieldRaw:
line = fmt.Sprintf("w.Raw(\"%s\", m.%s)", f.ColumnName, f.Name)
case model.FieldInt:
if isInstant(f.GoType) {
line = fmt.Sprintf("w.Int(\"%s\", int64(m.%s))", f.ColumnName, f.Name)
} else {
line = fmt.Sprintf("w.Int(\"%s\", m.%s)", f.ColumnName, f.Name)
}
case model.FieldFloat:
line = fmt.Sprintf("w.Float(\"%s\", m.%s)", f.ColumnName, f.Name)
case model.FieldBool:
line = fmt.Sprintf("w.Bool(\"%s\", m.%s)", f.ColumnName, f.Name)
case model.FieldBlob:
line = fmt.Sprintf("w.Bytes(\"%s\", m.%s)", f.ColumnName, f.Name)
case model.FieldStruct:
if f.IsPointer {
if f.OmitEmpty {
line = fmt.Sprintf("w.Object(\"%s\", m.%s)", f.ColumnName, f.Name)
} else {
buf.Write(fmt.Sprintf("\tif m.%s != nil { w.Object(\"%s\", m.%s) } else { w.Null(\"%s\") }\n", f.Name, f.ColumnName, f.Name, f.ColumnName))
}
} else {
line = fmt.Sprintf("w.Object(\"%s\", &m.%s)", f.ColumnName, f.Name)
}
case model.FieldIntSlice:
if f.OmitEmpty {
buf.Write(fmt.Sprintf("\tif len(m.%s) != 0 {\n", f.Name))
}
buf.Write(fmt.Sprintf("\t\t{\n\t\t\tarr := w.Array(\"%s\", len(m.%s))\n\t\t\tfor _, x := range m.%s {\n\t\t\t\tarr.Int(int64(x))\n\t\t\t}\n\t\t}\n", f.ColumnName, f.Name, f.Name))
if f.OmitEmpty {
buf.Write("\t}\n")
}
case model.FieldStructSlice:
isPtr := fmt.HasPrefix(f.GoType, "[]*")
if f.OmitEmpty {
buf.Write(fmt.Sprintf("\tif len(m.%s) != 0 {\n", f.Name))
}
buf.Write(fmt.Sprintf("\t\t{\n\t\t\tarr := w.Array(\"%s\", len(m.%s))\n\t\t\tfor _, x := range m.%s {\n", f.ColumnName, f.Name, f.Name))
if isPtr {
buf.Write("\t\t\t\tif x != nil { arr.Object(x) }\n")
} else {
buf.Write("\t\t\t\tarr.Object(&x)\n")
}
buf.Write("\t\t\t}\n\t\t}\n")
if f.OmitEmpty {
buf.Write("\t}\n")
}
}
if f.OmitEmpty && line != "" {
guard := ""
switch f.Type {
case model.FieldText:
guard = fmt.Sprintf("m.%s != \"\"", f.Name)
case model.FieldRaw, model.FieldBlob:
guard = fmt.Sprintf("len(m.%s) != 0", f.Name)
case model.FieldInt, model.FieldFloat:
guard = fmt.Sprintf("m.%s != 0", f.Name)
case model.FieldBool:
guard = fmt.Sprintf("m.%s", f.Name)
case model.FieldStruct:
if f.IsPointer {
guard = fmt.Sprintf("m.%s != nil", f.Name)
}
}
if guard != "" {
buf.Write(fmt.Sprintf("\tif %s { %s }\n", guard, line))
continue
}
}
if line != "" {
buf.Write("\t" + line + "\n")
}
}
buf.Write("}\n\n")
buf.Write(fmt.Sprintf("func (m *%s) DecodeFields(r model.FieldReader) {\n", info.Name))
for _, f := range info.Fields {
if f.Exclude {
continue
}
switch f.Type {
case model.FieldText:
buf.Write(fmt.Sprintf("\tif v, ok := r.String(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
case model.FieldRaw:
buf.Write(fmt.Sprintf("\tif v, ok := r.Raw(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
case model.FieldInt:
if isInstant(f.GoType) {
buf.Write(fmt.Sprintf("\tif v, ok := r.Int(\"%s\"); ok { m.%s = %s(v) }\n", f.ColumnName, f.Name, f.GoType))
} else {
buf.Write(fmt.Sprintf("\tif v, ok := r.Int(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
}
case model.FieldFloat:
buf.Write(fmt.Sprintf("\tif v, ok := r.Float(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
case model.FieldBool:
buf.Write(fmt.Sprintf("\tif v, ok := r.Bool(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
case model.FieldBlob:
buf.Write(fmt.Sprintf("\tif v, ok := r.Bytes(\"%s\"); ok { m.%s = v }\n", f.ColumnName, f.Name))
case model.FieldStruct:
elemType := f.GoType
if f.IsPointer {
buf.Write(fmt.Sprintf("\tif m.%s == nil { m.%s = new(%s) }\n", f.Name, f.Name, elemType))
buf.Write(fmt.Sprintf("\tif !r.Object(\"%s\", m.%s) { m.%s = nil }\n", f.ColumnName, f.Name, f.Name))
} else {
buf.Write(fmt.Sprintf("\tr.Object(\"%s\", &m.%s)\n", f.ColumnName, f.Name))
}
case model.FieldIntSlice:
elemType := fmt.Convert(f.GoType).TrimPrefix("[]").String()
buf.Write(fmt.Sprintf("\tif arr, ok := r.Array(\"%s\"); ok {\n", f.ColumnName))
buf.Write(fmt.Sprintf("\t\tn := arr.Len()\n\t\tm.%s = make(%s, n)\n\t\tfor i := 0; i < n; i++ {\n\t\t\tm.%s[i] = %s(arr.Int(i))\n\t\t}\n\t}\n", f.Name, f.GoType, f.Name, elemType))
case model.FieldStructSlice:
isPtr := fmt.HasPrefix(f.GoType, "[]*")
elemType := fmt.Convert(f.GoType).TrimPrefix("[]").TrimPrefix("*").String()
buf.Write(fmt.Sprintf("\tif arr, ok := r.Array(\"%s\"); ok {\n", f.ColumnName))
buf.Write(fmt.Sprintf("\t\tn := arr.Len()\n\t\tm.%s = make(%s, n)\n\t\tfor i := 0; i < n; i++ {\n", f.Name, f.GoType))
if isPtr {
buf.Write(fmt.Sprintf("\t\t\tm.%s[i] = new(%s)\n", f.Name, elemType))
buf.Write(fmt.Sprintf("\t\t\tarr.Object(i, m.%s[i])\n", f.Name))
} else {
buf.Write(fmt.Sprintf("\t\t\tarr.Object(i, &m.%s[i])\n", f.Name))
}
buf.Write("\t\t}\n\t}\n")
}
}
buf.Write("}\n\n")
// RenameProvider
hasOldNames := false
for _, f := range info.Fields {
if f.OldName != "" {
hasOldNames = true
break
}
}
if hasOldNames {
buf.Write(fmt.Sprintf("func (m *%s) OldNames() map[string]string {\n", info.Name))
buf.Write("\treturn map[string]string{\n")
for _, f := range info.Fields {
if f.OldName != "" {
buf.Write(fmt.Sprintf("\t\t\"%s\": \"%s\",\n", f.ColumnName, f.OldName))
}
}
buf.Write("\t}\n}\n\n")
}
// A pure wire model the package keeps to itself (unexported, no action) is never a list
// of rows: it is no crud entity and no other package can name it, so its List would be
// dead code that every consumer's lint flags (mcp, 2026-11-30).
if !info.Wire || info.Allow != 0 || isExported(info.Name) {
buf.Write(fmt.Sprintf("type %sList []*%s\n\n", info.Name, info.Name))
// A list exposes only traversal: it is a sequence of rows and has no columns of
// its own, so model.FielderSlice does not embed model.Fielder. The schema comes
// from the element, via At/Append.
buf.Write(fmt.Sprintf("func (s *%sList) Len() int { return len(*s) }\n", info.Name))
buf.Write(fmt.Sprintf("func (s *%sList) At(i int) model.Fielder { return (*s)[i] }\n", info.Name))
buf.Write(fmt.Sprintf("func (s *%sList) Append() model.Fielder { v := &%s{}; *s = append(*s, v); return v }\n", info.Name, info.Name))
buf.Write(fmt.Sprintf("func (s *%sList) IsNil() bool { return s == nil }\n", info.Name))
buf.Write(fmt.Sprintf("func (s *%sList) EncodeFields(_ model.FieldWriter) {}\n", info.Name))
buf.Write(fmt.Sprintf("func (s *%sList) DecodeFields(_ model.FieldReader) {}\n\n", info.Name))
}
buf.Write(fmt.Sprintf("func (m *%s) Validate(action byte) error {\n", info.Name))
buf.Write("\treturn model.ValidateFields(action, m)\n")
buf.Write("}\n\n")
if !info.Wire && (!info.NoDB || info.Allow == uint8(model.Read)) {
buf.Write(fmt.Sprintf("func (*%s) Allow() model.Action { return %sModel.Allow }\n", info.Name, info.Name))
buf.Write(fmt.Sprintf("func (*%sList) Allow() model.Action { return %sModel.Allow }\n\n", info.Name, info.Name))
if info.ListsOnlyAfterSearch {
buf.Write(fmt.Sprintf("func (*%s) ListsOnlyAfterSearch() bool { return %sModel.ListsOnlyAfterSearch }\n\n", info.Name, info.Name))
}
}
writeItem(buf, info)
if !info.NoDB {
// Metadata Descriptors
buf.Write(fmt.Sprintf("var %s_ = struct {\n", info.Name))
for _, f := range info.Fields {
buf.Write(fmt.Sprintf("\t%s string\n", f.Name))
}
buf.Write("}{\n")
for _, f := range info.Fields {
buf.Write(fmt.Sprintf("\t%s: \"%s\",\n", f.Name, f.ColumnName))
}
buf.Write("}\n\n")
// Typed Read Operations
buf.Write(fmt.Sprintf("func ReadOne%s(qb *orm.QB, model *%s) (*%s, error) {\n", info.Name, info.Name, info.Name))
buf.Write("\terr := qb.ReadOne()\n")
buf.Write("\tif err != nil {\n")
buf.Write("\t\treturn nil, err\n")
buf.Write("\t}\n")
buf.Write("\treturn model, nil\n")
buf.Write("}\n\n")
buf.Write(fmt.Sprintf("func ReadAll%s(qb *orm.QB) (%sList, error) {\n", info.Name, info.Name))
buf.Write(fmt.Sprintf("\tvar results %sList\n", info.Name))
buf.Write("\terr := qb.ReadAll(\n")
buf.Write(fmt.Sprintf("\t\tfunc() model.Model { return &%s{} },\n", info.Name))
buf.Write(fmt.Sprintf("\t\tfunc(m model.Model) { results = append(results, m.(*%s)) },\n", info.Name))
buf.Write("\t)\n")
buf.Write("\treturn results, err\n")
buf.Write("}\n\n")
// SchemaExt
hasFK := false
for _, f := range info.Fields {
if f.Ref != "" && f.Type != model.FieldStruct && f.Type != model.FieldStructSlice {
hasFK = true
break
}
}
if hasFK {
buf.Write(fmt.Sprintf("func (m *%s) SchemaExt() []model.FieldExt {\n", info.Name))
buf.Write("\treturn []model.FieldExt{\n")
schemaVar := fmt.Sprintf("%sModel.Fields", info.Name)
if hasExcludedField(info.Fields) {
schemaVar = fmt.Sprintf("_schema%s", info.Name)
}
j := 0
for _, f := range info.Fields {
if f.Exclude {
continue
}
if f.Ref != "" && f.Type != model.FieldStruct && f.Type != model.FieldStructSlice {
refName := refTable(f.Ref, sourceFile, defs)
buf.Write(fmt.Sprintf("\t\t{Field: %s[%d], Ref: \"%s\", RefColumn: \"%s\", OnDelete: \"%s\"},\n", schemaVar, j, refName, f.RefColumn, f.OnDelete))
}
j++
}
buf.Write("\t}\n}\n\n")
}
}
}
buf.Write(code.body)
outName := fmt.Convert(sourceFile).TrimSuffix(".go").String() + GeneratedSuffix
if err := os.WriteFile(outName, buf.Bytes(), 0644); err != nil {
return err
}
return o.finishModule(code, sourceFile)
}
// refTable is the table a foreign key points at. A Definition of the same package is found by its
// variable and its declared Name is used: Ref: &FloorModel with Name "room_floor" → "room_floor".
// One of another package is not parsed here and keeps refTableName's reading of the variable.
func refTable(ref, from string, defs []StructInfo) string {
name := strings.TrimPrefix(ref, "&")
if !strings.Contains(name, ".") {
for _, d := range defs {
if d.Name+"Model" == name && filepath.Dir(d.SourceFile) == filepath.Dir(from) {
return d.ModelName
}
}
}
return refTableName(ref)
}
// packageDefinitions parses every Definition of the package in dir (generated and test files
// apart), so a foreign key can name a table declared in another file of the same package.
func (o *Generator) packageDefinitions(dir string) ([]StructInfo, error) {
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
var defs []StructInfo
for _, e := range entries {
n := e.Name()
if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") || strings.HasSuffix(n, "_gen.go") || strings.HasSuffix(n, "_crud.go") {
continue
}
infos, err := o.parseDefinitionsInFile(filepath.Join(dir, n))
if err != nil {
return nil, err
}
defs = append(defs, infos...)
}
return defs, nil
}
// refTableName is the table a foreign key points at, from the Definition variable the model names in Ref:
// "&UserModel" → "user". A Definition of another package keeps only its own name:
// "&devicemanager.DeviceModel" → "device" (the Go package is not part of the table's name).
// The generated SchemaExt and the stubs Models returns must agree, so both call it.
func refTableName(ref string) string {
ref = strings.TrimPrefix(ref, "&")
if i := strings.LastIndex(ref, "."); i >= 0 {
ref = ref[i+1:]
}
return ToSnakeCase(strings.TrimSuffix(ref, "Model"))
}
type modelStub struct {
name string
schema []model.Field
exts []model.FieldExt
}
func (m *modelStub) ModelName() string { return m.name }
func (m *modelStub) Schema() []model.Field { return m.schema }
func (m *modelStub) Pointers() []any { return nil }
func (m *modelStub) IsNil() bool { return m == nil }
func (m *modelStub) EncodeFields(_ model.FieldWriter) {}
func (m *modelStub) DecodeFields(_ model.FieldReader) {}
func (m *modelStub) SchemaExt() []model.FieldExt { return m.exts }
func newModelStub(info StructInfo, defs []StructInfo) *modelStub {
stub := &modelStub{name: info.ModelName}
for _, f := range info.Fields {
var kind model.Kind
switch goTypeToFieldType(f.GoType) {
case model.FieldInt:
// An instant keeps its unit: a diagram must tell seconds from nanoseconds.
switch f.GoType {
case goTypeUnix:
kind = model.UnixTime()
case goTypeNano:
kind = model.NanoTime()
default:
kind = model.Int()
}
case model.FieldFloat:
kind = model.Float()
case model.FieldBool:
kind = model.Bool()
case model.FieldBlob:
kind = model.Blob()
case model.FieldRaw:
kind = model.Raw()
case model.FieldStruct:
kind = model.Struct(nil)
case model.FieldIntSlice:
kind = model.IntSlice()
case model.FieldStructSlice:
kind = model.StructSlice(nil)
default:
kind = model.Text()
}
field := model.Field{
Name: f.ColumnName,
Type: kind,
NotNull: f.NotNull,
}
if f.Options != "" {
field.Options = &model.Definition{Name: refTable(f.Options, info.SourceFile, defs)}
}
if f.PK || f.Unique || f.AutoInc || f.Revision {
field.DB = &model.FieldDB{PK: f.PK, Unique: f.Unique, AutoInc: f.AutoInc, Revision: f.Revision}
}
if f.Maximum > 0 {
if field.DB == nil {
field.DB = &model.FieldDB{}
}
field.Maximum = f.Maximum
}
stub.schema = append(stub.schema, field)
if f.Ref != "" {
refName := refTable(f.Ref, info.SourceFile, defs)
stub.exts = append(stub.exts, model.FieldExt{
Field: field,
Ref: refName,
RefColumn: f.RefColumn,
OnDelete: f.OnDelete,
})
}
}
return stub
}
func goTypeToFieldType(goType string) model.FieldType {
switch goType {
case "int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64", goTypeUnix, goTypeNano:
return model.FieldInt
case "float32", "float64":
return model.FieldFloat
case "bool":
return model.FieldBool
case "[]byte":
return model.FieldBlob
default:
return model.FieldText
}
}
// Exporter is implemented by SQL adapter compilers (sqlt, postgres) that can render a
// full schema export. Defined here — not imported from ddlc — per Go convention: the
// consumer of a single-method interface owns the interface, not the implementer.
type Exporter interface {
ExportDDL(models []model.Model) (string, error)
}
// Models scans root for definition.go and returns one model.Model per database struct
// (NoDB structs skipped), in the order the files and declarations were read — the same root
// always gives the same order. A model's foreign keys are in its SchemaExt(). It returns
// ErrNoModelsFound when there is none.
func (g *Generator) Models(root string) ([]model.Model, error) {
g.rootDir = root
all, order, _, err := g.collectAllStructs()
if err != nil {
return nil, err
}
defs := make([]StructInfo, 0, len(order))
for _, name := range order {
defs = append(defs, all[name])
}
var models []model.Model
for _, info := range defs {
if info.NoDB {
continue
}
models = append(models, newModelStub(info, defs))
}
if len(models) == 0 {
return nil, ErrNoModelsFound
}
return models, nil
}
// ExportSQL scans the directory for models and returns the full DDL.
// Requires an injected Exporter (e.g. from sqlt or postgres).
func (g *Generator) ExportSQL(root string, exporter Exporter) (string, error) {
models, err := g.Models(root)
if err != nil {
return "", err
}
return exporter.ExportDDL(models)
}
// itemExpr is the Go expression turning field f of m into text for model.Item.
// A date field becomes seconds since 1970 (what the date/hour widgets read).
func itemExpr(f FieldInfo) string {
switch f.GoType {
case "string":
return "m." + f.Name
case goTypeNano:
return "fmt.Convert(int64(m." + f.Name + ")/1000000000).String()"
case goTypeUnix:
return "fmt.Convert(int64(m." + f.Name + ")).String()"
default:
return "fmt.Convert(m." + f.Name + ").String()"
}
}
func writeItem(buf *fmt.Conv, info StructInfo) {
var id, label, badge string
var desc []string
var pks []string
for _, f := range info.Fields {
if f.PK {
pks = append(pks, itemExpr(f))
}
switch f.Item {
case model.ItemLabel:
label = itemExpr(f)
case model.ItemDescription:
desc = append(desc, itemExpr(f))
case model.ItemBadge:
badge = itemExpr(f)
}
}
if len(pks) > 1 {
id = "model.JoinKey(" + strings.Join(pks, ", ") + ")"
} else if len(pks) == 1 {
id = pks[0]
}
if label == "" {
return // not a listed model: no Item()
}
parts := []string{"ID: " + id, "Label: " + label}
switch len(desc) {
case 0:
case 1:
parts = append(parts, "Description: "+desc[0])
default:
parts = append(parts, "Description: model.JoinItem("+strings.Join(desc, ", ")+")")
}
if badge != "" {
parts = append(parts, "Badge: "+badge)
}
buf.Write(fmt.Sprintf("func (m *%s) Item() model.Item {\n\treturn model.Item{%s}\n}\n\n", info.Name, strings.Join(parts, ", ")))
}
// isExported reports whether a Go identifier is visible outside its package (starts with an upper-case letter).
func isExported(name string) bool { return name != "" && name[0] >= 'A' && name[0] <= 'Z' }