type_bridge.models¶
models
¶
TypeDB model classes - Entity, Relation, and Role.
TypeDBType
¶
Bases: BaseModel, ABC
Abstract base class for TypeDB entities and relations.
This class provides common functionality for both Entity and Relation types, including type name management, abstract/base flags, and attribute ownership.
Subclasses must implement: - get_supertype(): Get parent type in TypeDB hierarchy - to_schema_definition(): Generate TypeQL schema definition - to_insert_query(): Generate TypeQL insert query for instances
manager
classmethod
¶
Create a CRUD manager for this type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Database, Transaction, or TransactionContext |
required |
Returns:
| Type | Description |
|---|---|
TypeDBManager[Self]
|
Manager instance for this type |
Source code in type_bridge/models/base.py
insert
¶
Insert this instance into the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Database, Transaction, or TransactionContext |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Self for chaining |
Source code in type_bridge/models/base.py
delete
¶
Delete this instance from the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Database, Transaction, or TransactionContext |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Self for chaining |
Source code in type_bridge/models/base.py
has
classmethod
¶
Find all instances of this class (and its subtypes) that own attr_class.
Behaviour depends on the receiver:
Entity.has(...)/Relation.has(...): cross-type lookup — returns instances across all concrete types of that kind.<ConcreteType>.has(...)/<AbstractBase>.has(...): narrowed lookup — restricted to that type and its TypeDB subtypes viaisapolymorphism.
Returned relation instances always have their role players hydrated
(in addition to attributes). This is implemented by re-fetching each
relation through concrete_class.manager(connection).get(_iid=...)
after the initial wildcard query, so the relation path is N+1 in the
number of returned relations. Entity lookups remain single-query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Database, Transaction, or TransactionContext. |
required |
attr_class
|
type[Attribute]
|
Attribute type to search for (e.g. |
required |
value
|
Any | None
|
Optional filter — raw value, Attribute instance,
or Expression (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
list[TypeDBType]
|
List of hydrated model instances (may contain mixed concrete types |
list[TypeDBType]
|
when called on the base |
list[TypeDBType]
|
abstract base subclass). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If called directly on :class: |
Source code in type_bridge/models/base.py
__init_subclass__
¶
Called when a TypeDBType subclass is created.
Source code in type_bridge/models/base.py
__pydantic_init_subclass__
classmethod
¶
Called by Pydantic after model class initialization.
Injects FieldDescriptor instances for class-level query access. This runs after Pydantic's setup is complete, so descriptors won't be removed.
Example
Person.age # Returns FieldRef for query building (class-level access) person.age # Returns attribute value (instance-level access)
Source code in type_bridge/models/base.py
model_copy
¶
Override model_copy to ensure raw values are wrapped in Attribute instances.
Pydantic's model_copy bypasses validators even with revalidate_instances='always', so we pre-wrap values in the update dict before copying. Also preserves _iid from original using Pydantic's pydantic_private.
Source code in type_bridge/models/base.py
get_type_name
classmethod
¶
Get the TypeDB type name for this type.
If name is explicitly set in TypeFlags, it is used as-is. Otherwise, the class name is formatted according to the case parameter.
Source code in type_bridge/models/base.py
get_supertype
classmethod
¶
Get the supertype from Python inheritance, skipping base classes.
Base classes (with base=True) are Python-only and don't appear in TypeDB schema. This method skips them when determining the TypeDB supertype.
Returns:
| Type | Description |
|---|---|
str | None
|
Type name of the parent class, or None if direct subclass |
Source code in type_bridge/models/base.py
is_abstract
classmethod
¶
is_base
classmethod
¶
get_owned_attributes
classmethod
¶
Get attributes owned directly by this type (not inherited).
Returns:
| Type | Description |
|---|---|
dict[str, ModelAttrInfo]
|
Dictionary mapping field names to ModelAttrInfo (typ + flags) |
Source code in type_bridge/models/base.py
get_all_attributes
classmethod
¶
Get all attributes including inherited ones.
Traverses the class hierarchy to collect all owned attributes, including those from parent Entity/Relation classes.
Returns:
| Type | Description |
|---|---|
dict[str, ModelAttrInfo]
|
Dictionary mapping field names to ModelAttrInfo (typ + flags) |
Source code in type_bridge/models/base.py
get_polymorphic_attributes
classmethod
¶
Get all attributes including those from registered subtypes.
For polymorphic queries where the base class is used but concrete subtypes may be returned, this method collects attributes from all known subtypes so the query can fetch all possible attributes.
Returns:
| Type | Description |
|---|---|
dict[str, ModelAttrInfo]
|
Dictionary mapping field names to ModelAttrInfo, including |
dict[str, ModelAttrInfo]
|
attributes from all registered subtypes. |
Source code in type_bridge/models/base.py
to_schema_definition
abstractmethod
classmethod
¶
Generate TypeQL schema definition for this type.
Returns:
| Type | Description |
|---|---|
str | None
|
TypeQL schema definition string, or None if this is a base class |
get_match_clause_info
abstractmethod
¶
Get information to build a TypeQL match clause for this instance.
Used by TypeDBManager for delete/update operations. Returns IID-based matching when available, otherwise falls back to type-specific identification (key attributes for entities, role players for relations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name to use in the match clause |
'$x'
|
Returns:
| Type | Description |
|---|---|
MatchClauseInfo
|
MatchClauseInfo with main clause, extra clauses, and variable name |
Raises:
| Type | Description |
|---|---|
ValueError
|
If instance cannot be identified (no IID and no keys/role players) |
Source code in type_bridge/models/base.py
to_ast
abstractmethod
¶
Generate AST InsertClause for this instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Variable name to use |
'$x'
|
Returns:
| Type | Description |
|---|---|
Any
|
InsertClause containing statements |
to_insert_query
¶
Generate TypeQL insert query string for this instance.
This is a convenience method that uses the AST-based generation internally and compiles it to a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Variable name to use (default: "$e") |
'$e'
|
Returns:
| Type | Description |
|---|---|
str
|
TypeQL insert query string |
Source code in type_bridge/models/base.py
Entity
¶
Bases: TypeDBType
Base class for TypeDB entities with Pydantic validation.
Entities own attributes defined as Attribute subclasses. Use TypeFlags to configure type name and abstract status. Supertype is determined automatically from Python inheritance.
This class inherits from TypeDBType and Pydantic's BaseModel, providing: - Automatic validation of attribute values - JSON serialization/deserialization - Type checking and coercion - Field metadata via Pydantic's Field()
Example
class Name(String): pass
class Age(Integer): pass
class Person(Entity): flags = TypeFlags(name="person") name: Name = Flag(Key) age: Age
Abstract entity¶
class AbstractPerson(Entity): flags = TypeFlags(abstract=True) name: Name
Inheritance (Person sub abstract-person)¶
class ConcretePerson(AbstractPerson): age: Age
__init_subclass__
¶
Called when Entity subclass is created.
Source code in type_bridge/models/entity.py
to_schema_definition
classmethod
¶
Generate TypeQL schema definition for this entity.
Returns:
| Type | Description |
|---|---|
str | None
|
TypeQL schema definition string, or None if this is a base class |
Source code in type_bridge/models/entity.py
to_ast
¶
Generate AST InsertClause for this instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Variable name to use |
'$e'
|
Returns:
| Type | Description |
|---|---|
InsertClause
|
InsertClause containing statements |
Source code in type_bridge/models/entity.py
get_match_clause_info
¶
Get match clause info for this entity instance.
Prefers IID-based matching when available (most precise). Falls back to @key attribute matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name to use in the match clause |
'$e'
|
Returns:
| Type | Description |
|---|---|
MatchClauseInfo
|
MatchClauseInfo with the match clause |
Raises:
| Type | Description |
|---|---|
ValueError
|
If entity has neither _iid nor key attributes |
Source code in type_bridge/models/entity.py
get_match_pattern
¶
Get an AST EntityPattern for matching this entity instance.
Prefers IID-based matching when available (most precise). Falls back to @key attribute matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name to use in the pattern |
'$e'
|
Returns:
| Type | Description |
|---|---|
EntityPattern
|
EntityPattern AST node |
Raises:
| Type | Description |
|---|---|
ValueError
|
If entity has neither _iid nor key attributes |
Source code in type_bridge/models/entity.py
to_dict
¶
Serialize the entity to a primitive dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include
|
set[str] | None
|
Optional set of field names to include. |
None
|
exclude
|
set[str] | None
|
Optional set of field names to exclude. |
None
|
by_alias
|
bool
|
When True, use attribute TypeQL names instead of Python field names. |
False
|
exclude_unset
|
bool
|
When True, omit fields that were never explicitly set. |
False
|
Source code in type_bridge/models/entity.py
from_dict
classmethod
¶
Construct an Entity from a plain dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
External data to hydrate the Entity. |
required |
field_mapping
|
dict[str, str] | None
|
Optional mapping of external keys to internal field names. |
None
|
strict
|
bool
|
When True, raise on unknown fields; otherwise ignore them. |
True
|
Source code in type_bridge/models/entity.py
__repr__
¶
Developer-friendly string representation of entity.
Source code in type_bridge/models/entity.py
__str__
¶
User-friendly string representation of entity.
Source code in type_bridge/models/entity.py
Relation
¶
Bases: TypeDBType
Base class for TypeDB relations with Pydantic validation.
Relations can own attributes and have role players. Use TypeFlags to configure type name and abstract status. Supertype is determined automatically from Python inheritance.
This class inherits from TypeDBType and Pydantic's BaseModel, providing: - Automatic validation of attribute values - JSON serialization/deserialization - Type checking and coercion - Field metadata via Pydantic's Field()
Example
class Position(String): pass
class Salary(Integer): pass
class Employment(Relation): flags = TypeFlags(name="employment")
employee: Role[Person] = Role("employee", Person)
employer: Role[Company] = Role("employer", Company)
position: Position
salary: Salary | None
__init_subclass__
¶
Initialize relation subclass.
Source code in type_bridge/models/relation.py
__pydantic_init_subclass__
classmethod
¶
Called by Pydantic after model class initialization.
This is the right place to restore Role descriptors because: 1. init_subclass runs before Pydantic's metaclass finishes 2. Pydantic removes Role instances from class dict during construction 3. pydantic_init_subclass runs after Pydantic's setup is complete
This restores Role descriptors so class-level access (Employment.employee) returns a RoleRef for type-safe query building.
Source code in type_bridge/models/relation.py
get_roles
classmethod
¶
Get all roles defined on this relation.
Returns:
| Type | Description |
|---|---|
dict[str, Role]
|
Dictionary mapping role names to Role instances |
to_ast
¶
Generate AST InsertClause for this relation instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var
|
str
|
Variable name to use |
'$r'
|
Returns:
| Type | Description |
|---|---|
InsertClause
|
InsertClause containing statements |
Source code in type_bridge/models/relation.py
get_match_clause_info
¶
Get match clause info for this relation instance.
Prefers IID-based matching when available (most precise). Falls back to role player matching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name to use in the match clause |
'$r'
|
Returns:
| Type | Description |
|---|---|
MatchClauseInfo
|
MatchClauseInfo with the match clause and role player clauses |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any role player cannot be identified |
Source code in type_bridge/models/relation.py
get_match_patterns
¶
Get AST patterns for matching this relation instance.
Returns a list of patterns: the main RelationPattern plus EntityPatterns for each role player (when matching by role players, not IID).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
var_name
|
str
|
Variable name to use in the pattern |
'$r'
|
Returns:
| Type | Description |
|---|---|
list[Pattern]
|
List of Pattern AST nodes |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any role player cannot be identified |
Source code in type_bridge/models/relation.py
to_schema_definition
classmethod
¶
Generate TypeQL schema definition for this relation.
Returns:
| Type | Description |
|---|---|
str | None
|
TypeQL schema definition string, or None if this is a base class |
Source code in type_bridge/models/relation.py
__repr__
¶
Developer-friendly string representation of relation.
Source code in type_bridge/models/relation.py
__str__
¶
User-friendly string representation of relation.
Source code in type_bridge/models/relation.py
Role
¶
Descriptor for relation role players with type safety.
Generic type T represents the type (Entity or Relation) that can play this role. TypeDB supports both entities and relations as role players.
Example
Entity as role player¶
class Employment(Relation): employee: Role[Person] = Role("employee", Person) employer: Role[Company] = Role("employer", Company)
Relation as role player¶
class Permission(Relation): permitted_subject: Role[Subject] = Role("permitted_subject", Subject) permitted_access: Role[Access] = Role("permitted_access", Access) # Access is a Relation
Initialize a role.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_name
|
str
|
The name of the role in TypeDB |
required |
player_type
|
type[T]
|
The type (Entity or Relation) that can play this role |
required |
additional_player_types
|
type[T]
|
Optional additional types allowed to play this role |
()
|
cardinality
|
Card | None
|
Optional cardinality constraint for the role (e.g., Card(2, 2) for exactly 2) |
None
|
Raises:
| Type | Description |
|---|---|
ReservedWordError
|
If role_name is a TypeQL reserved word |
TypeError
|
If player type is a library base class (Entity, Relation, TypeDBType) |
Source code in type_bridge/models/role.py
is_multi_player
property
¶
Check if this role allows multiple players.
Returns True if cardinality allows more than one player (max > 1 or unbounded).
__set_name__
¶
__get__
¶
__get__(obj: None, objtype: type) -> RoleRef[T]
Get role player from instance or RoleRef from class.
When accessed from the class (obj is None), returns RoleRef for type-safe query building (e.g., Employment.employee.age.gt(Age(30))). When accessed from an instance, returns the entity playing the role.
Source code in type_bridge/models/role.py
__set__
¶
Set role player(s) on instance.
For roles with cardinality > 1, accepts a list of entities. For single-player roles, accepts a single entity.
Source code in type_bridge/models/role.py
multi
classmethod
¶
Define a role playable by multiple entity types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role_name
|
str
|
The name of the role in TypeDB |
required |
player_type
|
type[T]
|
The first entity type that can play this role |
required |
additional_player_types
|
type[T]
|
Additional entity types allowed to play this role |
()
|
cardinality
|
Card | None
|
Optional cardinality constraint for the role |
None
|
Source code in type_bridge/models/role.py
__get_pydantic_core_schema__
classmethod
¶
Define how Pydantic should validate Role fields.
Accepts either: - A single entity instance for single-player roles - A list of entity instances for multi-player roles (cardinality > 1)
Uses a custom validator that checks class names instead of isinstance, to handle generated code in different modules where the same class name exists but as a different Python object.
Source code in type_bridge/models/role.py
FieldInfo
dataclass
¶
Information extracted from a field type annotation.
Attributes:
| Name | Type | Description |
|---|---|---|
attr_type |
type[Attribute] | None
|
The Attribute subclass (e.g., Name, Age) |
card_min |
int | None
|
Minimum cardinality (None means use default) |
card_max |
int | None
|
Maximum cardinality (None means unbounded) |
is_key |
bool
|
Whether this field is marked as @key |
is_unique |
bool
|
Whether this field is marked as @unique |
MatchClauseInfo
dataclass
¶
Information needed to build a TypeQL match clause for an instance.
Used by TypeDBManager to build CRUD queries for both entities and relations.
Attributes:
| Name | Type | Description |
|---|---|---|
main_clause |
str
|
The primary match clause (e.g., "$e isa person, has Name "Alice"") |
extra_clauses |
list[str]
|
Additional match clauses (e.g., role player matches for relations) |
var_name |
str
|
The main variable name (e.g., "$e" or "$r") |
ModelAttrInfo
dataclass
¶
Metadata for an attribute owned by an Entity or Relation.
Attributes:
| Name | Type | Description |
|---|---|---|
typ |
type[Attribute]
|
The Attribute subclass (e.g., Name, Age) |
flags |
AttributeFlags
|
The AttributeFlags with key/unique/card annotations |
WriteQueryInfo
dataclass
¶
Information needed to build a TypeQL write query for an instance.
Supports both entities (which only need insert/put pattern) and relations (which need match clause for role players + insert/put pattern).
Attributes:
| Name | Type | Description |
|---|---|---|
match_clause |
str | None
|
Optional match clause (for relations with role players) |
write_pattern |
str
|
The insert/put pattern |