gotype

April 23, 2026 ยท View on GitHub

import "github.com/CaliLuke/go-typeql/gotype"

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

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

const MaxHydrationDepth = 10

Variables

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

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

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

func ActiveTransactionContexts

func ActiveTransactionContexts() int64

ActiveTransactionContexts returns the number of TransactionContexts that have been opened and not yet closed, committed, rolled back, or leaked.

func ArithmeticExpr

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

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 LeakedTransactionContexts

func LeakedTransactionContexts() int64

LeakedTransactionContexts returns the number of TransactionContexts observed by the finalizer without an explicit Close, Commit, or Rollback.

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

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

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

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

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

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.

type AddAttribute

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

type AddAttribute struct {
    Name      string
    ValueType string
}

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

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

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

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

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

type AddOwnership struct {
    Owner     string
    Attribute string
    Annots    string
}

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

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

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

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

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

type AddRole struct {
    Relation string
    Role     string
    Card     string
}

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

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

type AddRolePlayer struct {
    Entity   string
    Relation string
    Role     string
}

func (AddRolePlayer) IsDestructive

func (op AddRolePlayer) IsDestructive() bool

func (AddRolePlayer) IsReversible

func (op AddRolePlayer) IsReversible() bool

func (AddRolePlayer) RollbackTypeQL

func (op AddRolePlayer) RollbackTypeQL() string

func (AddRolePlayer) ToTypeQL

func (op AddRolePlayer) ToTypeQL() string

type AggregateQuery

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

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

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

AggregateSpec describes a single aggregation to compute.

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

type AndFilter

AndFilter combines multiple filters with AND (conjunction).

type AndFilter struct {
    Filters []Filter
}

func (*AndFilter) ToPatterns

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

ToPatterns generates TypeQL patterns by concatenating all child filter patterns.

type AttrChange

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

type AttrChange struct {
    Name      string
    ValueType string
}

type BaseEntity

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"`
}
type BaseEntity struct {
    // contains filtered or unexported fields
}

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

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"`
}
type BaseRelation struct {
    // contains filtered or unexported fields
}

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

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

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

type ChecksumMismatchError

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

type ChecksumMismatchError struct {
    Name     string
    Expected string
    Actual   string
}

func (*ChecksumMismatchError) Error

func (e *ChecksumMismatchError) Error() string

type ComparisonFilter

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

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

func (*ComparisonFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for a comparison filter.

type ComputedFilter

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

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
}

func (*ComputedFilter) ToPatterns

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

ToPatterns generates TypeQL let-assignment and comparison patterns.

type Conn

Conn is the interface for a TypeDB connection.

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
}

type ConnPool

ConnPool manages a pool of database connections for concurrent access.

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

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

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

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

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

func (db *Database) BeginContext(ctx context.Context, txType TransactionType) (*TransactionContext, error)

BeginContext starts a new TransactionContext with a ctx-aware transaction open. 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. If Commit fails, the underlying transaction has already been consumed by the driver and cannot be rolled back or reused.

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.

func (*Database) TransactionContext

func (db *Database) TransactionContext(ctx context.Context, txType TransactionType) (Tx, error)

TransactionContext opens a new transaction of the specified type and lets context-aware Conn implementations honor cancellation while acquiring it.

type DeleteOption

DeleteOption configures delete behavior.

type DeleteOption func(*deleteConfig)

func WithStrict

func WithStrict() DeleteOption

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

type Entity

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

type ExistsFilter

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

type ExistsFilter struct {
    Attr    string
    Negated bool
}

func (*ExistsFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for an existence filter.

type FetchBuilder

FetchBuilder generates fetch clauses for a model kind.

type FetchBuilder interface {
    // BuildFetchAll generates a fetch clause for all attributes of the type.
    BuildFetchAll(info *ModelInfo, varName string) (string, error)
    // BuildFetchAllWithType generates a fetch clause that includes the type label.
    BuildFetchAllWithType(info *ModelInfo, varName string) (string, error)
    // BuildFetchWithRoles generates a fetch clause including role player data for relations.
    BuildFetchWithRoles(info *ModelInfo, varName string) (matchAdditions string, fetchClause string, err error)
}

type FieldInfo

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

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

type FieldTag

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

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
}

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

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

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
}

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

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

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

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

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

func NewFunctionQuery

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

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

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

func (*FunctionQuery) ArgRaw

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

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

func (*FunctionQuery) Build

func (fq *FunctionQuery) Build() string

Build returns the TypeQL query string for calling the function.

func (*FunctionQuery) Execute

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

Execute runs the function query and returns the raw results.

type GroupByQuery

GroupByQuery groups results by an attribute and supports aggregate operations.

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

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

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

type HydrationError struct {
    TypeName string
    Field    string
    Cause    error
}

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

IIDFilter matches by internal ID.

type IIDFilter struct {
    IID string
}

