type_bridge.generator¶
generator
¶
TypeBridge code generator - Generate Python models from TypeDB schemas.
This module provides tools to parse TypeDB TQL schema files and generate corresponding type-bridge Python model classes.
Example usage:
from type_bridge.generator import generate_models
# Generate from a schema file
generate_models("schema.tql", "myapp/models/")
# Or from schema text
schema_text = '''
define
entity person,
owns name @key;
attribute name, value string;
'''
generate_models(schema_text, "myapp/models/")
The generated package structure:
myapp/models/
├── __init__.py # Package exports, ATTRIBUTES/ENTITIES/RELATIONS lists
├── attributes.py # Attribute class definitions
├── entities.py # Entity class definitions
├── relations.py # Relation class definitions
└── schema.tql # Copy of the source schema
BaseClassConfig
dataclass
¶
BaseClassConfig(source_entity, base_name, inherited_attrs=list(), extra_fields=dict(), field_syncs=list(), validators=list(), create_field_overrides=dict())
Configuration for a custom base class in the DTO hierarchy.
When an entity inherits from source_entity in the schema, its DTOs
will inherit from the custom base class instead of the default.
Attributes:
| Name | Type | Description |
|---|---|---|
source_entity |
str
|
The schema entity name that triggers this base class (e.g., "artifact"). Entities that inherit from this entity will use the custom base. |
base_name |
str
|
The base class name prefix (e.g., "BaseArtifact"). Will generate BaseArtifactOut, BaseArtifactCreate, BaseArtifactPatch. |
inherited_attrs |
list[str]
|
Attribute names that are defined in the base class. These will be skipped when rendering child DTOs to avoid duplication. |
extra_fields |
dict[str, str]
|
Additional fields to add to the base class. Keys are field names, values are type annotations as strings. |
field_syncs |
list[FieldSyncConfig]
|
Field sync configurations for this base class. |
validators |
list[str]
|
List of validator names to apply to fields in this base. |
Example
BaseClassConfig( source_entity="artifact", base_name="BaseArtifact", inherited_attrs=["display_id", "name", "description", "status"], extra_fields={"version": "int | None = None"}, field_syncs=[FieldSyncConfig("description", "content")], )
CompositeEntityConfig
dataclass
¶
CompositeEntityConfig(name, base_entity=None, include_entities=list(), exclude_entities=list(), common_fields=list(), field_syncs=list(), extra_fields=dict(), extra_fields_out=dict(), skip_variants=set(), id_field_name='id', type_field_name='type', type_enum_from_registry=True)
Configuration for a composite/flat DTO that merges multiple entity types.
Composite DTOs provide a polymorphic API where a single DTO class handles multiple entity types. This is useful for graph APIs where you want one endpoint to handle all node types.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name prefix for the composite (e.g., "GraphNode" generates GraphNodeOut, GraphNodeCreate, GraphNodePatch) |
base_entity |
str | None
|
Schema entity name - all entities inheriting from this will be included in the composite (e.g., "artifact") |
include_entities |
list[str]
|
Explicit list of entity names to include. Use this OR base_entity, not both. |
exclude_entities |
list[str]
|
Entity names to exclude (useful with base_entity) |
common_fields |
list[CompositeFieldConfig]
|
Fields that appear on all variants with specified types. These are required (or have defaults) in Create, present in Out/Patch. |
field_syncs |
list[FieldSyncConfig]
|
Field sync configurations for the composite |
extra_fields |
dict[str, str]
|
Additional fields not in schema (e.g., computed fields). Applied to all variants (Out, Create, Patch) unless overridden. |
extra_fields_out |
dict[str, str]
|
Per-variant override for extra_fields on Out DTOs.
If a field name appears here, the Out variant uses this annotation
instead of the one from extra_fields. Useful when Out fields have
different requiredness (e.g., |
skip_variants |
set[str]
|
Set of variant names to skip generating (e.g.,
|
id_field_name |
str
|
Name of the ID field (default: "id") |
type_field_name |
str
|
Name of the type discriminator field (default: "type") |
type_enum_from_registry |
bool
|
If True, generate dynamic enum from registry |
Example
CompositeEntityConfig( name="GraphNode", base_entity="artifact", exclude_entities=["design_aspect"], common_fields=[ CompositeFieldConfig("name", "str"), CompositeFieldConfig("content", "str", "''"), CompositeFieldConfig("status", "str", "'proposed'"), ], field_syncs=[FieldSyncConfig("description", "content")], extra_fields={"version": "int | None = None"}, )
get_included_entities
¶
Get list of entity names included in this composite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema_entities
|
dict[str, Any]
|
Dict of entity name -> EntitySpec from parsed schema |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of entity names to include in the composite |
Source code in type_bridge/generator/dto_config.py
CompositeFieldConfig
dataclass
¶
Configuration for a field in a composite entity DTO.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Field name in Python (snake_case) |
type_annotation |
str
|
Python type annotation as string (e.g., "str", "int | None") |
default |
str | None
|
Default value as string (e.g., "None", "'proposed'", "''") If None, field is required in Create DTOs. |
description |
str | None
|
Optional field description for documentation |
Example
CompositeFieldConfig( name="status", type_annotation="str", default="'proposed'", description="Lifecycle status" )
DTOConfig
dataclass
¶
DTOConfig(base_classes=list(), validators=list(), preamble=None, entity_union_name='Entity', relation_union_name='Relation', exclude_entities=list(), iid_field_name='iid', skip_relation_output=False, relation_create_base_class=None, relation_preamble=None, composite_entities=list(), strict_out_models=False, entity_field_overrides=list())
Configuration for API DTO generation.
This configuration controls how Pydantic DTOs are generated from a
TypeDB schema. It allows customization of base classes, validators,
field syncs, and naming conventions.
Attributes:
base_classes: Custom base class configurations for entity hierarchies.
validators: Custom validator type configurations.
preamble: Custom Python code to inject at the top of the file
(after imports). Use for complex validators or helper functions.
entity_union_name: Name for the entity union type (default: "Entity").
relation_union_name: Name for the relation union type (default: "Relation").
exclude_entities: Entity names to exclude from generation (e.g., internal
utility entities like "display_id_counter").
iid_field_name: Field name for TypeDB IID in output DTOs (default: "iid").
Set to "id" for more conventional REST API naming.
skip_relation_output: If True, don't generate XxxOut classes for relations.
Use with relation_preamble to define custom output classes.
relation_create_base_class: Name of custom base class for relation Create
DTOs (must be defined in preamble). If set, relation Create classes
won't generate role-specific fields, only owned attributes.
relation_preamble: Custom Python code to inject in the relation section.
Use for custom relation output classes like GraphEdgeOut.
composite_entities: Composite entity configurations for creating flat/merged
DTOs that handle multiple entity types in one class.
strict_out_models: If True, fields with @key or min>=1 cardinality will be
required (not Optional) in Out DTOs. Default False for safety.
Example:
config = DTOConfig(
base_classes=[
BaseClassConfig(
source_entity="artifact",
base_name="BaseArtifact",
inherited_attrs=["display_id", "name"],
),
],
validators=[
ValidatorConfig(name="DisplayId", pattern=r"^[A-Z]{1,10}-\d+$"),
],
exclude_entities=["display_id_counter", "schema_status"],
iid_field_name="id",
preamble='''
Custom node ID validator¶
def _validate_node_id(value: str) -> str: # Complex validation logic here return value
NodeId = Annotated[str, AfterValidator(_validate_node_id)] ''', )
get_base_class_for_entity
¶
Find the base class config for an entity based on inheritance.
Walks up the inheritance chain to find if this entity or any ancestor matches a configured base class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_name
|
str
|
The entity name to check |
required |
schema_entities
|
dict[str, Any]
|
Dict of entity name -> EntitySpec from parsed schema |
required |
Returns:
| Type | Description |
|---|---|
BaseClassConfig | None
|
The matching BaseClassConfig, or None if no match |
Source code in type_bridge/generator/dto_config.py
EntityFieldOverride
dataclass
¶
Per-entity, per-variant field override.
Allows targeting a specific entity + field + variant combination.
Attributes:
| Name | Type | Description |
|---|---|---|
entity |
str
|
TypeDB entity name (e.g., |
field |
str
|
TypeDB attribute name (e.g., |
variant |
str
|
DTO variant to override ( |
required |
bool | None
|
Override requiredness. |
default |
str | None
|
Override default value as a Python literal string.
|
FieldOverride
dataclass
¶
Per-variant override for a single field's requiredness or default.
Use this inside BaseClassConfig.create_field_overrides to make a
normally-required field optional (or vice-versa) on a specific DTO variant.
Attributes:
| Name | Type | Description |
|---|---|---|
required |
bool | None
|
Override requiredness. |
default |
str | None
|
Override default value as a Python literal string
(e.g., |
FieldSyncConfig
dataclass
¶
Configuration for syncing two fields in a model validator.
When one field is set but not the other, the value is copied.
Attributes:
| Name | Type | Description |
|---|---|---|
field_a |
str
|
First field name |
field_b |
str
|
Second field name |
Example
FieldSyncConfig(field_a="description", field_b="content")
Generates a model_validator that syncs description <-> content¶
ValidatorConfig
dataclass
¶
Configuration for a custom Pydantic validator type.
Validators are rendered as Annotated types with AfterValidator.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The validator type name (e.g., "DisplayId") |
pattern |
str | None
|
Regex pattern for validation (optional).
For complex validators that need more than a regex pattern,
use |
Example
ValidatorConfig(name="DisplayId", pattern=r"^[A-Z]{1,10}-\d+$")
Generates:¶
def _validate_display_id(value: str) -> str:¶
if not re.match(r"^[A-Z]{1,10}-\d+$", value):¶
raise ValueError(...)¶
return value¶
DisplayId = Annotated[str, AfterValidator(_validate_display_id)]¶
ParsedSchema
dataclass
¶
ParsedSchema(attributes=dict(), entities=dict(), relations=dict(), functions=dict(), structs=dict())
Container for all parsed schema components.
This is the main output of the parser and input to the renderers.
accumulate_inheritance
¶
parse_tql_schema
¶
Parse a TQL schema string into a :class:ParsedSchema.
Uses the Rust TypeSchema parser when available for speed, falling
back to the Lark-based parser otherwise. Annotations and docstrings
(extracted from comments) are always applied on the Python side.
Source code in type_bridge/generator/parser.py
generate_models
¶
generate_models(schema, output_dir, *, implicit_key_attributes=None, schema_version='1.0.0', copy_schema=True, schema_path=None, generate_dto=False, dto_config=None)
Generate TypeBridge models from a TypeDB schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
|
str | Path
|
Either a path to a .tql file, or the schema text directly |
required |
output_dir
|
str | Path
|
Directory to write the generated package to |
required |
implicit_key_attributes
|
Iterable[str] | None
|
Attribute names to treat as @key even if not marked |
None
|
schema_version
|
str
|
Version string for SCHEMA_VERSION constant |
'1.0.0'
|
copy_schema
|
bool
|
Whether to copy the schema file to the output directory |
True
|
schema_path
|
str | Path | None
|
Custom path for the schema file. If relative, resolved against output_dir. If None and copy_schema=True, uses "schema.tql" in output_dir. |
None
|
generate_dto
|
bool
|
Whether to generate Pydantic API DTOs |
False
|
dto_config
|
DTOConfig | None
|
Configuration for DTO generation (custom base classes, validators, etc.) |
None
|
Source code in type_bridge/generator/__init__.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |