Skip to content

type_bridge.generator.models

models

Data structures describing a parsed TypeDB schema.

These models represent the intermediate representation (IR) between raw TQL and generated Python code. They capture all schema information needed for code generation while abstracting away TQL syntax details.

Cardinality dataclass

Cardinality(min, max)

Cardinality constraint from @card annotation.

Examples:

@card(0..1) -> Cardinality(0, 1) - optional single @card(1) -> Cardinality(1, 1) - required single @card(0..) -> Cardinality(0, None) - optional multi @card(1..) -> Cardinality(1, None) - required multi @card(1..3) -> Cardinality(1, 3) - bounded multi

is_required property

is_required

True if at least one value is required.

is_single property

is_single

True if at most one value is allowed.

is_multi property

is_multi

True if multiple values are allowed.

is_optional_single property

is_optional_single

True if zero or one value (the default).

AttributeSpec dataclass

AttributeSpec(name, value_type, parent=None, abstract=False, independent=False, regex=None, allowed_values=None, range_min=None, range_max=None, docstring=None, annotations=dict(), default=None, transform=None, case=None)

Attribute definition extracted from a TypeDB schema.

Attributes:

Name Type Description
name str

The TypeDB attribute name (e.g., "isbn-13")

value_type str

The TypeDB value type (string, integer, double, etc.)

parent str | None

Parent attribute name for inheritance (sub)

abstract bool

Whether this is an abstract attribute

independent bool

Whether this is an independent attribute (@independent)

regex str | None

Regex constraint from @regex annotation

allowed_values tuple[str, ...] | None

Enum values from @values annotation

range_min str | None

Minimum value from @range annotation

range_max str | None

Maximum value from @range annotation

docstring str | None

Documentation extracted from comments

annotations dict[str, AnnotationValue]

