gen

package
v0.0.0-...-854dc90 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

Package gen provides code generation for Velox ORM schemas.

This package is responsible for generating Go code from schema definitions, producing type-safe database access code, GraphQL schemas/resolvers, and gRPC proto definitions.

Architecture

The code generation pipeline follows this flow:

Schema Definition (schema/*.go)
        ↓
   velox.Schema interface + builders
        ↓
   Graph (internal representation)
        ↓
   DialectGenerator (database-specific code)
        ↓
   Generated code (ent/)

Key Types

The package provides several key types:

  • Graph: Holds all Type definitions with validation
  • Type: Represents an entity with fields, edges, indexes
  • Field: Field with type info, constraints, annotations
  • Edge: Relationship with type (O2O, O2M, M2M), foreign keys
  • Config: Global configuration for code generation

Interface Hierarchy

The generator interfaces follow the Interface Segregation Principle:

MinimalDialect (basic dialect support)
├── Name() string
├── EntityGenerator (8 methods for per-entity code)
│   ├── GenEntity, GenCreate, GenUpdate, GenDelete
│   └── GenQuery, GenMutation, GenPredicate, GenPackage
└── GraphGenerator (5 methods for graph-level code)
    └── GenClient, GenVelox, GenTx, GenRuntime, GenPredicatePackage

DialectGenerator (full interface, extends MinimalDialect)
├── FeatureGenerator (feature detection and generation)
└── OptionalFeatureGenerator (optional features like privacy, intercept)

Custom dialects can implement MinimalDialect for basic support, or DialectGenerator for full feature support.

Error Handling

The package uses structured error types for better error handling:

  • SchemaError: Schema definition errors
  • ConfigError: Configuration errors
  • EdgeError: Edge/relationship errors
  • GenerationError: Code generation errors
  • ValidationError: Validation errors

Example error handling:

graph, err := gen.NewGraph(config, schemas...)
if err != nil {
    if gen.IsEdgeError(err) {
        // Handle edge-specific error
    }
    return err
}

Configuration

Configuration is done via the functional options pattern:

// Recommended: schema/ for definitions, velox/ for generated code
config, err := gen.NewConfig(
    gen.WithTarget("./velox"),  // Generate to velox/ folder
)
compiler.Generate("./schema", config)

Additional options available:

config, err := gen.NewConfig(
    gen.WithTarget("./velox"),
    gen.WithFeatures(gen.FeaturePrivacy),     // Enable privacy feature
    gen.WithHeader("// Custom header"),       // Custom file header
)

Package is auto-inferred from go.mod. Override only if needed:

config, err := gen.NewConfig(
    gen.WithTarget("./velox"),
    gen.WithPackage("github.com/org/project/velox"),  // Override package
)

Jennifer Generator

Code generation uses the Jennifer library instead of templates for:

  • Auto-tracking imports (no goimports needed)
  • Streaming writes to disk (lower memory)
  • Compile-time type safety
  • Parallel generation with configurable workers

Usage

The recommended way to generate code is through the sql package:

import "github.com/syssam/velox/compiler/gen/sql"

err := sql.Generate(graph)

Or manually configure the generator:

import (
    "github.com/syssam/velox/compiler/gen"
    "github.com/syssam/velox/compiler/gen/sql"
)

generator := gen.NewJenniferGenerator(graph, outDir).
    WithDialect(sql.NewDialect(generator)).
    WithWorkers(4)
err := generator.Generate(ctx)

Code Organization

The package is organized into several files:

  • config.go: Config type methods and grouped configuration
  • dialect.go: Generator interface definitions (ISP-based)
  • errors.go: Structured error types
  • feature.go: Feature flags and definitions
  • generate.go: JenniferGenerator for code generation
  • graph.go: Graph type and schema processing
  • option.go: Functional option pattern for configuration
  • template.go: Template utilities
  • type.go: Type definition and methods
  • type_field.go: Field-related methods
  • type_edge.go: Edge-related methods
  • type_helpers.go: Helper functions and utilities

Generated Output

The generator produces the following structure:

{output}/
├── velox.go            // Base types, errors, interfaces
├── client.go           // Client struct with entity clients
├── tx.go               // Transaction support
├── runtime.go          // Runtime utilities
├── predicate/
│   └── predicate.go    // Predicate type definitions
├── {entity}.go         // Entity struct and client
├── {entity}_create.go  // Create builder
├── {entity}_update.go  // Update builder
├── {entity}_delete.go  // Delete builder
├── {entity}_query.go   // Query builder
└── {entity}/
    ├── {entity}.go     // Package constants (table, columns)
    └── where.go        // Predicate functions

Features

The generator supports optional features that can be enabled:

  • privacy: ORM-level authorization policies
  • intercept: Query interceptors for middleware
  • hook: Mutation lifecycle hooks
  • sql/schemaconfig: Schema configuration
  • sql/versioned-migration: Migration file generation
  • sql/globalid: Relay Global ID support

Package gen provides code generation for Velox schemas.

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

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidSchema indicates a schema definition error.
	ErrInvalidSchema = errors.New("velox: invalid schema")
	// ErrMissingConfig indicates a configuration error.
	ErrMissingConfig = errors.New("velox: missing configuration")
	// ErrInvalidEdge indicates an edge definition error.
	ErrInvalidEdge = errors.New("velox: invalid edge definition")
	// ErrGenerationFailed indicates a code generation failure.
	ErrGenerationFailed = errors.New("velox: code generation failed")
	// ErrValidationFailed indicates a validation failure.
	ErrValidationFailed = errors.New("velox: validation failed")
)

Sentinel errors for common failure cases.

View Source
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",
	}

	FeatureGlobalID = Feature{
		Name:        "sql/globalid",
		Stage:       Experimental,
		Default:     false,
		Description: "Ensures all nodes have a unique global identifier", GraphTemplates: []GraphTemplate{
			{
				Name:   "internal/globalid",
				Format: "internal/globalid.go",
			},
		},
		// contains filtered or unexported fields
	}

	// FeatureValidator enables ORM-level validator code generation.
	// When enabled, built-in validators (NotEmpty, MaxLen, Range, etc.) generate
	// validation code that runs before save operations.
	//
	// Example:
	//
	//	err := entc.Generate("./schema", &gen.Config{
	//	    Features: []gen.Feature{
	//	        gen.FeatureValidator,
	//	    },
	//	})
	//
	// Without this feature, use GraphQL/gRPC annotations for API-layer validation:
	//
	//	field.String("email").Annotations(
	//	    graphql.CreateInputValidate("required,email"),
	//	)
	FeatureValidator = Feature{
		Name:        "validator",
		Stage:       Stable,
		Default:     false,
		Description: "Enables ORM-level validator code generation for built-in validators (NotEmpty, MaxLen, Range, etc.)",
	}

	// FeatureEntPredicates generates Ent-compatible predicate functions.
	// By default, Velox uses generic predicates with a Where struct (compact, ~90% less code).
	// Enable this feature for Ent-style standalone predicate functions.
	//
	// Example usage:
	//
	//	// Default (generic predicates via Where struct):
	//	user.Where.Email.EQ("[email protected]")
	//	user.Where.Age.GT(18)
	//
	//	// With FeatureEntPredicates (Ent-compatible functions):
	//	user.EmailEQ("[email protected]")
	//	user.AgeGT(18)
	//
	// Use this feature when migrating from Ent or when you prefer the function-based API.
	FeatureEntPredicates = Feature{
		Name:        "sql/entpredicates",
		Stage:       Stable,
		Default:     false,
		Description: "Generates Ent-compatible predicate functions (EmailEQ, AgeGT, etc.)",
	}

	// FeatureAutoDefault automatically adds database DEFAULT values for ALL NOT NULL fields
	// (both Required and Optional) that don't have an explicit Default() set. This ensures
	// safe migrations on tables with existing data by using zero values (empty string for
	// strings, 0 for integers, false for booleans, etc.).
	//
	// This follows big tech best practices where DB DEFAULT is for migration safety,
	// while application-layer validation enforces "required" semantics.
	//
	// Without this feature:
	//   field.String("email").Unique()        // DB: NOT NULL, no DEFAULT
	//   field.String("nickname").Optional()   // DB: NOT NULL, no DEFAULT
	//
	// With this feature enabled:
	//   field.String("email").Unique()        // DB: NOT NULL DEFAULT ”
	//   field.String("nickname").Optional()   // DB: NOT NULL DEFAULT ”
	//
	// Note: Enum and JSON fields still require explicit Default() as they have no universal zero value.
	FeatureAutoDefault = Feature{
		Name:        "sql/autodefault",
		Stage:       Alpha,
		Default:     false,
		Description: "Automatically adds database DEFAULT values for all NOT NULL fields using zero values, ensuring safe migrations",
	}

	// AllFeatures holds a list of all feature-flags.
	AllFeatures = []Feature{
		FeaturePrivacy,
		FeatureIntercept,
		FeatureEntQL,
		FeatureNamedEdges,
		FeatureBidiEdgeRefs,
		FeatureSnapshot,
		FeatureSchemaConfig,
		FeatureLock,
		FeatureModifier,
		FeatureExecQuery,
		FeatureUpsert,
		FeatureVersionedMigration,
		FeatureGlobalID,
		FeatureValidator,
		FeatureEntPredicates,
		FeatureAutoDefault,
	}
)
View Source
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: "velox.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: "querylanguage.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",
		},
	}
)
View Source
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,
		"json":          jsonString,
		"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,
		"allZero":       allZero,
	}
)

Functions

func AddAcronym

func AddAcronym(word string)

AddAcronym adds initialism to the global ruleset.

func GenerateJennifer

func GenerateJennifer(g *Graph) error

GenerateJennifer is a convenience function to generate code using the Jennifer generator. It replaces the template-based generation for improved performance.

IMPORTANT: You must set a dialect before calling this function. Use the sql.Generate() helper from gen/sql package instead:

import "github.com/syssam/velox/compiler/gen/sql"
err := sql.Generate(graph)

Or manually:

import "github.com/syssam/velox/compiler/gen/sql"
gen := gen.NewJenniferGenerator(graph, outDir)
dialect := sql.NewDialect(gen)
gen.WithDialect(dialect).Generate(ctx)

func GenerateTemplates

func GenerateTemplates(g *Graph) error

GenerateTemplates is the convenience function to generate code using templates. It replaces the Jennifer-based generation for backward compatibility with templates.

func IncrementStartAnnotation

func IncrementStartAnnotation(g *Graph) error

IncrementStartAnnotation assigns a unique range to each node in the graph.

func IncrementStartsFilePath

func IncrementStartsFilePath(dir string) string

func IsConfigError

func IsConfigError(err error) bool

IsConfigError reports whether the error is a ConfigError.

func IsEdgeError

func IsEdgeError(err error) bool

IsEdgeError reports whether the error is an EdgeError.

func IsGenerationError

func IsGenerationError(err error) bool

IsGenerationError reports whether the error is a GenerationError.

func IsSchemaError

func IsSchemaError(err error) bool

IsSchemaError reports whether the error is a SchemaError.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether the error is a ValidationError.

func Pascal

func Pascal(s string) string

Pascal converts the given name into PascalCase. Exported for use by dialect packages.

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 ResolveIncrementStartsConflict

func ResolveIncrementStartsConflict(dir string) error

ResolveIncrementStartsConflict resolves git/mercurial conflicts by "accepting theirs".

func ToMap

func ToMap(a *sqlschema.Annotation) (map[string]any, error)

func ValidSchemaName

func ValidSchemaName(name string) error

ValidSchemaName will determine if a name is going to conflict with any pre-defined names or contains unsafe characters.

Types

type Annotations

type Annotations map[string]any

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 velox/schema.
	// For example, "<project>/velox/schema".
	Schema string

	// Target defines the filepath for the target directory that
	// holds the generated code. For example, "./project/velox".
	//
	// By default, 'velox generate ./velox/schema' uses './velox' as a
	// target directory.
	Target string

	// Package defines the Go package path of the target directory
	// mentioned above. For example, "github.com/org/project/velox".
	//
	// By default, for schema package named "<project>/velox/schema",
	// 'velox generate' uses "<project>/velox" 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 velox, 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

	// Generator is the code generator to use. If nil, defaults to the SQL
	// dialect generator. This allows for custom dialects or code generators.
	Generator Generator
}

The Config holds the global codegen configuration to be shared between all generated nodes.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a Config with default values applied.

func MustNewConfig

func MustNewConfig(opts ...Option) *Config

MustNewConfig creates a new Config with the given options. It panics if any option fails.

func NewConfig

func NewConfig(opts ...Option) (*Config, error)

NewConfig creates a new Config with the given options.

func (*Config) Apply

func (c *Config) Apply(opts ...Option) error

Apply applies options to the config. It returns the first error encountered.

func (*Config) ApplyAll

func (c *Config) ApplyAll(opts ...Option) error

ApplyAll applies options and collects all errors. Returns a joined error if any options failed.

func (*Config) FeatureEnabled

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

func (c *Config) HasFeature(name string) bool

HasFeature checks if the given feature is enabled by name.

func (*Config) ModuleInfo

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

ModuleInfo returns the velox module version.

func (*Config) Output

func (c *Config) Output() OutputConfig

Output returns the output configuration grouped together. This is a convenience method for accessing related settings.

func (*Config) SchemaOpts

func (c *Config) SchemaOpts() SchemaConfigGroup

SchemaOpts returns the schema configuration grouped together. This is a convenience method for accessing related settings.

type ConfigError

type ConfigError struct {
	Option  string
	Value   any
	Message string
}

ConfigError represents a configuration error.

func NewConfigError

func NewConfigError(option string, value any, message string) *ConfigError

NewConfigError creates a new ConfigError.

func (*ConfigError) Error

func (e *ConfigError) Error() string

Error implements the error interface.

func (*ConfigError) Is

func (e *ConfigError) Is(target error) bool

Is reports whether the target matches the sentinel error for ConfigError.

type Dependencies

type Dependencies []*Dependency

Dependencies wraps a list of dependencies as codegen annotation.

func (Dependencies) Merge

Merge implements the schema.Merger interface.

func (Dependencies) Name

func (Dependencies) Name() string

Name describes the annotation name.

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 DialectGenerator

type DialectGenerator interface {
	MinimalDialect
	FeatureGenerator
	OptionalFeatureGenerator
}

DialectGenerator defines the interface for dialect-specific code generation. Each database dialect (SQL, Gremlin, etc.) implements this interface to generate dialect-specific code for CRUD operations.

Architecture:

┌─────────────────────────────────────────────────────────────┐
│                    JenniferGenerator                        │
│  (Orchestration: parallel execution, file writing)          │
└─────────────────────────┬───────────────────────────────────┘
                          │ uses
                          ▼
┌─────────────────────────────────────────────────────────────┐
│                   DialectGenerator                          │
│  (Interface: defines what each dialect must implement)      │
└─────────────────────────┬───────────────────────────────────┘
                          │ implemented by
          ┌───────────────┼───────────────┐
          ▼               ▼               ▼
   ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
   │ SQLDialect  │ │GremlinDialect│ │ CustomDialect│
   │ (gen/sql)   │ │  (future)   │ │ (user-defined)│
   └─────────────┘ └─────────────┘ └─────────────┘

Methods return *jen.File containing the generated code. The main generator orchestrates calling these methods and writing the files to disk.

Usage:

import "github.com/syssam/velox/compiler/gen/sql"

generator := gen.NewJenniferGenerator(graph, outDir).
    WithDialect(sql.NewDialect(generator))

For custom dialects, you can implement MinimalDialect for basic support, or the full DialectGenerator for complete feature support.

type DialectOption

type DialectOption func(DialectGenerator)

DialectOption configures dialect-specific options.

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

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

func (e Edge) Comment() string

Comment returns the comment of the edge.

func (Edge) Constant

func (e Edge) Constant() string

Constant returns the constant name of the edge.

func (Edge) EagerLoadField

func (e Edge) EagerLoadField() string

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

func (Edge) EagerLoadNamedField

func (e Edge) EagerLoadNamedField() string

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

func (Edge) EntSQL

func (e Edge) EntSQL() *sqlschema.Annotation

EntSQL returns the EntSQL annotation if exists.

func (Edge) Field

func (e Edge) Field() *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

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.

func (Edge) HasFieldSetter

func (e Edge) HasFieldSetter() bool

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

func (e Edge) Index() (int, error)

Index returns the index of the edge in the schema. Used mainly to extract its position in the "loadedTypes" array.

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 label name of the edge (owner_edgename format).

func (Edge) LabelConstant

func (e Edge) LabelConstant() string

LabelConstant returns the constant name of the edge label. 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

func (e Edge) MutationAdd() string

MutationAdd returns the method name for adding edge ids.

func (Edge) MutationClear

func (e Edge) MutationClear() string

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

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 method conflicts with the mutation methods, add "Edge" the after the edge name.

func (Edge) MutationRemove

func (e Edge) MutationRemove() string

MutationRemove returns the method name for removing edge ids.

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 method conflicts with the mutation methods, suffix the method with "Edge".

func (Edge) MutationSet

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

func (e Edge) OrderCountName() (string, error)

OrderCountName returns the function/option name for ordering by the edge count.

func (Edge) OrderFieldName

func (e Edge) OrderFieldName() (string, error)

OrderFieldName returns the function/option name for ordering by edge field.

func (Edge) OrderTermsName

func (e Edge) OrderTermsName() (string, error)

OrderTermsName returns the function/option name for ordering by any term.

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

func (e Edge) StorageKey() (*edge.StorageKey, error)

StorageKey returns the storage-key defined on the schema if exists.

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. The value id Edge.Rel.Table, which is table that holds the relation/edge.

func (*Edge) TableSchema

func (e *Edge) TableSchema() (string, error)

TableSchema returns the schema name of where the type table resides (intentionally exported).

type EdgeError

type EdgeError struct {
	From    string
	To      string
	Edge    string
	Message string
	Cause   error
}

EdgeError represents an edge/relationship error.

func NewEdgeError

func NewEdgeError(from, to, edgeName, message string, cause error) *EdgeError

NewEdgeError creates a new EdgeError.

func (*EdgeError) Error

func (e *EdgeError) Error() string

Error implements the error interface.

func (*EdgeError) Is

func (e *EdgeError) Is(target error) bool

Is reports whether the target matches the sentinel error for EdgeError.

func (*EdgeError) Unwrap

func (e *EdgeError) Unwrap() error

Unwrap returns the underlying error.

type EntityGenerator

type EntityGenerator interface {
	// GenEntity generates the entity struct ({entity}.go)
	GenEntity(t *Type) *jen.File
	// GenCreate generates the create builder ({entity}_create.go)
	GenCreate(t *Type) *jen.File
	// GenUpdate generates the update builder ({entity}_update.go)
	GenUpdate(t *Type) *jen.File
	// GenDelete generates the delete builder ({entity}_delete.go)
	GenDelete(t *Type) *jen.File
	// GenQuery generates the query builder ({entity}_query.go)
	GenQuery(t *Type) *jen.File
	// GenMutation generates the mutation type ({entity}_mutation.go)
	GenMutation(t *Type) *jen.File
	// GenPredicate generates where predicates ({entity}/where.go)
	GenPredicate(t *Type) *jen.File
	// GenPackage generates entity package constants ({entity}/{entity}.go)
	GenPackage(t *Type) *jen.File
}

EntityGenerator generates per-entity code. Each method is called once per entity type in the schema.

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 FeatureGenerator

type FeatureGenerator interface {
	// SupportsFeature checks if the dialect supports a feature
	SupportsFeature(feature string) bool
	// GenFeature generates feature-specific code
	GenFeature(feature string) *jen.File
}

FeatureGenerator generates feature-specific code.

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

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

func (f Field) Comment() string

Comment returns the comment of the field,

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

func (f Field) DefaultFunc() bool

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() any

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

func (Field) DeprecationReason

func (f Field) DeprecationReason() string

DeprecationReason returns the deprecation reason of the field.

func (Field) Edge

func (f Field) Edge() (*Edge, error)

Edge returns the edge this field is point to.

func (Field) EntSQL

func (f Field) EntSQL() *sqlschema.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) EnumPkgPath

func (f Field) EnumPkgPath() string

EnumPkgPath returns the import path of the subpackage where the enum type is defined. For example, "github.com/project/velox/abtesting" for an ABTesting entity. Returns empty string if the field doesn't belong to a type.

func (Field) EnumTypeName

func (f Field) EnumTypeName() string

EnumTypeName returns the generated enum type name for fields without custom GoType. The format is {EntityName}{FieldStructField}, e.g., "ABTestingType" for ABTesting.Type field. This is used when generating code in the main ent package.

func (Field) EnumValues

func (f Field) EnumValues() []string

EnumValues returns the values of the enum field.

func (Field) FromValueFunc

func (f Field) FromValueFunc() (string, error)

FromValueFunc returns a path to the FromValue field (func) of the external ValueScanner.

func (Field) HasGoType

func (f Field) HasGoType() bool

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

func (Field) HasValueScanner

func (f Field) HasValueScanner() bool

HasValueScanner indicates if the field has (an external) ValueScanner.

func (Field) IsBool

func (f Field) IsBool() bool

IsBool returns true if the field is a bool field.

func (Field) IsBytes

func (f Field) IsBytes() bool

IsBytes returns true if the field is a bytes field.

func (Field) IsDeprecated

func (f Field) IsDeprecated() bool

IsDeprecated returns true if the field is deprecated.

func (Field) IsEdgeField

func (f Field) IsEdgeField() bool

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

func (f Field) IsInt64() bool

IsInt64 returns true if the field is an int64 field.

func (Field) IsJSON

func (f Field) IsJSON() bool

IsJSON returns true if the field is a JSON field.

func (Field) IsOther

func (f Field) IsOther() bool

IsOther returns true if the field is an Other 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) MutationAdd

func (f Field) MutationAdd() string

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

func (f Field) MutationAddAssignExpr(ident1, ident2 string) (string, error)

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

func (f Field) MutationAdded() string

MutationAdded returns the method name for getting the field value that was added to the field.

func (Field) MutationAppend

func (f Field) MutationAppend() string

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

func (f Field) MutationAppended() string

MutationAppended returns the method name for getting the field value that was added to the field.

func (Field) MutationClear

func (f Field) MutationClear() string

MutationClear returns the method name for clearing the field value.

func (Field) MutationCleared

func (f Field) MutationCleared() string

MutationCleared returns the method name for indicating if the field was cleared in the mutation.

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 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 method conflicts with the mutation methods, suffix the method with "Field".

func (Field) MutationSet

func (f Field) MutationSet() string

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

func (f Field) NewScanType() string

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

func (f Field) NillableValue() bool

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

func (f *Field) Ops() []Op

Ops returns all predicate operations of the field.

func (Field) OrderName

func (f Field) OrderName() string

OrderName returns the function/option name for ordering by this field.

func (Field) PK

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

PK is like Column, but for table primary key.

func (Field) RequiredFor

func (f Field) RequiredFor() (dialects []string)

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

func (f Field) ScanType() string

ScanType returns the Go type that is used for `rows.Scan`.

func (Field) ScanTypeField

func (f Field) ScanTypeField(rec string) string

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

func (Field) ScanValueFunc

func (f Field) ScanValueFunc() (string, error)

ScanValueFunc returns a path to the ScanValue field (func) of the external ValueScanner.

func (Field) Sensitive

func (f Field) Sensitive() bool

Sensitive returns true if the field is a sensitive field.

func (Field) SignedType

func (f Field) SignedType() (*field.TypeInfo, error)

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

func (f Field) StorageKey() string

StorageKey returns the storage name of the field (SQL column name).

func (Field) StructField

func (f Field) StructField() string

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

func (Field) SubpackageEnumTypeName

func (f Field) SubpackageEnumTypeName() string

SubpackageEnumTypeName returns the enum type name as used in the entity's subpackage. This is just the field struct name, e.g., "Type" for the type field. Used when generating code in subpackages.

func (Field) SupportsMutationAdd

func (f Field) SupportsMutationAdd() bool

SupportsMutationAdd reports if the field supports the mutation "Add(T) T" interface.

func (Field) SupportsMutationAppend

func (f Field) SupportsMutationAppend() bool

SupportsMutationAppend reports if the field supports the mutation append operation.

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.

func (Field) ValueFunc

func (f Field) ValueFunc() (string, error)

ValueFunc returns a path to the Value field (func) of the external ValueScanner.

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

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

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

Generate calls f(g).

type GenerationError

type GenerationError struct {
	Phase   string // "entity", "client", "predicate", etc.
	File    string
	Message string
	Cause   error
}

GenerationError represents a code generation error.

func NewGenerationError

func NewGenerationError(phase, file, message string, cause error) *GenerationError

NewGenerationError creates a new GenerationError.

func (*GenerationError) Error

func (e *GenerationError) Error() string

Error implements the error interface.

func (*GenerationError) Is

func (e *GenerationError) Is(target error) bool

Is reports whether the target matches the sentinel error for GenerationError.

func (*GenerationError) Unwrap

func (e *GenerationError) Unwrap() error

Unwrap returns the underlying error.

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 GeneratorHelper

type GeneratorHelper interface {
	// NewFile creates a new Jennifer file with the standard header comment.
	NewFile(pkg string) *jen.File

	// GoType returns the Jennifer code for a field's Go type.
	GoType(f *Field) jen.Code

	// BaseType returns the Jennifer code for a field's base type (without pointer).
	BaseType(f *Field) jen.Code

	// IDType returns the Jennifer code for the ID field type of a type.
	IDType(t *Type) jen.Code

	// ZeroValue returns the Jennifer code for a field's zero value.
	ZeroValue(f *Field) jen.Code

	// BaseZeroValue returns the Jennifer code for a field's base type zero value.
	BaseZeroValue(f *Field) jen.Code

	// StructTags returns the struct tags for a field.
	StructTags(f *Field) map[string]string

	// EdgeStructTags returns the struct tags for an edge field.
	EdgeStructTags(e *Edge) map[string]string

	// VeloxPkg returns the import path for the velox package.
	VeloxPkg() string

	// SQLPkg returns the import path for the dialect/sql package.
	SQLPkg() string

	// SQLGraphPkg returns the import path for the dialect/sql/sqlgraph package.
	SQLGraphPkg() string

	// FieldPkg returns the import path for the schema field package.
	FieldPkg() string

	// PredicatePkg returns the import path for the predicate package.
	PredicatePkg() string

	// EntityPkgPath returns the full import path for an entity's subpackage.
	EntityPkgPath(t *Type) string

	// EdgeRelType returns the sqlgraph relationship type constant name for an edge.
	EdgeRelType(e *Edge) string

	// FieldTypeConstant returns the field type constant name for a field.
	FieldTypeConstant(f *Field) string

	// PredicateType returns the predicate type for an entity (e.g., predicate.User).
	PredicateType(t *Type) jen.Code

	// EdgePredicateType returns the predicate type for an edge's target entity.
	EdgePredicateType(e *Edge) jen.Code

	// Graph returns the schema graph.
	Graph() *Graph

	// Pkg returns the output package name.
	Pkg() string

	// CheckEnumGenerated checks if an enum type has already been generated.
	// Returns true if it was already generated, false if this is the first time.
	CheckEnumGenerated(enumName string) bool

	// FeatureEnabled reports if the given feature name is enabled.
	FeatureEnabled(name string) bool

	// AnnotationExists checks if a global annotation with the given name exists.
	AnnotationExists(name string) bool

	// InternalPkg returns the import path for the internal package.
	InternalPkg() string
}

GeneratorHelper provides helper methods for dialect implementations. JenniferGenerator implements this interface, allowing dialect packages to use helper methods without importing the full generator.

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

func NewGraph(c *Config, schemas ...*load.Schema) (*Graph, 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) MutableNodes

func (g *Graph) MutableNodes() []*Type

MutableNodes returns the list of nodes that are mutable. i.e., not views.

func (*Graph) SchemaSnapshot

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

func (g *Graph) TableSchemas() ([]string, error)

TableSchemas returns all table schemas in ent/schema (intentionally exported).

func (*Graph) Tables

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

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

func (*Graph) Views

func (g *Graph) Views() (views []*schema.Table, err error)

Views returns all schema views

type GraphGenerator

type GraphGenerator interface {
	// GenClient generates the client (client.go)
	GenClient() *jen.File
	// GenVelox generates base types, errors, interfaces (velox.go)
	GenVelox() *jen.File
	// GenTx generates transaction support (tx.go)
	GenTx() *jen.File
	// GenRuntime generates runtime utilities (runtime.go)
	GenRuntime() *jen.File
	// GenPredicatePackage generates the predicate package (predicate/predicate.go)
	GenPredicatePackage() *jen.File
}

GraphGenerator generates graph-level code. Each method is called once per generation run.

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

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 IncrementStarts

type IncrementStarts map[string]int

IncrementStarts holds the autoincrement start value for each type.

func (IncrementStarts) Name

func (IncrementStarts) Name() string

Name implements Annotation interface.

func (IncrementStarts) WriteToDisk

func (i IncrementStarts) WriteToDisk(target string) error

WriteToDisk writes the increment starts to the disk.

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 JenniferGenerator

type JenniferGenerator struct {
	// contains filtered or unexported fields
}

JenniferGenerator generates code using Jennifer instead of templates. This provides better performance by: - Auto-tracking imports (no goimports needed) - Streaming writes to disk (lower memory) - Compile-time type safety

func NewJenniferGenerator

func NewJenniferGenerator(g *Graph, outDir string) *JenniferGenerator

NewJenniferGenerator creates a new Jennifer-based generator. You must call WithDialect() to set a dialect before calling Generate().

Example:

import "github.com/syssam/velox/compiler/gen/sql"

gen := gen.NewJenniferGenerator(graph, outDir)
dialect := sql.NewDialect(gen)
gen.WithDialect(dialect)
gen.Generate(ctx)

func (*JenniferGenerator) AnnotationExists

func (g *JenniferGenerator) AnnotationExists(name string) bool

AnnotationExists checks if a global annotation with the given name exists.

func (*JenniferGenerator) BaseType

func (g *JenniferGenerator) BaseType(f *Field) jen.Code

BaseType returns the Jennifer code for a field's base type (without pointer).

func (*JenniferGenerator) BaseZeroValue

func (g *JenniferGenerator) BaseZeroValue(f *Field) jen.Code

BaseZeroValue returns the Jennifer code for a field's base type zero value.

func (*JenniferGenerator) CheckEnumGenerated

func (g *JenniferGenerator) CheckEnumGenerated(enumName string) bool

CheckEnumGenerated checks if an enum type has already been generated. Returns true if it was already generated, false if this is the first time. This method is thread-safe.

func (*JenniferGenerator) EdgePredicateType

func (g *JenniferGenerator) EdgePredicateType(e *Edge) jen.Code

EdgePredicateType returns the predicate type for an edge's target entity.

func (*JenniferGenerator) EdgeRelType

func (g *JenniferGenerator) EdgeRelType(e *Edge) string

EdgeRelType returns the sqlgraph relationship type constant name for an edge.

func (*JenniferGenerator) EdgeStructTags

func (g *JenniferGenerator) EdgeStructTags(e *Edge) map[string]string

EdgeStructTags returns the struct tags for an edge field.

func (*JenniferGenerator) EntityPkgPath

func (g *JenniferGenerator) EntityPkgPath(t *Type) string

EntityPkgPath returns the full import path for an entity's subpackage.

func (*JenniferGenerator) FeatureEnabled

func (g *JenniferGenerator) FeatureEnabled(name string) bool

FeatureEnabled reports if the given feature name is enabled.

func (*JenniferGenerator) FieldPkg

func (g *JenniferGenerator) FieldPkg() string

FieldPkg returns the import path for the schema field package.

func (*JenniferGenerator) FieldTypeConstant

func (g *JenniferGenerator) FieldTypeConstant(f *Field) string

FieldTypeConstant returns the field type constant name for a field.

func (*JenniferGenerator) Generate

func (g *JenniferGenerator) Generate(ctx context.Context) error

Generate generates all code with parallel execution and streaming writes. It uses the configured dialect generator for database-specific code. Returns an error if no dialect has been set via WithDialect().

func (*JenniferGenerator) GoType

func (g *JenniferGenerator) GoType(f *Field) jen.Code

GoType returns the Jennifer code for a field's Go type.

func (*JenniferGenerator) Graph

func (g *JenniferGenerator) Graph() *Graph

Graph returns the schema graph.

func (*JenniferGenerator) IDType

func (g *JenniferGenerator) IDType(t *Type) jen.Code

IDType returns the Jennifer code for the ID field type of a type.

func (*JenniferGenerator) InternalPkg

func (g *JenniferGenerator) InternalPkg() string

InternalPkg returns the import path for the internal package.

func (*JenniferGenerator) NewFile

func (g *JenniferGenerator) NewFile(pkg string) *jen.File

NewFile creates a new Jennifer file with the standard header comment.

func (*JenniferGenerator) Pkg

func (g *JenniferGenerator) Pkg() string

Pkg returns the output package name.

func (*JenniferGenerator) PredicatePkg

func (g *JenniferGenerator) PredicatePkg() string

PredicatePkg returns the import path for the predicate package.

func (*JenniferGenerator) PredicateType

func (g *JenniferGenerator) PredicateType(t *Type) jen.Code

PredicateType returns the predicate type for an entity (e.g., predicate.User).

func (*JenniferGenerator) SQLGraphPkg

func (g *JenniferGenerator) SQLGraphPkg() string

SQLGraphPkg returns the import path for the dialect/sql/sqlgraph package.

func (*JenniferGenerator) SQLPkg

func (g *JenniferGenerator) SQLPkg() string

SQLPkg returns the import path for the dialect/sql package.

func (*JenniferGenerator) StructTags

func (g *JenniferGenerator) StructTags(f *Field) map[string]string

StructTags returns the struct tags for a field.

func (*JenniferGenerator) VeloxPkg

func (g *JenniferGenerator) VeloxPkg() string

VeloxPkg returns the import path for the velox package.

func (*JenniferGenerator) WithDialect

WithDialect sets a custom dialect generator. This allows using different database dialects (e.g., Gremlin). The dialect must implement MinimalDialect at minimum. Additional capabilities are detected via FeatureGenerator and OptionalFeatureGenerator.

func (*JenniferGenerator) WithFullDialect

func (g *JenniferGenerator) WithFullDialect(d DialectGenerator) *JenniferGenerator

WithFullDialect sets a full DialectGenerator. This is a convenience method for dialects that implement all interfaces. Deprecated: Use WithDialect instead, which auto-detects capabilities.

func (*JenniferGenerator) WithPackage

func (g *JenniferGenerator) WithPackage(pkg string) *JenniferGenerator

WithPackage sets the output package name.

func (*JenniferGenerator) WithWorkers

func (g *JenniferGenerator) WithWorkers(n int) *JenniferGenerator

WithWorkers sets the number of parallel workers.

func (*JenniferGenerator) ZeroValue

func (g *JenniferGenerator) ZeroValue(f *Field) jen.Code

ZeroValue returns the Jennifer code for a field's zero value.

type MigrateGenerator

type MigrateGenerator interface {
	// GenMigrate generates the migrate package files.
	// Returns [schema.go, migrate.go] for the migrate package.
	GenMigrate() []*jen.File
}

MigrateGenerator generates the migrate package for auto-migration support. This is optional - dialects that support it will generate migrate/schema.go and migrate/migrate.go files.

type MinimalDialect

type MinimalDialect interface {
	// Name returns the dialect name (e.g., "sql", "gremlin")
	Name() string
	EntityGenerator
	GraphGenerator
}

MinimalDialect requires only entity and graph generation. This is the minimum interface a dialect must implement.

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.

func (Op) Name

func (o Op) Name() string

Name returns the string representation of an operator.

func (Op) Niladic

func (o Op) Niladic() bool

Niladic reports if the operator is niladic (takes no arguments).

func (Op) Variadic

func (o Op) Variadic() bool

Variadic reports if the operator is a variadic function (takes a varying number of arguments).

type Option

type Option func(*Config) error

Option configures code generation.

func WithAnnotations

func WithAnnotations(annotations Annotations) Option

WithAnnotations sets global annotations. Annotations are accessible from all templates.

func WithBuildFlags

func WithBuildFlags(flags ...string) Option

WithBuildFlags sets custom build flags for loading schema packages.

func WithFeatures

func WithFeatures(features ...Feature) Option

WithFeatures enables specific features. Features control optional code generation capabilities.

func WithGenerator

func WithGenerator(g Generator) Option

WithGenerator sets a custom code generator. This allows using custom dialects or completely custom code generation. If not set, defaults to the SQL dialect generator.

func WithHeader

func WithHeader(header string) Option

WithHeader sets the file header comment. The header is added at the top of each generated file.

func WithHooks

func WithHooks(hooks ...Hook) Option

WithHooks adds generation hooks. Hooks are called before/after code generation.

func WithIDType

func WithIDType(t string) Option

WithIDType sets the default ID field type. Supported types: "int", "int64", "uint64", "string", "uuid".

func WithIDTypeInfo

func WithIDTypeInfo(info *field.TypeInfo) Option

WithIDTypeInfo sets the default ID field type using a TypeInfo struct. This allows for more fine-grained control over the ID type configuration.

func WithPackage

func WithPackage(pkg string) Option

WithPackage sets the output package import path. For example: "github.com/org/project/velox".

func WithSchema

func WithSchema(schema string) Option

WithSchema sets the schema package import path. For example: "<project>/velox/schema".

func WithStorage

func WithStorage(storage *Storage) Option

WithStorage sets the storage configuration. The storage configuration controls database dialect and schema migration.

func WithStorageDriver

func WithStorageDriver(driver string) Option

WithStorageDriver sets the database driver type by name. This is a convenience function that creates a Storage configuration. Supported drivers: "sqlite", "mysql", "postgres".

func WithTarget

func WithTarget(dir string) Option

WithTarget sets the output directory. The directory where generated code will be written.

func WithTemplates

func WithTemplates(templates ...*Template) Option

WithTemplates adds custom templates for code generation. Templates allow extending or overriding default code generation.

type OptionalFeatureGenerator

type OptionalFeatureGenerator interface {
	// GenSchemaConfig generates internal/schemaconfig.go
	GenSchemaConfig() *jen.File
	// GenIntercept generates intercept/intercept.go
	GenIntercept() *jen.File
	// GenPrivacy generates privacy/privacy.go
	GenPrivacy() *jen.File
	// GenSnapshot generates internal/schema.go
	GenSnapshot() *jen.File
	// GenVersionedMigration generates migrate/migrate.go
	GenVersionedMigration() *jen.File
	// GenGlobalID generates internal/globalid.go
	GenGlobalID() *jen.File
	// GenEntQL generates querylanguage.go
	GenEntQL() *jen.File
}

OptionalFeatureGenerator provides optional feature generation. Dialects may implement some or all of these methods.

type OutputConfig

type OutputConfig struct {
	// Target defines the filepath for the target directory that
	// holds the generated code. For example, "./project/velox".
	Target string

	// Package defines the Go package path of the target directory.
	// For example, "github.com/org/project/velox".
	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 velox, DO NOT EDIT.'.
	Header string
}

OutputConfig groups output-related settings.

type PrivacyFilterGenerator

type PrivacyFilterGenerator interface {
	// GenFilter generates the filter file ({entity}_filter.go) for privacy filtering.
	// Returns nil if the dialect doesn't support filter generation.
	GenFilter(t *Type) *jen.File
}

PrivacyFilterGenerator generates per-entity filter files for privacy feature. This is optional - dialects that support privacy filtering implement this interface.

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

func (Relation) Column

func (r Relation) Column() string

Column returns the first element from the columns slice.

type SchemaConfigGroup

type SchemaConfigGroup struct {
	// Schema holds the Go package path for the user velox/schema.
	// For example, "<project>/velox/schema".
	Schema string

	// IDType specifies the type of the id field in the codegen.
	// The supported types are string and int, which is also the default.
	IDType *field.TypeInfo

	// Storage configuration for the codegen. Defaults to sql.
	Storage *Storage
}

SchemaConfigGroup groups schema-related settings. Named SchemaConfigGroup to avoid conflict with the Schema field.

type SchemaError

type SchemaError struct {
	Type    string // Entity type name
	Field   string // Field name (if applicable)
	Message string
	Cause   error
}

SchemaError represents a schema definition error.

func NewSchemaError

func NewSchemaError(typeName, fieldName, message string, cause error) *SchemaError

NewSchemaError creates a new SchemaError.

func (*SchemaError) Error

func (e *SchemaError) Error() string

Error implements the error interface.

func (*SchemaError) Is

func (e *SchemaError) Is(target error) bool

Is reports whether the target matches the sentinel error for SchemaError.

func (*SchemaError) Unwrap

func (e *SchemaError) Unwrap() error

Unwrap returns the underlying error.

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

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.
	Init       func(*Graph) error // optional init function.
}

Storage driver type for codegen.

func NewStorage

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

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.

func (*Storage) String

func (s *Storage) String() string

String implements the fmt.Stringer interface for template usage.

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

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

func NewTemplate(name string) *Template

NewTemplate creates an empty template with the standard codegen functions.

func (*Template) AddParseTree

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

AddParseTree adds the given parse tree to the template.

func (*Template) Funcs

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

Funcs merges the given funcMap with the template functions.

func (*Template) Parse

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

Parse parses text as a template body for t.

func (*Template) ParseDir

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

func (t *Template) ParseFS(fsys fs.FS, patterns ...string) (*Template, error)

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

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

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

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

func (*Template) SkipIf

func (t *Template) SkipIf(cond func(*Graph) bool) *Template

SkipIf allows registering a function to determine if the template needs to be skipped or not.

type TemplateWriter

type TemplateWriter struct {
	// contains filtered or unexported fields
}

TemplateWriter generates code using templates with parallel execution and optimized formatting (using go/format library instead of CLI).

func NewTemplateWriter

func NewTemplateWriter(g *Graph, tmpl *Template, outDir string) *TemplateWriter

NewTemplateWriter creates a new template-based writer.

func (*TemplateWriter) GenerateAll

func (w *TemplateWriter) GenerateAll(ctx context.Context) error

GenerateAll generates all files using templates in parallel.

func (*TemplateWriter) GenerateGraph

func (w *TemplateWriter) GenerateGraph(ctx context.Context) error

GenerateGraph generates all graph-level files.

func (*TemplateWriter) GenerateType

func (w *TemplateWriter) GenerateType(ctx context.Context, t *Type) error

GenerateType generates all files for a single type.

func (*TemplateWriter) Metrics

func (w *TemplateWriter) Metrics() *WriterMetrics

Metrics returns the generation metrics.

func (*TemplateWriter) WithWorkers

func (w *TemplateWriter) WithWorkers(n int) *TemplateWriter

WithWorkers sets the number of parallel workers.

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

func (t Type) ClientName() string

ClientName returns the struct name denoting the client of this type.

func (Type) CreateBulReceiver

func (t Type) CreateBulReceiver() string

CreateBulReceiver returns the receiver name of the create-bulk-builder for this type. Matches Ent's convention of using "_c" for create-bulk (same as CreateReceiver).

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

func (t Type) CreateReceiver() string

CreateReceiver returns the receiver name of the create-builder for this type. Matches Ent's convention of using "_c" for all create builders.

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

func (t Type) DeleteOneReceiver() string

DeleteOneReceiver returns the receiver name of the delete-one-builder for this type. Matches Ent's convention of using "_d" for delete-one (same as DeleteReceiver).

func (Type) DeleteReceiver

func (t Type) DeleteReceiver() string

DeleteReceiver returns the receiver name of the delete-builder for this type. Matches Ent's convention of using "_d" for all delete builders.

func (Type) DeprecatedFields

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

DeprecatedFields returns all deprecated fields of the type.

func (Type) EdgesWithID

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

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() *sqlschema.Annotation

EntSQL returns the EntSQL annotation if exists.

func (Type) EnumFields

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

EnumFields returns the enum fields of the schema, if any.

func (Type) FKEdges

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

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

func (Type) FieldBy

func (t Type) FieldBy(fn func(*Field) bool) (*Field, bool)

FieldBy returns the first field that the given function returns true on it.

func (Type) FilterName

func (t Type) FilterName() string

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

func (Type) GroupReceiver

func (t Type) GroupReceiver() string

GroupReceiver returns the receiver name of the group-by builder for this type. Matches Ent's convention of using "_g" for all group-by builders.

func (Type) HasAssoc

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

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

func (t Type) HasCompositeID() bool

HasCompositeID indicates if the type has a composite ID field.

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

func (t Type) HasOneFieldID() bool

HasOneFieldID indicates if the type has an ID with one field (not composite).

func (Type) HasOptional

func (t Type) HasOptional() bool

HasOptional reports if this type has an optional field.

func (Type) HasUpdateCheckers

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

func (t Type) HasValueScanner() bool

HasValueScanner reports if any of the fields has (an external) ValueScanner.

func (Type) HookPositions

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

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

func (Type) ImmutableFields

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

ImmutableFields returns all type fields that are immutable (for update).

func (Type) InterceptorPositions

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

InterceptorPositions returns the position information of interceptors declared in the type schema.

func (Type) IsEdgeSchema

func (t Type) IsEdgeSchema() bool

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

func (t Type) IsView() bool

IsView indicates if the type (schema) is a view.

func (Type) Label

func (t Type) Label() string

Label returns the label name of the node/type (snake_case).

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

func (t Type) MixedInInterceptors() []int

MixedInInterceptors returns the indices of mixin with interceptors.

func (Type) MixedInPolicies

func (t Type) MixedInPolicies() []int

MixedInPolicies returns the indices of mixin with policies.

func (Type) MutableFields

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

MutableFields returns all type fields that are mutable (on update).

func (Type) MutationFields

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

MutationFields returns all the fields that are available on the typed-mutation.

func (Type) MutationName

func (t Type) MutationName() string

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

func (Type) MutationOptionName

func (t Type) MutationOptionName() string

MutationOptionName returns the name of the mutation option type. Uses lowercase prefix like Ent (e.g., "abtesteventOption") since it's internal.

func (Type) NeedsDefaults

func (t Type) NeedsDefaults() bool

NeedsDefaults reports if this type needs a defaults() method. Returns true if any field needs a default value set: - Fields with explicit Default() - Optional fields (without Nillable) with standard Go types or custom types (TypeOther) Note: TypeEnum requires explicit Default() and won't use zero value.

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

func (t Type) NumInterceptors() int

NumInterceptors returns the number of interceptors 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

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

func (t Type) PackageAlias() string

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

func (t Type) PackageDir() string

PackageDir returns the name of the package directory.

func (Type) PolicyPositions

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

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

func (Type) Pos

func (t Type) Pos() string

Pos returns the filename:line position information of this type in the schema.

func (Type) QueryName

func (t Type) QueryName() string

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

func (Type) QueryReceiver

func (t Type) QueryReceiver() string

QueryReceiver returns the receiver name of the query-builder for this type. Matches Ent's convention of using "_q" for all query builders.

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

func (t Type) SelectReceiver() string

SelectReceiver returns the receiver name of the selector builder for this type. Matches Ent's convention of using "_s" for all select builders.

func (Type) SiblingImports

func (t Type) SiblingImports() []struct{ Alias, Path 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) TableSchema

func (t *Type) TableSchema() (string, error)

TableSchema returns the schema name of where the type table resides (intentionally exported).

func (Type) TagTypes

func (t Type) TagTypes() []string

TagTypes returns all struct-tag types of the type fields. The result is sorted for deterministic output.

func (Type) TypeName

func (t Type) TypeName() string

TypeName returns the constant name of the type defined in mutation.go.

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

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.

func (Type) UpdateOneReceiver

func (t Type) UpdateOneReceiver() string

UpdateOneReceiver returns the receiver name of the update-one-builder for this type. Matches Ent's convention of using "_u" for all update-one builders (same as UpdateReceiver).

func (Type) UpdateReceiver

func (t Type) UpdateReceiver() string

UpdateReceiver returns the receiver name of the update-builder for this type. Matches Ent's convention of using "_u" for all update builders.

func (Type) ValueName

func (t Type) ValueName() string

ValueName returns the name of the value method 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.

type ValidationError

type ValidationError struct {
	Type    string
	Field   string
	Value   any
	Message string
	Cause   error
}

ValidationError represents a validation error.

func NewValidationError

func NewValidationError(typeName, field string, value any, message string) *ValidationError

NewValidationError creates a new ValidationError.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is reports whether the target matches the sentinel error for ValidationError.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying error.

type WriterMetrics

type WriterMetrics struct {
	FilesGenerated int
	TotalBytes     int64
	TemplateTime   int64 // nanoseconds
	FormatTime     int64 // nanoseconds
	WriteTime      int64 // nanoseconds
}

WriterMetrics tracks generation performance

Directories

Path Synopsis
cmd
testgen command
testgen is a simple test program to demonstrate the Jennifer-based code generator.
testgen is a simple test program to demonstrate the Jennifer-based code generator.
Package sql provides SQL dialect code generation for the Jennifer generator.
Package sql provides SQL dialect code generation for the Jennifer generator.

Jump to

Keyboard shortcuts

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