-
Notifications
You must be signed in to change notification settings - Fork 893
/
graph.go
848 lines (794 loc) · 25 KB
/
graph.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
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
// Copyright 2019-present Facebook Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
// Package gen is the interface for generating loaded schemas into a Go package.
package gen
import (
"bytes"
"encoding/json"
"fmt"
"go/parser"
"go/token"
"os"
"path/filepath"
"runtime/debug"
"strings"
"text/template/parse"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/load"
"entgo.io/ent/schema/field"
"golang.org/x/tools/imports"
)
type (
// The Config holds the global codegen configuration to be
// shared between all generated nodes.
Config struct {
// Schema holds the Go package path for the user ent/schema.
// For example, "<project>/ent/schema".
Schema string
// Target defines the filepath for the target directory that
// holds the generated code. For example, "./project/ent".
//
// By default, 'ent generate ./ent/schema' uses './ent' as a
// target directory.
Target string
// Package defines the Go package path of the target directory
// mentioned above. For example, "github.com/org/project/ent".
//
// By default, for schema package named "<project>/ent/schema",
// 'ent generate' uses "<project>/ent" as a default package.
Package string
// Header allows users to provides an optional header signature for
// the generated files. It defaults to the standard 'go generate'
// format: '// Code generated by entc, DO NOT EDIT.'.
Header string
// Storage configuration for the codegen. Defaults to sql.
Storage *Storage
// IDType specifies the type of the id field in the codegen.
// The supported types are string and int, which also the default.
IDType *field.TypeInfo
// Templates specifies a list of alternative templates to execute or
// to override the default. If nil, the default template is used.
//
// Note that, additional templates are executed on the Graph object and
// the execution output is stored in a file derived by the template name.
Templates []*Template
// Features defines a list of additional features to add to the codegen phase.
// For example, the PrivacyFeature.
Features []Feature
// Hooks holds an optional list of Hooks to apply on the graph before/after the code-generation.
Hooks []Hook
// Annotations that are injected to the Config object can be accessed
// globally in all templates. In order to access an annotation from a
// graph template, do the following:
//
// {{- with $.Annotations.GQL }}
// {{/* Annotation usage goes here. */}}
// {{- end }}
//
// For type templates, we access the Config field to access the global
// annotations, and not the type-specific annotation.
//
// {{- with $.Config.Annotations.GQL }}
// {{/* Annotation usage goes here. */}}
// {{- end }}
//
// Note that the mapping is from the annotation-name (e.g. "GQL") to a JSON decoded object.
Annotations Annotations
}
// Graph holds the nodes/entities of the loaded graph schema. Note that, it doesn't
// hold the edges of the graph. Instead, each Type holds the edges for other Types.
Graph struct {
*Config
// Nodes are list of Go types that mapped to the types in the loaded schema.
Nodes []*Type
// Schemas holds the raw interfaces for the loaded schemas.
Schemas []*load.Schema
}
// Generator is the interface that wraps the Generate method.
Generator interface {
// Generate generates the ent artifacts for the given graph.
Generate(*Graph) error
}
// The GenerateFunc type is an adapter to allow the use of ordinary
// function as Generator. If f is a function with the appropriate signature,
// GenerateFunc(f) is a Generator that calls f.
GenerateFunc func(*Graph) error
// Hook defines the "generate middleware". A function that gets a Generator
// and returns a Generator. For example:
//
// hook := func(next gen.Generator) gen.Generator {
// return gen.GenerateFunc(func(g *Graph) error {
// fmt.Println("Graph:", g)
// return next.Generate(g)
// })
// }
//
Hook func(Generator) Generator
// Annotations defines code generation annotations to be passed to the templates.
// It can be defined on most elements in the schema (node, field, edge), or globally
// on the Config object.
// The mapping is from the annotation name (e.g. "EntGQL") to the annotation itself.
// Note that, annotations that are defined in the schema must be JSON encoded/decoded.
Annotations map[string]interface{}
)
// Generate calls f(g).
func (f GenerateFunc) Generate(g *Graph) error {
return f(g)
}
// NewGraph creates a new Graph for the code generation from the given schema definitions.
// It fails if one of the schemas is invalid.
func NewGraph(c *Config, schemas ...*load.Schema) (g *Graph, err error) {
defer catch(&err)
g = &Graph{c, make([]*Type, 0, len(schemas)), schemas}
for i := range schemas {
g.addNode(schemas[i])
}
for i := range schemas {
g.addEdges(schemas[i])
}
for _, t := range g.Nodes {
check(resolve(t), "resolve %q relations", t.Name)
}
for _, t := range g.Nodes {
check(t.setupFKs(), "set %q foreign-keys", t.Name)
}
for i := range schemas {
g.addIndexes(schemas[i])
}
aliases(g)
g.defaults()
return
}
// defaultIDType holds the default value for IDType.
var defaultIDType = &field.TypeInfo{Type: field.TypeInt}
// defaults sets the default value of the IDType. The IDType field is used
// by multiple templates. If the IDType wasn't provided, it will fallback to
// int, or the one used in the schema (if all schemas share the same IDType).
func (g *Graph) defaults() {
if g.IDType != nil {
return
}
if len(g.Nodes) == 0 {
g.IDType = defaultIDType
return
}
// Check that all nodes have the same type for the ID field.
for i := 0; i < len(g.Nodes)-1; i++ {
cid, nid := g.Nodes[i].ID.Type, g.Nodes[i+1].ID.Type
if cid.Type != nid.Type {
g.IDType = defaultIDType
return
}
}
g.IDType = g.Nodes[0].ID.Type
}
// Gen generates the artifacts for the graph.
func (g *Graph) Gen() error {
var gen Generator = GenerateFunc(generate)
for i := len(g.Hooks) - 1; i >= 0; i-- {
gen = g.Hooks[i](gen)
}
return gen.Generate(g)
}
// generate is the default Generator implementation.
func generate(g *Graph) error {
var (
assets assets
external []GraphTemplate
)
templates, external = g.templates()
for _, n := range g.Nodes {
assets.dirs = append(assets.dirs, filepath.Join(g.Config.Target, n.PackageDir()))
for _, tmpl := range Templates {
b := bytes.NewBuffer(nil)
if err := templates.ExecuteTemplate(b, tmpl.Name, n); err != nil {
return fmt.Errorf("execute template %q: %w", tmpl.Name, err)
}
assets.files = append(assets.files, file{
path: filepath.Join(g.Config.Target, tmpl.Format(n)),
content: b.Bytes(),
})
}
}
for _, tmpl := range append(GraphTemplates, external...) {
if tmpl.Skip != nil && tmpl.Skip(g) {
continue
}
if dir := filepath.Dir(tmpl.Format); dir != "." {
assets.dirs = append(assets.dirs, filepath.Join(g.Config.Target, dir))
}
b := bytes.NewBuffer(nil)
if err := templates.ExecuteTemplate(b, tmpl.Name, g); err != nil {
return fmt.Errorf("execute template %q: %w", tmpl.Name, err)
}
assets.files = append(assets.files, file{
path: filepath.Join(g.Config.Target, tmpl.Format),
content: b.Bytes(),
})
}
for _, f := range AllFeatures {
if f.cleanup == nil || g.featureEnabled(f) {
continue
}
if err := f.cleanup(g.Config); err != nil {
return fmt.Errorf("cleanup %q feature assets: %w", f.Name, err)
}
}
// Write and format assets only if template execution
// finished successfully.
if err := assets.write(); err != nil {
return err
}
// We can't run "imports" on files when the state is not completed.
// Because, "goimports" will drop undefined package. Therefore, it's
// suspended to the end of the writing.
return assets.format()
}
// addNode creates a new Type/Node/Ent to the graph.
func (g *Graph) addNode(schema *load.Schema) {
t, err := NewType(g.Config, schema)
check(err, "create type %s", schema.Name)
g.Nodes = append(g.Nodes, t)
}
// addIndexes adds the indexes for the schema type.
func (g *Graph) addIndexes(schema *load.Schema) {
typ, _ := g.typ(schema.Name)
for _, idx := range schema.Indexes {
check(typ.AddIndex(idx), "invalid index for schema %q", schema.Name)
}
}
// addEdges adds the node edges to the graph.
func (g *Graph) addEdges(schema *load.Schema) {
t, _ := g.typ(schema.Name)
seen := make(map[string]struct{}, len(schema.Edges))
for _, e := range schema.Edges {
typ, ok := g.typ(e.Type)
expect(ok, "type %q does not exist for edge", e.Type)
_, ok = t.fields[e.Name]
expect(!ok, "%s schema can't contain field and edge with the same name %q", schema.Name, e.Name)
_, ok = seen[e.Name]
expect(!ok, "%s schema contains multiple %q edges", schema.Name, e.Name)
seen[e.Name] = struct{}{}
switch {
// Assoc only.
case !e.Inverse:
t.Edges = append(t.Edges, &Edge{
def: e,
Type: typ,
Name: e.Name,
Owner: t,
Unique: e.Unique,
Optional: !e.Required,
StructTag: structTag(e.Name, e.Tag),
Annotations: e.Annotations,
})
// Inverse only.
case e.Inverse && e.Ref == nil:
expect(e.RefName != "", "missing reference name for inverse edge: %s.%s", t.Name, e.Name)
t.Edges = append(t.Edges, &Edge{
def: e,
Type: typ,
Name: e.Name,
Owner: typ,
Inverse: e.RefName,
Unique: e.Unique,
Optional: !e.Required,
StructTag: structTag(e.Name, e.Tag),
Annotations: e.Annotations,
})
// Inverse and assoc.
case e.Inverse:
ref := e.Ref
expect(e.RefName == "", "reference name is derived from the assoc name: %s.%s <-> %s.%s", t.Name, ref.Name, t.Name, e.Name)
expect(ref.Type == t.Name, "assoc-inverse edge allowed only as o2o relation of the same type")
from := &Edge{
def: e,
Type: typ,
Name: e.Name,
Owner: t,
Inverse: ref.Name,
Unique: e.Unique,
Optional: !e.Required,
StructTag: structTag(e.Name, e.Tag),
Annotations: e.Annotations,
}
to := &Edge{
def: ref,
Ref: from,
Type: typ,
Owner: t,
Name: ref.Name,
Unique: ref.Unique,
Optional: !ref.Required,
StructTag: structTag(ref.Name, ref.Tag),
Annotations: ref.Annotations,
}
from.Ref = to
t.Edges = append(t.Edges, from, to)
default:
panic(graphError{"edge must be either an assoc or inverse edge"})
}
}
}
// resolve resolves the type reference and relation of edges.
// It fails if one of the references is missing or invalid.
//
// relation definitions between A and B, where A is the owner of
// the edge and B uses this edge as a back-reference:
//
// O2O
// - A have a unique edge (E) to B, and B have a back-reference unique edge (E') for E.
// - A have a unique edge (E) to A.
//
// O2M (The "Many" side, keeps a reference to the "One" side).
// - A have an edge (E) to B (not unique), and B doesn't have a back-reference edge for E.
// - A have an edge (E) to B (not unique), and B have a back-reference unique edge (E') for E.
//
// M2O (The "Many" side, holds the reference to the "One" side).
// - A have a unique edge (E) to B, and B doesn't have a back-reference edge for E.
// - A have a unique edge (E) to B, and B have a back-reference non-unique edge (E') for E.
//
// M2M
// - A have an edge (E) to B (not unique), and B have a back-reference non-unique edge (E') for E.
// - A have an edge (E) to A (not unique).
//
func resolve(t *Type) error {
for _, e := range t.Edges {
switch {
case e.IsInverse():
ref, ok := e.Type.HasAssoc(e.Inverse)
if !ok {
return fmt.Errorf("edge %q is missing for inverse edge: %s.%s(%s)", e.Inverse, t.Name, e.Name, e.Type.Name)
}
if !e.Optional && !ref.Optional {
return fmt.Errorf("edges cannot be required in both directions: %s.%s <-> %s.%s", t.Name, e.Name, e.Type.Name, ref.Name)
}
if ref.Type != t {
return fmt.Errorf("mismatch type for back-ref %q of %s.%s <-> %s.%s", e.Inverse, t.Name, e.Name, e.Type.Name, ref.Name)
}
e.Ref, ref.Ref = ref, e
table := t.Table()
// Name the foreign-key column in a format that wouldn't change even if an inverse
// edge is dropped (or added). The format is: "<Edge-Owner>_<Edge-Name>".
column := fmt.Sprintf("%s_%s", e.Type.Label(), snake(ref.Name))
switch a, b := ref.Unique, e.Unique; {
// If the relation column is in the inverse side/table. The rule is simple, if assoc is O2M,
// then inverse is M2O and the relation is in its table.
case a && b:
e.Rel.Type, ref.Rel.Type = O2O, O2O
case !a && b:
e.Rel.Type, ref.Rel.Type = M2O, O2M
// If the relation column is in the assoc side.
case a && !b:
e.Rel.Type, ref.Rel.Type = O2M, M2O
table = e.Type.Table()
case !a && !b:
e.Rel.Type, ref.Rel.Type = M2M, M2M
table = e.Type.Label() + "_" + ref.Name
c1, c2 := ref.Owner.Label()+"_id", ref.Type.Label()+"_id"
// If the relation is from the same type: User has Friends ([]User).
// give the second column a different name (the relation name).
if c1 == c2 {
c2 = rules.Singularize(e.Name) + "_id"
}
e.Rel.Columns = []string{c1, c2}
ref.Rel.Columns = []string{c1, c2}
}
e.Rel.Table, ref.Rel.Table = table, table
if !e.M2M() {
e.Rel.Columns = []string{column}
ref.Rel.Columns = []string{column}
}
// Assoc with uninitialized relation.
case !e.IsInverse() && e.Rel.Type == Unk:
switch {
case !e.Unique && e.Type == t:
e.Rel.Type = M2M
e.Bidi = true
e.Rel.Table = t.Label() + "_" + e.Name
e.Rel.Columns = []string{e.Owner.Label() + "_id", rules.Singularize(e.Name) + "_id"}
case e.Unique && e.Type == t:
e.Rel.Type = O2O
e.Bidi = true
e.Rel.Table = t.Table()
case e.Unique:
e.Rel.Type = M2O
e.Rel.Table = t.Table()
default:
e.Rel.Type = O2M
e.Rel.Table = e.Type.Table()
}
if !e.M2M() {
e.Rel.Columns = []string{fmt.Sprintf("%s_%s", t.Label(), snake(e.Name))}
}
}
}
return nil
}
// Tables returns the schema definitions of SQL tables for the graph.
func (g *Graph) Tables() (all []*schema.Table, err error) {
tables := make(map[string]*schema.Table)
for _, n := range g.Nodes {
table := schema.NewTable(n.Table()).
AddPrimary(n.ID.PK()).
SetAnnotation(n.EntSQL())
for _, f := range n.Fields {
if !f.IsEdgeField() {
table.AddColumn(f.Column())
}
}
tables[table.Name] = table
all = append(all, table)
}
for _, n := range g.Nodes {
// Foreign key and a reference, or a join table.
for _, e := range n.Edges {
if e.IsInverse() {
continue
}
switch e.Rel.Type {
case O2O, O2M:
// The "owner" is the table that owns the relation (we set
// the foreign-key on) and "ref" is the referenced table.
owner, ref := tables[e.Rel.Table], tables[n.Table()]
pk := ref.PrimaryKey[0]
column := &schema.Column{Name: e.Rel.Column(), Size: pk.Size, Type: pk.Type, Unique: e.Rel.Type == O2O, SchemaType: pk.SchemaType, Nullable: true}
// If it's not a circular reference (self-referencing table),
// and the inverse edge is required, make it non-nullable.
if n != e.Type && e.Ref != nil && !e.Ref.Optional {
column.Nullable = false
}
mayAddColumn(owner, column)
owner.AddForeignKey(&schema.ForeignKey{
RefTable: ref,
OnDelete: deleteAction(e, column),
Columns: []*schema.Column{column},
RefColumns: []*schema.Column{ref.PrimaryKey[0]},
Symbol: fkSymbol(e, owner, ref),
})
case M2O:
ref, owner := tables[e.Type.Table()], tables[e.Rel.Table]
pk := ref.PrimaryKey[0]
column := &schema.Column{Name: e.Rel.Column(), Size: pk.Size, Type: pk.Type, SchemaType: pk.SchemaType, Nullable: true}
// If it's not a circular reference (self-referencing table),
// and the edge is non-optional (required), make it non-nullable.
if n != e.Type && !e.Optional {
column.Nullable = false
}
mayAddColumn(owner, column)
owner.AddForeignKey(&schema.ForeignKey{
RefTable: ref,
OnDelete: deleteAction(e, column),
Columns: []*schema.Column{column},
RefColumns: []*schema.Column{ref.PrimaryKey[0]},
Symbol: fkSymbol(e, owner, ref),
})
case M2M:
t1, t2 := tables[n.Table()], tables[e.Type.Table()]
c1 := &schema.Column{Name: e.Rel.Columns[0], Type: field.TypeInt}
if ref := n.ID; ref.UserDefined {
c1.Type = ref.Type.Type
c1.Size = ref.size()
}
c2 := &schema.Column{Name: e.Rel.Columns[1], Type: field.TypeInt}
if ref := e.Type.ID; ref.UserDefined {
c2.Type = ref.Type.Type
c2.Size = ref.size()
}
s1, s2 := fkSymbols(e, c1, c2)
all = append(all, &schema.Table{
Name: e.Rel.Table,
Columns: []*schema.Column{c1, c2},
PrimaryKey: []*schema.Column{c1, c2},
ForeignKeys: []*schema.ForeignKey{
{
RefTable: t1,
OnDelete: schema.Cascade,
Columns: []*schema.Column{c1},
RefColumns: []*schema.Column{t1.PrimaryKey[0]},
Symbol: s1,
},
{
RefTable: t2,
OnDelete: schema.Cascade,
Columns: []*schema.Column{c2},
RefColumns: []*schema.Column{t2.PrimaryKey[0]},
Symbol: s2,
},
},
})
}
}
}
// Append indexes to tables after all columns were added (including relation columns).
for _, n := range g.Nodes {
table := tables[n.Table()]
for _, idx := range n.Indexes {
table.AddIndex(idx.Name, idx.Unique, idx.Columns)
// Set the entsql.IndexAnnotation from the schema if exists.
index, _ := table.Index(idx.Name)
index.Annotation = entsqlIndexAnnotate(idx.Annotations)
}
}
return
}
// mayAddColumn adds the given column if it doesn't already exist in the table.
func mayAddColumn(t *schema.Table, c *schema.Column) {
if !t.HasColumn(c.Name) {
t.AddColumn(c)
}
}
// fkSymbol returns the symbol of the foreign-key constraint for edges of type O2M, M2O and O2O.
// It returns the symbol of the storage-key if it was provided, and generate custom one otherwise.
func fkSymbol(e *Edge, ownerT, refT *schema.Table) string {
if k, _ := e.StorageKey(); k != nil && len(k.Symbols) == 1 {
return k.Symbols[0]
}
return fmt.Sprintf("%s_%s_%s", ownerT.Name, refT.Name, e.Name)
}
// fkSymbols is like fkSymbol but for M2M edges.
func fkSymbols(e *Edge, c1, c2 *schema.Column) (string, string) {
s1 := fmt.Sprintf("%s_%s", e.Rel.Table, c1.Name)
s2 := fmt.Sprintf("%s_%s", e.Rel.Table, c2.Name)
if k, _ := e.StorageKey(); k != nil {
if len(k.Symbols) > 0 {
s1 = k.Symbols[0]
}
if len(k.Symbols) > 1 {
s2 = k.Symbols[1]
}
}
return s1, s2
}
// deleteAction returns the referential action for DELETE operations of the given edge.
func deleteAction(e *Edge, c *schema.Column) schema.ReferenceOption {
action := schema.NoAction
if c.Nullable {
action = schema.SetNull
}
if ant := e.EntSQL(); ant != nil && ant.OnDelete != "" {
action = schema.ReferenceOption(ant.OnDelete)
}
return action
}
// SupportMigrate reports if the codegen supports schema migration.
func (g *Graph) SupportMigrate() bool {
return g.Storage.SchemaMode.Support(Migrate)
}
// Snapshot holds the information for storing the schema snapshot.
type Snapshot struct {
Schema string
Package string
Schemas []*load.Schema
Features []string
}
// SchemaSnapshot returns a JSON string represents the graph schema in loadable format.
func (g *Graph) SchemaSnapshot() (string, error) {
schemas := make([]*load.Schema, len(g.Nodes))
for i := range g.Nodes {
schemas[i] = g.Nodes[i].schema
}
snap := Snapshot{
Schema: g.Schema,
Package: g.Package,
Schemas: schemas,
}
for _, feat := range g.Features {
snap.Features = append(snap.Features, feat.Name)
}
out, err := json.Marshal(snap)
if err != nil {
return "", err
}
return string(out), nil
}
func (g *Graph) typ(name string) (*Type, bool) {
for _, n := range g.Nodes {
if name == n.Name {
return n, true
}
}
return nil, false
}
// templates returns the Template to execute on the Graph,
// and a list of optional external templates if provided.
func (g *Graph) templates() (*Template, []GraphTemplate) {
initTemplates()
var (
roots = make(map[string]struct{})
helpers = make(map[string]struct{})
external = make([]GraphTemplate, 0, len(g.Templates))
)
for _, rootT := range g.Templates {
templates.Funcs(rootT.FuncMap)
for _, tmpl := range rootT.Templates() {
if parse.IsEmptyTree(tmpl.Root) {
continue
}
name := tmpl.Name()
switch {
// Helper templates can be either global (prefixed with "helper/"),
// or local, where their names follow the format: "<root-tmpl>/helper/.+").
case strings.HasPrefix(name, "helper/"):
case strings.Contains(name, "/helper/"):
helpers[name] = struct{}{}
case templates.Lookup(name) == nil && !extendExisting(name):
// If the template does not override or extend one of
// the builtin templates, generate it in a new file.
external = append(external, GraphTemplate{
Name: name,
Format: snake(name) + ".go",
})
roots[name] = struct{}{}
}
templates = MustParse(templates.AddParseTree(name, tmpl.Tree))
}
}
for name := range helpers {
root := name[:strings.Index(name, "/helper/")]
// If the name is prefixed with a name of a root
// template, we treat it as a local helper template.
if _, ok := roots[root]; ok {
continue
}
external = append(external, GraphTemplate{
Name: name,
Format: snake(name) + ".go",
})
}
for _, f := range g.Features {
external = append(external, f.GraphTemplates...)
}
return templates, external
}
// ModuleInfo returns the entgo.io/ent version.
func (Config) ModuleInfo() (m debug.Module) {
const pkg = "entgo.io/ent"
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
// Was running as a CLI (ent/cmd/ent).
if info.Main.Path == pkg {
return info.Main
}
// Or, as a main package (ent/entc).
for _, dep := range info.Deps {
if dep.Path == pkg {
return *dep
}
}
return
}
// FeatureEnabled reports if the given feature name is enabled.
// It's exported to be used by the template engine as follows:
//
// {{ with $.FeatureEnabled "privacy" }}
// ...
// {{ end }}
//
func (c Config) FeatureEnabled(name string) (bool, error) {
for _, f := range AllFeatures {
if name == f.Name {
return c.featureEnabled(f), nil
}
}
return false, fmt.Errorf("unexpected feature name %q", name)
}
// featureEnabled reports if the given feature-flag is enabled.
func (c Config) featureEnabled(f Feature) bool {
for i := range c.Features {
if f.Name == c.Features[i].Name {
return true
}
}
return false
}
// PrepareEnv makes sure the generated directory (environment)
// is suitable for loading the `ent` package (avoid cyclic imports).
func PrepareEnv(c *Config) (undo func() error, err error) {
var (
nop = func() error { return nil }
path = filepath.Join(c.Target, "runtime.go")
)
out, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return nop, nil
}
return nil, err
}
fi, err := parser.ParseFile(token.NewFileSet(), path, out, parser.ImportsOnly)
if err != nil {
return nil, err
}
// Targeted package doesn't import the schema.
if len(fi.Imports) == 0 {
return nop, nil
}
if err := os.WriteFile(path, append([]byte("// +build tools\n"), out...), 0644); err != nil {
return nil, err
}
return func() error { return os.WriteFile(path, out, 0644) }, nil
}
type (
file struct {
path string
content []byte
}
assets struct {
dirs []string
files []file
}
)
// write files and dirs in the assets.
func (a assets) write() error {
for _, dir := range a.dirs {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return fmt.Errorf("create dir %q: %w", dir, err)
}
}
for _, file := range a.files {
if err := os.WriteFile(file.path, file.content, 0644); err != nil {
return fmt.Errorf("write file %q: %w", file.path, err)
}
}
return nil
}
// format runs "goimports" on all assets.
func (a assets) format() error {
for _, file := range a.files {
path := file.path
src, err := imports.Process(path, file.content, nil)
if err != nil {
return fmt.Errorf("format file %s: %w", path, err)
}
if err := os.WriteFile(path, src, 0644); err != nil {
return fmt.Errorf("write file %s: %w", path, err)
}
}
return nil
}
// expect panics if the condition is false.
func expect(cond bool, msg string, args ...interface{}) {
if !cond {
panic(graphError{fmt.Sprintf(msg, args...)})
}
}
// check panics if the error is not nil.
func check(err error, msg string, args ...interface{}) {
if err != nil {
args = append(args, err)
panic(graphError{fmt.Sprintf(msg+": %s", args...)})
}
}
type graphError struct {
msg string
}
func (p graphError) Error() string { return fmt.Sprintf("entc/gen: %s", p.msg) }
func catch(err *error) {
if e := recover(); e != nil {
gerr, ok := e.(graphError)
if !ok {
panic(e)
}
*err = gerr
}
}
func extendExisting(name string) bool {
if match(partialPatterns[:], name) {
return true
}
for _, t := range Templates {
if match(t.ExtendPatterns, name) {
return true
}
}
for _, t := range GraphTemplates {
if match(t.ExtendPatterns, name) {
return true
}
}
return false
}