func (*IIDFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for an IID filter.

type IIDInFilter

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

type IIDInFilter struct {
    IIDs []string
}

func (*IIDInFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for matching multiple IIDs.

type InFilter

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

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

func (*InFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for a set membership filter.

type InsertBuilder

InsertBuilder generates write-oriented TypeQL clauses for a model kind.

type InsertBuilder interface {
    // BuildInsertQuery generates a TypeQL insert statement for an instance.
    BuildInsertQuery(info *ModelInfo, instance any, varName string) (string, error)
    // BuildPutQuery generates a TypeQL put (upsert) statement for an instance.
    BuildPutQuery(info *ModelInfo, instance any, varName string) (string, error)
}

type InvalidIdentifierError

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

type InvalidIdentifierError struct {
    Name    string
    Context string
    Reason  string
}

func (*InvalidIdentifierError) Error

func (e *InvalidIdentifierError) Error() string

type KeyAttributeError

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

type KeyAttributeError struct {
    EntityType string
    FieldName  string
    Operation  string
}

func (*KeyAttributeError) Error

func (e *KeyAttributeError) Error() string

Error returns the error message for KeyAttributeError.

type Manager

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

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

func MustNewManager

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

MustNewManager creates a new Manager for the model type T and panics if the type has not been registered. Prefer NewManager when the caller needs to handle registration failures explicitly.

func MustNewManagerWithTx

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

MustNewManagerWithTx creates a Manager bound to an existing transaction context and panics if the model type has not been registered.

func NewManager

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

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], error)

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 MatchBuilder

MatchBuilder generates match clauses for a model kind.

type MatchBuilder interface {
    // BuildMatchByKey generates a match clause based on the model's key attributes.
    BuildMatchByKey(info *ModelInfo, instance any, varName string) (string, error)
    // BuildMatchByIID generates a match clause based on the internal instance ID.
    BuildMatchByIID(iid string, varName string) (string, error)
    // BuildMatchAll generates a match clause for all instances of the type.
    BuildMatchAll(info *ModelInfo, varName string) (string, error)
    // BuildMatchAllStrict generates a strict match clause using isa!.
    BuildMatchAllStrict(info *ModelInfo, varName string) (string, error)
}

type MigrateOption

MigrateOption configures migration behavior.

type MigrateOption func(*migrateConfig)

func WithDestructive

func WithDestructive() MigrateOption

WithDestructive enables destructive migration (removals).

type MigrationError

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

type MigrationError struct {
    Operation string
    Cause     error
}

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

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

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
}

type MigrationState

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

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

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

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

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

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

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

type ModelKind int

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

type ModelStrategy

ModelStrategy composes the query builders needed for a model kind.

type ModelStrategy interface {
    InsertBuilder
    MatchBuilder
    FetchBuilder
}

type ModifyOwnership

ModifyOwnership represents changing annotations on an existing owns clause.

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

func (ModifyOwnership) IsDestructive

func (op ModifyOwnership) IsDestructive() bool

func (ModifyOwnership) IsReversible

func (op ModifyOwnership) IsReversible() bool

func (ModifyOwnership) RollbackTypeQL

func (op ModifyOwnership) RollbackTypeQL() string

func (ModifyOwnership) ToTypeQL

func (op ModifyOwnership) ToTypeQL() string

type NotFilter

NotFilter negates a filter expression.

type NotFilter struct {
    Inner Filter
}

func (*NotFilter) ToPatterns

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

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

type NotFoundError

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

type NotFoundError struct {
    TypeName string
}

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error returns the error message for NotFoundError.

type NotRegisteredError

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

type NotRegisteredError struct {
    TypeName string
}

func (*NotRegisteredError) Error

func (e *NotRegisteredError) Error() string

Error returns the error message for NotRegisteredError.

type NotUniqueError

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

type NotUniqueError struct {
    TypeName string
    Count    int
}

func (*NotUniqueError) Error

func (e *NotUniqueError) Error() string

Error returns the error message for NotUniqueError.

type Operation

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

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
}

type OrFilter

OrFilter combines alternatives with OR (disjunction).

type OrFilter struct {
    Filters []Filter
}

func (*OrFilter) ToPatterns

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

ToPatterns generates TypeQL or-branch patterns with scoped variables.

type OrderClause

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

type OrderClause struct {
    Attr string
    Desc bool
}

type OwnsChange

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

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

type PoolConfig

PoolConfig specifies connection pool behavior.

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
}

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns a reasonable default pool configuration.

type PoolStats

PoolStats provides statistics about the connection pool.

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
}

type Query

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

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

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.

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

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

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

