gotype

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Overview

Package gotype provides high-level TypeDB data mapping and CRUD operations.

Package gotype provides reflection-based TypeDB data mapping.

Package gotype defines various error types for ORM operations and schema management.

Package gotype provides utilities for formatting Go values into TypeQL syntax.

Package gotype provides mechanisms for hydrating Go structs from TypeDB results.

Package gotype provides automated schema migration capabilities.

Package gotype defines discrete migration operations.

Package gotype handles the persistence and tracking of schema migrations.

Package gotype provides reflection-based mapping between Go types and TypeDB models.

Package gotype provides a fluent query builder for TypeDB.

Package gotype provides a central registry for TypeDB model metadata.

Package gotype provides reflection-based TypeDB data mapping.

Package gotype provides utilities for generating TypeQL schema definitions from Go models.

Package gotype provides a sequential, file-based migration runner for TypeDB.

Package gotype provides state tracking for sequential migrations.

Package gotype provides a high-level, struct-tag based ORM layer for TypeDB. It maps Go structs to TypeDB entities and relations, providing generic CRUD operations and automatic query generation.

Package gotype defines query generation strategies for different TypeDB model kinds.

Package gotype provides parsing and representation of 'typedb' struct tags.

Index

Constants

View Source
const MaxHydrationDepth = 10

MaxHydrationDepth is the maximum nesting depth for recursive role player hydration. This prevents infinite loops when the database graph contains cycles.

Variables

View Source
var (
	// ErrPoolClosed is returned when attempting to get a connection from a closed pool.
	ErrPoolClosed = errors.New("connection pool is closed")
	// ErrPoolTimeout is returned when waiting for a connection times out.
	ErrPoolTimeout = errors.New("timeout waiting for available connection")
)
View Source
var TypeQLReservedWords = map[string]bool{

	"define": true, "undefine": true, "redefine": true,

	"match": true, "fetch": true, "insert": true, "delete": true, "update": true, "put": true,

	"select": true, "require": true, "sort": true, "limit": true, "offset": true, "reduce": true,

	"with": true,

	"or": true, "not": true, "try": true,

	"entity": true, "relation": true, "attribute": true, "struct": true, "fun": true,

	"sub": true, "relates": true, "plays": true, "value": true, "owns": true, "alias": true,

	"isa": true, "links": true, "has": true, "is": true, "let": true, "contains": true, "like": true,

	"label": true, "iid": true,

	"card": true, "cascade": true, "independent": true, "abstract": true,
	"key": true, "subkey": true, "unique": true, "values": true,
	"range": true, "regex": true, "distinct": true,

	"check": true, "first": true, "count": true, "max": true, "min": true,
	"mean": true, "median": true, "std": true, "sum": true, "list": true,

	"boolean": true, "integer": true, "double": true, "decimal": true,
	"datetime-tz": true, "datetime_tz": true, "datetime": true,
	"date": true, "duration": true, "string": true,

	"round": true, "ceil": true, "floor": true, "abs": true, "length": true,

	"true": true, "false": true,

	"asc": true, "desc": true, "return": true, "of": true,
	"from": true, "in": true, "as": true,
}

TypeQLReservedWords is the set of TypeQL reserved keywords that cannot be used as type names, attribute names, or role names.

Functions

func ArithmeticExpr added in v1.4.0

func ArithmeticExpr(varName, leftAttr, op, rightAttr string) string

ArithmeticExpr builds a TypeQL arithmetic expression string from two attribute references and an operator. Useful with Computed filter.

func BuiltinFuncExpr added in v1.4.0

func BuiltinFuncExpr(funcName string, args ...string) string

BuiltinFuncExpr builds a TypeQL function call expression string. Useful with Computed filter.

func ClearRegistry

func ClearRegistry()

ClearRegistry resets the global registry, removing all registered models. This is primarily used for testing purposes.

func EnsureDatabase

func EnsureDatabase(ctx context.Context, conn Conn, name string) (bool, error)

EnsureDatabase checks whether a database exists and creates it if not. Returns true if the database was newly created, false if it already existed.

func FormatValue

func FormatValue(value any) string

FormatValue converts a Go value into its TypeQL literal string representation. It handles basic types, pointers, and time.Time, ensuring correct escaping for use in TypeQL queries.

This function delegates to ast.FormatGoValue for the actual formatting logic.

func FromDict

func FromDict[T any](data map[string]any) (*T, error)

FromDict creates a new model instance from a map[string]any. Keys are TypeDB attribute names. This is the inverse of ToDict.

func GenerateSchema

func GenerateSchema() string

GenerateSchema produces a complete TypeQL `define` query string for all models currently registered in the global registry.

func GenerateSchemaFor

func GenerateSchemaFor(info *ModelInfo) string

GenerateSchemaFor produces a TypeQL `define` query string specifically for the provided ModelInfo, including its required attribute declarations.

func HashStatements

func HashStatements(stmts []string) string

HashStatements generates a SHA-256 hash for a slice of migration statements to uniquely identify a set of schema changes.

func Hydrate

func Hydrate(target any, data map[string]any) error

Hydrate populates the fields of a target struct pointer with data from a map of TypeDB attribute names to values. The struct type must be registered.

func HydrateAny

func HydrateAny(data map[string]any) (any, error)

HydrateAny creates and hydrates an instance of the concrete type identified by the "_type" field in data. This enables true polymorphic hydration where the returned value's concrete type matches the TypeDB type label. Returns the hydrated instance as any (actual type is a pointer to the concrete struct).

func HydrateNew

func HydrateNew[T any](data map[string]any) (*T, error)

HydrateNew is a convenience function that creates a new instance of type T, hydrates it with the provided data, and returns a pointer to it.

func IntrospectSchemaFromString

func IntrospectSchemaFromString(schemaStr string) (*tqlgen.ParsedSchema, error)

IntrospectSchemaFromString parses a TypeQL schema string into a ParsedSchema structure.

func IsReservedWord

func IsReservedWord(name string) bool

IsReservedWord returns true if the given name is a TypeQL reserved keyword. The check is case-insensitive.

func MigrateFromEmpty

func MigrateFromEmpty(ctx context.Context, db *Database) error

MigrateFromEmpty applies the complete schema defined by registered Go models to an empty database.

func MigrationChecksum added in v1.4.0

func MigrationChecksum(m SequentialMigration) string

MigrationChecksum computes a SHA256 checksum for a migration's statements.

func MustRegister

func MustRegister[T any]()

MustRegister is a helper that calls Register and panics if an error occurs. It is intended for use during application initialization.

func Register

func Register[T any]() error

Register adds a Go struct type to the global registry as a TypeDB model. The type T must embed either BaseEntity or BaseRelation.

func RollbackSequentialMigration added in v1.1.0

func RollbackSequentialMigration(ctx context.Context, db *Database, migrations []SequentialMigration, steps int) ([]string, error)

RollbackSequentialMigration rolls back the last N applied migrations in reverse order. Returns the names of rolled-back migrations.

func RunSequentialMigrations added in v1.1.0

func RunSequentialMigrations(ctx context.Context, db *Database, migrations []SequentialMigration, opts ...SeqMigrationOption) ([]string, error)

RunSequentialMigrations validates, sorts, and applies pending migrations. Returns the names of migrations that were applied (or would be applied in dry-run mode).

func StampSequentialMigrations added in v1.1.0

func StampSequentialMigrations(ctx context.Context, db *Database, migrations []SequentialMigration, opts ...SeqMigrationOption) ([]string, error)

StampSequentialMigrations marks the specified migrations as applied without executing their Up functions. Migrations that are already applied are skipped. Returns the names of newly stamped migrations.

This is useful when a database's schema was applied in bulk (e.g., via ExecuteSchema) and the migration records need to catch up to reflect the current state.

Supports WithSeqDryRun (report without stamping), WithSeqTarget (stamp up to a named migration), and WithSeqLogger (progress callback).

func ToDict

func ToDict[T any](instance *T) (map[string]any, error)

ToDict converts a registered model instance to a map[string]any using TypeDB attribute names as keys. Includes "_iid" if set.

