gen

package
v0.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 6, 2021 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package gen is the interface for generating loaded schemas into a Go package.

Index

Constants

This section is empty.

Variables

View Source
var (
	// FeaturePrivacy provides a feature-flag for the privacy extension for ent.
	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
	}

	// FeatureEntQL provides a feature-flag for the entql extension for ent.
	FeatureEntQL = Feature{
		Name:        "entql",
		Stage:       Experimental,
		Default:     false,
		Description: "EntQL provides a generic filtering capability at runtime",
		// contains filtered or unexported fields
	}

	// 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)",
		// contains filtered or unexported fields
	}

	// AllFeatures holds a list of all feature-flags.
	AllFeatures = []Feature{
		FeaturePrivacy,
		FeatureEntQL,
		FeatureSnapshot,
	}
)
View Source
var (
	// Templates holds the template information for a file that the graph is generating.
	Templates = []TypeTemplate{
		{
			Name:   "create",
			Format: pkgf("%s_create.go"),
		},
		{
			Name:   "update",
			Format: pkgf("%s_update.go"),
		},
		{
			Name:   "delete",
			Format: pkgf("%s_delete.go"),
		},
		{
			Name:   "query",
			Format: pkgf("%s_query.go"),
		},
		{
			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("%s/%s.go", t.Package(), t.Package())
			},
			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/*",
			},
		},
		{
			Name:   "context",
			Format: "context.go",
		},
		{
			Name:   "tx",
			Format: "tx.go",
		},
		{
			Name:   "config",
			Format: "config.go",
			ExtendPatterns: []string{
				"dialect/*/config/*/*",
			},
		},
		{
			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:   "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",
		},
		{
			Name:   "internal/schema",
			Format: "internal/schema.go",
			Skip: func(g *Graph) bool {
				return !g.featureEnabled(FeatureSnapshot)
			},
		},
	}
)
View Source
var (
	// Funcs are the predefined template
	// functions used by the codegen.
	Funcs = template.FuncMap{
		"ops":           ops,
		"add":           add,
		"append":        reflect.Append,
		"appends":       reflect.AppendSlice,
		"order":         order,
		"camel":         camel,
		"dumpFields":    dumpFields,
		"snake":         snake,
		"pascal":        pascal,
		"extend":        extend,
		"xrange":        xrange,
		"receiver":      receiver,
		"plural":        plural,
		"aggregate":     aggregate,
		"primitives":    primitives,
		"singular":      rules.Singularize,
		"quote":         strconv.Quote,
		"base":          filepath.Base,
		"keys":          keys,
		"join":          join,
		"lower":         strings.ToLower,
		"upper":         strings.ToUpper,
		"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,
		"fail":          fail,
		"replace":       strings.ReplaceAll,
	}
)

Functions

func PrepareEnv

func PrepareEnv(c *Config) (undo func() error, err error)

PrepareEnv makes sure the generated directory (environment) is suitable for loading the `ent` package (avoid cyclic imports).

func ValidSchemaName added in v0.5.4

func ValidSchemaName(name string) error

ValidSchemaName will determine if a name is going to conflict with any pre-defined names

Types

type Config

type Config struct {
	// Schema is the package path for the schema package.
	Schema string
	// Target is the filepath for the directory that holds the generated code.
	Target string
	// Package path for the targeted directory that holds the generated code.
	Package string
	// Header is an optional header signature for generated files.
	Header string
	// Storage to support in codegen.
	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
}

Config for global codegen to be shared between all nodes.

func (Config) FeatureEnabled added in v0.5.0

func (c Config) FeatureEnabled(name string) (bool, error)

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

func (Config) ModuleInfo() (m debug.Module)

ModuleInfo returns the entc binary module version.

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
	// 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
	// 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 map[string]interface{}
	// contains filtered or unexported fields
}

Edge of a graph between two types.

func (Edge) BuilderField

func (e Edge) BuilderField() string

BuilderField returns the struct member of the edge in the builder.

func (Edge) ColumnConstant

func (e Edge) ColumnConstant() string

ColumnConstant returns the constant name of the relation column.

func (Edge) Constant

func (e Edge) Constant() string

Constant returns the constant name of the edge.

func (Edge) EagerLoadField added in v0.5.0

func (e Edge) EagerLoadField() string

EagerLoadField returns the struct field (of query builder) for storing the eager-loading info.

func (Edge) HasConstraint

func (e Edge) HasConstraint() bool

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) InverseLabelConstant

func (e Edge) InverseLabelConstant() string

InverseLabelConstant returns the inverse constant name of the edge.

func (Edge) InverseTableConstant

func (e Edge) InverseTableConstant() string

InverseTableConstant returns the constant name of the other/inverse type of the relation.

func (Edge) IsInverse

func (e Edge) IsInverse() bool

IsInverse returns if this edge is an inverse edge.

func (Edge) Label

func (e Edge) Label() string

Label returns the Gremlin label name of the edge. If the edge is inverse

func (Edge) LabelConstant

func (e Edge) LabelConstant() string

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) M2M

func (e Edge) M2M() bool

M2M indicates if this edge is M2M edge.

func (Edge) M2O

func (e Edge) M2O() bool

M2O indicates if this edge is M2O edge.

func (Edge) MutationAdd added in v0.5.3

func (e Edge) MutationAdd() string

MutationAdd returns the method name for adding edge ids.

func (Edge) MutationClear added in v0.4.3

func (e Edge) MutationClear() string

MutationClear returns the method name for clearing the edge value. The default name is "Clear<EdgeName>". If the the method conflicts with the mutation methods, suffix the method with "Edge".

func (Edge) MutationCleared added in v0.4.3

func (e Edge) MutationCleared() string

MutationCleared returns the method name for indicating if the edge was cleared in the mutation. The default name is "<EdgeName>Cleared". If the the method conflicts with the mutation methods, add "Edge" the after the edge name.

func (Edge) MutationReset

func (e Edge) MutationReset() string

MutationReset returns the method name for resetting the edge value. The default name is "Reset<EdgeName>". If the the method conflicts with the mutation methods, suffix the method with "Edge".

func (Edge) MutationSet added in v0.5.3

func (e Edge) MutationSet() string

MutationSet returns the method name for setting the edge id.

func (Edge) O2M

func (e Edge) O2M() bool

O2M indicates if this edge is O2M edge.

func (Edge) O2O

func (e Edge) O2O() bool

O2O indicates if this edge is O2O edge.

func (Edge) OwnFK

func (e Edge) OwnFK() bool

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

func (e Edge) PKConstant() string

PKConstant returns the constant name of the primary key. Used for M2M edges.

func (Edge) StructFKField

func (e Edge) StructFKField() string

StructFKField returns the struct member for holding the edge foreign-key in the model.

func (Edge) StructField

func (e Edge) StructField() string

StructField returns the struct member of the edge in the model.

func (Edge) TableConstant

func (e Edge) TableConstant() string

TableConstant returns the constant name of the relation table.

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 added in v0.5.0

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
	// contains filtered or unexported fields
}

A Feature of the ent codegen.

type FeatureStage added in v0.5.0

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 this field have.
	Validators int
	// Position info of the field.
	Position *load.Position
	// UserDefined indicates that this field was defined by the loaded schema.
	// Unlike 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 map[string]interface{}
	// contains filtered or unexported fields
}

Field holds the information of a type field used for the templates.

func (Field) BasicType

func (f Field) BasicType(ident string) (expr string)

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

func (f Field) BuilderField() string

BuilderField returns the struct member of the field in the builder.

func (Field) Column

func (f Field) Column() *schema.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) Constant

func (f Field) Constant() string

Constant returns the constant name of the field.

func (Field) ConvertedToBasic

func (f Field) ConvertedToBasic() bool

ConvertedToBasic indicates if the Go type of the field can be converted to basic type (string, int, etc).

func (Field) DefaultFunc added in v0.5.4

func (f Field) DefaultFunc() interface{}

DefaultFunc returns a bool stating if the default value is a func. Invoked by the template.

func (Field) DefaultName

func (f Field) DefaultName() string

DefaultName returns the variable name of the default value of this field.

func (Field) DefaultValue

func (f Field) DefaultValue() interface{}

DefaultValue returns the default value of the field. Invoked by the template.

func (Field) EntSQL added in v0.5.1

func (f Field) EntSQL() *entsql.Annotation

EntSQL returns the EntSQL annotation if exists.

func (Field) EnumName

func (f Field) EnumName(enum string) string

EnumName returns the constant name for the enum.

func (Field) EnumNames

func (f Field) EnumNames() []string

EnumNames returns the enum values of a field.

func (Field) EnumValues

func (f Field) EnumValues() []string

EnumValues returns the values of the enum field.

func (Field) HasGoType

func (f Field) HasGoType() bool

HasGoType indicate if a basic field (like string or bool) has a custom GoType.

func (Field) IsBool

func (f Field) IsBool() bool

IsBool returns true if the field is a bool field.

func (Field) IsBytes added in v0.5.0

func (f Field) IsBytes() bool

IsBytes returns true if the field is a bytes field.

func (Field) IsEnum

func (f Field) IsEnum() bool

IsEnum returns true if the field is an enum field.

func (Field) IsInt

func (f Field) IsInt() bool

IsInt returns true if the field is an int field.

func (Field) IsJSON

func (f Field) IsJSON() bool

IsJSON returns true if the field is a JSON field.

func (Field) IsString

func (f Field) IsString() bool

IsString returns true if the field is a string field.

func (Field) IsTime

func (f Field) IsTime() bool

IsTime returns true if the field is a timestamp field.

func (Field) IsUUID

func (f Field) IsUUID() bool

IsUUID returns true if the field is a UUID field.

func (Field) MutationGet

func (f Field) MutationGet() string

MutationGet returns the method name for getting the field value. The default name is just a pascal format. If the the method conflicts with the mutation methods, prefix the method with "Get".

func (Field) MutationGetOld

func (f Field) MutationGetOld() string

MutationGetOld returns the method name for getting the old value of a field.

func (Field) MutationReset

func (f Field) MutationReset() string

MutationReset returns the method name for resetting the field value. The default name is "Reset<FieldName>". If the the method conflicts with the mutation methods, suffix the method with "Field".

func (Field) MutationSet added in v0.5.4

func (f Field) MutationSet() string

MutationSet returns the method name for setting the field value. The default name is "Set<FieldName>". If the the method conflicts with the mutation methods, suffix the method with "Field".

func (Field) NullType

func (f Field) NullType() string

NullType returns the sql null-type for optional and nullable fields.

func (Field) NullTypeField

func (f Field) NullTypeField(rec string) string

NullTypeField extracts the nullable type field (if exists) from the given receiver. It also does the type conversion if needed.

func (Field) PK

func (f Field) PK() *schema.Column

PK is like Column, but for table primary key.

func (Field) Sensitive

func (f Field) Sensitive() bool

Sensitive returns true if the field is a sensitive field.

func (Field) StorageKey

func (f Field) StorageKey() string

StorageKey returns the storage name of the field. SQL column or Gremlin property.

func (Field) StructField

func (f Field) StructField() string

StructField returns the struct member of the field in the model.

func (Field) UpdateDefaultName

func (f Field) UpdateDefaultName() string

UpdateDefaultName returns the variable name of the update default value of this field.

func (Field) Validator

func (f Field) Validator() string

Validator returns the validator name.

type ForeignKey

type ForeignKey struct {
	// Field information for the foreign-key column.
	Field *Field
	// Edge that is associated with this foreign-key.
	Edge *Edge
}

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.

type GenerateFunc added in v0.5.0

type GenerateFunc func(*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.

func (GenerateFunc) Generate added in v0.5.0

func (f GenerateFunc) Generate(g *Graph) error

Generate calls f(g).

type Generator added in v0.5.0

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
}

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

func NewGraph(c *Config, schemas ...*load.Schema) (g *Graph, err error)

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) Gen

func (g *Graph) Gen() error

Gen generates the artifacts for the graph.

func (*Graph) SchemaSnapshot added in v0.5.0

func (g *Graph) SchemaSnapshot() (string, error)

SchemaSnapshot returns a JSON string represents the graph schema in loadable format.

func (*Graph) SupportMigrate

func (g *Graph) SupportMigrate() bool

SupportMigrate reports if the codegen supports schema migration.

func (*Graph) Tables

func (g *Graph) Tables() (all []*schema.Table)

Tables returns the schema definitions of SQL tables for the graph.

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 added in v0.5.0

type Hook func(Generator) Generator

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
}

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 is a predicate for the where clause.

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.

func (Op) Name

func (o Op) Name() string

Name returns the string representation of an predicate.

func (Op) Niladic

func (o Op) Niladic() bool

Niladic reports if the predicate is a niladic predicate.

func (Op) Variadic

func (o Op) Variadic() bool

Variadic reports if the predicate is a variadic function.

type Rel

type Rel int

Rel is a relation type of an edge.

const (
	Unk Rel = iota // Unknown.
	O2O            // One to one / has one.
	O2M            // One to many / has many.
	M2O            // Many to one (inverse perspective for O2M).
	M2M            // Many to many.
)

Relation types.

func (Rel) String

func (r Rel) String() string

String returns the relation name.

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 in the relation table above.
	// In O2M, M2O and O2O, this the first element.
	Columns []string
}

Relation holds the relational database information for edges.

func (Relation) Column

func (r Relation) Column() string

Column returns the first element from the columns slice.

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 Snapshot added in v0.5.0

type Snapshot struct {
	Schema   string
	Package  string
	Schemas  []*load.Schema
	Features []string
}

Snapshot holds the information for storing the schema snapshot.

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.
}

Storage driver type for codegen.

func NewStorage

func NewStorage(s string) (*Storage, error)

NewStorage returns a 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.

func (*Storage) String

func (s *Storage) String() string

String implements the fmt.Stringer interface for template usage.

type Template added in v0.5.0

type Template struct {
	*template.Template
	FuncMap template.FuncMap
}

Template wraps the standard template.Template to provide additional functionality for ent extensions.

func MustParse added in v0.5.0

func MustParse(t *Template, err error) *Template

MustParse is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil.

func NewTemplate added in v0.5.0

func NewTemplate(name string) *Template

NewTemplate creates an empty template with the standard codegen functions.

func (*Template) AddParseTree added in v0.5.0

func (t *Template) AddParseTree(name string, tree *parse.Tree) (*Template, error)

AddParseTree adds the given parse tree to the template.

func (*Template) Funcs added in v0.5.0

func (t *Template) Funcs(funcMap template.FuncMap) *Template

Funcs merges the given funcMap to the template functions.

func (*Template) Parse added in v0.5.0

func (t *Template) Parse(text string) (*Template, error)

Parse parses text as a template body for t.

func (*Template) ParseDir added in v0.5.0

func (t *Template) ParseDir(path string) (*Template, error)

ParseDir walks on the given dir path and parses the given matches with aren't Go files.

func (*Template) ParseFiles added in v0.5.0

func (t *Template) ParseFiles(filenames ...string) (*Template, error)

ParseFiles parses a list of files as templates and associate them with t. Each file can be a standalone template.

func (*Template) ParseGlob added in v0.5.0

func (t *Template) ParseGlob(pattern string) (*Template, error)

ParseGlob parses the files that match the given pattern as templates and associate them with t.

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 map[string]interface{}
	// contains filtered or unexported fields
}

Type represents one node-type in the graph, its relations and the information it holds.

func NewType

func NewType(c *Config, schema *load.Schema) (*Type, error)

NewType creates a new type and its fields from the given schema.

func (*Type) AddIndex

func (t *Type) AddIndex(idx *load.Index) error

AddIndex adds a new index for the type. It fails if the schema index is invalid.

func (Type) CreateBulkName

func (t Type) CreateBulkName() string

CreateBulkName returns the struct name denoting the create-bulk-builder for this type.

func (Type) CreateName

func (t Type) CreateName() string

CreateName returns the struct name denoting the create-builder for this type.

func (Type) DeleteName

func (t Type) DeleteName() string

DeleteName returns the struct name denoting the delete-builder for this type.

func (Type) DeleteOneName

func (t Type) DeleteOneName() string

DeleteOneName returns the struct name denoting the delete-one-builder for this type.

func (Type) EntSQL added in v0.5.0

func (t Type) EntSQL() *entsql.Annotation

EntSQL returns the EntSQL annotation if exists.

func (Type) EnumFields

func (t Type) EnumFields() []*Field

EnumFields returns the types's enum fields.

func (Type) FKEdges

func (t Type) FKEdges() (edges []*Edge)

FKEdges returns all edges that reside on the type table as foreign-keys.

func (Type) FilterName added in v0.5.0

func (t Type) FilterName() string

FilterName returns the struct name denoting the filter-builder for this type.

func (Type) HasAssoc

func (t Type) HasAssoc(name string) (*Edge, bool)

HasAssoc returns true if this type has an assoc-edge (non-inverse) with the given name. faster than map access for most cases.

func (Type) HasDefault

func (t Type) HasDefault() bool

HasDefault reports if any of this type's fields has default value on creation.

func (Type) HasNumeric

func (t Type) HasNumeric() bool

HasNumeric reports if this type has a numeric field.

func (Type) HasOptional

func (t Type) HasOptional() bool

HasOptional reports if this type has an optional field.

func (Type) HasUpdateCheckers added in v0.4.3

func (t Type) HasUpdateCheckers() bool

HasUpdateCheckers reports if this type has any checkers to run on update(one).

func (Type) HasUpdateDefault

func (t Type) HasUpdateDefault() bool

HasUpdateDefault reports if any of this type's fields has default value on update.

func (Type) HasValidators

func (t Type) HasValidators() bool

HasValidators reports if any of the type's field has validators.

func (Type) HookPositions

func (t Type) HookPositions() []*load.Position

HookPositions returns the position information of hooks declared in the type schema.

func (Type) Label

func (t Type) Label() string

Label returns Gremlin label name of the node/type.

func (Type) MixedInFields

func (t Type) MixedInFields() []int

MixedInFields returns the indices of mixin holds runtime code.

func (Type) MixedInHooks

func (t Type) MixedInHooks() []int

MixedInHooks returns the indices of mixin with hooks.

func (Type) MixedInPolicies added in v0.5.0

func (t Type) MixedInPolicies() []int

MixedInPolicies returns the indices of mixin with policies.

func (Type) MutableFields

func (t Type) MutableFields() []*Field

MutableFields returns the types's mutable fields.

func (Type) MutationName

func (t Type) MutationName() string

MutationName returns the struct name of the mutation builder for this type.

func (Type) NumConstraint

func (t Type) NumConstraint() int

NumConstraint returns the type's constraint count. Used for slice allocation.

func (Type) NumHooks

func (t Type) NumHooks() int

NumHooks returns the number of hooks declared in the type schema.

func (Type) NumM2M

func (t Type) NumM2M() int

NumM2M returns the type's many-to-many edge count

func (Type) NumMixin

func (t Type) NumMixin() int

NumMixin returns the type's mixin count.

func (Type) NumPolicy added in v0.5.0

func (t Type) NumPolicy() int

NumPolicy returns the number of privacy-policy declared in the type schema.

func (Type) Package

func (t Type) Package() string

Package returns the package name of this node.

func (Type) PolicyPositions added in v0.5.0

func (t Type) PolicyPositions() []*load.Position

PolicyPositions returns the position information of privacy policy declared in the type schema.

func (Type) QueryName

func (t Type) QueryName() string

QueryName returns the struct name denoting the query-builder for this type.

func (Type) Receiver

func (t Type) Receiver() string

Receiver returns the receiver name of this node. It makes sure the receiver names doesn't conflict with import names.

func (Type) RelatedTypes

func (t Type) RelatedTypes() []*Type

RelatedTypes returns all the types (nodes) that are related (with edges) to this type.

func (Type) RuntimeMixin

func (t Type) RuntimeMixin() bool

RuntimeMixin returns schema mixin that needs to be loaded at runtime. For example, for default values, validators or hooks.

func (Type) SiblingImports

func (t Type) SiblingImports() []string

SiblingImports returns all sibling packages that are needed for the different builders.

func (Type) Table

func (t Type) Table() string

Table returns SQL table name of the node/type.

func (Type) TagTypes

func (t Type) TagTypes() []string

TagTypes returns all struct-tag types of the type fields.

func (Type) UpdateName

func (t Type) UpdateName() string

UpdateName returns the struct name denoting the update-builder for this type.

func (Type) UpdateOneName

func (t Type) UpdateOneName() string

UpdateOneName returns the struct name denoting the update-one-builder for this type.

type TypeTemplate

type TypeTemplate struct {
	Name           string             // template name.
	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.

Directories

Path Synopsis
Package internal Code generated by go-bindata.
Package internal Code generated by go-bindata.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL