tqlgen

April 23, 2026 ยท View on GitHub

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

Package tqlgen provides tools for parsing TypeQL schemas and generating Go code from them.

Package tqlgen provides utilities for transforming TypeDB names into Go-idiomatic names.

Package tqlgen provides code generation from TypeQL schemas.

Index

Variables

CommonAcronyms defines a set of common abbreviations that should be fully uppercased when generating Go names.

var CommonAcronyms = map[string]string{
    "id":   "ID",
    "url":  "URL",
    "uuid": "UUID",
    "api":  "API",
    "http": "HTTP",
    "iid":  "IID",
    "nf":   "NF",
}

func ExtractAnnotations

func ExtractAnnotations(input string) map[string]map[string]string

ExtractAnnotations parses comment annotations of the form "# @key value" from schema text. Returns a map of type name -> annotation map.

func Render

func Render(w io.Writer, schema *ParsedSchema, cfg RenderConfig) error

Render processes a ParsedSchema and writes the generated Go source code to the provided writer.

func RenderDTO

func RenderDTO(w io.Writer, data *DTOData) error

RenderDTO writes a DTO Go file from DTOData.

func RenderLeafConstants

func RenderLeafConstants(w io.Writer, schema *ParsedSchema, cfg LeafConstantsConfig) error

RenderLeafConstants writes a standalone leaf package containing only type, relation, and enum constants. This package has zero internal dependencies, making it safe to import from any package.

func RenderRegistry

func RenderRegistry(w io.Writer, data *RegistryData) error

RenderRegistry writes a complete schema registry Go file from RegistryData.

func ToPascalCase

func ToPascalCase(name string) string

ToPascalCase transforms a kebab-case or snake_case string into PascalCase.

func ToPascalCaseAcronyms

func ToPascalCaseAcronyms(name string) string

ToPascalCaseAcronyms transforms a string into PascalCase while preserving the casing of common Go acronyms.

func ToSnakeCase

func ToSnakeCase(name string) string

ToSnakeCase transforms a kebab-case string into snake_case.

type Annotation

Annotation parses: @key, @unique, @abstract, @card(...), @regex(...), @values(...), @range(...)

type Annotation struct {
    Key    bool         `parser:"  @'@key'"`
    Unique bool         `parser:"| @'@unique'"`
    Card   *CardAnnot   `parser:"| @@"`
    Regex  *RegexAnnot  `parser:"| @@"`
    Values *ValuesAnnot `parser:"| @@"`
    Range  *RangeAnnot  `parser:"| @@"`
}

type AsClause

AsClause parses: as parent-role

type AsClause struct {
    Parent string `parser:"'as' @Ident"`
}

type AttrDef

AttrDef parses: attribute name [,] value type [@constraint(...)];

type AttrDef struct {
    Name      string       `parser:"'attribute' @Ident ','?"`
    ValueType string       `parser:"'value' @Ident"`
    Annots    []Annotation `parser:"@@*"`
    Semi      string       `parser:"';'"`
}

type AttributeSpec

AttributeSpec describes a TypeQL attribute definition.

type AttributeSpec struct {
    // Name is the name of the attribute type.
    Name string
    // ValueType is the base value type of the attribute (string, integer, double, boolean, datetime).
    ValueType string

    // Regex is an optional regular expression constraint for the attribute values.
    Regex string
    // Values is an optional list of allowed values (enumeration constraint).
    Values []string
    // RangeOp is an optional range constraint (e.g., "1..5").
    RangeOp string
}

type BaseStructConfig

BaseStructConfig configures a shared embedded base struct for an entity hierarchy. When an entity inherits from SourceEntity, its DTOs embed the base struct instead of repeating the inherited fields.

type BaseStructConfig struct {
    // SourceEntity is the schema entity name that triggers this base struct.
    SourceEntity string
    // BaseName is the Go struct name prefix (e.g., "BaseArtifact").
    BaseName string
    // InheritedAttrs lists attribute names defined in the base struct.
    // These are skipped when rendering child entity DTOs.
    InheritedAttrs []string
    // ExtraFields adds additional fields as name โ†’ Go type annotation.
    ExtraFields map[string]string
}

type CardAnnot

CardAnnot parses: @card(expr)

type CardAnnot struct {
    Expr string `parser:"'@card' '(' @CardExpr ')'"`
}

type CompositeEntityConfig

CompositeEntityConfig merges multiple entity subtypes into a single flat DTO with a Type discriminator. Useful for polymorphic API endpoints.

type CompositeEntityConfig struct {
    // Name is the Go struct name for the composite DTO (e.g., "ArtifactDTO").
    Name string
    // Entities lists the TypeDB entity names to merge.
    Entities []string
    // TypeName is the TypeDB type name for TypeName() method (e.g., "artifact").
    TypeName string
}

type DTOConfig

DTOConfig configures DTO (Data Transfer Object) code generation. DTOs generate Out/Create/Patch struct variants for HTTP API layers.

type DTOConfig struct {
    // PackageName is the Go package name for the generated file (required).
    PackageName string
    // UseAcronyms applies Go acronym naming conventions (e.g., "ID" not "Id").
    UseAcronyms bool
    // SkipAbstract excludes abstract types from DTO generation.
    SkipAbstract bool
    // IDFieldName is the name of the ID field in Out structs (default "ID").
    IDFieldName string
    // StrictOut makes required fields non-pointer in Out structs.
    // When false (default), all attribute fields in Out are pointers for safety.
    StrictOut bool
    // ExcludeEntities lists entity names to skip during generation.
    ExcludeEntities []string
    // ExcludeRelations lists relation names to skip during generation.
    ExcludeRelations []string
    // SkipRelationOut skips generating Out structs for relations.
    SkipRelationOut bool
    // BaseStructs configures shared base structs for entity hierarchies.
    BaseStructs []BaseStructConfig
    // EntityFieldOverrides provides per-entity, per-variant field overrides.
    EntityFieldOverrides []EntityFieldOverride
    // CompositeEntities configures merged flat structs from multiple entity types.
    CompositeEntities []CompositeEntityConfig
    // EntityOutName overrides the interface name for entity Out DTOs (default "EntityOut").
    EntityOutName string
    // EntityCreateName overrides the interface name for entity Create DTOs (default "EntityCreate").
    EntityCreateName string
    // EntityPatchName overrides the interface name for entity Patch DTOs (default "EntityPatch").
    EntityPatchName string
    // RelationOutName overrides the interface name for relation Out DTOs (default "RelationOut").
    RelationOutName string
    // RelationCreateName overrides the interface name for relation Create DTOs (default "RelationCreate").
    RelationCreateName string
    // RelationCreateEmbed is a struct name to embed in all relation Create DTOs.
    RelationCreateEmbed string
}

type DTOData

DTOData holds all schema-derived data for DTO code generation.

type DTOData struct {
    PackageName string
    NeedsTime   bool
    IDFieldName string

    // Base structs (from BaseStructConfig)
    BaseStructs []baseStructDTOCtx

    // Entity DTOs
    Entities []entityDTOCtx

    // Relation DTOs
    Relations           []relationDTOCtx
    SkipRelationOut     bool
    RelationCreateEmbed string

    // Composite entity DTOs
    Composites []compositeDTOCtx

    // Union interface lists (concrete types only)
    ConcreteEntities  []string // Go type names
    ConcreteRelations []string

    // Configurable interface names
    EntityOutName      string
    EntityCreateName   string
    EntityPatchName    string
    RelationOutName    string
    RelationCreateName string
}

func BuildDTOData

func BuildDTOData(schema *ParsedSchema, cfg DTOConfig) *DTOData

BuildDTOData populates DTOData from a parsed schema. The schema should have AccumulateInheritance() called before this.

type EntityClause

EntityClause is one of: owns or plays.

type EntityClause struct {
    Owns  *OwnsDef  `parser:"  @@"`
    Plays *PlaysDef `parser:"| @@"`
}

type EntityDef

EntityDef parses: entity name [sub parent] [@abstract] [, clause...];

type EntityDef struct {
    Name     string         `parser:"'entity' @Ident"`
    Parent   *SubClause     `parser:"@@?"`
    Abstract bool           `parser:"@'@abstract'?"`
    Comma    string         `parser:"','?"`
    Clauses  []EntityClause `parser:"( @@ ( ',' @@ )* )? ';'"`
}

type EntityFieldOverride

EntityFieldOverride provides per-entity, per-variant field overrides.

type EntityFieldOverride struct {
    // Entity is the TypeDB entity name.
    Entity string
    // Field is the TypeDB attribute name.
    Field string
    // Variant is the DTO variant: "out", "create", or "patch".
    Variant string
    // Required overrides whether the field is required (non-pointer).
    // nil means keep the schema default.
    Required *bool
}

type EntitySpec

EntitySpec describes a TypeQL entity definition.

type EntitySpec struct {
    // Name is the name of the entity type.
    Name string
    // Parent is the name of the parent entity type if this is a subtype.
    Parent string
    // Abstract indicates whether the entity type is defined as abstract.
    Abstract bool

    // Owns is a list of attributes owned by this entity type.
    Owns []OwnsSpec
    // Plays is a list of relation roles this entity type can play.
    Plays []PlaysSpec
}

type EnumCtx

EnumCtx holds enum constants derived from @values constraints.

type EnumCtx = enumCtx

type EnumValueCtx

EnumValueCtx holds a single enum constant.

type EnumValueCtx = enumValueCtx

type FunBodyTok

FunBodyTok matches every token type EXCEPT FunKW. When the parser hits the next `fun`, it exits the current FunDef and starts a new one.

type FunBodyTok struct {
    Tok string `parser:"@(Ident | Keyword | Punct | String | CardExpr | AnnotKW | Var | Arrow | Operator)"`
}

type FunDef

FunDef parses: fun name <body tokens until next fun or EOF> The body is captured as a flat list of tokens for signature extraction.

type FunDef struct {
    Name string       `parser:"FunKW @Ident"`
    Body []FunBodyTok `parser:"@@*"`
}

type FunctionSpec

FunctionSpec describes the signature of a TypeQL function definition.

type FunctionSpec struct {
    // Name is the name of the function.
    Name string
    // Parameters is a list of parameters accepted by the function.
    Parameters []ParameterSpec
    // ReturnType is the TypeQL return type of the function.
    ReturnType string
}

type JSONSchemaCtx

JSONSchemaCtx holds a JSON schema fragment for a single type.

type JSONSchemaCtx struct {
    TypeName   string
    Properties []JSONSchemaPropCtx
    Required   []string
}

type JSONSchemaPropCtx

JSONSchemaPropCtx describes a single property in a JSON schema fragment.

type JSONSchemaPropCtx struct {
    Name     string
    JSONType string
}

type KVCtx

KVCtx is a simple key-value pair.

type KVCtx struct {
    Key, Value string
}

type KVMapCtx

KVMapCtx is a key with a map of string key-value pairs (for annotations).

type KVMapCtx struct {
    Key    string
    Values []KVCtx
}

type KVSliceCtx

KVSliceCtx is a key with multiple string values.

type KVSliceCtx struct {
    Key    string
    Values []string
}

type LeafConstantsConfig

LeafConstantsConfig configures leaf constants package generation.

type LeafConstantsConfig struct {
    // PackageName for the generated file (e.g. "schema").
    PackageName string
    // UseAcronyms applies Go acronym naming conventions.
    UseAcronyms bool
    // SkipAbstract excludes abstract types.
    SkipAbstract bool
}

type OwnsDef

OwnsDef parses: owns attr-name [@key] [@unique] [@card(...)]

type OwnsDef struct {
    Attribute string       `parser:"'owns' @Ident"`
    Annots    []Annotation `parser:"@@*"`
}

type OwnsSpec

OwnsSpec describes an "owns attribute" clause in an entity or relation definition.

type OwnsSpec struct {
    // Attribute is the name of the attribute type being owned.
    Attribute string
    // Key indicates whether this attribute is a key for the owner.
    Key bool
    // Unique indicates whether the attribute value must be unique across all instances.
    Unique bool
    // Card specifies the cardinality of the ownership (e.g., "0..1", "1..5").
    Card string
}

type ParameterSpec

ParameterSpec describes a single parameter of a TypeQL function.

type ParameterSpec struct {
    // Name is the name of the parameter (without the '$' prefix).
    Name string
    // TypeName is the TypeQL type name expected for this parameter.
    TypeName string
}

type ParsedSchema

ParsedSchema holds all components extracted from a TypeQL schema file, including attribute, entity, and relation definitions, as well as functions and structs.

type ParsedSchema struct {
    // Attributes is a list of all attribute definitions in the schema.
    Attributes []AttributeSpec
    // Entities is a list of all entity definitions in the schema.
    Entities []EntitySpec
    // Relations is a list of all relation definitions in the schema.
    Relations []RelationSpec
    // Functions is a list of all function signatures in the schema.
    Functions []FunctionSpec
    // Structs is a list of all struct definitions in the schema.
    Structs []StructSpec
}

func ParseSchema

func ParseSchema(input string) (*ParsedSchema, error)

ParseSchema parses a TypeQL schema string into a ParsedSchema structure. It handles attribute, entity, relation, function, and struct definitions. Function blocks are parsed by the grammar natively โ€” no pre-processing needed.

func ParseSchemaFile

func ParseSchemaFile(path string) (*ParsedSchema, error)

ParseSchemaFile reads a TypeQL schema from the specified file path and parses it.

func (*ParsedSchema) AccumulateInheritance

func (s *ParsedSchema) AccumulateInheritance()

AccumulateInheritance propagates owns/plays from parent entities/relations to their children, so each child has the complete set of fields.

type PlaysDef

PlaysDef parses: plays relation:role

type PlaysDef struct {
    Relation string `parser:"'plays' @Ident"`
    Role     string `parser:"':' @Ident"`
}

type PlaysSpec

PlaysSpec describes a "plays relation:role" clause.

type PlaysSpec struct {
    // Relation is the name of the relation type.
    Relation string
    // Role is the name of the role played by the owner within that relation.
    Role string
}

type RangeAnnot

RangeAnnot parses: @range(expr)

type RangeAnnot struct {
    Expr string `parser:"'@range' '(' @CardExpr ')'"`
}

type RegexAnnot

RegexAnnot parses: @regex("pattern")

type RegexAnnot struct {
    Pattern string `parser:"'@regex' '(' @String ')'"`
}

type RegistryConfig

RegistryConfig specifies settings for generating a schema registry.

type RegistryConfig struct {
    // PackageName is the Go package name for the generated code (required).
    PackageName string
    // UseAcronyms applies Go acronym naming conventions (e.g., "ID" not "Id").
    UseAcronyms bool
    // SkipAbstract excludes abstract types from entity/relation constants and EntityAttributes.
    SkipAbstract bool
    // Enums generates string constants from @values constraints.
    Enums bool
    // TypePrefix is the prefix for entity type constants (default "Type").
    TypePrefix string
    // RelPrefix is the prefix for relation type constants (default "Rel").
    RelPrefix string
    // SchemaText is the raw schema source. If non-empty, a SHA256-based SchemaHash is computed
    // and annotations are extracted from comments.
    SchemaText string
    // SchemaVersion is a user-provided version string emitted as a constant.
    SchemaVersion string
    // TypedConstants generates typed string constants (type EntityType string, etc.)
    // for compile-time safety instead of plain string constants.
    TypedConstants bool
    // JSONSchema generates JSON schema fragment maps for each entity/relation type.
    JSONSchema bool
}

type RegistryData

RegistryData holds all schema-derived data for registry code generation.

type RegistryData struct {
    PackageName       string
    EntityConstants   []TypeConstCtx
    RelationConstants []TypeConstCtx
    Enums             []EnumCtx
    EntityParents     []KVCtx
    EntityAttributes  []KVSliceCtx
    AttrValueTypes    []KVCtx
    AttrEnumValues    []KVSliceCtx
    RelationSchema    []RelSchemaCtx
    RelationAttrs     []KVSliceCtx
    AllEntityTypes    []string
    AllRelationTypes  []string
    // Metadata fields
    EntityKeys       []KVSliceCtx
    EntityAbstract   []string
    RelationAbstract []string
    RelationParents  []KVCtx
    SchemaHash       string
    SchemaVersion    string
    AttributeTypes   []string

    // Annotations from schema comments (# @key value)
    EntityAnnotations    []KVMapCtx
    AttributeAnnotations []KVMapCtx
    RelationAnnotations  []KVMapCtx

    // Typed constants (StrEnum-style)
    TypedConstants         bool
    AttributeTypeConstants []TypeConstCtx

    // JSON schema fragments
    JSONSchema       bool
    EntityJSONSchema []JSONSchemaCtx
}

func BuildRegistryData

func BuildRegistryData(schema *ParsedSchema, cfg RegistryConfig) *RegistryData

BuildRegistryData populates a RegistryData from a parsed schema. The schema should have AccumulateInheritance() called before this.

type RelSchemaCtx

RelSchemaCtx describes a relation's role schema with N roles.

type RelSchemaCtx struct {
    Name  string
    Roles []RoleCtx
}

type RelatesDef

RelatesDef parses: relates role-name [as parent-role] [@card(...)]

type RelatesDef struct {
    Role     string       `parser:"'relates' @Ident"`
    AsParent *AsClause    `parser:"@@?"`
    Annots   []Annotation `parser:"@@*"`
}

type RelatesSpec

RelatesSpec describes a "relates role" clause in a relation definition.

type RelatesSpec struct {
    // Role is the name of the role in the relation.
    Role string
    // AsParent specifies an overridden role from a parent relation type.
    AsParent string
    // Card specifies the cardinality of players allowed for this role.
    Card string
}

type RelationClause

RelationClause is one of: relates, owns, or plays.

type RelationClause struct {
    Relates *RelatesDef `parser:"  @@"`
    Owns    *OwnsDef    `parser:"| @@"`
    Plays   *PlaysDef   `parser:"| @@"`
}