func ToInsertQuery

func ToInsertQuery[T any](instance *T) (string, error)

ToInsertQuery generates a TypeQL insert query string for the given instance.

func ToMatchQuery

func ToMatchQuery[T any](instance *T) (string, error)

ToMatchQuery generates a TypeQL match clause for the given instance (by key fields).

func ValidateIdentifier added in v1.4.0

func ValidateIdentifier(name, context string) error

ValidateIdentifier checks that a name is a valid TypeQL identifier. Valid identifiers start with a letter or underscore and continue with letters, digits, hyphens, or underscores. Returns nil if valid, or an error describing the problem.

Types

type AddAttribute

type AddAttribute struct {
	Name      string
	ValueType string
}

AddAttribute represents the creation of a new attribute type in the schema.

func (AddAttribute) IsDestructive

func (op AddAttribute) IsDestructive() bool

func (AddAttribute) IsReversible

func (op AddAttribute) IsReversible() bool

func (AddAttribute) RollbackTypeQL

func (op AddAttribute) RollbackTypeQL() string

func (AddAttribute) ToTypeQL

func (op AddAttribute) ToTypeQL() string

type AddEntity

type AddEntity struct {
	Name     string
	Parent   string
	Abstract bool
	TypeQL   string // The full define statement for the entity.
}

AddEntity represents the creation of a new entity type in the schema.

func (AddEntity) IsDestructive

func (op AddEntity) IsDestructive() bool

func (AddEntity) IsReversible

func (op AddEntity) IsReversible() bool

func (AddEntity) RollbackTypeQL

func (op AddEntity) RollbackTypeQL() string

func (AddEntity) ToTypeQL

func (op AddEntity) ToTypeQL() string

type AddOwnership

type AddOwnership struct {
	Owner     string
	Attribute string
	Annots    string
}

AddOwnership represents the assignment of an attribute ownership to a type.

func (AddOwnership) IsDestructive

func (op AddOwnership) IsDestructive() bool

func (AddOwnership) IsReversible

func (op AddOwnership) IsReversible() bool

func (AddOwnership) RollbackTypeQL

func (op AddOwnership) RollbackTypeQL() string

func (AddOwnership) ToTypeQL

func (op AddOwnership) ToTypeQL() string

type AddRelation

type AddRelation struct {
	Name     string
	Parent   string
	Abstract bool
	TypeQL   string // The full define statement for the relation.
}

AddRelation represents the creation of a new relation type in the schema.

func (AddRelation) IsDestructive

func (op AddRelation) IsDestructive() bool

func (AddRelation) IsReversible

func (op AddRelation) IsReversible() bool

func (AddRelation) RollbackTypeQL

func (op AddRelation) RollbackTypeQL() string

func (AddRelation) ToTypeQL

func (op AddRelation) ToTypeQL() string

type AddRole

type AddRole struct {
	Relation string
	Role     string
	Card     string
}

AddRole represents the addition of a role to a relation type.

func (AddRole) IsDestructive

func (op AddRole) IsDestructive() bool

func (AddRole) IsReversible

func (op AddRole) IsReversible() bool

func (AddRole) RollbackTypeQL

func (op AddRole) RollbackTypeQL() string

func (AddRole) ToTypeQL

func (op AddRole) ToTypeQL() string

type AddRolePlayer added in v1.4.0

type AddRolePlayer struct {
	Entity   string
	Relation string
	Role     string
}

AddRolePlayer represents adding a plays clause (entity plays relation:role).

func (AddRolePlayer) IsDestructive added in v1.4.0

func (op AddRolePlayer) IsDestructive() bool

func (AddRolePlayer) IsReversible added in v1.4.0

func (op AddRolePlayer) IsReversible() bool

func (AddRolePlayer) RollbackTypeQL added in v1.4.0

func (op AddRolePlayer) RollbackTypeQL() string

func (AddRolePlayer) ToTypeQL added in v1.4.0

func (op AddRolePlayer) ToTypeQL() string

type AggregateQuery

type AggregateQuery[T any] struct {
	// contains filtered or unexported fields
}

AggregateQuery runs a reduce query and returns a single numeric result.

func (*AggregateQuery[T]) Execute

func (aq *AggregateQuery[T]) Execute(ctx context.Context) (float64, error)

Execute runs the aggregate query and returns the result as float64.

type AggregateSpec

type AggregateSpec struct {
	Attr string
	Fn   string // sum, mean, min, max, std, median, variance, count
}

AggregateSpec describes a single aggregation to compute.

type AndFilter

type AndFilter struct {
	Filters []Filter
}

AndFilter combines multiple filters with AND (conjunction).

func (*AndFilter) ToPatterns