func (*RangeFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for a range filter.

type RegexFilter

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

type RegexFilter struct {
    Attr    string
    Pattern string
    Negated bool
}

func (*RegexFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for a regex filter.

type Registry

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

type RelatesChange

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

type RelatesChange struct {
    TypeName string
    Role     string
    Card     string
}

type Relation

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

type RemoveAttribute

RemoveAttribute removes an attribute type.

type RemoveAttribute struct {
    Name string
}

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

RemoveEntity removes an entity type.

type RemoveEntity struct {
    Name string
}

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

RemoveOwnership removes an owns clause from a type.

type RemoveOwnership struct {
    Owner     string
    Attribute string
}

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

RemoveRelation removes a relation type.

type RemoveRelation struct {
    Name string
}

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

RemoveRole removes a relates clause from a relation type.

type RemoveRole struct {
    Relation string
    Role     string
}

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

RemoveRolePlayer removes a plays clause from an entity type.

type RemoveRolePlayer struct {
    Entity   string
    Relation string
    Role     string
}

func (RemoveRolePlayer) IsDestructive

func (op RemoveRolePlayer) IsDestructive() bool

func (RemoveRolePlayer) IsReversible

func (op RemoveRolePlayer) IsReversible() bool

func (RemoveRolePlayer) RollbackTypeQL

func (op RemoveRolePlayer) RollbackTypeQL() string

func (RemoveRolePlayer) ToTypeQL

func (op RemoveRolePlayer) ToTypeQL() string

type RenameAttribute

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.

type RenameAttribute struct {
    OldName   string
    NewName   string
    ValueType string
}

func (RenameAttribute) IsDestructive

func (op RenameAttribute) IsDestructive() bool

func (RenameAttribute) IsReversible

func (op RenameAttribute) IsReversible() bool

func (RenameAttribute) RollbackTypeQL

func (op RenameAttribute) RollbackTypeQL() string

func (RenameAttribute) ToTypeQL

func (op RenameAttribute) ToTypeQL() string

type ReservedWordError

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

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

func (*ReservedWordError) Error

func (e *ReservedWordError) Error() string

Error returns the error message for ReservedWordError.

type RoleInfo

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

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
}

type RolePlayerFilter

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

type RolePlayerFilter struct {
    RoleName string
    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

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

type RunTypeQL struct {
    Up   string
    Down string
}

func (RunTypeQL) IsDestructive

func (op RunTypeQL) IsDestructive() bool

func (RunTypeQL) IsReversible

func (op RunTypeQL) IsReversible() bool

func (RunTypeQL) RollbackTypeQL

func (op RunTypeQL) RollbackTypeQL() string

func (RunTypeQL) ToTypeQL

func (op RunTypeQL) ToTypeQL() string

type SchemaConflictError

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

type SchemaConflictError struct {
    TypeName string
    Change   string
}

func (*SchemaConflictError) Error

func (e *SchemaConflictError) Error() string

Error returns the error message for SchemaConflictError.

type SchemaDiff

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

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
}

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

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

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

type SchemaValidationError struct {
    TypeName string
    Message  string
}

func (*SchemaValidationError) Error

func (e *SchemaValidationError) Error() string

Error returns the error message for SchemaValidationError.

type SeqMigrationError

SeqMigrationError is returned when a sequential migration fails.

type SeqMigrationError struct {
    Name  string
    Cause error
}

func (*SeqMigrationError) Error

func (e *SeqMigrationError) Error() string

Error returns the error message.

func (*SeqMigrationError) Unwrap

func (e *SeqMigrationError) Unwrap() error

Unwrap returns the underlying cause.

type SeqMigrationInfo

SeqMigrationInfo describes the status of a single migration.

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

func SeqMigrationStatus

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

SeqMigrationStatus returns the status of all provided migrations.

type SeqMigrationOption

SeqMigrationOption configures RunSequentialMigrations.

type SeqMigrationOption func(*seqMigrationOptions)

func WithSeqDryRun

func WithSeqDryRun() SeqMigrationOption

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

func WithSeqLogger

func WithSeqLogger(fn func(string)) SeqMigrationOption

WithSeqLogger sets a callback for migration progress messages.

func WithSeqTarget

func WithSeqTarget(name string) SeqMigrationOption

WithSeqTarget stops migration after applying the named migration.

type SeqValidationIssue

SeqValidationIssue describes a problem found during migration validation.

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

func ValidateSequentialMigrations

func ValidateSequentialMigrations(migrations []SequentialMigration) []SeqValidationIssue

ValidateSequentialMigrations checks migrations for structural issues without touching the database.

type SequentialMigration

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

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
}

func TQLMigration

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

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

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

func (*StringFilter) ToPatterns

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

ToPatterns generates TypeQL patterns for a string filter.

type SyncSchemaOption

SyncSchemaOption configures SyncSchema behavior.

type SyncSchemaOption func(*syncSchemaConfig)

func WithForce

func WithForce() SyncSchemaOption

WithForce enables destructive changes (removing types/attributes).

func WithSkipIfExists

func WithSkipIfExists() SyncSchemaOption

WithSkipIfExists skips the migration if the schema already matches.

type TQLStatements

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

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

type TransactionContext

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

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

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

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

type TransactionType int

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

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

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
}

type TypeChange

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

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

Generated by gomarkdoc