Documentation ¶
Overview ¶
Package gen is the interface for generating loaded schemas into a Go package.
Index ¶
- Variables
- func AddAcronym(word string)
- func PrepareEnv(c *Config) (undo func() error, err error)
- func ValidSchemaName(name string) error
- type Annotations
- type Config
- type Dependencies
- type Dependency
- type Edge
- func (e Edge) BuilderField() string
- func (e Edge) ColumnConstant() string
- func (e Edge) Comment() string
- func (e Edge) Constant() string
- func (e Edge) EagerLoadField() string
- func (e Edge) EagerLoadNamedField() string
- func (e Edge) EntSQL() *entsql.Annotation
- func (e Edge) Field() *Field
- func (e *Edge) ForeignKey() (*ForeignKey, error)
- func (e Edge) HasConstraint() bool
- func (e Edge) HasFieldSetter() bool
- func (e Edge) Index() (int, error)
- func (e Edge) InverseLabelConstant() string
- func (e Edge) InverseTableConstant() string
- func (e Edge) IsInverse() bool
- func (e Edge) Label() string
- func (e Edge) LabelConstant() string
- func (e Edge) M2M() bool
- func (e Edge) M2O() bool
- func (e Edge) MutationAdd() string
- func (e Edge) MutationClear() string
- func (e Edge) MutationCleared() string
- func (e Edge) MutationRemove() string
- func (e Edge) MutationReset() string
- func (e Edge) MutationSet() string
- func (e Edge) O2M() bool
- func (e Edge) O2O() bool
- func (e Edge) OrderCountName() (string, error)
- func (e Edge) OrderFieldName() (string, error)
- func (e Edge) OrderTermsName() (string, error)
- func (e Edge) OwnFK() bool
- func (e Edge) PKConstant() string
- func (e Edge) StorageKey() (*edge.StorageKey, error)
- func (e Edge) StructField() string
- func (e Edge) TableConstant() string
- func (e *Edge) TableSchema() (string, error)
- type Enum
- type Feature
- type FeatureStage
- type Field
- func (f Field) BasicType(ident string) (expr string)
- func (f Field) BuilderField() string
- func (f Field) Column() *schema.Column
- func (f Field) Comment() string
- func (f Field) Constant() string
- func (f Field) ConvertedToBasic() bool
- func (f Field) DefaultFunc() bool
- func (f Field) DefaultName() string
- func (f Field) DefaultValue() any
- func (f Field) DeprecationReason() string
- func (f Field) Edge() (*Edge, error)
- func (f Field) EntSQL() *entsql.Annotation
- func (f Field) EnumName(enum string) string
- func (f Field) EnumNames() []string
- func (f Field) EnumValues() []string
- func (f Field) FromValueFunc() (string, error)
- func (f Field) HasGoType() bool
- func (f Field) HasValueScanner() bool
- func (f Field) IsBool() bool
- func (f Field) IsBytes() bool
- func (f Field) IsDeprecated() bool
- func (f Field) IsEdgeField() bool
- func (f Field) IsEnum() bool
- func (f Field) IsInt() bool
- func (f Field) IsInt64() bool
- func (f Field) IsJSON() bool
- func (f Field) IsOther() bool
- func (f Field) IsString() bool
- func (f Field) IsTime() bool
- func (f Field) IsUUID() bool
- func (f Field) MutationAdd() string
- func (f Field) MutationAddAssignExpr(ident1, ident2 string) (string, error)
- func (f Field) MutationAdded() string
- func (f Field) MutationAppend() string
- func (f Field) MutationAppended() string
- func (f Field) MutationClear() string
- func (f Field) MutationCleared() string
- func (f Field) MutationGet() string
- func (f Field) MutationGetOld() string
- func (f Field) MutationReset() string
- func (f Field) MutationSet() string
- func (f Field) NewScanType() string
- func (f Field) NillableValue() bool
- func (f *Field) Ops() []Op
- func (f Field) OrderName() string
- func (f Field) PK() *schema.Column
- func (f Field) RequiredFor() (dialects []string)
- func (f Field) ScanType() string
- func (f Field) ScanTypeField(rec string) string
- func (f Field) ScanValueFunc() (string, error)
- func (f Field) Sensitive() bool
- func (f Field) SignedType() (*field.TypeInfo, error)
- func (f Field) StorageKey() string
- func (f Field) StructField() string
- func (f Field) SupportsMutationAdd() bool
- func (f Field) SupportsMutationAppend() bool
- func (f Field) UpdateDefaultName() string
- func (f Field) Validator() string
- func (f Field) ValueFunc() (string, error)
- type ForeignKey
- type GenerateFunc
- type Generator
- type Graph
- func (g *Graph) Gen() error
- func (g *Graph) MutableNodes() []*Type
- func (g *Graph) SchemaSnapshot() (string, error)
- func (g *Graph) SupportMigrate() bool
- func (g *Graph) TableSchemas() ([]string, error)
- func (g *Graph) Tables() (all []*schema.Table, err error)
- func (g *Graph) Views() (views []*schema.Table, err error)
- type GraphTemplate
- type Hook
- type Index
- type Op
- type Rel
- type Relation
- type SchemaMode
- type Snapshot
- type Storage
- type Template
- func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)
- func (t *Template) Funcs(funcMap template.FuncMap) *Template
- func (t *Template) Parse(text string) (*Template, error)
- func (t *Template) ParseDir(path string) (*Template, error)
- func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error)
- func (t *Template) ParseFiles(filenames ...string) (*Template, error)
- func (t *Template) ParseGlob(pattern string) (*Template, error)
- func (t *Template) SkipIf(cond func(*Graph) bool) *Template
- type Type
- func (t *Type) AddIndex(idx *load.Index) error
- func (t Type) ClientName() string
- func (t Type) CreateBulReceiver() string
- func (t Type) CreateBulkName() string
- func (t Type) CreateName() string
- func (t Type) CreateReceiver() string
- func (t Type) DeleteName() string
- func (t Type) DeleteOneName() string
- func (t Type) DeleteOneReceiver() string
- func (t Type) DeleteReceiver() string
- func (t Type) DeprecatedFields() []*Field
- func (t Type) EdgesWithID() (edges []*Edge)
- func (t Type) EntSQL() *entsql.Annotation
- func (t Type) EnumFields() []*Field
- func (t Type) FKEdges() (edges []*Edge)
- func (t Type) FieldBy(fn func(*Field) bool) (*Field, bool)
- func (t Type) FilterName() string
- func (t Type) HasAssoc(name string) (*Edge, bool)
- func (t Type) HasCompositeID() bool
- func (t Type) HasDefault() bool
- func (t Type) HasNumeric() bool
- func (t Type) HasOneFieldID() bool
- func (t Type) HasOptional() bool
- func (t Type) HasUpdateCheckers() bool
- func (t Type) HasUpdateDefault() bool
- func (t Type) HasValidators() bool
- func (t Type) HasValueScanner() bool
- func (t Type) HookPositions() []*load.Position
- func (t Type) ImmutableFields() []*Field
- func (t Type) InterceptorPositions() []*load.Position
- func (t Type) IsEdgeSchema() bool
- func (t Type) IsView() bool
- func (t Type) Label() string
- func (t Type) MixedInFields() []int
- func (t Type) MixedInHooks() []int
- func (t Type) MixedInInterceptors() []int
- func (t Type) MixedInPolicies() []int
- func (t Type) MutableFields() []*Field
- func (t Type) MutationFields() []*Field
- func (t Type) MutationName() string
- func (t Type) NumConstraint() int
- func (t Type) NumHooks() int
- func (t Type) NumInterceptors() int
- func (t Type) NumM2M() int
- func (t Type) NumMixin() int
- func (t Type) NumPolicy() int
- func (t Type) Package() string
- func (t Type) PackageAlias() string
- func (t Type) PackageDir() string
- func (t Type) PolicyPositions() []*load.Position
- func (t Type) QueryName() string
- func (t Type) Receiver() string
- func (t Type) RelatedTypes() []*Type
- func (t Type) RuntimeMixin() bool
- func (t Type) SiblingImports() []struct{ ... }
- func (t Type) Table() string
- func (t *Type) TableSchema() (string, error)
- func (t Type) TagTypes() []string
- func (t Type) TypeName() string
- func (t Type) UnexportedForeignKeys() []*ForeignKey
- func (t Type) UpdateName() string
- func (t Type) UpdateOneName() string
- func (t Type) UpdateOneReceiver() string
- func (t Type) UpdateReceiver() string
- func (t Type) ValueName() string
- type TypeTemplate
Constants ¶
This section is empty.
Variables ¶
var ( // FeaturePrivacy provides a feature-flag for the privacy extension. FeaturePrivacy = Feature{ Name: "privacy", Stage: Alpha, Default: false, Description: "Privacy provides a privacy layer for ent through the schema configuration", // contains filtered or unexported fields } // FeatureIntercept provides a feature-flag for the interceptors' extension. FeatureIntercept = Feature{ Name: "intercept", Stage: Alpha, Default: false, Description: "Intercept generates a helper package to make working with interceptors easier", // contains filtered or unexported fields } // FeatureEntQL provides a feature-flag for the EntQL extension. FeatureEntQL = Feature{ Name: "entql", Stage: Experimental, Default: false, Description: "EntQL provides a generic filtering capability at runtime", // contains filtered or unexported fields } // FeatureNamedEdges provides a feature-flag for eager-loading edges with dynamic names. FeatureNamedEdges = Feature{ Name: "namedges", Stage: Experimental, Default: false, Description: "NamedEdges provides an API for eager-loading edges with dynamic names", } // FeatureBidiEdgeRefs provides a feature-flag for sql dialect to set two-way // references when loading (unique) edges. Note, users that use the standard // encoding/json.MarshalJSON should detach the circular references before marshaling. FeatureBidiEdgeRefs = Feature{ Name: "bidiedges", Stage: Experimental, Default: false, Description: "This features guides Ent to set two-way references when loading (O2M/O2O) edges", } // FeatureSnapshot stores a snapshot of ent/schema and auto-solve merge-conflict (issue #852). FeatureSnapshot = Feature{ Name: "schema/snapshot", Stage: Experimental, Default: false, Description: "Schema snapshot stores a snapshot of ent/schema and auto-solve merge-conflict (issue #852)", GraphTemplates: []GraphTemplate{ { Name: "internal/schema", Format: "internal/schema.go", }, }, // contains filtered or unexported fields } // FeatureSchemaConfig allows users to pass init time alternate schema names // for each ent model. This is useful if your SQL tables are spread out against // multiple databases. FeatureSchemaConfig = Feature{ Name: "sql/schemaconfig", Stage: Stable, Default: false, Description: "Allows alternate schema names for each ent model. Useful if SQL tables are spread out against multiple databases", GraphTemplates: []GraphTemplate{ { Name: "dialect/sql/internal/schemaconfig", Format: "internal/schemaconfig.go", }, }, // contains filtered or unexported fields } // FeatureLock provides a feature-flag for sql locking extension. FeatureLock = Feature{ Name: "sql/lock", Stage: Experimental, Default: false, Description: "Allows users to use row-level locking in SQL using the 'FOR {UPDATE|SHARE}' clauses", } // FeatureModifier provides a feature-flag for adding query modifiers. FeatureModifier = Feature{ Name: "sql/modifier", Stage: Experimental, Default: false, Description: "Allows users to attach custom modifiers to queries", } // FeatureExecQuery provides a feature-flag for exposing the ExecContext/QueryContext methods of the underlying SQL drivers. FeatureExecQuery = Feature{ Name: "sql/execquery", Stage: Experimental, Default: false, Description: "Allows users to execute statements using the ExecContext/QueryContext methods of the underlying driver", } // FeatureUpsert provides a feature-flag for adding upsert (ON CONFLICT) capabilities to create builders. FeatureUpsert = Feature{ Name: "sql/upsert", Stage: Experimental, Default: false, Description: "Allows users to configure the `ON CONFLICT`/`ON DUPLICATE KEY` clause for `INSERT` statements", } FeatureVersionedMigration = Feature{ Name: "sql/versioned-migration", Stage: Experimental, Default: false, Description: "Allows users to work with versioned migrations / migration files", } // AllFeatures holds a list of all feature-flags. AllFeatures = []Feature{ FeaturePrivacy, FeatureIntercept, FeatureEntQL, FeatureNamedEdges, FeatureBidiEdgeRefs, FeatureSnapshot, FeatureSchemaConfig, FeatureLock, FeatureModifier, FeatureExecQuery, FeatureUpsert, FeatureVersionedMigration, } )
var ( // Templates holds the template information for a file that the graph is generating. Templates = []TypeTemplate{ { Name: "create", Cond: notView, Format: pkgf("%s_create.go"), ExtendPatterns: []string{ "dialect/*/create/fields/additional/*", "dialect/*/create_bulk/fields/additional/*", }, }, { Name: "update", Cond: notView, Format: pkgf("%s_update.go"), }, { Name: "delete", Cond: notView, Format: pkgf("%s_delete.go"), }, { Name: "query", Format: pkgf("%s_query.go"), ExtendPatterns: []string{ "dialect/*/query/fields/additional/*", }, }, { Name: "model", Format: pkgf("%s.go"), }, { Name: "where", Format: pkgf("%s/where.go"), ExtendPatterns: []string{ "where/additional/*", }, }, { Name: "meta", Format: func(t *Type) string { return fmt.Sprintf("%[1]s/%[1]s.go", t.PackageDir()) }, ExtendPatterns: []string{ "meta/additional/*", }, }, } // GraphTemplates holds the templates applied on the graph. GraphTemplates = []GraphTemplate{ { Name: "base", Format: "ent.go", }, { Name: "client", Format: "client.go", ExtendPatterns: []string{ "client/fields/additional/*", "dialect/*/query/fields/init/*", }, }, { Name: "tx", Format: "tx.go", }, { Name: "mutation", Format: "mutation.go", }, { Name: "migrate", Format: "migrate/migrate.go", Skip: func(g *Graph) bool { return !g.SupportMigrate() }, }, { Name: "schema", Format: "migrate/schema.go", Skip: func(g *Graph) bool { return !g.SupportMigrate() }, }, { Name: "predicate", Format: "predicate/predicate.go", }, { Name: "hook", Format: "hook/hook.go", }, { Name: "privacy", Format: "privacy/privacy.go", Skip: func(g *Graph) bool { return !g.featureEnabled(FeaturePrivacy) }, }, { Name: "intercept", Format: "intercept/intercept.go", Skip: func(g *Graph) bool { return !g.featureEnabled(FeatureIntercept) }, }, { Name: "entql", Format: "entql.go", Skip: func(g *Graph) bool { return !g.featureEnabled(FeatureEntQL) }, }, { Name: "runtime/ent", Format: "runtime.go", }, { Name: "enttest", Format: "enttest/enttest.go", }, { Name: "runtime/pkg", Format: "runtime/runtime.go", }, } )
var ( // Funcs are the predefined template // functions used by the codegen. Funcs = template.FuncMap{ "ops": fieldOps, "add": add, "append": reflect.Append, "appends": reflect.AppendSlice, "order": order, "camel": camel, "snake": snake, "pascal": pascal, "extend": extend, "xrange": xrange, "receiver": receiver, "plural": plural, "aggregate": aggregate, "primitives": primitives, "singular": rules.Singularize, "quote": quote, "base": filepath.Base, "keys": keys, "indexOf": indexOf, "join": join, "joinWords": joinWords, "isNil": isNil, "lower": strings.ToLower, "upper": strings.ToUpper, "trim": strings.Trim, "hasField": hasField, "hasImport": hasImport, "indirect": indirect, "hasPrefix": strings.HasPrefix, "hasSuffix": strings.HasSuffix, "trimPackage": trimPackage, "xtemplate": xtemplate, "hasTemplate": hasTemplate, "matchTemplate": matchTemplate, "split": strings.Split, "tagLookup": tagLookup, "toString": toString, "dict": dict, "get": get, "set": set, "unset": unset, "hasKey": hasKey, "list": list[any], "slist": list[string], "fail": fail, "replace": strings.ReplaceAll, } )
Functions ¶
func PrepareEnv ¶
PrepareEnv makes sure the generated directory (environment) is suitable for loading the `ent` package (avoid cyclic imports).
func ValidSchemaName ¶
ValidSchemaName will determine if a name is going to conflict with any pre-defined names
Types ¶
type Annotations ¶
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.
func (*Annotations) Set ¶
func (a *Annotations) Set(k string, v any)
Set sets an annotation a new annotation in the map. A new map is created if the receiver is nil.
type Config ¶
type 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 provide an optional header signature for // the generated files. It defaults to the standard 'go generate' // format: '// Code generated by ent, 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 // BuildFlags holds a list of custom build flags to use // when loading the schema packages. BuildFlags []string }
The Config holds the global codegen configuration to be shared between all generated nodes.
func (Config) FeatureEnabled ¶
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 (Config) ModuleInfo ¶
ModuleInfo returns the github.com/go-ent/ent version.
type Dependencies ¶
type Dependencies []*Dependency
Dependencies wraps a list of dependencies as codegen annotation.
func (Dependencies) Merge ¶
func (d Dependencies) Merge(other schema.Annotation) schema.Annotation
Merge implements the schema.Merger interface.
type Dependency ¶
type Dependency struct { // Field defines the struct field name on the builders. // It defaults to the full type name. For example: // // http.Client => HTTPClient // net.Conn => NetConn // url.URL => URL // Field string // Type defines the type identifier. For example, `*http.Client`. Type *field.TypeInfo // Option defines the name of the config option. // It defaults to the field name. Option string }
Dependency allows configuring optional dependencies as struct fields on the generated builders. For example:
DependencyAnnotation{ Field: "HTTPClient", Type: "*http.Client", Option: "WithClient", }
Although the Dependency and the DependencyAnnotation are exported, used should use the entc.Dependency option in order to build this annotation.
func (*Dependency) Build ¶
func (d *Dependency) Build() error
Build builds the annotation and fails if it is invalid.
type Edge ¶
type Edge struct { // 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 // Immutable indicates is this edge cannot be updated. Immutable 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 // Through edge schema type. Through *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 // contains filtered or unexported fields }
Edge of a graph between two types.
func (Edge) BuilderField ¶
BuilderField returns the struct member of the edge in the builder.
func (Edge) ColumnConstant ¶
ColumnConstant returns the constant name of the relation column.
func (Edge) EagerLoadField ¶
EagerLoadField returns the struct field (of query builder) for storing the eager-loading info.
func (Edge) EagerLoadNamedField ¶
EagerLoadNamedField returns the struct field (of query builder) for storing the eager-loading info for named edges.
func (Edge) EntSQL ¶
func (e Edge) EntSQL() *entsql.Annotation
EntSQL returns the EntSQL annotation if exists.
func (Edge) Field ¶
Field returns the field that was referenced in the schema. For example:
edge.From("owner", User.Type). Ref("pets"). Field("owner_id")
Note that the zero value is returned if no field was defined in the schema.
func (*Edge) ForeignKey ¶
func (e *Edge) ForeignKey() (*ForeignKey, error)
ForeignKey returns the foreign-key of the inverse-field.
func (Edge) HasConstraint ¶
HasConstraint indicates if this edge has a unique constraint check. We check uniqueness when both-directions are unique or one of them. Used by the Gremlin storage-layer.
func (Edge) HasFieldSetter ¶
HasFieldSetter reports if this edge already has a field-edge setters for its mutation API. It's used by the codegen templates to avoid generating duplicate setters for id APIs (e.g. SetOwnerID).
func (Edge) Index ¶
Index returns the index of the edge in the schema. Used mainly to extract its position in the "loadedTypes" array.
func (Edge) InverseLabelConstant ¶
InverseLabelConstant returns the inverse constant name of the edge.
func (Edge) InverseTableConstant ¶
InverseTableConstant returns the constant name of the other/inverse type of the relation.
func (Edge) LabelConstant ¶
LabelConstant returns the constant name of the edge for the gremlin dialect. If the edge is inverse, it returns the constant name of the owner-edge (assoc-edge).
func (Edge) MutationAdd ¶
MutationAdd returns the method name for adding edge ids.
func (Edge) MutationClear ¶
MutationClear returns the method name for clearing the edge value. The default name is "Clear<EdgeName>". If the method conflicts with the mutation methods, suffix the method with "Edge".
func (Edge) MutationCleared ¶
MutationCleared returns the method name for indicating if the edge was cleared in the mutation. The default name is "<EdgeName>Cleared". If the method conflicts with the mutation methods, add "Edge" the after the edge name.
func (Edge) MutationRemove ¶
MutationRemove returns the method name for removing edge ids.
func (Edge) MutationReset ¶
MutationReset returns the method name for resetting the edge value. The default name is "Reset<EdgeName>". If the method conflicts with the mutation methods, suffix the method with "Edge".
func (Edge) MutationSet ¶
MutationSet returns the method name for setting the edge id.
func (Edge) OrderCountName ¶
OrderCountName returns the function/option name for ordering by the edge count.
func (Edge) OrderFieldName ¶
OrderFieldName returns the function/option name for ordering by edge field.
func (Edge) OrderTermsName ¶
OrderTermsName returns the function/option name for ordering by any term.
func (Edge) OwnFK ¶
OwnFK indicates if the foreign-key of this edge is owned by the edge column (reside in the type's table). Used by the SQL storage-driver.
func (Edge) PKConstant ¶
PKConstant returns the constant name of the primary key. Used for M2M edges.
func (Edge) StorageKey ¶
func (e Edge) StorageKey() (*edge.StorageKey, error)
StorageKey returns the storage-key defined on the schema if exists.
func (Edge) StructField ¶
StructField returns the struct member of the edge in the model.
func (Edge) TableConstant ¶
TableConstant returns the constant name of the relation table. The value id Edge.Rel.Table, which is table that holds the relation/edge.
func (*Edge) TableSchema ¶
TableSchema returns the schema name of where the type table resides (intentionally exported).
type Enum ¶
type Enum struct { // Name is the Go name of the enum. Name string // Value in the schema. Value string }
Enum holds the enum information for schema enums in codegen.
type Feature ¶
type Feature struct { // Name of the feature. Name string // Stage of the feature. Stage FeatureStage // Default values indicates if this feature is enabled by default. Default bool // A Description of this feature. Description string // Templates defines list of templates for extending or overriding the default // templates. In order to write the template output to a standalone file, use // the GraphTemplates below. Templates []*Template // GraphTemplates defines optional templates to be executed on the graph // and will their output will be written to the configured destination. GraphTemplates []GraphTemplate // contains filtered or unexported fields }
A Feature of the ent codegen.
type FeatureStage ¶
type FeatureStage int
FeatureStage describes the stage of the codegen feature.
const ( // Experimental features are in development, and actively being tested in the // integration environment. Experimental FeatureStage // Alpha features are features whose initial development was finished, tested // on the infra of the ent team, but we expect breaking-changes to their APIs. Alpha // Beta features are Alpha features that were added to the entgo.io // documentation, and no breaking-changes are expected for them. Beta // Stable features are Beta features that were running for a while on ent // infra. Stable )
type Field ¶
type Field struct { // 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 the 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 // contains filtered or unexported fields }
Field holds the information of a type field used for the templates.
func (Field) BasicType ¶
BasicType returns a Go expression for the given identifier to convert it to a basic type. For example:
v (http.Dir) => string(v) v (fmt.Stringer) => v.String() v (sql.NullString) => v.String
func (Field) BuilderField ¶
BuilderField returns the struct member of the field in the builder.
func (Field) Column ¶
Column returns the table column. It sets it as a primary key (auto_increment) in case of ID field, unless stated otherwise.
func (Field) ConvertedToBasic ¶
ConvertedToBasic indicates if the Go type of the field can be converted to basic type (string, int, etc.).
func (Field) DefaultFunc ¶
DefaultFunc returns a bool stating if the default value is a func. Invoked by the template.
func (Field) DefaultName ¶
DefaultName returns the variable name of the default value of this field.
func (Field) DefaultValue ¶
DefaultValue returns the default value of the field. Invoked by the template.
func (Field) DeprecationReason ¶
DeprecationReason returns the deprecation reason of the field.
func (Field) EntSQL ¶
func (f Field) EntSQL() *entsql.Annotation
EntSQL returns the EntSQL annotation if exists.
func (Field) EnumValues ¶
EnumValues returns the values of the enum field.
func (Field) FromValueFunc ¶
FromValueFunc returns a path to the FromValue field (func) of the external ValueScanner.
func (Field) HasGoType ¶
HasGoType indicate if a basic field (like string or bool) has a custom GoType.
func (Field) HasValueScanner ¶
HasValueScanner indicates if the field has (an external) ValueScanner.
func (Field) IsDeprecated ¶
IsDeprecated returns true if the field is deprecated.
func (Field) IsEdgeField ¶
IsEdgeField reports if the given field is an edge-field (i.e. a foreign-key) that was referenced by one of the edges.
func (Field) MutationAdd ¶
MutationAdd returns the method name for adding a value to the field. The default name is "Add<FieldName>". If the method conflicts with the mutation methods, suffix the method with "Field".
func (Field) MutationAddAssignExpr ¶
MutationAddAssignExpr returns the expression for summing to identifiers and assigning to the mutation field.
MutationAddAssignExpr(a, b) => *m.a += b // Basic Go type. MutationAddAssignExpr(a, b) => *m.a = m.Add(b) // Custom Go types that implement the (Add(T) T) interface.
func (Field) MutationAdded ¶
MutationAdded returns the method name for getting the field value that was added to the field.
func (Field) MutationAppend ¶
MutationAppend returns the method name for appending a list of values to the field. The default name is "Append<FieldName>". If the method conflicts with the mutation methods, suffix the method with "Field".
func (Field) MutationAppended ¶
MutationAppended returns the method name for getting the field value that was added to the field.
func (Field) MutationClear ¶
MutationClear returns the method name for clearing the field value.
func (Field) MutationCleared ¶
MutationCleared returns the method name for indicating if the field was cleared in the mutation.
func (Field) MutationGet ¶
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 (Field) MutationGetOld ¶
MutationGetOld returns the method name for getting the old value of a field.
func (Field) MutationReset ¶
MutationReset returns the method name for resetting the field value. The default name is "Reset<FieldName>". If the method conflicts with the mutation methods, suffix the method with "Field".
func (Field) MutationSet ¶
MutationSet returns the method name for setting the field value. The default name is "Set<FieldName>". If the method conflicts with the mutation methods, suffix the method with "Field".
func (Field) NewScanType ¶
NewScanType returns an expression for creating a new object to be used by the `rows.Scan` method. A sql.Scanner or a nillable-type supported by the SQL driver (e.g. []byte).
func (Field) NillableValue ¶
NillableValue reports if the field holds a Go value (not a pointer), but the field is nillable. It's used by the templates to prefix values with pointer operators (e.g. &intValue or *intValue).
func (Field) RequiredFor ¶
RequiredFor returns a list of dialects that this field is required for. A field can be required in one database, but optional in the other. e.g., in case a SchemaType was defined as "serial" for PostgreSQL, but "int" for SQLite.
func (Field) ScanTypeField ¶
ScanTypeField extracts the nullable type field (if exists) from the given receiver. It also does the type conversion if needed.
func (Field) ScanValueFunc ¶
ScanValueFunc returns a path to the ScanValue field (func) of the external ValueScanner.
func (Field) SignedType ¶
SignedType returns the "signed type version" of the field type. This behavior is required for supporting addition/subtraction in mutations for unsigned types.
func (Field) StorageKey ¶
StorageKey returns the storage name of the field. SQL column or Gremlin property.
func (Field) StructField ¶
StructField returns the struct member of the field in the model.
func (Field) SupportsMutationAdd ¶
SupportsMutationAdd reports if the field supports the mutation "Add(T) T" interface.
func (Field) SupportsMutationAppend ¶
SupportsMutationAppend reports if the field supports the mutation append operation.
func (Field) UpdateDefaultName ¶
UpdateDefaultName returns the variable name of the update default value of this field.
type ForeignKey ¶
type 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 }
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.
func (ForeignKey) StructField ¶
func (f ForeignKey) StructField() string
StructField returns the struct member of the foreign-key in the generated model.
type GenerateFunc ¶
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.
type Generator ¶
type Generator interface { // Generate generates the ent artifacts for the given graph. Generate(*Graph) error }
Generator is the interface that wraps the Generate method.
type Graph ¶
type 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 // contains filtered or unexported fields }
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.
func NewGraph ¶
NewGraph creates a new Graph for the code generation from the given schema definitions. It fails if one of the schemas is invalid.
func (*Graph) MutableNodes ¶
MutableNodes returns the list of nodes that are mutable. i.e., not views.
func (*Graph) SchemaSnapshot ¶
SchemaSnapshot returns a JSON string represents the graph schema in loadable format.
func (*Graph) SupportMigrate ¶
SupportMigrate reports if the codegen supports schema migration.
func (*Graph) TableSchemas ¶
TableSchemas returns all table schemas in ent/schema (intentionally exported).
type GraphTemplate ¶
type GraphTemplate struct { Name string // template name. Skip func(*Graph) bool // skip condition (storage constraints or gated by a feature-flag). Format string // file name format. ExtendPatterns []string // extend patterns. }
GraphTemplate specifies a template that is executed with the Graph object.
type Hook ¶
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) }) }
type Index ¶
type 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 }
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.
type Op ¶
type Op int
Op represents a predicate operation for schema fields.
const ( EQ Op = iota // = NEQ // <> GT // > GTE // >= LT // < LTE // <= IsNil // IS NULL / has NotNil // IS NOT NULL / hasNot In // within NotIn // without EqualFold // equals case-insensitive Contains // containing ContainsFold // containing case-insensitive HasPrefix // startingWith HasSuffix // endingWith )
List of all builtin predicates.
type Rel ¶
type Rel int
Rel is a relation type of an edge.
type Relation ¶
type 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(s) in the relation table above. // For O2M, M2O and O2O, it contains one element with the column name. // For M2M edges, it contains two columns defined in the join table with // the same order as defined in the schema: (owner_id, reference_id). Columns []string // contains filtered or unexported fields }
Relation holds the relational database information for edges.
type SchemaMode ¶
type SchemaMode uint
A SchemaMode defines what type of schema feature a storage driver support.
const ( // Unique defines field and edge uniqueness support. Unique SchemaMode = 1 << iota // Indexes defines indexes support. Indexes // Cascade defines cascading operations (e.g. cascade deletion). Cascade // Migrate defines static schema and migration support (e.g. SQL-based). Migrate )
func (SchemaMode) Support ¶
func (m SchemaMode) Support(mode SchemaMode) bool
Support reports whether m support the given mode.
type Storage ¶
type Storage struct { Name string // storage name. Builder reflect.Type // query builder type. Dialects []string // supported dialects. IdentName string // identifier name (fields and funcs). Imports []string // import packages needed. SchemaMode SchemaMode // schema mode support. Ops func(*Field) []Op // storage specific operations. OpCode func(Op) string // operation code for predicates. Init func(*Graph) error // optional init function. }
Storage driver type for codegen.
func NewStorage ¶
NewStorage returns the storage driver type from the given string. It fails if the provided string is not a valid option. this function is here in order to remove the validation logic from entc command line.
type Template ¶
type Template struct { *template.Template FuncMap template.FuncMap // contains filtered or unexported fields }
Template wraps the standard template.Template to provide additional functionality for ent extensions.
func MustParse ¶
MustParse is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil.
func NewTemplate ¶
NewTemplate creates an empty template with the standard codegen functions.
func (*Template) AddParseTree ¶
AddParseTree adds the given parse tree to the template.
func (*Template) ParseDir ¶
ParseDir walks on the given dir path and parses the given matches with aren't Go files.
func (*Template) ParseFS ¶
ParseFS is like ParseFiles or ParseGlob but reads from the file system fsys instead of the host operating system's file system.
func (*Template) ParseFiles ¶
ParseFiles parses a list of files as templates and associate them with t. Each file can be a standalone template.
type Type ¶
type Type struct { *Config // Name holds the type/ent name. Name string // ID holds the ID field of this type. ID *Field // Fields holds all the primitive fields of this type. Fields []*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 // Annotations that were defined for the field in the schema. // The mapping is from the Annotation.Name() to a JSON decoded object. Annotations Annotations // EdgeSchema indicates that this type (schema) is being used as an "edge schema". // The To and From fields holds references to the edges that go "through" this type. EdgeSchema struct { ID []*Field To, From *Edge } // contains filtered or unexported fields }
Type represents one node-type in the graph, its relations and the information it holds.
func (*Type) AddIndex ¶
AddIndex adds a new index for the type. It fails if the schema index is invalid.
func (Type) ClientName ¶
ClientName returns the struct name denoting the client of this type.
func (Type) CreateBulReceiver ¶
CreateBulReceiver returns the receiver name of the create-bulk-builder for this type.
func (Type) CreateBulkName ¶
CreateBulkName returns the struct name denoting the create-bulk-builder for this type.
func (Type) CreateName ¶
CreateName returns the struct name denoting the create-builder for this type.
func (Type) CreateReceiver ¶
CreateReceiver returns the receiver name of the create-builder for this type.
func (Type) DeleteName ¶
DeleteName returns the struct name denoting the delete-builder for this type.
func (Type) DeleteOneName ¶
DeleteOneName returns the struct name denoting the delete-one-builder for this type.
func (Type) DeleteOneReceiver ¶
DeleteOneReceiver returns the receiver name of the delete-one-builder for this type.
func (Type) DeleteReceiver ¶
DeleteReceiver returns the receiver name of the delete-builder for this type.
func (Type) DeprecatedFields ¶
DeprecatedFields returns all deprecated fields of the type.
func (Type) EdgesWithID ¶
EdgesWithID returns all edges that point to entities with non-composite identifiers. These types of edges can be created, updated and deleted by their identifiers.
func (Type) EntSQL ¶
func (t Type) EntSQL() *entsql.Annotation
EntSQL returns the EntSQL annotation if exists.
func (Type) EnumFields ¶
EnumFields returns the enum fields of the schema, if any.
func (Type) FilterName ¶
FilterName returns the struct name denoting the filter-builder for this type.
func (Type) HasAssoc ¶
HasAssoc returns true if this type has an assoc-edge (edge.To) with the given name. faster than map access for most cases.
func (Type) HasCompositeID ¶
HasCompositeID indicates if the type has a composite ID field.
func (Type) HasDefault ¶
HasDefault reports if any of this type's fields has default value on creation.
func (Type) HasNumeric ¶
HasNumeric reports if this type has a numeric field.
func (Type) HasOneFieldID ¶
HasOneFieldID indicates if the type has an ID with one field (not composite).
func (Type) HasOptional ¶
HasOptional reports if this type has an optional field.
func (Type) HasUpdateCheckers ¶
HasUpdateCheckers reports if this type has any checkers to run on update(one).
func (Type) HasUpdateDefault ¶
HasUpdateDefault reports if any of this type's fields has default value on update.
func (Type) HasValidators ¶
HasValidators reports if any of the type's field has validators.
func (Type) HasValueScanner ¶
HasValueScanner reports if any of the fields has (an external) ValueScanner.
func (Type) HookPositions ¶
HookPositions returns the position information of hooks declared in the type schema.
func (Type) ImmutableFields ¶
ImmutableFields returns all type fields that are immutable (for update).
func (Type) InterceptorPositions ¶
InterceptorPositions returns the position information of interceptors declared in the type schema.
func (Type) IsEdgeSchema ¶
IsEdgeSchema indicates if the type (schema) is used as an edge-schema. i.e. is being used by an edge (or its inverse) with edge.Through modifier.
func (Type) MixedInFields ¶
MixedInFields returns the indices of mixin holds runtime code.
func (Type) MixedInHooks ¶
MixedInHooks returns the indices of mixin with hooks.
func (Type) MixedInInterceptors ¶
MixedInInterceptors returns the indices of mixin with interceptors.
func (Type) MixedInPolicies ¶
MixedInPolicies returns the indices of mixin with policies.
func (Type) MutableFields ¶
MutableFields returns all type fields that are mutable (on update).
func (Type) MutationFields ¶
MutationFields returns all the fields that are available on the typed-mutation.
func (Type) MutationName ¶
MutationName returns the struct name of the mutation builder for this type.
func (Type) NumConstraint ¶
NumConstraint returns the type's constraint count. Used for slice allocation.
func (Type) NumInterceptors ¶
NumInterceptors returns the number of interceptors declared in the type schema.
func (Type) PackageAlias ¶
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 or ent builtin types.
func (Type) PackageDir ¶
PackageDir returns the name of the package directory.
func (Type) PolicyPositions ¶
PolicyPositions returns the position information of privacy policy declared in the type schema.
func (Type) Receiver ¶
Receiver returns the receiver name of this node. It makes sure the receiver names doesn't conflict with import names.
func (Type) RelatedTypes ¶
RelatedTypes returns all the types (nodes) that are related (with edges) to this type.
func (Type) RuntimeMixin ¶
RuntimeMixin returns schema mixin that needs to be loaded at runtime. For example, for default values, validators or hooks.
func (Type) SiblingImports ¶
SiblingImports returns all sibling packages that are needed for the different builders.
func (*Type) TableSchema ¶
TableSchema returns the schema name of where the type table resides (intentionally exported).
func (Type) UnexportedForeignKeys ¶
func (t Type) UnexportedForeignKeys() []*ForeignKey
UnexportedForeignKeys returns all foreign-keys that belong to the type but are not exported (not defined with field). i.e. generated by ent.
func (Type) UpdateName ¶
UpdateName returns the struct name denoting the update-builder for this type.
func (Type) UpdateOneName ¶
UpdateOneName returns the struct name denoting the update-one-builder for this type.
func (Type) UpdateOneReceiver ¶
UpdateOneReceiver returns the receiver name of the update-one-builder for this type.
func (Type) UpdateReceiver ¶
UpdateReceiver returns the receiver name of the update-builder for this type.
type TypeTemplate ¶
type TypeTemplate struct { Name string // template name. Cond func(*Type) bool // condition to apply the template. Format func(*Type) string // file name format. ExtendPatterns []string // extend patterns. }
TypeTemplate specifies a template that is executed with each Type object of the graph.