-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
1860 lines (1702 loc) · 53.1 KB
/
type.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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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
import (
"database/sql"
"encoding/json"
"fmt"
"go/token"
"go/types"
"path"
"reflect"
"sort"
"strings"
"unicode"
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/entc/load"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// The following types and their exported methods used by the codegen
// to generate the assets.
type (
// Type represents one node-type in the graph, its relations and
// the information it holds.
Type struct {
*Config
schema *load.Schema
// Name holds the type/ent name.
Name string
// alias, or local package name of the generated package.
// Empty means no alias.
alias string
// ID holds the ID field of this type.
ID *Field
// Fields holds all the primitive fields of this type.
Fields []*Field
fields map[string]*Field
// Edge holds all the edges of this type.
Edges []*Edge
// Indexes are the configured indexes for this type.
Indexes []*Index
// ForeignKeys are the foreign-keys that resides in the type table.
ForeignKeys []*ForeignKey
foreignKeys map[string]struct{}
// Annotations that were defined for the field in the schema.
// The mapping is from the Annotation.Name() to a JSON decoded object.
Annotations Annotations
}
// Field holds the information of a type field used for the templates.
Field struct {
cfg *Config
def *load.Field
// Name is the name of this field in the database schema.
Name string
// Type holds the type information of the field.
Type *field.TypeInfo
// Unique indicate if this field is a unique field.
Unique bool
// Optional indicates is this field is optional on create.
Optional bool
// Nillable indicates that this field can be null in the
// database and pointer in the generated entities.
Nillable bool
// Default indicates if this field has a default value for creation.
Default bool
// Enums information for enum fields.
Enums []Enum
// UpdateDefault indicates if this field has a default value for update.
UpdateDefault bool
// Immutable indicates is this field cannot be updated.
Immutable bool
// StructTag of the field. default to "json".
StructTag string
// Validators holds the number of validators this field have.
Validators int
// Position info of the field.
Position *load.Position
// UserDefined indicates that this field was defined explicitly by the user in
// the schema. Unlike the default id field, which is defined by the generator.
UserDefined bool
// Annotations that were defined for the field in the schema.
// The mapping is from the Annotation.Name() to a JSON decoded object.
Annotations Annotations
// referenced foreign-key.
fk *ForeignKey
}
// Edge of a graph between two types.
Edge struct {
def *load.Edge
// Name holds the name of the edge.
Name string
// Type holds a reference to the type this edge is directed to.
Type *Type
// Optional indicates is this edge is optional on create.
Optional bool
// Unique indicates if this edge is a unique edge.
Unique bool
// Inverse holds the name of the reference edge declared in the schema.
Inverse string
// Ref points to the reference edge. For Inverse edges (edge.From),
// its points to the Assoc (edge.To). For Assoc edges, it points to
// the inverse edge if it exists.
Ref *Edge
// Owner holds the type of the edge-owner. For assoc-edges it's the
// type that holds the edge, for inverse-edges, it's the assoc type.
Owner *Type
// StructTag of the edge-field in the struct. default to "json".
StructTag string
// Relation holds the relation info of an edge.
Rel Relation
// Bidi indicates if this edge is a bidirectional edge. A self-reference
// to the same type with the same name (symmetric relation). For example,
// a User type have one of following edges:
//
// edge.To("friends", User.Type) // many 2 many.
// edge.To("spouse", User.Type).Unique() // one 2 one.
//
Bidi bool
// Annotations that were defined for the edge in the schema.
// The mapping is from the Annotation.Name() to a JSON decoded object.
Annotations Annotations
}
// Relation holds the relational database information for edges.
Relation struct {
// Type holds the relation type of the edge.
Type Rel
// Table holds the relation table for this edge.
// For O2O and O2M, it's the table name of the type we're this edge point to.
// For M2O, this is the owner's type, and for M2M this is the join table.
Table string
// Columns holds the relation column in the relation table above.
// In O2M, M2O and O2O, this the first element.
Columns []string
// foreign-key information for non-M2M edges.
fk *ForeignKey
}
// Index represents a database index used for either increasing speed
// on database operations or defining constraints such as "UNIQUE INDEX".
// Note that some indexes are created implicitly like table foreign keys.
Index struct {
// Name of the index. One column index is simply the column name.
Name string
// Unique index or not.
Unique bool
// Columns are the table columns.
Columns []string
// Annotations that were defined for the index in the schema.
// The mapping is from the Annotation.Name() to a JSON decoded object.
Annotations Annotations
}
// ForeignKey holds the information for foreign-key columns of types.
// It's exported only because it's used by the codegen templates and
// should not be used beside that.
ForeignKey struct {
// Field information for the foreign-key column.
Field *Field
// Edge that is associated with this foreign-key.
Edge *Edge
// UserDefined indicates that this foreign-key was defined explicitly as a field in the schema,
// and was referenced by an edge. For example:
//
// field.Int("owner_id").
// Optional()
//
// edge.From("owner", User.Type).
// Ref("pets").
// Field("owner_id")
//
UserDefined bool
}
// Enum holds the enum information for schema enums in codegen.
Enum struct {
// Name is the Go name of the enum.
Name string
// Value in the schema.
Value string
}
)
// NewType creates a new type and its fields from the given schema.
func NewType(c *Config, schema *load.Schema) (*Type, error) {
idType := c.IDType
if idType == nil {
idType = defaultIDType
}
typ := &Type{
Config: c,
ID: &Field{
cfg: c,
Name: "id",
def: &load.Field{
Name: "id",
},
Type: idType,
StructTag: structTag("id", ""),
},
schema: schema,
Name: schema.Name,
Annotations: schema.Annotations,
Fields: make([]*Field, 0, len(schema.Fields)),
fields: make(map[string]*Field, len(schema.Fields)),
foreignKeys: make(map[string]struct{}),
}
if err := ValidSchemaName(typ.Name); err != nil {
return nil, err
}
for _, f := range schema.Fields {
tf := &Field{
cfg: c,
def: f,
Name: f.Name,
Type: f.Info,
Unique: f.Unique,
Position: f.Position,
Nillable: f.Nillable,
Optional: f.Optional,
Default: f.Default,
UpdateDefault: f.UpdateDefault,
Immutable: f.Immutable,
StructTag: structTag(f.Name, f.Tag),
Validators: f.Validators,
UserDefined: true,
Annotations: f.Annotations,
}
if err := typ.checkField(tf, f); err != nil {
return nil, err
}
// User defined id field.
if tf.Name == typ.ID.Name {
if tf.Optional {
return nil, fmt.Errorf("id field cannot be optional")
}
typ.ID = tf
} else {
typ.Fields = append(typ.Fields, tf)
typ.fields[f.Name] = tf
}
}
return typ, nil
}
// Label returns Gremlin label name of the node/type.
func (t Type) Label() string {
return snake(t.Name)
}
// Table returns SQL table name of the node/type.
func (t Type) Table() string {
if ant := t.EntSQL(); ant != nil && ant.Table != "" {
return ant.Table
}
if t.schema != nil && t.schema.Config.Table != "" {
return t.schema.Config.Table
}
return snake(rules.Pluralize(t.Name))
}
// EntSQL returns the EntSQL annotation if exists.
func (t Type) EntSQL() *entsql.Annotation {
return entsqlAnnotate(t.Annotations)
}
// Package returns the package name of this node.
func (t Type) Package() string {
if name := t.PackageAlias(); name != "" {
return name
}
return t.PackageDir()
}
// PackageDir returns the name of the package directory.
func (t Type) PackageDir() string { return strings.ToLower(t.Name) }
// PackageAlias returns local package name of a type if there is one.
// A package has an alias if its generated name conflicts with
// one of the imports of the user-defined types.
func (t Type) PackageAlias() string { return t.alias }
// Receiver returns the receiver name of this node. It makes sure the
// receiver names doesn't conflict with import names.
func (t Type) Receiver() string {
return receiver(t.Name)
}
// HasAssoc returns true if this type has an assoc-edge (edge.To)
// with the given name. faster than map access for most cases.
func (t Type) HasAssoc(name string) (*Edge, bool) {
for _, e := range t.Edges {
if name == e.Name && !e.IsInverse() {
return e, true
}
}
return nil, false
}
// HasValidators reports if any of the type's field has validators.
func (t Type) HasValidators() bool {
fields := t.Fields
if t.ID.UserDefined {
fields = append(fields, t.ID)
}
for _, f := range fields {
if f.Validators > 0 {
return true
}
}
return false
}
// HasDefault reports if any of this type's fields has default value on creation.
func (t Type) HasDefault() bool {
fields := t.Fields
if t.ID.UserDefined {
fields = append(fields, t.ID)
}
for _, f := range fields {
if f.Default {
return true
}
}
return false
}
// HasUpdateDefault reports if any of this type's fields has default value on update.
func (t Type) HasUpdateDefault() bool {
for _, f := range t.Fields {
if f.UpdateDefault {
return true
}
}
return false
}
// HasOptional reports if this type has an optional field.
func (t Type) HasOptional() bool {
for _, f := range t.Fields {
if f.Optional {
return true
}
}
return false
}
// HasNumeric reports if this type has a numeric field.
func (t Type) HasNumeric() bool {
for _, f := range t.Fields {
if f.Type.Numeric() {
return true
}
}
return false
}
// HasUpdateCheckers reports if this type has any checkers to run on update(one).
func (t Type) HasUpdateCheckers() bool {
for _, f := range t.Fields {
if (f.Validators > 0 || f.IsEnum()) && !f.Immutable {
return true
}
}
for _, e := range t.Edges {
if e.Unique && !e.Optional {
return true
}
}
return false
}
// FKEdges returns all edges that reside on the type table as foreign-keys.
func (t Type) FKEdges() (edges []*Edge) {
for _, e := range t.Edges {
if e.OwnFK() {
edges = append(edges, e)
}
}
return
}
// RuntimeMixin returns schema mixin that needs to be loaded at
// runtime. For example, for default values, validators or hooks.
func (t Type) RuntimeMixin() bool {
return len(t.MixedInFields()) > 0 || len(t.MixedInHooks()) > 0 || len(t.MixedInPolicies()) > 0
}
// MixedInFields returns the indices of mixin holds runtime code.
func (t Type) MixedInFields() []int {
idx := make(map[int]struct{})
fields := t.Fields
if t.ID.UserDefined {
fields = append(fields, t.ID)
}
for _, f := range fields {
if f.Position != nil && f.Position.MixedIn && (f.Default || f.UpdateDefault || f.Validators > 0) {
idx[f.Position.MixinIndex] = struct{}{}
}
}
return sortedKeys(idx)
}
// MixedInHooks returns the indices of mixin with hooks.
func (t Type) MixedInHooks() []int {
if t.schema == nil {
return nil
}
idx := make(map[int]struct{})
for _, h := range t.schema.Hooks {
if h.MixedIn {
idx[h.MixinIndex] = struct{}{}
}
}
return sortedKeys(idx)
}
// MixedInPolicies returns the indices of mixin with policies.
func (t Type) MixedInPolicies() []int {
if t.schema == nil {
return nil
}
idx := make(map[int]struct{})
for _, h := range t.schema.Policy {
if h.MixedIn {
idx[h.MixinIndex] = struct{}{}
}
}
return sortedKeys(idx)
}
// NumMixin returns the type's mixin count.
func (t Type) NumMixin() int {
m := make(map[int]struct{})
for _, f := range t.Fields {
if p := f.Position; p != nil && p.MixedIn {
m[p.MixinIndex] = struct{}{}
}
}
return len(m)
}
// NumConstraint returns the type's constraint count. Used for slice allocation.
func (t Type) NumConstraint() int {
var n int
for _, f := range t.Fields {
if f.Unique {
n++
}
}
for _, e := range t.Edges {
if e.HasConstraint() {
n++
}
}
return n
}
// MutableFields returns all type fields that are mutable (on update).
func (t Type) MutableFields() []*Field {
fields := make([]*Field, 0, len(t.Fields))
for _, f := range t.Fields {
if !f.Immutable {
fields = append(fields, f)
}
}
return fields
}
// ImmutableFields returns all type fields that are immutable (for update).
func (t Type) ImmutableFields() []*Field {
fields := make([]*Field, 0, len(t.Fields))
for _, f := range t.Fields {
if f.Immutable {
fields = append(fields, f)
}
}
return fields
}
// MutationFields returns all the fields that are available on the typed-mutation.
func (t Type) MutationFields() []*Field {
fields := make([]*Field, 0, len(t.Fields))
for _, f := range t.Fields {
if !f.IsEdgeField() {
fields = append(fields, f)
}
}
return fields
}
// EnumFields returns the enum fields of the schema, if any.
func (t Type) EnumFields() []*Field {
var fields []*Field
for _, f := range t.Fields {
if f.IsEnum() {
fields = append(fields, f)
}
}
return fields
}
// FieldBy returns the first field that the given function returns true on it.
func (t Type) FieldBy(fn func(*Field) bool) (*Field, bool) {
if fn(t.ID) {
return t.ID, true
}
for _, f := range t.Fields {
if fn(f) {
return f, true
}
}
return nil, false
}
// NumM2M returns the type's many-to-many edge count
func (t Type) NumM2M() int {
var n int
for _, e := range t.Edges {
if e.M2M() {
n++
}
}
return n
}
// TagTypes returns all struct-tag types of the type fields.
func (t Type) TagTypes() []string {
tags := make(map[string]bool)
for _, f := range t.Fields {
tag := reflect.StructTag(f.StructTag)
fields := strings.FieldsFunc(f.StructTag, func(r rune) bool {
return r == ':' || unicode.IsSpace(r)
})
for _, name := range fields {
_, ok := tag.Lookup(name)
if ok && !tags[name] {
tags[name] = true
}
}
}
r := make([]string, 0, len(tags))
for tag := range tags {
r = append(r, tag)
}
sort.Strings(r)
return r
}
// AddIndex adds a new index for the type.
// It fails if the schema index is invalid.
func (t *Type) AddIndex(idx *load.Index) error {
index := &Index{Name: idx.StorageKey, Unique: idx.Unique, Annotations: idx.Annotations}
if len(idx.Fields) == 0 && len(idx.Edges) == 0 {
return fmt.Errorf("missing fields or edges")
}
switch ant := entsqlIndexAnnotate(idx.Annotations); {
case ant == nil:
case len(ant.PrefixColumns) != 0 && ant.Prefix != 0:
return fmt.Errorf("index %q cannot contain both entsql.Prefix and entsql.PrefixColumn in annotation", index.Name)
case ant.Prefix != 0 && len(idx.Fields)+len(idx.Edges) != 1:
return fmt.Errorf("entsql.Prefix is used in a multicolumn index %q. Use entsql.PrefixColumn instead", index.Name)
case len(ant.PrefixColumns) > len(idx.Fields)+len(idx.Fields):
return fmt.Errorf("index %q has more entsql.PrefixColumn than column in its definitions", index.Name)
}
for _, name := range idx.Fields {
var f *Field
if name == t.ID.Name {
f = t.ID
} else {
var ok bool
f, ok = t.fields[name]
if !ok {
return fmt.Errorf("unknown index field %q", name)
}
}
index.Columns = append(index.Columns, f.StorageKey())
}
for _, name := range idx.Edges {
var ed *Edge
for _, e := range t.Edges {
if e.Name == name {
ed = e
break
}
}
switch {
case ed == nil:
return fmt.Errorf("unknown index field %q", name)
case ed.Rel.Type == O2O && !ed.IsInverse():
return fmt.Errorf("non-inverse edge (edge.From) for index %q on O2O relation", name)
case ed.Rel.Type != M2O && ed.Rel.Type != O2O:
return fmt.Errorf("relation %s for inverse edge %q is not one of (O2O, M2O)", ed.Rel.Type, name)
default:
index.Columns = append(index.Columns, ed.Rel.Column())
}
}
// If no storage-key was defined for this index, generate one.
if idx.StorageKey == "" {
// Add the type name as a prefix to the index parts, because
// multiple types can share the same index attributes.
parts := append([]string{strings.ToLower(t.Name)}, index.Columns...)
index.Name = strings.Join(parts, "_")
}
t.Indexes = append(t.Indexes, index)
return nil
}
// setupFKs makes sure all edge-fks are created for the edges.
func (t *Type) setupFKs() error {
for _, e := range t.Edges {
if err := e.setStorageKey(); err != nil {
return fmt.Errorf("%q edge: %w", e.Name, err)
}
if ef := e.def.Field; ef != "" && !e.OwnFK() {
return fmt.Errorf("edge %q has a field %q but it is not holding a foreign key", e.Name, ef)
}
if e.IsInverse() || e.M2M() {
continue
}
owner, refid := t, e.Type.ID
if !e.OwnFK() {
owner, refid = e.Type, t.ID
}
fk := &ForeignKey{
Edge: e,
Field: &Field{
Name: builderField(e.Rel.Column()),
Type: refid.Type,
Nillable: true,
Optional: true,
Unique: e.Unique,
UserDefined: refid.UserDefined,
},
}
// Update the foreign-key/edge-field info of the assoc-edge.
e.Rel.fk = fk
if edgeField := e.def.Field; edgeField != "" {
if err := owner.setupFieldEdge(fk, e, edgeField); err != nil {
return err
}
}
// Update inverse-edge info as well (optional).
if ref := e.Ref; ref != nil {
ref.Rel.fk = fk
if edgeField := e.Ref.def.Field; edgeField != "" {
if err := owner.setupFieldEdge(fk, e.Ref, edgeField); err != nil {
return err
}
}
}
// Special case for checking if the FK is already defined as the ID field (see issue 1288).
if key, _ := e.StorageKey(); key != nil && len(key.Columns) == 1 && key.Columns[0] == refid.StorageKey() {
fk.Field = refid
fk.UserDefined = true
}
owner.addFK(fk)
}
return nil
}
// setupEdgeField check the field-edge validity and configures it and its foreign-key.
func (t *Type) setupFieldEdge(fk *ForeignKey, fkOwner *Edge, fkName string) error {
tf, ok := t.fields[fkName]
if !ok {
return fmt.Errorf("field %q was not found in the schema for edge %q", fkName, fkOwner.Name)
}
if tf.Optional != fkOwner.Optional {
return fmt.Errorf("mismatch optional/required config for edge %q and field %q", fkOwner.Name, fkName)
}
if tf.Immutable {
return fmt.Errorf("field edge %q cannot be immutable", fkName)
}
if t1, t2 := tf.Type.Type, fkOwner.Type.ID.Type.Type; t1 != t2 {
return fmt.Errorf("mismatch field type between edge field %q and id of type %q (%s != %s)", fkName, fkOwner.Type.Name, t1, t2)
}
fk.UserDefined = true
tf.fk, fk.Field = fk, tf
ekey, err := fkOwner.StorageKey()
if err != nil {
return err
}
if ekey != nil && len(ekey.Columns) == 1 {
if fkey := tf.def.StorageKey; fkey != "" && fkey != ekey.Columns[0] {
return fmt.Errorf("mismatch storage-key for edge %q and field %q", fkOwner.Name, fkName)
}
// Update the field storage key.
tf.def.StorageKey = ekey.Columns[0]
}
fkOwner.Rel.Columns = []string{tf.StorageKey()}
if ref := fkOwner.Ref; ref != nil {
ref.Rel.Columns = []string{tf.StorageKey()}
}
return nil
}
// addFK adds a foreign-key for the type if it doesn't exist.
func (t *Type) addFK(fk *ForeignKey) {
if _, ok := t.foreignKeys[fk.Field.Name]; ok {
return
}
t.foreignKeys[fk.Field.Name] = struct{}{}
t.ForeignKeys = append(t.ForeignKeys, fk)
}
// QueryName returns the struct name denoting the query-builder for this type.
func (t Type) QueryName() string {
return pascal(t.Name) + "Query"
}
// FilterName returns the struct name denoting the filter-builder for this type.
func (t Type) FilterName() string {
return pascal(t.Name) + "Filter"
}
// CreateName returns the struct name denoting the create-builder for this type.
func (t Type) CreateName() string {
return pascal(t.Name) + "Create"
}
// CreateBulkName returns the struct name denoting the create-bulk-builder for this type.
func (t Type) CreateBulkName() string {
return pascal(t.Name) + "CreateBulk"
}
// UpdateName returns the struct name denoting the update-builder for this type.
func (t Type) UpdateName() string {
return pascal(t.Name) + "Update"
}
// UpdateOneName returns the struct name denoting the update-one-builder for this type.
func (t Type) UpdateOneName() string {
return pascal(t.Name) + "UpdateOne"
}
// DeleteName returns the struct name denoting the delete-builder for this type.
func (t Type) DeleteName() string {
return pascal(t.Name) + "Delete"
}
// DeleteOneName returns the struct name denoting the delete-one-builder for this type.
func (t Type) DeleteOneName() string {
return pascal(t.Name) + "DeleteOne"
}
// MutationName returns the struct name of the mutation builder for this type.
func (t Type) MutationName() string {
return pascal(t.Name) + "Mutation"
}
// SiblingImports returns all sibling packages that are needed for the different builders.
func (t Type) SiblingImports() []struct{ Alias, Path string } {
var (
imports = []struct{ Alias, Path string }{{Alias: t.PackageAlias(), Path: path.Join(t.Config.Package, t.PackageDir())}}
seen = map[string]bool{imports[0].Path: true}
)
for _, e := range t.Edges {
p := path.Join(t.Config.Package, e.Type.PackageDir())
if !seen[p] {
seen[p] = true
imports = append(imports, struct{ Alias, Path string }{Alias: e.Type.PackageAlias(), Path: p})
}
}
return imports
}
// NumHooks returns the number of hooks declared in the type schema.
func (t Type) NumHooks() int {
if t.schema != nil {
return len(t.schema.Hooks)
}
return 0
}
// HookPositions returns the position information of hooks declared in the type schema.
func (t Type) HookPositions() []*load.Position {
if t.schema != nil {
return t.schema.Hooks
}
return nil
}
// NumPolicy returns the number of privacy-policy declared in the type schema.
func (t Type) NumPolicy() int {
if t.schema != nil {
return len(t.schema.Policy)
}
return 0
}
// PolicyPositions returns the position information of privacy policy declared in the type schema.
func (t Type) PolicyPositions() []*load.Position {
if t.schema != nil {
return t.schema.Policy
}
return nil
}
// RelatedTypes returns all the types (nodes) that
// are related (with edges) to this type.
func (t Type) RelatedTypes() []*Type {
seen := make(map[string]struct{})
related := make([]*Type, 0, len(t.Edges))
for _, e := range t.Edges {
if _, ok := seen[e.Type.Name]; !ok {
related = append(related, e.Type)
seen[e.Type.Name] = struct{}{}
}
}
return related
}
// ValidSchemaName will determine if a name is going to conflict with any
// pre-defined names
func ValidSchemaName(name string) error {
// Schema package is lower-cased (see Type.Package).
pkg := strings.ToLower(name)
if token.Lookup(pkg).IsKeyword() {
return fmt.Errorf("schema lowercase name conflicts with Go keyword %q", pkg)
}
if types.Universe.Lookup(pkg) != nil {
return fmt.Errorf("schema lowercase name conflicts with Go predeclared identifier %q", pkg)
}
if _, ok := globalIdent[pkg]; ok {
return fmt.Errorf("schema lowercase name conflicts ent predeclared identifier %q", pkg)
}
if _, ok := globalIdent[name]; ok {
return fmt.Errorf("schema name conflicts with ent predeclared identifier %q", name)
}
return nil
}
// checkField checks the schema field.
func (t *Type) checkField(tf *Field, f *load.Field) (err error) {
switch {
case f.Name == "":
err = fmt.Errorf("field name cannot be empty")
case f.Info == nil || !f.Info.Valid():
err = fmt.Errorf("invalid type for field %s", f.Name)
case f.Nillable && !f.Optional:
err = fmt.Errorf("nillable field %q must be optional", f.Name)
case f.Unique && f.Default && f.DefaultKind != reflect.Func:
err = fmt.Errorf("unique field %q cannot have default value", f.Name)
case t.fields[f.Name] != nil:
err = fmt.Errorf("field %q redeclared for type %q", f.Name, t.Name)
case f.Sensitive && f.Tag != "":
err = fmt.Errorf("sensitive field %q cannot have struct tags", f.Name)
case f.Info.Type == field.TypeEnum:
if tf.Enums, err = tf.enums(f); err == nil && !tf.HasGoType() {
// Enum types should be named as follows: typepkg.Field.
f.Info.Ident = fmt.Sprintf("%s.%s", t.PackageDir(), pascal(f.Name))
}
case tf.Validators > 0 && !tf.ConvertedToBasic():
err = fmt.Errorf("GoType %q for field %q must be converted to the basic %q type for validators", tf.Type, f.Name, tf.Type.Type)
}
return err
}
// UnexportedForeignKeys returns all foreign-keys that belong to the type
// but are not exported (not defined with field). i.e. generated by ent.
func (t Type) UnexportedForeignKeys() []*ForeignKey {
fks := make([]*ForeignKey, 0, len(t.ForeignKeys))
for _, fk := range t.ForeignKeys {
if !fk.UserDefined {
fks = append(fks, fk)
}
}
return fks
}
// aliases adds package aliases (local names) for all type-packages that
// their import identifier conflicts with user-defined packages (i.e. GoType).
func aliases(g *Graph) {
names := make(map[string]*Type)
for _, n := range g.Nodes {
names[n.PackageDir()] = n
}
for _, n := range g.Nodes {
for _, f := range n.Fields {
if !f.HasGoType() {
continue
}
name := f.Type.PkgName
if name == "" && f.Type.PkgPath != "" {
name = path.Base(f.Type.PkgPath)
}
// An user-defined type already uses the
// package local name.
if n, ok := names[name]; ok {
// By default, a package named "pet" will be named as "entpet".
n.alias = path.Base(g.Package) + name
}
}
}
}
// Constant returns the constant name of the field.
func (f Field) Constant() string {
return "Field" + pascal(f.Name)
}
// DefaultName returns the variable name of the default value of this field.
func (f Field) DefaultName() string { return "Default" + pascal(f.Name) }
// UpdateDefaultName returns the variable name of the update default value of this field.
func (f Field) UpdateDefaultName() string { return "Update" + f.DefaultName() }
// DefaultValue returns the default value of the field. Invoked by the template.
func (f Field) DefaultValue() interface{} { return f.def.DefaultValue }
// DefaultFunc returns a bool stating if the default value is a func. Invoked by the template.
func (f Field) DefaultFunc() bool { return f.def.DefaultKind == reflect.Func }
// BuilderField returns the struct member of the field in the builder.
func (f Field) BuilderField() string {
if f.IsEdgeField() {
e, err := f.Edge()
if err != nil {
panic(err)
}
return e.BuilderField()
}
return builderField(f.Name)
}
// StructField returns the struct member of the field in the model.
func (f Field) StructField() string {
return pascal(f.Name)
}
// EnumNames returns the enum values of a field.
func (f Field) EnumNames() []string {
names := make([]string, 0, len(f.Enums))
for _, e := range f.Enums {
names = append(names, e.Name)
}
return names
}
// EnumValues returns the values of the enum field.
func (f Field) EnumValues() []string {
values := make([]string, 0, len(f.Enums))
for _, e := range f.Enums {
values = append(values, e.Value)
}
return values
}
// EnumName returns the constant name for the enum.
func (f Field) EnumName(enum string) string {
if !token.IsExported(enum) || !token.IsIdentifier(enum) {
enum = pascal(enum)
}
return pascal(f.Name) + enum
}
// Validator returns the validator name.
func (f Field) Validator() string {
return pascal(f.Name) + "Validator"
}
// EntSQL returns the EntSQL annotation if exists.
func (f Field) EntSQL() *entsql.Annotation {
return entsqlAnnotate(f.Annotations)
}
// mutMethods returns the method names of mutation interface.
var mutMethods = func() map[string]struct{} {
t := reflect.TypeOf(new(ent.Mutation)).Elem()
names := make(map[string]struct{})
for i := 0; i < t.NumMethod(); i++ {
names[t.Method(i).Name] = struct{}{}
}
return names
}()
// MutationGet returns the method name for getting the field value.
// The default name is just a pascal format. If the method conflicts
// with the mutation methods, prefix the method with "Get".
func (f Field) MutationGet() string {
name := pascal(f.Name)
if _, ok := mutMethods[name]; ok {
name = "Get" + name
}
return name
}
// MutationGetOld returns the method name for getting the old value of a field.
func (f Field) MutationGetOld() string {
name := "Old" + pascal(f.Name)
if _, ok := mutMethods[name]; ok {
name = "Get" + name