Custom annotations from TQL comments (e.g., # @default(new))

EntitySpec dataclass

EntitySpec(name, parent=None, owns=set(), owns_order=list(), plays=set(), abstract=False, keys=set(), uniques=set(), cascades=set(), subkeys=dict(), cardinalities=dict(), plays_cardinalities=dict(), docstring=None, annotations=dict(), prefix=None, internal=False)

Entity definition extracted from a TypeDB schema.

Attributes:

Name Type Description
name str

The TypeDB entity name (e.g., "person")

parent str | None

Parent entity name for inheritance (sub)

owns set[str]

Set of owned attribute names

owns_order list[str]

Ordered list preserving TQL declaration order

plays set[str]

Set of role references (e.g., "friendship:friend")

abstract bool

Whether this is an abstract entity

keys set[str]

Attributes marked with @key

uniques set[str]

Attributes marked with @unique

cascades set[str]

Attributes marked with @cascade

subkeys dict[str, str]

Attributes -> subkey group name mapping (from @subkey)

cardinalities dict[str, Cardinality]

Per-attribute cardinality constraints

plays_cardinalities dict[str, Cardinality]

Per-role cardinality constraints (e.g., plays friendship:friend @card(0..5))

annotations dict[str, AnnotationValue]

Custom annotations from TQL comments (e.g., # @prefix(PROJ))

RoleSpec dataclass

RoleSpec(name, overrides=None, cardinality=None, distinct=False, annotations=dict())

Role definition within a relation.

Attributes:

Name Type Description
name str

The role name (e.g., "author")

overrides str | None

Parent role this overrides (from "as" syntax)

cardinality Cardinality | None

Optional cardinality constraint on the role

distinct bool

Whether this role has @distinct annotation

annotations dict[str, AnnotationValue]

Custom annotations from TQL comments

RelationSpec dataclass

RelationSpec(name, parent=None, roles=list(), owns=set(), owns_order=list(), abstract=False, keys=set(), uniques=set(), cascades=set(), subkeys=dict(), cardinalities=dict(), docstring=None, annotations=dict())

Relation definition extracted from a TypeDB schema.

Attributes:

Name Type Description
name str

The TypeDB relation name (e.g., "authoring")

parent str | None

Parent relation name for inheritance (sub)

roles list[RoleSpec]

List of role specifications

owns set[str]

Set of owned attribute names

owns_order list[str]

Ordered list preserving TQL declaration order

abstract bool

Whether this is an abstract relation

cascades set[str]

Attributes marked with @cascade

subkeys dict[str, str]

Attributes -> subkey group name mapping (from @subkey)

annotations dict[str, AnnotationValue]

Custom annotations from TQL comments

role_names property

role_names

Get list of role names for backward compatibility.

role_overrides property

role_overrides

Get role -> parent_role mapping for overrides.

ParameterSpec dataclass

ParameterSpec(name, type)

Parameter definition for a TypeDB function.

Attributes:

Name Type Description
name str

The parameter name (e.g., "birth-date")

type str

The parameter type (e.g., "date")

FunctionSpec dataclass

FunctionSpec(name, parameters, return_type, docstring=None)

Function definition extracted from a TypeDB schema.

Attributes:

Name Type Description
name str

The function name (e.g., "calculate-age")

parameters list[ParameterSpec]

List of parameters

return_type str

The return type (e.g., "int")

StructFieldSpec dataclass

StructFieldSpec(name, value_type, optional=False)

Field definition within a struct.

Attributes:

Name Type Description
name str

The field name (e.g., "first-name")

value_type str

The TypeDB value type (string, integer, etc.)

optional bool

Whether the field is optional (marked with ?)

StructSpec dataclass

StructSpec(name, fields=list(), docstring=None, annotations=dict())

Struct definition extracted from a TypeDB schema.

Structs are composite value types introduced in TypeDB 3.0.

Attributes:

Name Type Description
name str

The struct name (e.g., "person-name")

fields list[StructFieldSpec]

List of field specifications

docstring str | None

Documentation extracted from comments

annotations dict[str, AnnotationValue]

Custom annotations from TQL comments

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

accumulate_inheritance()

Propagate inherited members down all type hierarchies.

Source code in type_bridge/generator/models.py
def accumulate_inheritance(self) -> None:
    """Propagate inherited members down all type hierarchies."""
    _accumulate_entity_inheritance(self)
    _accumulate_relation_inheritance(self)

minimal_role_players

minimal_role_players(schema, relation, role)

Return the minimal set of entity names that can play a given role.

Removes ancestors when a descendant is also present, keeping MultiRole declarations as narrow as possible.

Source code in type_bridge/generator/models.py
def minimal_role_players(schema: ParsedSchema, relation: str, role: str) -> list[str]:
    """Return the minimal set of entity names that can play a given role.

    Removes ancestors when a descendant is also present, keeping MultiRole
    declarations as narrow as possible.
    """
    role_token = f"{relation}:{role}"
    players = [e.name for e in schema.entities.values() if role_token in e.plays]
    if not players:
        return []

    parent_map = {name: entity.parent for name, entity in schema.entities.items()}

    def is_ancestor(candidate: str, target: str) -> bool:
        current = parent_map.get(target)
        while current:
            if current == candidate:
                return True
            current = parent_map.get(current)
        return False

    unique_players = set(players)
    minimal = set(unique_players)
    for player in unique_players:
        for other in unique_players:
            if player != other and is_ancestor(other, player) and player in minimal:
                minimal.remove(player)
                break

    return sorted(minimal)

to_tuple_literal

to_tuple_literal(values)

Render a Python tuple literal of strings.

Source code in type_bridge/generator/models.py
def to_tuple_literal(values: Iterable[str]) -> str:
    """Render a Python tuple literal of strings."""
    entries = [f'"{val}"' for val in values]
    if not entries:
        return "()"
    if len(entries) == 1:
        return f"({entries[0]},)"
    return f"({', '.join(entries)})"