type RelationDef

RelationDef parses: relation name [sub parent] [@abstract] [, clause...];

type RelationDef struct {
    Name     string           `parser:"'relation' @Ident"`
    Parent   *SubClause       `parser:"@@?"`
    Abstract bool             `parser:"@'@abstract'?"`
    Comma    string           `parser:"','?"`
    Clauses  []RelationClause `parser:"( @@ ( ',' @@ )* )? ';'"`
}

type RelationSpec

RelationSpec describes a TypeQL relation definition.

type RelationSpec struct {
    // Name is the name of the relation type.
    Name string
    // Parent is the name of the parent relation type if this is a subtype.
    Parent string
    // Abstract indicates whether the relation type is defined as abstract.
    Abstract bool

    // Relates is a list of roles involved in this relation.
    Relates []RelatesSpec
    // Owns is a list of attributes owned by this relation type.
    Owns []OwnsSpec
    // Plays is a list of relation roles this relation type can play.
    Plays []PlaysSpec
}

type RenderConfig

RenderConfig specifies the settings for generating Go code from a TypeQL schema.

type RenderConfig struct {
    // PackageName is the name of the Go package for the generated code.
    PackageName string
    // ModulePath is the module import path for the 'gotype' package.
    ModulePath string
    // UseAcronyms, if true, applies Go acronym naming conventions (e.g., 'ID' instead of 'Id').
    UseAcronyms bool
    // SkipAbstract, if true, excludes abstract TypeDB types from the generated Go code.
    SkipAbstract bool
    // SchemaVersion is an optional string included in the generated file header.
    SchemaVersion string
    // Enums, if true, generates string constants from @values constraints on attributes.
    Enums bool
}

func DefaultConfig

func DefaultConfig() RenderConfig

DefaultConfig returns a standard RenderConfig with sensible defaults.

type RoleCtx

RoleCtx describes a single role in a relation: its name and which entity types can fill it.

type RoleCtx struct {
    RoleName    string
    PlayerTypes []string
    Card        string // e.g. "1", "0..", "1.."
}

type SimpleDef

SimpleDef represents a single top-level definition within a TypeQL define block.

type SimpleDef struct {
    Attribute *AttrDef     `parser:"  @@"`
    Entity    *EntityDef   `parser:"| @@"`
    Relation  *RelationDef `parser:"| @@"`
    Struct    *StructDefP  `parser:"| @@"`
    Fun       *FunDef      `parser:"| @@"`
}

type StructDefP

StructDefP parses: struct name (: | ,) field [, field]* [,] ; Supports both official TypeQL syntax (`:` separator, `name value type`) and legacy syntax (`,` separator, `value name type`).

type StructDefP struct {
    Name   string         `parser:"'struct' @Ident (':' | ',')"`
    Fields []StructFieldP `parser:"@@ (',' @@)* ','? ';'"`
}

type StructFieldP

StructFieldP parses a struct field in either official or legacy order:

  • Official: field-name value type[?]
  • Legacy: value field-name type[?]
type StructFieldP struct {
    FieldName string `parser:"( @Ident 'value' | 'value' @Ident )"`
    ValueType string `parser:"@Ident"`
    Optional  bool   `parser:"@'?'?"`
}

type StructFieldSpec

StructFieldSpec describes a single field within a TypeQL struct.

type StructFieldSpec struct {
    // Name is the name of the field.
    Name string
    // ValueType is the TypeQL type of the field's value.
    ValueType string
    // Optional indicates whether the field is marked as optional in the schema.
    Optional bool
}

type StructSpec

StructSpec describes a TypeQL struct definition, which is a collection of named fields.

type StructSpec struct {
    // Name is the name of the struct type.
    Name string
    // Fields is a list of fields defined within the struct.
    Fields []StructFieldSpec
}

type SubClause

SubClause parses: sub parent-name

type SubClause struct {
    Parent string `parser:"'sub' @Ident"`
}

type TQLFileSimple

TQLFileSimple is the top-level grammar for a TypeQL define block.

type TQLFileSimple struct {
    Define      string      `parser:"'define'"`
    Definitions []SimpleDef `parser:"@@*"`
}

type TypeConstCtx

TypeConstCtx holds a Go constant name and its string value.

type TypeConstCtx struct {
    Name  string // e.g. "TypePersona"
    Value string // e.g. "persona"
}

type ValuesAnnot

ValuesAnnot parses: @values("a", "b", ...)

type ValuesAnnot struct {
    Values []string `parser:"'@values' '(' @String ( ',' @String )* ')'"`
}

Generated by gomarkdoc