Documentation
¶
Overview ¶
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
- func ExtractAnnotations(input string) map[string]map[string]string
- func Render(w io.Writer, schema *ParsedSchema, cfg RenderConfig) error
- func RenderDTO(w io.Writer, data *DTOData) error
- func RenderLeafConstants(w io.Writer, schema *ParsedSchema, cfg LeafConstantsConfig) error
- func RenderRegistry(w io.Writer, data *RegistryData) error
- func ToPascalCase(name string) string
- func ToPascalCaseAcronyms(name string) string
- func ToSnakeCase(name string) string
- type Annotation
- type AsClause
- type AttrDef
- type AttributeSpec
- type BaseStructConfig
- type CardAnnot
- type CompositeEntityConfig
- type DTOConfig
- type DTOData
- type EntityClause
- type EntityDef
- type EntityFieldOverride
- type EntitySpec
- type EnumCtx
- type EnumValueCtx
- type FunBodyTok
- type FunDef
- type FunctionSpec
- type JSONSchemaCtx
- type JSONSchemaPropCtx
- type KVCtx
- type KVMapCtx
- type KVSliceCtx
- type LeafConstantsConfig
- type OwnsDef
- type OwnsSpec
- type ParameterSpec
- type ParsedSchema
- type PlaysDef
- type PlaysSpec
- type RangeAnnot
- type RegexAnnot
- type RegistryConfig
- type RegistryData
- type RelSchemaCtx
- type RelatesDef
- type RelatesSpec
- type RelationClause
- type RelationDef
- type RelationSpec
- type RenderConfig
- type RoleCtx
- type SimpleDef
- type StructDefP
- type StructFieldP
- type StructFieldSpec
- type StructSpec
- type SubClause
- type TQLFileSimple
- type TypeConstCtx
- type ValuesAnnot
Constants ¶
This section is empty.
Variables ¶
var CommonAcronyms = map[string]string{
"id": "ID",
"url": "URL",
"uuid": "UUID",
"api": "API",
"http": "HTTP",
"iid": "IID",
"nf": "NF",
}
CommonAcronyms defines a set of common abbreviations that should be fully uppercased when generating Go names.
Functions ¶
func ExtractAnnotations ¶
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 RenderLeafConstants ¶ added in v1.3.0
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 ¶ added in v1.2.0
func RenderRegistry(w io.Writer, data *RegistryData) error
RenderRegistry writes a complete schema registry Go file from RegistryData.
func ToPascalCase ¶
ToPascalCase transforms a kebab-case or snake_case string into PascalCase.
func ToPascalCaseAcronyms ¶
ToPascalCaseAcronyms transforms a string into PascalCase while preserving the casing of common Go acronyms.
func ToSnakeCase ¶
ToSnakeCase transforms a kebab-case string into snake_case.
Types ¶
type Annotation ¶
type Annotation struct {
Key bool `parser:" @'@key'"`
Unique bool `parser:"| @'@unique'"`
Card *CardAnnot `parser:"| @@"`
Regex *RegexAnnot `parser:"| @@"`
Values *ValuesAnnot `parser:"| @@"`
Range *RangeAnnot `parser:"| @@"`
}
Annotation parses: @key, @unique, @abstract, @card(...), @regex(...), @values(...), @range(...)
type AsClause ¶
type AsClause struct {
Parent string `parser:"'as' @Ident"`
}
AsClause parses: as parent-role
type AttrDef ¶
type AttrDef struct {
Name string `parser:"'attribute' @Ident ','?"`
ValueType string `parser:"'value' @Ident"`
Annots []Annotation `parser:"@@*"`
Semi string `parser:"';'"`
}
AttrDef parses: attribute name [,] value type [@constraint(...)];
type AttributeSpec ¶
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
}
AttributeSpec describes a TypeQL attribute definition.
type BaseStructConfig ¶ added in v1.3.0
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
}
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 CardAnnot ¶
type CardAnnot struct {
Expr string `parser:"'@card' '(' @CardExpr ')'"`
}
CardAnnot parses: @card(expr)
type CompositeEntityConfig ¶ added in v1.3.0
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
}
CompositeEntityConfig merges multiple entity subtypes into a single flat DTO with a Type discriminator. Useful for polymorphic API endpoints.
type DTOConfig ¶ added in v1.3.0
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
}
DTOConfig configures DTO (Data Transfer Object) code generation. DTOs generate Out/Create/Patch struct variants for HTTP API layers.
type DTOData ¶ added in v1.3.0
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
}
DTOData holds all schema-derived data for DTO code generation.
func BuildDTOData ¶ added in v1.3.0
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 EntityDef ¶
type EntityDef struct {
Name string `parser:"'entity' @Ident"`
Parent *SubClause `parser:"@@?"`
Abstract bool `parser:"@'@abstract'?"`
Comma string `parser:"','?"`
Clauses []EntityClause `parser:"( @@ ( ',' @@ )* )? ';'"`
}
EntityDef parses: entity name [sub parent] [@abstract] [, clause...];
type EntityFieldOverride ¶ added in v1.3.0
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
}
EntityFieldOverride provides per-entity, per-variant field overrides.
type EntitySpec ¶
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
}
EntitySpec describes a TypeQL entity definition.
type EnumCtx ¶ added in v1.2.0
type EnumCtx = enumCtx
EnumCtx holds enum constants derived from @values constraints.
type EnumValueCtx ¶ added in v1.2.0
type EnumValueCtx = enumValueCtx
EnumValueCtx holds a single enum constant.
type FunBodyTok ¶
type FunBodyTok struct {
Tok string `parser:"@(Ident | Keyword | Punct | String | CardExpr | AnnotKW | Var | Arrow | Operator)"`
}
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 FunDef ¶
type FunDef struct {
Name string `parser:"FunKW @Ident"`
Body []FunBodyTok `parser:"@@*"`
}
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 FunctionSpec ¶
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
}
FunctionSpec describes the signature of a TypeQL function definition.
type JSONSchemaCtx ¶ added in v1.3.0
type JSONSchemaCtx struct {
TypeName string
Properties []JSONSchemaPropCtx
Required []string
}
JSONSchemaCtx holds a JSON schema fragment for a single type.
type JSONSchemaPropCtx ¶ added in v1.3.0
JSONSchemaPropCtx describes a single property in a JSON schema fragment.
type KVCtx ¶ added in v1.2.0
type KVCtx struct {
Key, Value string
}
KVCtx is a simple key-value pair.
type KVMapCtx ¶ added in v1.3.0
KVMapCtx is a key with a map of string key-value pairs (for annotations).
type KVSliceCtx ¶ added in v1.2.0
KVSliceCtx is a key with multiple string values.
type LeafConstantsConfig ¶ added in v1.3.0
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
}
LeafConstantsConfig configures leaf constants package generation.
type OwnsDef ¶
type OwnsDef struct {
Attribute string `parser:"'owns' @Ident"`
Annots []Annotation `parser:"@@*"`
}
OwnsDef parses: owns attr-name [@key] [@unique] [@card(...)]
type OwnsSpec ¶
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
}
OwnsSpec describes an "owns attribute" clause in an entity or relation definition.
type ParameterSpec ¶
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
}
ParameterSpec describes a single parameter of a TypeQL function.
type ParsedSchema ¶
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
}
ParsedSchema holds all components extracted from a TypeQL schema file, including attribute, entity, and relation definitions, as well as functions and structs.
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 ¶
type PlaysDef struct {
Relation string `parser:"'plays' @Ident"`
Role string `parser:"':' @Ident"`
}
PlaysDef parses: plays relation:role
type PlaysSpec ¶
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
}
PlaysSpec describes a "plays relation:role" clause.
type RangeAnnot ¶
type RangeAnnot struct {
Expr string `parser:"'@range' '(' @CardExpr ')'"`
}
RangeAnnot parses: @range(expr)
type RegexAnnot ¶
type RegexAnnot struct {
Pattern string `parser:"'@regex' '(' @String ')'"`
}
RegexAnnot parses: @regex("pattern")
type RegistryConfig ¶ added in v1.2.0
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
}
RegistryConfig specifies settings for generating a schema registry.
type RegistryData ¶ added in v1.2.0
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
}
RegistryData holds all schema-derived data for registry code generation.
func BuildRegistryData ¶ added in v1.2.0
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 ¶ added in v1.2.0
RelSchemaCtx describes a relation's role schema with N roles.
type RelatesDef ¶
type RelatesDef struct {
Role string `parser:"'relates' @Ident"`
AsParent *AsClause `parser:"@@?"`
Annots []Annotation `parser:"@@*"`
}
RelatesDef parses: relates role-name [as parent-role] [@card(...)]
type RelatesSpec ¶
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
}
RelatesSpec describes a "relates role" clause in a relation definition.
type RelationClause ¶
type RelationClause struct {
Relates *RelatesDef `parser:" @@"`
Owns *OwnsDef `parser:"| @@"`
Plays *PlaysDef `parser:"| @@"`
}
RelationClause is one of: relates, owns, or plays.
type RelationDef ¶
type RelationDef struct {
Name string `parser:"'relation' @Ident"`
Parent *SubClause `parser:"@@?"`
Abstract bool `parser:"@'@abstract'?"`
Comma string `parser:"','?"`
Clauses []RelationClause `parser:"( @@ ( ',' @@ )* )? ';'"`
}
RelationDef parses: relation name [sub parent] [@abstract] [, clause...];
type RelationSpec ¶
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
}
RelationSpec describes a TypeQL relation definition.
type RenderConfig ¶
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
}
RenderConfig specifies the settings for generating Go code from a TypeQL schema.
func DefaultConfig ¶
func DefaultConfig() RenderConfig
DefaultConfig returns a standard RenderConfig with sensible defaults.
type RoleCtx ¶ added in v1.3.0
RoleCtx describes a single role in a relation: its name and which entity types can fill it.
type SimpleDef ¶
type SimpleDef struct {
Attribute *AttrDef `parser:" @@"`
Entity *EntityDef `parser:"| @@"`
Relation *RelationDef `parser:"| @@"`
Struct *StructDefP `parser:"| @@"`
Fun *FunDef `parser:"| @@"`
}
SimpleDef represents a single top-level definition within a TypeQL define block.
type StructDefP ¶
type StructDefP struct {
Name string `parser:"'struct' @Ident (':' | ',')"`
Fields []StructFieldP `parser:"@@ (',' @@)* ','? ';'"`
}
StructDefP parses: struct name (: | ,) field [, field]* [,] ; Supports both official TypeQL syntax (`:` separator, `name value type`) and legacy syntax (`,` separator, `value name type`).
type StructFieldP ¶
type StructFieldP struct {
FieldName string `parser:"( @Ident 'value' | 'value' @Ident )"`
ValueType string `parser:"@Ident"`
Optional bool `parser:"@'?'?"`
}
StructFieldP parses a struct field in either official or legacy order:
- Official: field-name value type[?]
- Legacy: value field-name type[?]
type StructFieldSpec ¶
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
}
StructFieldSpec describes a single field within a TypeQL struct.
type StructSpec ¶
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
}
StructSpec describes a TypeQL struct definition, which is a collection of named fields.
type SubClause ¶
type SubClause struct {
Parent string `parser:"'sub' @Ident"`
}
SubClause parses: sub parent-name
type TQLFileSimple ¶
type TQLFileSimple struct {
Define string `parser:"'define'"`
Definitions []SimpleDef `parser:"@@*"`
}
TQLFileSimple is the top-level grammar for a TypeQL define block.
type TypeConstCtx ¶ added in v1.2.0
TypeConstCtx holds a Go constant name and its string value.
type ValuesAnnot ¶
type ValuesAnnot struct {
Values []string `parser:"'@values' '(' @String ( ',' @String )* ')'"`
}
ValuesAnnot parses: @values("a", "b", ...)