func (f *AndFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns by concatenating all child filter patterns.

type AttrChange

type AttrChange struct {
	Name      string
	ValueType string
}

AttrChange describes an attribute type to be added to the schema.

type BaseEntity

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

BaseEntity is an embeddable base type for all Go structs mapping to TypeDB entities. It provides the internal state and methods required to satisfy the Entity interface.

Example usage:

type Person struct {
    gotype.BaseEntity
    Name  string `typedb:"name,key"`
}

func (*BaseEntity) GetIID

func (e *BaseEntity) GetIID() string

GetIID returns the TypeDB internal instance ID.

func (*BaseEntity) SetIID

func (e *BaseEntity) SetIID(iid string)

SetIID sets the TypeDB internal instance ID.

func (BaseEntity) TypeDBTypeName

func (BaseEntity) TypeDBTypeName() string

TypeDBTypeName returns the TypeDB type name for the entity.

type BaseRelation

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

BaseRelation is an embeddable base type for all Go structs mapping to TypeDB relations. It provides the internal state and methods required to satisfy the Relation interface.

Example usage:

type Employment struct {
    gotype.BaseRelation
    Employee *Person  `typedb:"role:employee"`
    Employer *Company `typedb:"role:employer"`
}

func (*BaseRelation) GetIID

func (r *BaseRelation) GetIID() string

GetIID returns the TypeDB internal instance ID.

func (*BaseRelation) SetIID

func (r *BaseRelation) SetIID(iid string)

SetIID sets the TypeDB internal instance ID.

func (BaseRelation) TypeDBTypeName

func (BaseRelation) TypeDBTypeName() string

TypeDBTypeName returns the TypeDB type name for the relation.

type BreakingChange

type BreakingChange struct {
	Type   string // "removal", "type_change", "cardinality_change"
	Entity string // affected type name
	Detail string // human-readable description
}

BreakingChange describes a change that could cause data loss or schema errors.

type ChecksumMismatchError added in v1.4.0

type ChecksumMismatchError struct {
	Name     string
	Expected string
	Actual   string
}

ChecksumMismatchError is returned when a migration's checksum doesn't match what was recorded when it was first applied.

func (*ChecksumMismatchError) Error added in v1.4.0

func (e *ChecksumMismatchError) Error() string

type ComparisonFilter

type ComparisonFilter struct {
	Attr    string
	Op      string
	Value   any
	Negated bool
}

ComparisonFilter compares an attribute to a value using a TypeQL operator.

func (*ComparisonFilter) ToPatterns

func (f *ComparisonFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for a comparison filter.

type ComputedFilter added in v1.4.0

type ComputedFilter struct {
	// VarName is the name for the computed variable (without $).
	VarName string
	// Expr is the TypeQL expression to compute (e.g., "$e__price * $e__quantity").
	Expr string
	// Op is the comparison operator (==, !=, >, <, >=, <=).
	Op string
	// Value is the comparison target.
	Value any
}

ComputedFilter uses a let-assignment to compute a value and compare it. Generates: let $computed = <expr>; $computed <op> <value>;

func (*ComputedFilter) ToPatterns added in v1.4.0

func (f *ComputedFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL let-assignment and comparison patterns.

type Conn

type Conn interface {
	// Transaction opens a new transaction on the specified database.
	Transaction(dbName string, txType int) (Tx, error)
	// Schema returns the current TypeQL schema definition for the named database.
	Schema(dbName string) (string, error)
	// DatabaseCreate creates a new database with the given name.
	DatabaseCreate(name string) error
	// DatabaseDelete permanently removes the named database.
	DatabaseDelete(name string) error
	// DatabaseContains returns true if the named database exists.
	DatabaseContains(name string) (bool, error)
	// DatabaseAll returns the names of all databases on the server.
	DatabaseAll() ([]string, error)
	// Close terminates the connection.
	Close()
	// IsOpen returns true if the connection is active.
	IsOpen() bool
}

Conn is the interface for a TypeDB connection.

type ConnPool

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

ConnPool manages a pool of database connections for concurrent access.

func NewConnPool

func NewConnPool(config PoolConfig, factory func() (Conn, error)) (*ConnPool, error)

NewConnPool creates a new connection pool with the given configuration and factory function. The factory function is called to create new connections when needed. If config.MinSize > 0, the pool will be pre-warmed with MinSize connections.

func (*ConnPool) Close

func (p *ConnPool) Close()

Close closes all connections in the pool and prevents new connections from being acquired.

func (*ConnPool) Get

func (p *ConnPool) Get(ctx context.Context) (Conn, error)

Get acquires a connection from the pool. If no connections are available and the pool is at max capacity, it waits for one to become available. Returns ErrPoolClosed if the pool is closed, or ErrPoolTimeout if WaitTimeout is exceeded.

func (*ConnPool) Put

func (p *ConnPool) Put(conn Conn)

Put returns a connection to the pool. If the connection is no longer open, it is discarded instead of being returned to the pool.

func (*ConnPool) Stats

func (p *ConnPool) Stats() PoolStats

Stats returns current pool statistics.

type Database

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

Database represents a high-level handle to a specific TypeDB database, providing convenient methods for transaction management and query execution.

func NewDatabase

func NewDatabase(conn Conn, dbName string) *Database

NewDatabase creates a new Database handle bound to a specific database name.

func NewDatabaseWithPool

func NewDatabaseWithPool(config PoolConfig, dbName string, factory func() (Conn, error)) (*Database, error)

NewDatabaseWithPool creates a Database that uses a connection pool for concurrent access. The pool is created with the given configuration and pre-warmed with MinSize connections. The Database takes ownership of the pool and will close it when Database.Close() is called.

func (*Database) Begin

func (db *Database) Begin(txType TransactionType) (*TransactionContext, error)

Begin starts a new TransactionContext. The caller must call Close() when done. A finalizer will log a warning if the transaction is garbage-collected without being closed.

func (*Database) Close

func (db *Database) Close()

Close closes the underlying connection if it is owned by this Database handle.

func (*Database) ExecuteRead

func (db *Database) ExecuteRead(ctx context.Context, query string) ([]map[string]any, error)

ExecuteRead executes a query in a new read transaction.

func (*Database) ExecuteSchema

func (db *Database) ExecuteSchema(ctx context.Context, query string) error

ExecuteSchema executes a schema modification query in a schema transaction.

func (*Database) ExecuteWrite

func (db *Database) ExecuteWrite(ctx context.Context, query string) ([]map[string]any, error)

ExecuteWrite executes a query in a new write transaction and commits it.

func (*Database) GetConn

func (db *Database) GetConn() Conn

GetConn returns the underlying Conn implementation.

func (*Database) Name

func (db *Database) Name() string

Name returns the name of the database.

func (*Database) Schema

func (db *Database) Schema(ctx context.Context) (string, error)

Schema returns the current TypeQL schema definition for this database.

func (*Database) Transaction

func (db *Database) Transaction(txType TransactionType) (Tx, error)

Transaction opens a new transaction of the specified type.

type DeleteOption

type DeleteOption func(*deleteConfig)

DeleteOption configures delete behavior.

func WithStrict

func WithStrict() DeleteOption

WithStrict enables strict mode: delete returns an error if the instance doesn't exist.

type Entity

type Entity interface {

	// TypeDBTypeName returns the TypeDB label for this entity type.
	TypeDBTypeName() string
	// GetIID returns the internal TypeDB instance ID (IID) for the entity instance.
	GetIID() string
	// SetIID assigns the internal TypeDB instance ID (IID) to the entity instance.
	SetIID(iid string)
	// contains filtered or unexported methods
}

Entity is the marker interface for TypeDB entity types. Structs that represent TypeDB entities must satisfy this interface, typically by embedding the BaseEntity type.

type ExistsFilter

type ExistsFilter struct {
	Attr    string
	Negated bool
}

ExistsFilter checks whether an attribute exists (has) or not.

func (*ExistsFilter) ToPatterns

func (f *ExistsFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for an existence filter.

type FieldInfo

type FieldInfo struct {
	// Tag is the parsed 'typedb' struct tag.
	Tag FieldTag
	// FieldName is the name of the field in the Go struct.
	FieldName string
	// FieldIndex is the 0-based index of the field in the Go struct.
	FieldIndex int
	// FieldType is the reflection type of the field.
	FieldType reflect.Type
	// IsPointer is true if the field is a pointer, used for optional attributes.
	IsPointer bool
	// IsSlice is true if the field is a slice, used for multi-valued attributes.
	IsSlice bool
	// ElemType is the base element type for slices and pointers.
	ElemType reflect.Type
	// ValueType is the TypeDB value type (e.g., "string", "long", "boolean").
	ValueType string
}

FieldInfo contains metadata about a single field in a model struct, mapping it to a TypeDB attribute.

type FieldTag

type FieldTag struct {
	// Name is the TypeDB attribute name.
	Name string
	// Key specifies if the attribute is a primary key (@key).
	Key bool
	// Unique specifies if the attribute value must be unique (@unique).
	Unique bool
	// CardMin is the minimum cardinality constraint.
	CardMin *int
	// CardMax is the maximum cardinality constraint.
	CardMax *int
	// RoleName is the name of the role for relation player fields.
	RoleName string
	// Abstract marks the model type as abstract.
	Abstract bool
	// TypeName provides an explicit override for the TypeDB type name.
	TypeName string
	// Skip indicates the field should be ignored by the ORM.
	Skip bool
}

FieldTag contains the structured representation of a parsed `typedb` struct tag.

func ParseTag

func ParseTag(tag string) (FieldTag, error)

ParseTag parses the content of a `typedb` struct tag into a FieldTag structure. It supports options like key, unique, cardinality (card=M..N), roles (role:name), and type name overrides (type:name).

func (FieldTag) IsRole

func (ft FieldTag) IsRole() bool

IsRole returns true if the tag identifies the field as a role player in a relation.

type Filter

type Filter interface {
	// ToPatterns generates TypeQL pattern strings for this filter.
	// varName is the entity/relation variable name (e.g., "e").
	ToPatterns(varName string) []string
}

Filter represents a query filter expression that generates TypeQL patterns. Filters compose via And, Or, and Not to build complex match clauses.

func And

func And(filters ...Filter) Filter

And combines filters with logical AND.

func ByIID

func ByIID(iid string) Filter

ByIID creates a filter matching a specific internal ID.

func Computed added in v1.4.0

func Computed(varName, expr, op string, value any) Filter

Computed creates a filter that assigns a computed expression to a variable and compares it using the given operator.

func Contains

func Contains(attr string, pattern string) Filter

Contains creates a string contains filter.

func Eq

func Eq(attr string, value any) Filter

Eq creates an equality filter: attribute == value.

func Gt

func Gt(attr string, value any) Filter

Gt creates a greater-than filter: attribute > value.

func Gte

func Gte(attr string, value any) Filter

Gte creates a greater-or-equal filter: attribute >= value.

func HasAttr

func HasAttr(attr string) Filter

HasAttr creates an attribute existence filter.

func IIDIn added in v1.4.0

func IIDIn(iids ...string) Filter

IIDIn creates a filter matching any of the specified internal IDs.

func In

func In(attr string, values []any) Filter

In creates a filter that checks if an attribute value is in a set.

func Like

func Like(attr string, pattern string) Filter

Like creates a string like filter (TypeQL pattern matching).

func Lt

func Lt(attr string, value any) Filter

Lt creates a less-than filter: attribute < value.

func Lte

func Lte(attr string, value any) Filter

Lte creates a less-or-equal filter: attribute <= value.

func Neq

func Neq(attr string, value any) Filter

Neq creates a not-equal filter: attribute != value.

func Not

func Not(filter Filter) Filter

Not negates a filter.

func NotHasAttr

func NotHasAttr(attr string) Filter

NotHasAttr creates a negated attribute existence filter.

func NotIn

func NotIn(attr string, values []any) Filter

NotIn creates a filter that checks if an attribute value is NOT in a set.

func Or

func Or(filters ...Filter) Filter

Or combines filters with logical OR.

func Range

func Range(attr string, min, max any) Filter

Range creates a filter that checks if an attribute value is between min and max (inclusive).

func Regex

func Regex(attr string, pattern string) Filter

Regex creates a filter that matches an attribute value against a regex pattern.

func RolePlayer

func RolePlayer(roleName string, inner Filter) Filter

RolePlayer creates a filter that matches relations where the given role player satisfies the inner filter.

func Startswith

func Startswith(attr string, prefix string) Filter

Startswith creates a filter that checks if a string attribute starts with a prefix. This is sugar over Like with a prefix pattern.

type FunctionQuery added in v1.4.0

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

FunctionQuery builds and executes a TypeDB schema function call. TypeDB functions are defined with `fun` in the schema and called via match/return patterns.

func NewFunctionQuery added in v1.4.0

func NewFunctionQuery(db *Database, funcName string) *FunctionQuery

NewFunctionQuery creates a query for a TypeDB schema function. funcName is the function name as defined in the schema.

func (*FunctionQuery) Arg added in v1.4.0

func (fq *FunctionQuery) Arg(value any) *FunctionQuery

Arg adds an argument to the function call. The value is formatted using FormatValue.

func (*FunctionQuery) ArgRaw added in v1.4.0

func (fq *FunctionQuery) ArgRaw(expr string) *FunctionQuery

ArgRaw adds a pre-formatted argument string (e.g., a variable reference).

func (*FunctionQuery) Build added in v1.4.0

func (fq *FunctionQuery) Build() string

Build returns the TypeQL query string for calling the function.

func (*FunctionQuery) Execute added in v1.4.0

func (fq *FunctionQuery) Execute(ctx context.Context) ([]map[string]any, error)

Execute runs the function query and returns the raw results.

type GroupByQuery

type GroupByQuery[T any] struct {
	// contains filtered or unexported fields
}

GroupByQuery groups results by an attribute and supports aggregate operations.

func (*GroupByQuery[T]) Aggregate

func (gq *GroupByQuery[T]) Aggregate(ctx context.Context, specs ...AggregateSpec) (map[string]map[string]float64, error)

Aggregate runs aggregations per group and returns results keyed by group value. Returns map[groupValue]map[aggKey]float64, where aggKey is "fn_attr".

type HydrationError

type HydrationError struct {
	TypeName string
	Field    string
	Cause    error
}

HydrationError is returned when an error occurs while populating a Go struct with data retrieved from TypeDB.

func (*HydrationError) Error

func (e *HydrationError) Error() string

Error returns the error message for HydrationError.

func (*HydrationError) Unwrap

func (e *HydrationError) Unwrap() error

Unwrap returns the underlying cause of the HydrationError.

type IIDFilter

type IIDFilter struct {
	IID string
}

IIDFilter matches by internal ID.

func (*IIDFilter) ToPatterns

func (f *IIDFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for an IID filter.

type IIDInFilter added in v1.4.0

type IIDInFilter struct {
	IIDs []string
}

IIDInFilter matches any of multiple internal IDs using an OR pattern.

func (*IIDInFilter) ToPatterns added in v1.4.0

func (f *IIDInFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for matching multiple IIDs.

type InFilter

type InFilter struct {
	Attr    string
	Values  []any
	Negated bool
}

InFilter checks whether an attribute value is in a set of values.

func (*InFilter) ToPatterns

func (f *InFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for a set membership filter.

type InvalidIdentifierError added in v1.4.0

type InvalidIdentifierError struct {
	Name    string
	Context string
	Reason  string
}

InvalidIdentifierError is returned when a name contains characters not allowed in TypeQL identifiers.

func (*InvalidIdentifierError) Error added in v1.4.0

func (e *InvalidIdentifierError) Error() string

type KeyAttributeError

type KeyAttributeError struct {
	EntityType string
	FieldName  string
	Operation  string
}

KeyAttributeError is returned when a mandatory key attribute is missing during an insert or update operation.

func (*KeyAttributeError) Error

func (e *KeyAttributeError) Error() string

Error returns the error message for KeyAttributeError.

type Manager

type Manager[T any] struct {
	// contains filtered or unexported fields
}

Manager provides high-level, generic CRUD (Create, Read, Update, Delete) operations for a registered TypeDB model type T.

func NewManager

func NewManager[T any](db *Database) *Manager[T]

NewManager creates a new Manager for the model type T. T must be a struct that has been registered via Register[T]().

func NewManagerWithTx

func NewManagerWithTx[T any](tc *TransactionContext) *Manager[T]

NewManagerWithTx creates a Manager bound to an existing transaction context. All operations performed by this manager will use the provided transaction.

func (*Manager[T]) All

func (m *Manager[T]) All(ctx context.Context) ([]*T, error)

All retrieves all instances of the model type T from the database.

func (*Manager[T]) Delete

func (m *Manager[T]) Delete(ctx context.Context, instance *T, opts ...DeleteOption) error

Delete deletes an instance by IID.

func (*Manager[T]) DeleteMany

func (m *Manager[T]) DeleteMany(ctx context.Context, instances []*T, opts ...DeleteOption) error

DeleteMany deletes multiple instances in a single transaction.

func (*Manager[T]) Get

func (m *Manager[T]) Get(ctx context.Context, filters map[string]any) ([]*T, error)

Get retrieves instances of T that match the specified attribute filters. filters is a map where keys are TypeDB attribute names and values are the target values.

func (*Manager[T]) GetByIID

func (m *Manager[T]) GetByIID(ctx context.Context, iid string) (*T, error)

GetByIID retrieves a single instance of T by its internal instance ID (IID). It returns nil if no instance is found with the given IID.

func (*Manager[T]) GetByIIDPolymorphic

func (m *Manager[T]) GetByIIDPolymorphic(ctx context.Context, iid string) (*T, string, error)

GetByIIDPolymorphic fetches a single instance by IID with polymorphic type resolution. It resolves the actual stored type and fetches all of that type's attributes, so subtype-specific fields are preserved when the concrete type is registered. Returns the instance hydrated as *T (base type fields only), the type label, and an error if any. Use GetByIIDPolymorphicAny for full subtype hydration. Returns nil, "", nil if not found.

func (*Manager[T]) GetByIIDPolymorphicAny

func (m *Manager[T]) GetByIIDPolymorphicAny(ctx context.Context, iid string) (any, string, error)

GetByIIDPolymorphicAny fetches a single instance by IID and hydrates it as the actual concrete subtype. Unlike GetByIIDPolymorphic which always returns *T, this returns any (the concrete type pointer) so subtype-specific fields are preserved. The concrete subtype must be registered via Register[ConcreteType](). Returns nil, "", nil if not found.

func (*Manager[T]) GetWithRoles

func (m *Manager[T]) GetWithRoles(ctx context.Context, filters map[string]any) ([]*T, error)

GetWithRoles retrieves instances of T and populates their role players. This is primarily used for relation models.

func (*Manager[T]) Insert

func (m *Manager[T]) Insert(ctx context.Context, instance *T) error

Insert adds a new instance of T to the database. If T has key fields, the instance's internal IID will be populated upon success.

func (*Manager[T]) InsertMany

func (m *Manager[T]) InsertMany(ctx context.Context, instances []*T) error

InsertMany inserts multiple instances in a single transaction.

func (*Manager[T]) Put

func (m *Manager[T]) Put(ctx context.Context, instance *T) error

Put upserts an instance (insert or update). After a successful put, the instance's IID is populated (if it has key fields).

func (*Manager[T]) PutMany

func (m *Manager[T]) PutMany(ctx context.Context, instances []*T) error

PutMany upserts multiple instances in a single transaction.

func (*Manager[T]) Query

func (m *Manager[T]) Query() *Query[T]

Query returns a new chainable query builder for this model.

func (*Manager[T]) Update

func (m *Manager[T]) Update(ctx context.Context, instance *T) error

Update modifies an existing instance of T in the database. The instance must have its IID populated (typically from a prior Get or Insert).

func (*Manager[T]) UpdateMany

func (m *Manager[T]) UpdateMany(ctx context.Context, instances []*T) error

UpdateMany updates multiple instances in a single transaction.

type MigrateOption

type MigrateOption func(*migrateConfig)

MigrateOption configures migration behavior.

func WithDestructive

func WithDestructive() MigrateOption

WithDestructive enables destructive migration (removals).

type MigrationError

type MigrationError struct {
	Operation string
	Cause     error
}

MigrationError is returned when an error occurs during the execution of a schema migration.

func (*MigrationError) Error

func (e *MigrationError) Error() string

Error returns the error message for MigrationError.

func (*MigrationError) Unwrap

func (e *MigrationError) Unwrap() error

Unwrap returns the underlying cause of the MigrationError.

type MigrationRecord

type MigrationRecord struct {
	// Hash is the deterministic SHA-256 hash of the migration's TypeQL statements.
	Hash string
	// Summary is a human-readable description of the changes in the migration.
	Summary string
	// AppliedAt is the timestamp when the migration was recorded in the database.
	AppliedAt time.Time
}

MigrationRecord represents a single schema migration that has been successfully applied to the database.

type MigrationState

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

MigrationState provides methods for tracking and managing the history of applied migrations within a TypeDB database.

func NewMigrationState

func NewMigrationState(db *Database) *MigrationState

NewMigrationState initializes a new MigrationState tracker for the given database.

func (*MigrationState) Applied

func (ms *MigrationState) Applied(ctx context.Context) ([]MigrationRecord, error)

Applied retrieves all migration records stored in the database, ordered by their application timestamp.

func (*MigrationState) EnsureSchema

func (ms *MigrationState) EnsureSchema(ctx context.Context) error

EnsureSchema creates the internal TypeDB schema required for tracking migrations. This operation is idempotent and safe to call multiple times.

func (*MigrationState) IsApplied

func (ms *MigrationState) IsApplied(ctx context.Context, hash string) (bool, error)

IsApplied checks if a migration with the specified hash has already been applied.

func (*MigrationState) Record

func (ms *MigrationState) Record(ctx context.Context, hash, summary string) error

Record saves a new migration record to the database after it has been applied.

type ModelInfo

type ModelInfo struct {
	// GoType is the reflection type of the Go struct representing the model.
	GoType reflect.Type
	// Kind indicates whether this model is an entity or a relation.
	Kind ModelKind
	// TypeName is the name of the type in the TypeDB schema.
	TypeName string
	// IsAbstract is true if the TypeDB type is defined as abstract.
	IsAbstract bool
	// Supertype is the name of the parent type in the TypeDB schema.
	Supertype string
	// Fields is a list of metadata for each attribute field in the model.
	Fields []FieldInfo
	// Roles is a list of metadata for each role player field (only for relations).
	Roles []RoleInfo
	// KeyFields is a subset of Fields containing attributes marked as keys.
	KeyFields []FieldInfo
}

ModelInfo contains comprehensive metadata about a registered TypeDB model, including its mapping to a Go struct and its TypeDB schema properties.

func ExtractModelInfo

func ExtractModelInfo(t reflect.Type) (*ModelInfo, error)

ExtractModelInfo analyzes a Go struct type and extracts its TypeDB model metadata. The struct must embed BaseEntity or BaseRelation to be a valid model.

func Lookup

func Lookup(typeName string) (*ModelInfo, bool)

Lookup retrieves ModelInfo for a given TypeDB type name.

func LookupByGoName

func LookupByGoName(name string) (*ModelInfo, bool)

LookupByGoName retrieves ModelInfo based on the name of the Go struct.

func LookupType

func LookupType(t reflect.Type) (*ModelInfo, bool)

LookupType retrieves ModelInfo for a given Go reflect.Type.

func RegisteredTypes

func RegisteredTypes() []*ModelInfo

RegisteredTypes returns a slice containing ModelInfo for all registered types.

func ResolveType

func ResolveType(typeLabel string) (*ModelInfo, bool)

ResolveType maps a TypeDB type label to its registered ModelInfo.

func SubtypesOf

func SubtypesOf(typeName string) []*ModelInfo

SubtypesOf returns a slice of registered types that are direct subtypes of the specified parent type.

func (*ModelInfo) FieldByAttrName

func (m *ModelInfo) FieldByAttrName(attrName string) (FieldInfo, bool)

FieldByAttrName retrieves FieldInfo by the TypeDB attribute name.

func (*ModelInfo) FieldByName

func (m *ModelInfo) FieldByName(name string) (FieldInfo, bool)

FieldByName retrieves FieldInfo by the Go struct field name.

type ModelKind

type ModelKind int

ModelKind specifies whether a registered TypeDB model is an entity or a relation.

const (
	// ModelKindEntity represents a TypeDB entity type.
	ModelKindEntity ModelKind = iota
	// ModelKindRelation represents a TypeDB relation type.
	ModelKindRelation
)

type ModelStrategy

type ModelStrategy interface {
	// BuildInsertQuery generates a TypeQL insert statement for an instance.
	BuildInsertQuery(info *ModelInfo, instance any, varName string) string
	// BuildPutQuery generates a TypeQL put (upsert) statement for an instance.
	BuildPutQuery(info *ModelInfo, instance any, varName string) string
	// BuildMatchByKey generates a match clause based on the model's key attributes.
	BuildMatchByKey(info *ModelInfo, instance any, varName string) string
	// BuildMatchByIID generates a match clause based on the internal instance ID.
	BuildMatchByIID(iid string, varName string) string
	// BuildMatchAll generates a match clause for all instances of the type.
	BuildMatchAll(info *ModelInfo, varName string) string
	// BuildFetchAll generates a fetch clause for all attributes of the type.
	BuildFetchAll(info *ModelInfo, varName string) string
	// BuildMatchAllStrict generates a strict match clause using isa!.
	BuildMatchAllStrict(info *ModelInfo, varName string) string
	// BuildFetchAllWithType generates a fetch clause that includes the type label.
	BuildFetchAllWithType(info *ModelInfo, varName string) string
	// BuildFetchWithRoles generates a fetch clause including role player data for relations.
	BuildFetchWithRoles(info *ModelInfo, varName string) (matchAdditions string, fetchClause string)
}

ModelStrategy specifies the interface for building TypeQL queries based on the kind of model (entity or relation).

type ModifyOwnership added in v1.4.0

type ModifyOwnership struct {
	Owner     string
	Attribute string
	OldAnnots string
	NewAnnots string
}

ModifyOwnership represents changing annotations on an existing owns clause.

func (ModifyOwnership) IsDestructive added in v1.4.0

func (op ModifyOwnership) IsDestructive() bool

func (ModifyOwnership) IsReversible added in v1.4.0

func (op ModifyOwnership) IsReversible() bool

func (ModifyOwnership) RollbackTypeQL added in v1.4.0

func (op ModifyOwnership) RollbackTypeQL() string

func (ModifyOwnership) ToTypeQL added in v1.4.0

func (op ModifyOwnership) ToTypeQL() string

type NotFilter

type NotFilter struct {
	Inner Filter
}

NotFilter negates a filter expression.

func (*NotFilter) ToPatterns

func (f *NotFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns wrapped in a not {} block.

type NotFoundError

type NotFoundError struct {
	TypeName string
}

NotFoundError is returned when a query expected to return an instance finds no matching results.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error returns the error message for NotFoundError.

type NotRegisteredError

type NotRegisteredError struct {
	TypeName string
}

NotRegisteredError is returned when an operation is attempted on a Go type that has not been registered with the ORM.

func (*NotRegisteredError) Error

func (e *NotRegisteredError) Error() string

Error returns the error message for NotRegisteredError.

type NotUniqueError

type NotUniqueError struct {
	TypeName string
	Count    int
}

NotUniqueError is returned when a query expected to return a single unique instance finds multiple matches.

func (*NotUniqueError) Error

func (e *NotUniqueError) Error() string

Error returns the error message for NotUniqueError.

type Operation

type Operation interface {
	// ToTypeQL returns the TypeQL statement required to perform the operation.
	ToTypeQL() string
	// IsReversible returns true if the operation can be undone without data loss.
	IsReversible() bool
	// RollbackTypeQL returns the TypeQL statement required to undo the operation.
	RollbackTypeQL() string
	// IsDestructive returns true if the operation results in the deletion of schema elements or data.
	IsDestructive() bool
}

Operation defines the interface for a single, atomic schema migration step.

type OrFilter

type OrFilter struct {
	Filters []Filter
}

OrFilter combines alternatives with OR (disjunction).

func (*OrFilter) ToPatterns

func (f *OrFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL or-branch patterns with scoped variables.

type OrderClause

type OrderClause struct {
	Attr string
	Desc bool
}

OrderClause specifies an attribute name and sort direction for query results.

type OwnsChange

type OwnsChange struct {
	TypeName  string
	Attribute string
	Annots    string // TypeQL annotations like @key or @card.
}

OwnsChange describes an attribute ownership to be added to a type.

type PoolConfig

type PoolConfig struct {
	// MinSize is the minimum number of connections to maintain (0 = no minimum).
	MinSize int
	// MaxSize is the maximum number of connections allowed (0 = unlimited).
	MaxSize int
	// IdleTimeout is the duration after which idle connections are closed (0 = never expire).
	IdleTimeout time.Duration
	// WaitTimeout is the maximum time to wait for an available connection (0 = no timeout).
	WaitTimeout time.Duration
}

PoolConfig specifies connection pool behavior.

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns a reasonable default pool configuration.

type PoolStats

type PoolStats struct {
	Available int // connections available in the pool
	InUse     int // connections currently in use
	Total     int // total open connections
	Waiting   int // goroutines waiting for a connection
}

PoolStats provides statistics about the connection pool.

type Query

type Query[T any] struct {
	// contains filtered or unexported fields
}

Query provides a chainable, type-safe API for constructing and executing TypeDB queries for a specific model type T.

func (*Query[T]) Aggregate

func (q *Query[T]) Aggregate(ctx context.Context, specs ...AggregateSpec) (map[string]float64, error)

Aggregate runs multiple aggregations in one call and returns named results. Each spec produces a result keyed by "fn_attr" (e.g., "sum_age", "mean_score"). All aggregations are computed in a single query using multiple reduce assignments.

func (*Query[T]) All

func (q *Query[T]) All(ctx context.Context) ([]*T, error)

All executes the query and returns all matching instances as a slice of pointers to T.

func (*Query[T]) Avg

func (q *Query[T]) Avg(attr string) *AggregateQuery[T]

Avg creates an aggregate query for the mean of an attribute.

func (*Query[T]) Count

func (q *Query[T]) Count(ctx context.Context) (int64, error)

Count returns the number of instances matching the query filters.

func (*Query[T]) Delete

func (q *Query[T]) Delete(ctx context.Context) (int64, error)

Delete removes all instances that match the query filters.

func (*Query[T]) Execute

func (q *Query[T]) Execute(ctx context.Context) ([]*T, error)

Execute performs the query against the database and hydrates the results into Go structs.

func (*Query[T]) Exists

func (q *Query[T]) Exists(ctx context.Context) (bool, error)

Exists returns true if the query matches at least one instance in the database.

func (*Query[T]) Filter

func (q *Query[T]) Filter(filters ...Filter) *Query[T]

Filter adds one or more filtering conditions to the query. Multiple calls to Filter are combined using logical AND.

func (*Query[T]) First

func (q *Query[T]) First(ctx context.Context) (*T, error)

First executes the query with a limit of 1 and returns the first result, or nil if none found.

func (*Query[T]) GroupBy

func (q *Query[T]) GroupBy(attr string) *GroupByQuery[T]

GroupBy creates a grouped query for computing per-group aggregates.

func (*Query[T]) Limit

func (q *Query[T]) Limit(n int) *Query[T]

Limit restricts the number of results returned by the query.

func (*Query[T]) Max

func (q *Query[T]) Max(attr string) *AggregateQuery[T]

Max creates an aggregate query for the maximum of an attribute.

func (*Query[T]) Median

func (q *Query[T]) Median(attr string) *AggregateQuery[T]

Median creates an aggregate query for the median of an attribute.

func (*Query[T]) Min

func (q *Query[T]) Min(attr string) *AggregateQuery[T]

Min creates an aggregate query for the minimum of an attribute.

func (*Query[T]) Offset

func (q *Query[T]) Offset(n int) *Query[T]

Offset skips the first n results returned by the query.

func (*Query[T]) OrderAsc

func (q *Query[T]) OrderAsc(attr string) *Query[T]

OrderAsc adds an ascending sort order on the specified attribute.

func (*Query[T]) OrderDesc

func (q *Query[T]) OrderDesc(attr string) *Query[T]

OrderDesc adds a descending sort order on the specified attribute.

func (*Query[T]) Std

func (q *Query[T]) Std(attr string) *AggregateQuery[T]

Std creates an aggregate query for the standard deviation of an attribute.

func (*Query[T]) Sum

func (q *Query[T]) Sum(attr string) *AggregateQuery[T]

Sum creates an aggregate query for the sum of an attribute.

func (*Query[T]) Update

func (q *Query[T]) Update(ctx context.Context, updates map[string]any) (int64, error)

Update performs a bulk attribute update on all matching instances. Keys in the updates map are TypeDB attribute names; values are the new values. Returns the number of instances updated, or -1 if the count is unknown.

func (*Query[T]) UpdateWith

func (q *Query[T]) UpdateWith(ctx context.Context, fn func(*T)) ([]*T, error)

UpdateWith fetches all matching instances, applies fn to each, then updates them all. The fetch and update are performed within a single write transaction for atomicity.

func (*Query[T]) Variance

func (q *Query[T]) Variance(attr string) *AggregateQuery[T]

Variance creates an aggregate query for the variance of an attribute.

type RangeFilter

type RangeFilter struct {
	Attr    string
	Min     any
	Max     any
	Negated bool
}

RangeFilter checks whether an attribute value falls between min and max (inclusive).

func (*RangeFilter) ToPatterns

func (f *RangeFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for a range filter.

type RegexFilter

type RegexFilter struct {
	Attr    string
	Pattern string
	Negated bool
}

RegexFilter applies a regex match on a string attribute using TypeQL "like".

func (*RegexFilter) ToPatterns

func (f *RegexFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for a regex filter.

type Registry

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

Registry maintains a mapping between Go struct types and TypeDB model metadata. It is used to look up schema information during query generation and hydration.

type RelatesChange

type RelatesChange struct {
	TypeName string
	Role     string
	Card     string
}

RelatesChange describes a role to be added to a relation type.

type Relation

type Relation interface {

	// TypeDBTypeName returns the TypeDB label for this relation type.
	TypeDBTypeName() string
	// GetIID returns the internal TypeDB instance ID (IID) for the relation instance.
	GetIID() string
	// SetIID assigns the internal TypeDB instance ID (IID) to the relation instance.
	SetIID(iid string)
	// contains filtered or unexported methods
}

Relation is the marker interface for TypeDB relation types. Structs that represent TypeDB relations must satisfy this interface, typically by embedding the BaseRelation type.

type RemoveAttribute

type RemoveAttribute struct {
	Name string
}

RemoveAttribute removes an attribute type.

func (RemoveAttribute) IsDestructive

func (op RemoveAttribute) IsDestructive() bool

func (RemoveAttribute) IsReversible

func (op RemoveAttribute) IsReversible() bool

func (RemoveAttribute) RollbackTypeQL

func (op RemoveAttribute) RollbackTypeQL() string

func (RemoveAttribute) ToTypeQL

func (op RemoveAttribute) ToTypeQL() string

type RemoveEntity

type RemoveEntity struct {
	Name string
}

RemoveEntity removes an entity type.

func (RemoveEntity) IsDestructive

func (op RemoveEntity) IsDestructive() bool

func (RemoveEntity) IsReversible

func (op RemoveEntity) IsReversible() bool

func (RemoveEntity) RollbackTypeQL

func (op RemoveEntity) RollbackTypeQL() string

func (RemoveEntity) ToTypeQL

func (op RemoveEntity) ToTypeQL() string

type RemoveOwnership

type RemoveOwnership struct {
	Owner     string
	Attribute string
}

RemoveOwnership removes an owns clause from a type.

func (RemoveOwnership) IsDestructive

func (op RemoveOwnership) IsDestructive() bool

func (RemoveOwnership) IsReversible

func (op RemoveOwnership) IsReversible() bool

func (RemoveOwnership) RollbackTypeQL

func (op RemoveOwnership) RollbackTypeQL() string

func (RemoveOwnership) ToTypeQL

func (op RemoveOwnership) ToTypeQL() string

type RemoveRelation

type RemoveRelation struct {
	Name string
}

RemoveRelation removes a relation type.

func (RemoveRelation) IsDestructive

func (op RemoveRelation) IsDestructive() bool

func (RemoveRelation) IsReversible

func (op RemoveRelation) IsReversible() bool

func (RemoveRelation) RollbackTypeQL

func (op RemoveRelation) RollbackTypeQL() string

func (RemoveRelation) ToTypeQL

func (op RemoveRelation) ToTypeQL() string

type RemoveRole

type RemoveRole struct {
	Relation string
	Role     string
}

RemoveRole removes a relates clause from a relation type.

func (RemoveRole) IsDestructive

func (op RemoveRole) IsDestructive() bool

func (RemoveRole) IsReversible

func (op RemoveRole) IsReversible() bool

func (RemoveRole) RollbackTypeQL

func (op RemoveRole) RollbackTypeQL() string

func (RemoveRole) ToTypeQL

func (op RemoveRole) ToTypeQL() string

type RemoveRolePlayer added in v1.4.0

type RemoveRolePlayer struct {
	Entity   string
	Relation string
	Role     string
}

RemoveRolePlayer removes a plays clause from an entity type.

func (RemoveRolePlayer) IsDestructive added in v1.4.0

func (op RemoveRolePlayer) IsDestructive() bool

func (RemoveRolePlayer) IsReversible added in v1.4.0

func (op RemoveRolePlayer) IsReversible() bool

func (RemoveRolePlayer) RollbackTypeQL added in v1.4.0

func (op RemoveRolePlayer) RollbackTypeQL() string

func (RemoveRolePlayer) ToTypeQL added in v1.4.0

func (op RemoveRolePlayer) ToTypeQL() string

type RenameAttribute added in v1.4.0

type RenameAttribute struct {
	OldName   string
	NewName   string
	ValueType string
}

RenameAttribute represents renaming an attribute type. TypeDB has no native rename, so this generates a multi-step sequence: 1. Define new attribute 2. Reassign ownership from old to new Note: data migration must be handled separately.

func (RenameAttribute) IsDestructive added in v1.4.0

func (op RenameAttribute) IsDestructive() bool

func (RenameAttribute) IsReversible added in v1.4.0

func (op RenameAttribute) IsReversible() bool

func (RenameAttribute) RollbackTypeQL added in v1.4.0

func (op RenameAttribute) RollbackTypeQL() string

func (RenameAttribute) ToTypeQL added in v1.4.0

func (op RenameAttribute) ToTypeQL() string

type ReservedWordError

type ReservedWordError struct {
	Word    string
	Context string // "attribute", "entity", "relation", "role"
}

ReservedWordError is returned when a TypeQL reserved keyword is used as a name for a type, attribute, or role.

func (*ReservedWordError) Error

func (e *ReservedWordError) Error() string

Error returns the error message for ReservedWordError.

type RoleInfo

type RoleInfo struct {
	// RoleName is the TypeDB name of the role (e.g., "employee").
	RoleName string

	// FieldName is the name of the Go struct field representing the player.
	FieldName string

	// FieldIndex is the 0-based index of the field in the Go struct.
	FieldIndex int

	// PlayerTypeName is the TypeDB type label of the expected role player.
	PlayerTypeName string
}

RoleInfo contains metadata about a role player in a relation model, defining how a struct field maps to a TypeDB role.

type RolePlayerFilter

type RolePlayerFilter struct {
	RoleName string
	Inner    Filter
}

RolePlayerFilter matches relations where a given role player satisfies the inner filter.

func (*RolePlayerFilter) ToPatterns

func (f *RolePlayerFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns linking a role player and applying inner filters.

type RunTypeQL added in v1.4.0

type RunTypeQL struct {
	Up   string
	Down string
}

RunTypeQL executes arbitrary TypeQL as a migration step. Provide Up for the forward migration and optionally Down for rollback.

func (RunTypeQL) IsDestructive added in v1.4.0

func (op RunTypeQL) IsDestructive() bool

func (RunTypeQL) IsReversible added in v1.4.0

func (op RunTypeQL) IsReversible() bool

func (RunTypeQL) RollbackTypeQL added in v1.4.0

func (op RunTypeQL) RollbackTypeQL() string

func (RunTypeQL) ToTypeQL added in v1.4.0

func (op RunTypeQL) ToTypeQL() string

type SchemaConflictError

type SchemaConflictError struct {
	TypeName string
	Change   string
}

SchemaConflictError is returned when a proposed schema migration conflicts with the existing database schema in a non-recoverable way.

func (*SchemaConflictError) Error

func (e *SchemaConflictError) Error() string

Error returns the error message for SchemaConflictError.

type SchemaDiff

type SchemaDiff struct {
	// AddAttributes are new attribute types to be defined.
	AddAttributes []AttrChange
	// AddEntities are new entity types to be defined.
	AddEntities []TypeChange
	// AddRelations are new relation types to be defined.
	AddRelations []TypeChange
	// AddOwns are new attribute ownerships to be added to existing types.
	AddOwns []OwnsChange
	// AddRelates are new role relations to be added to existing relation types.
	AddRelates []RelatesChange
	// RemoveOwns identifies attribute ownerships present in the DB but not in the code.
	RemoveOwns []OwnsChange
	// RemoveTypes identifies types present in the DB but not in the code.
	RemoveTypes []string
}

SchemaDiff represents the calculated differences between the schema defined by Go structs and the current schema in the TypeDB database.

func DiffSchema

func DiffSchema(desired *tqlgen.ParsedSchema, current *tqlgen.ParsedSchema) *SchemaDiff

DiffSchema compares two parsed schemas and returns a SchemaDiff representing the changes needed to transform the current schema into the desired schema.

func DiffSchemaFromRegistry

func DiffSchemaFromRegistry(currentDB *tqlgen.ParsedSchema) *SchemaDiff

DiffSchemaFromRegistry compares the currently registered Go models against the provided database schema.

func Migrate

func Migrate(ctx context.Context, db *Database) (*SchemaDiff, error)

Migrate performs a schema migration by fetching the current database schema, comparing it with registered Go models, and applying any necessary additive changes.

func MigrateFromSchema

func MigrateFromSchema(ctx context.Context, db *Database, currentSchemaStr string) (*SchemaDiff, error)

MigrateFromSchema performs a schema migration using the provided schema string, comparing it with registered Go models, and applying any necessary additive changes.

func MigrateWithState

func MigrateWithState(ctx context.Context, db *Database) (*SchemaDiff, error)

MigrateWithState performs a migration while tracking progress in the database. It fetches the current schema automatically and ensures that identical migrations are not applied more than once.

func MigrateWithStateFromSchema

func MigrateWithStateFromSchema(ctx context.Context, db *Database, currentSchemaStr string) (*SchemaDiff, error)

MigrateWithStateFromSchema performs a migration using the provided schema string while tracking progress in the database. It ensures that identical migrations are not applied more than once.

func SyncSchema added in v1.4.0

func SyncSchema(ctx context.Context, db *Database, opts ...SyncSchemaOption) (*SchemaDiff, error)

SyncSchema performs a one-shot schema synchronization: introspect current DB schema, diff against registered Go models, and apply changes. Use WithForce() to also apply destructive changes (removals). Use WithSkipIfExists() to skip if the schema already matches.

func (*SchemaDiff) BreakingChanges

func (d *SchemaDiff) BreakingChanges() []BreakingChange

BreakingChanges analyzes the diff for changes that could cause data loss.

func (*SchemaDiff) DestructiveOperations

func (d *SchemaDiff) DestructiveOperations() []Operation

DestructiveOperations returns operations that remove schema elements. These are only generated when explicitly requested.

func (*SchemaDiff) GenerateMigration

func (d *SchemaDiff) GenerateMigration() []string

GenerateMigration produces a slice of TypeQL 'define' statements required to reconcile the database schema with the Go models.

func (*SchemaDiff) GenerateMigrationWithOpts

func (d *SchemaDiff) GenerateMigrationWithOpts(opts ...MigrateOption) []string

GenerateMigrationWithOpts produces TypeQL statements to apply the diff. With WithDestructive(), also generates undefine statements for removals.

func (*SchemaDiff) HasBreakingChanges

func (d *SchemaDiff) HasBreakingChanges() bool

HasBreakingChanges returns true if the diff contains any breaking changes.

func (*SchemaDiff) IsEmpty

func (d *SchemaDiff) IsEmpty() bool

IsEmpty returns true if no schema differences were detected.

func (*SchemaDiff) Operations

func (d *SchemaDiff) Operations() []Operation

Operations converts the diff into a list of discrete, ordered operations.

func (*SchemaDiff) Summary

func (d *SchemaDiff) Summary() string

Summary returns a human-readable description of the changes in the diff.

type SchemaValidationError

type SchemaValidationError struct {
	TypeName string
	Message  string
}

SchemaValidationError is returned when the registered Go models do not align with the expected TypeDB schema patterns.

func (*SchemaValidationError) Error

func (e *SchemaValidationError) Error() string

Error returns the error message for SchemaValidationError.

type SeqMigrationError added in v1.1.0

type SeqMigrationError struct {
	Name  string
	Cause error
}

SeqMigrationError is returned when a sequential migration fails.

func (*SeqMigrationError) Error added in v1.1.0

func (e *SeqMigrationError) Error() string

Error returns the error message.

func (*SeqMigrationError) Unwrap added in v1.1.0

func (e *SeqMigrationError) Unwrap() error

Unwrap returns the underlying cause.

type SeqMigrationInfo added in v1.1.0

type SeqMigrationInfo struct {
	Name      string
	Applied   bool
	AppliedAt string // RFC3339 or empty
}

SeqMigrationInfo describes the status of a single migration.

func SeqMigrationStatus added in v1.1.0

func SeqMigrationStatus(ctx context.Context, db *Database, migrations []SequentialMigration) ([]SeqMigrationInfo, error)

SeqMigrationStatus returns the status of all provided migrations.

type SeqMigrationOption added in v1.1.0

type SeqMigrationOption func(*seqMigrationOptions)

SeqMigrationOption configures RunSequentialMigrations.

func WithSeqDryRun added in v1.1.0

func WithSeqDryRun() SeqMigrationOption

WithSeqDryRun enables dry-run mode: validates and returns pending migrations without executing.

func WithSeqLogger added in v1.1.0

func WithSeqLogger(fn func(string)) SeqMigrationOption

WithSeqLogger sets a callback for migration progress messages.

func WithSeqTarget added in v1.1.0

func WithSeqTarget(name string) SeqMigrationOption

WithSeqTarget stops migration after applying the named migration.

type SeqValidationIssue added in v1.1.0

type SeqValidationIssue struct {
	Name     string
	Message  string
	Severity string // "error" or "warning"
}

SeqValidationIssue describes a problem found during migration validation.

func ValidateSequentialMigrations added in v1.1.0

func ValidateSequentialMigrations(migrations []SequentialMigration) []SeqValidationIssue

ValidateSequentialMigrations checks migrations for structural issues without touching the database.

type SequentialMigration added in v1.1.0

type SequentialMigration struct {
	// Name is the unique identifier, typically prefixed with a timestamp (e.g. "20240101_create_users").
	Name string
	// Up applies the migration.
	Up func(ctx context.Context, db *Database) error
	// Down reverses the migration. May be nil if rollback is not supported.
	Down func(ctx context.Context, db *Database) error
	// Statements is optionally set by TQLMigration for dry-run introspection.
	// nil for migrations with custom Up/Down functions.
	Statements *TQLStatements
}

SequentialMigration represents a single named migration with Up and optional Down functions.

func TQLMigration added in v1.1.0

func TQLMigration(name string, up []string, down []string) SequentialMigration

TQLMigration creates a SequentialMigration from raw TypeQL statement slices. Each statement is routed to ExecuteSchema or ExecuteWrite based on its prefix.

type StringFilter

type StringFilter struct {
	Attr    string
	Op      string // "contains" or "like"
	Pattern string
	Negated bool
}

StringFilter applies string operations (contains, like) on an attribute.

func (*StringFilter) ToPatterns

func (f *StringFilter) ToPatterns(varName string) []string

ToPatterns generates TypeQL patterns for a string filter.

type SyncSchemaOption added in v1.4.0

type SyncSchemaOption func(*syncSchemaConfig)

SyncSchemaOption configures SyncSchema behavior.

func WithForce added in v1.4.0

func WithForce() SyncSchemaOption

WithForce enables destructive changes (removing types/attributes).

func WithSkipIfExists added in v1.4.0

func WithSkipIfExists() SyncSchemaOption

WithSkipIfExists skips the migration if the schema already matches.

type TQLStatements added in v1.1.0

type TQLStatements struct {
	Up   []string
	Down []string // nil if no down statements
}

TQLStatements holds raw TypeQL statements for introspection. Populated automatically by TQLMigration; nil for custom Up/Down functions.

type TransactionContext

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

TransactionContext provides a scoped transaction that can be explicitly managed and shared across multiple Manager operations.

func (*TransactionContext) Close

func (tc *TransactionContext) Close()

Close releases resources associated with the scoped transaction.

func (*TransactionContext) Commit

func (tc *TransactionContext) Commit() error

Commit persists changes in the scoped transaction.

func (*TransactionContext) Rollback

func (tc *TransactionContext) Rollback() error

Rollback discards changes in the scoped transaction.

func (*TransactionContext) Tx

func (tc *TransactionContext) Tx() Tx

Tx returns the underlying Tx for direct query execution.

type TransactionType

type TransactionType int

TransactionType represents the intended mode of operation for a TypeDB transaction.

const (
	// ReadTransaction is for data retrieval only.
	ReadTransaction TransactionType = 0
	// WriteTransaction allows for data modification.
	WriteTransaction TransactionType = 1
	// SchemaTransaction is for modifying the database schema.
	SchemaTransaction TransactionType = 2
)

type Tx

type Tx interface {
	// Query executes a TypeQL query and returns the results.
	Query(query string) ([]map[string]any, error)
	// QueryWithContext executes a TypeQL query with context cancellation support.
	QueryWithContext(ctx context.Context, query string) ([]map[string]any, error)
	// Commit persists changes made in the transaction.
	Commit() error
	// Rollback discards changes made in the transaction.
	Rollback() error
	// Close releases resources associated with the transaction.
	Close()
	// IsOpen returns true if the transaction is active.
	IsOpen() bool
}

Tx is the interface for a TypeDB transaction, allowing for query execution and lifecycle management.

type TypeChange

type TypeChange struct {
	TypeQL string // The full 'define' statement for the type.
}

TypeChange describes an entity or relation type to be added to the schema.

Jump to

Keyboard shortcuts

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