type_bridge¶
type_bridge
¶
TypeBridge - A Python ORM for TypeDB with Attribute-based API.
Attribute
¶
Bases: ABC
Base class for TypeDB attributes.
Attributes in TypeDB are value types that can be owned by entities and relations.
Attribute instances can store values, allowing type-safe construction: Name("Alice") # Creates Name instance with value "Alice" Age(30) # Creates Age instance with value 30
Type name formatting
You can control how the class name is converted to TypeDB attribute name using the 'case' class variable or 'attr_name' for explicit control.
Example
class Name(String): pass # TypeDB attribute: "Name" (default CLASS_NAME)
class PersonName(String): case = TypeNameCase.SNAKE_CASE # TypeDB attribute: "person_name"
class PersonName(String): attr_name = "full_name" # Explicit override
class Age(Integer): pass
class Person(Entity): name: Name age: Age
Direct instantiation with wrapped types (best practice):¶
person = Person(name=Name("Alice"), age=Age(30))
Initialize attribute with a value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The value to store in this attribute instance |
None
|
Source code in type_bridge/attribute/base.py
__init_subclass__
¶
Called when a subclass is created.
Source code in type_bridge/attribute/base.py
__str__
¶
__repr__
¶
__eq__
¶
Compare attribute with another attribute instance.
For strict type safety, Attribute instances do NOT compare equal to raw values.
To access the raw value, use the .value property.
Examples:
Age(20) == Age(20) # True (same type, same value) Age(20) == Id(20) # False (different types!) Age(20) == 20 # False (not equal to raw value!) Age(20).value == 20 # True (access raw value explicitly)
Source code in type_bridge/attribute/base.py
__hash__
¶
get_attribute_name
classmethod
¶
Get the TypeDB attribute name.
If attr_name is explicitly set, it is used as-is. Otherwise, the class name is formatted according to the case parameter. Default case is CLASS_NAME (preserves class name as-is).
Source code in type_bridge/attribute/base.py
get_value_type
classmethod
¶
is_key
classmethod
¶
is_abstract
classmethod
¶
is_independent
classmethod
¶
get_owners
classmethod
¶
Get all Entity/Relation classes that own this attribute.
Returns:
| Type | Description |
|---|---|
set[type[TypeDBType]]
|
Set of model classes that define this attribute as a field. |
set[type[TypeDBType]]
|
Does not require a database connection (static discovery). |
Source code in type_bridge/attribute/base.py
get_supertype
classmethod
¶
to_schema_definition
classmethod
¶
Generate TypeQL schema definition for this attribute.
Includes support for TypeDB annotations: - @abstract (comes right after attribute name) - @independent (comes right after attribute name, allows standalone existence) - @range(min..max) from range_constraint ClassVar (after value type) - @regex("pattern") from regex ClassVar (after value type) - @values("a", "b", ...) from allowed_values ClassVar (after value type)
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Source code in type_bridge/attribute/base.py
gt
classmethod
¶
Create greater-than comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr > value |
Example
Age.gt(Age(30)) # age > 30
Source code in type_bridge/attribute/base.py
lt
classmethod
¶
Create less-than comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr < value |
Example
Age.lt(Age(30)) # age < 30
Source code in type_bridge/attribute/base.py
gte
classmethod
¶
Create greater-than-or-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr >= value |
Example
Salary.gte(Salary(80000.0)) # salary >= 80000
Source code in type_bridge/attribute/base.py
lte
classmethod
¶
Create less-than-or-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr <= value |
Example
Age.lte(Age(65)) # age <= 65
Source code in type_bridge/attribute/base.py
eq
classmethod
¶
Create equality comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr == value |
Example
Status.eq(Status("active")) # status == "active"
Source code in type_bridge/attribute/base.py
neq
classmethod
¶
Create not-equal comparison expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Attribute
|
Value to compare against |
required |
Returns:
| Type | Description |
|---|---|
ComparisonExpr
|
ComparisonExpr for attr != value |
Example
Status.neq(Status("deleted")) # status != "deleted"
Source code in type_bridge/attribute/base.py
sum
classmethod
¶
Create sum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for sum(attr) |
Example
Salary.sum() # sum of all salaries
Source code in type_bridge/attribute/base.py
avg
classmethod
¶
Create average (mean) aggregation expression.
Note
Automatically converts to TypeQL 'mean' function. TypeDB 3.x uses 'mean' instead of 'avg'.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for mean(attr) |
Example
Age.avg() # Generates TypeQL: mean($age)
Source code in type_bridge/attribute/base.py
max
classmethod
¶
Create maximum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for max(attr) |
Example
Score.max() # maximum score
Source code in type_bridge/attribute/base.py
min
classmethod
¶
Create minimum aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for min(attr) |
Example
Price.min() # minimum price
Source code in type_bridge/attribute/base.py
median
classmethod
¶
Create median aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for median(attr) |
Example
Salary.median() # median salary
Source code in type_bridge/attribute/base.py
std
classmethod
¶
Create standard deviation aggregation expression.
Returns:
| Type | Description |
|---|---|
AggregateExpr
|
AggregateExpr for std(attr) |
Example
Score.std() # standard deviation of scores
Source code in type_bridge/attribute/base.py
__get_pydantic_core_schema__
classmethod
¶
Unified Pydantic schema generation for all attribute types.
This base implementation handles the common patterns: - Serialization: extract _value from attribute instances - Validation: wrap raw values in attribute instances - Literal type support (for types that enable it)
Subclasses can override for completely custom behavior, or override the helper methods (_pydantic_serialize, _pydantic_validate, etc.) for targeted customization.
Source code in type_bridge/attribute/base.py
__class_getitem__
classmethod
¶
build_lookup
classmethod
¶
Build an expression for a lookup operator.
This method centralizes the logic for converting lookup names (e.g., 'gt', 'in') into TypeQL expressions. Subclasses (like String) should override this to handle type-specific lookups.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookup
|
str
|
The lookup operator name (e.g., 'exact', 'gt', 'contains') |
required |
value
|
Any
|
The value to filter by |
required |
Returns:
| Type | Description |
|---|---|
Expression
|
Expression object representing the filter |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the lookup operator is not supported by this attribute type |
Source code in type_bridge/attribute/base.py
AttributeFlags
dataclass
¶
AttributeFlags(is_key=False, is_unique=False, card_min=None, card_max=None, has_explicit_card=False, name=None, case=None)
Metadata for attribute ownership and type configuration.
Represents TypeDB ownership annotations like @key, @card(min..max), @unique, and allows overriding the attribute type name with explicit name or case formatting.
Example
class Person(Entity): name: Name = Flag(Key) # @key (implies @card(1..1)) email: Email = Flag(Unique) # @unique @card(1..1) age: Optional[Age] # @card(0..1) - no Flag needed tags: list[Tag] = Flag(Card(min=2)) # @card(2..) jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5)
Override attribute type name explicitly¶
class Name(String): flags = AttributeFlags(name="name")
Or use case formatting¶
class PersonName(String): flags = AttributeFlags(case=TypeNameCase.SNAKE_CASE) # -> person_name
to_typeql_annotations
¶
Convert to TypeQL annotations like @key, @card(0..5).
Rules: - @key implies @card(1..1), so never output @card with @key - @unique with @card(1..1) is redundant, so omit @card in that case - Otherwise, always output @card if cardinality is specified
Returns:
| Type | Description |
|---|---|
list[str]
|
List of TypeQL annotation strings |
Source code in type_bridge/attribute/flags.py
Boolean
¶
Bases: Attribute
Boolean attribute type that accepts bool values.
Example
class IsActive(Boolean): pass
class IsVerified(Boolean): pass
Initialize Boolean attribute with a bool value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
bool
|
The boolean value to store |
required |
Source code in type_bridge/attribute/boolean.py
Card
¶
Cardinality marker for multi-value attribute ownership.
IMPORTANT: Card() should only be used with list[Type] annotations. For optional single values, use Optional[Type] instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min
|
int | None
|
Minimum cardinality (default: None, which means unspecified) |
None
|
max
|
int | None
|
Maximum cardinality (default: None, which means unbounded) |
None
|
Examples:
tags: list[Tag] = Flag(Card(min=2)) # @card(2..) - at least two jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5) - one to five ids: list[ID] = Flag(Key, Card(min=1)) # @key @card(1..)
INCORRECT - use Optional[Type] instead:¶
age: Age = Flag(Card(min=0, max=1)) # ❌ Wrong!¶
age: Optional[Age] # ✓ Correct
Initialize cardinality marker.
Supports both positional and keyword arguments: - Card(1, 5) → min=1, max=5 - Card(min=2) → min=2, max=None (unbounded) - Card(max=5) → min=0, max=5 (defaults min to 0) - Card(min=0, max=10) → min=0, max=10
Source code in type_bridge/attribute/flags.py
Date
¶
Bases: Attribute
Date attribute type that accepts date values (date only, no time).
This maps to TypeDB's 'date' type, which is an ISO 8601 compliant date without time information.
Range: January 1, 262144 BCE to December 31, 262142 CE
Example
from datetime import date
class PublishDate(Date): pass
class BirthDate(Date): pass
Usage with date values¶
published = PublishDate(date(2024, 3, 30)) birthday = BirthDate(date(1990, 5, 15))
Initialize Date attribute with a date value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
date | str
|
The date value to store. Can be: - datetime.date instance - str in ISO 8601 format (YYYY-MM-DD) |
required |
Example
from datetime import date
From date instance¶
publish_date = PublishDate(date(2024, 3, 30))
From ISO string¶
publish_date = PublishDate("2024-03-30")
Source code in type_bridge/attribute/date.py
__add__
¶
Add a Duration to this Date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this date |
required |
Returns:
| Type | Description |
|---|---|
Date
|
New Date with the duration added |
Example
from type_bridge import Duration d = Date(date(2024, 1, 31)) duration = Duration("P1M") result = d + duration # Date(2024-02-29)
Source code in type_bridge/attribute/date.py
__radd__
¶
__sub__
¶
Subtract a Duration from this Date.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to subtract from this date |
required |
Returns:
| Type | Description |
|---|---|
Date
|
New Date with the duration subtracted |
Example
from type_bridge import Duration d = Date(date(2024, 3, 31)) duration = Duration("P1M") result = d - duration # Date(2024-02-29)
Source code in type_bridge/attribute/date.py
DateTime
¶
Bases: Attribute
DateTime attribute type that accepts naive datetime values.
This maps to TypeDB's 'datetime' type, which does not include timezone information.
Example
class CreatedAt(DateTime): pass
Usage with naive datetime¶
event = Event(created_at=CreatedAt(datetime(2024, 1, 15, 10, 30, 45)))
Convert to DateTimeTZ¶
aware_dt = created_at.add_timezone() # Implicit: add system timezone aware_dt_utc = created_at.add_timezone(timezone.utc) # Explicit: add UTC
Initialize DateTime attribute with a datetime value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The datetime value to store |
required |
Source code in type_bridge/attribute/datetime.py
add_timezone
¶
Convert DateTime to DateTimeTZ by adding timezone information.
Implicit conversion (tz=None): Add system/local timezone Explicit conversion (tz provided): Add specified timezone
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tz
|
timezone | None
|
Optional timezone to add to the naive datetime. If None, uses system local timezone (astimezone()). If provided, uses that specific timezone. |
None
|
Returns:
| Type | Description |
|---|---|
DateTimeTZ
|
DateTimeTZ instance with timezone-aware datetime |
Example
Implicit: add system timezone¶
aware = naive_dt.add_timezone()
Explicit: add UTC timezone¶
from datetime import timezone aware_utc = naive_dt.add_timezone(timezone.utc)
Explicit: add JST (+9) timezone¶
from datetime import timezone, timedelta jst = timezone(timedelta(hours=9)) aware_jst = naive_dt.add_timezone(jst)
Source code in type_bridge/attribute/datetime.py
__add__
¶
Add a Duration to this DateTime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this datetime |
required |
Returns:
| Type | Description |
|---|---|
DateTime
|
New DateTime with the duration added |
Example
from type_bridge import Duration dt = DateTime(datetime(2024, 1, 31, 14, 0, 0)) duration = Duration("P1M") result = dt + duration # DateTime(2024-02-28 14:00:00)
Source code in type_bridge/attribute/datetime.py
DateTimeTZ
¶
Bases: Attribute
DateTimeTZ attribute type that accepts timezone-aware datetime values.
This maps to TypeDB's 'datetime-tz' type, which requires timezone information. The datetime must have tzinfo set (e.g., using datetime.timezone.utc or zoneinfo).
Example
from datetime import datetime, timezone
class CreatedAt(DateTimeTZ): pass
Usage with timezone¶
event = Event(created_at=CreatedAt(datetime(2024, 1, 15, 10, 30, 45, tzinfo=timezone.utc)))
Convert to DateTime¶
naive_dt = created_at.strip_timezone() # Implicit: just strip tz naive_dt_jst = created_at.strip_timezone(timezone(timedelta(hours=9))) # Explicit: convert to JST, then strip
Initialize DateTimeTZ attribute with a timezone-aware datetime value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
datetime
|
The timezone-aware datetime value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the datetime does not have timezone information |
Source code in type_bridge/attribute/datetimetz.py
strip_timezone
¶
Convert DateTimeTZ to DateTime by stripping timezone information.
Implicit conversion (tz=None): Just strip timezone as-is Explicit conversion (tz provided): Convert to specified timezone first, then strip
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tz
|
timezone | None
|
Optional timezone to convert to before stripping. If None, strips timezone without conversion. If provided, converts to that timezone first. |
None
|
Returns:
| Type | Description |
|---|---|
DateTime
|
DateTime instance with naive datetime |
Example
Implicit: strip timezone as-is¶
naive = dt_tz.strip_timezone()
Explicit: convert to JST (+9), then strip¶
from datetime import timezone, timedelta jst = timezone(timedelta(hours=9)) naive_jst = dt_tz.strip_timezone(jst)
Source code in type_bridge/attribute/datetimetz.py
__add__
¶
Add a Duration to this DateTimeTZ.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
A Duration to add to this timezone-aware datetime |
required |
Returns:
| Type | Description |
|---|---|
DateTimeTZ
|
New DateTimeTZ with the duration added |
Note
Duration addition respects timezone changes (DST, etc.)
Example
from type_bridge import Duration from datetime import datetime, timezone dt = DateTimeTZ(datetime(2024, 1, 31, 14, 0, 0, tzinfo=timezone.utc)) duration = Duration("P1M") result = dt + duration # DateTimeTZ(2024-02-28 14:00:00+00:00)
Source code in type_bridge/attribute/datetimetz.py
Decimal
¶
Bases: NumericAttribute
Decimal attribute type that accepts fixed-point decimal values.
This maps to TypeDB's 'decimal' type, which is a fixed-point signed decimal number with 64 bits to the left of the decimal point and 19 decimal digits of precision after the point.
Range: −2^63 to 2^63 − 10^−19 (inclusive)
Example
from decimal import Decimal as DecimalType
class AccountBalance(Decimal): pass
class Price(Decimal): pass
Usage with decimal values¶
balance = AccountBalance(DecimalType("1234.567890")) price = Price(DecimalType("0.02"))
Initialize Decimal attribute with a decimal value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Decimal | str | int | float
|
The decimal value to store. Can be: - decimal.Decimal instance - str that can be parsed as decimal - int or float (will be converted to Decimal) |
required |
Example
from decimal import Decimal as DecimalType
From Decimal¶
balance = AccountBalance(DecimalType("123.45"))
From string (recommended for precision)¶
balance = AccountBalance("123.45")
From int or float (may lose precision)¶
balance = AccountBalance(123.45)
Source code in type_bridge/attribute/decimal.py
Double
¶
Bases: NumericAttribute
Double precision float attribute type that accepts float values.
Example
class Price(Double): pass
class Score(Double): pass
Initialize Double attribute with a float value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The float value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value violates range_constraint |
Source code in type_bridge/attribute/double.py
Duration
¶
Bases: Attribute
Duration attribute type that accepts ISO 8601 duration values.
This maps to TypeDB's 'duration' type, which represents calendar-aware time spans using months, days, and nanoseconds.
TypeDB duration format: ISO 8601 duration (e.g., P1Y2M3DT4H5M6.789S) Storage: 32-bit months, 32-bit days, 64-bit nanoseconds
Important notes: - Durations are partially ordered (P1M and P30D cannot be compared) - P1D ≠ PT24H (calendar day vs 24 hours) - P1M ≠ P30D (months vary in length) - Addition is not commutative with calendar components
Example
from datetime import timedelta
class SessionDuration(Duration): pass
class EventCadence(Duration): pass
From ISO 8601 string¶
cadence = EventCadence("P1M") # 1 month interval = SessionDuration("PT1H30M") # 1 hour 30 minutes
From timedelta (converted to Duration internally)¶
session = SessionDuration(timedelta(hours=2))
Complex duration¶
complex = EventCadence("P1Y2M3DT4H5M6.789S")
Initialize Duration attribute with a duration value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str | timedelta | Duration
|
The duration value to store. Can be: - str: ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S") - timedelta: Python timedelta (converted to Duration) - isodate.Duration: Direct Duration object |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If duration components exceed storage limits |
Example
From ISO string¶
duration1 = Duration("P1M") # 1 month duration2 = Duration("PT1H30M") # 1 hour 30 minutes
From timedelta¶
from datetime import timedelta duration3 = Duration(timedelta(hours=2, minutes=30))
Complex duration¶
duration4 = Duration("P1Y2M3DT4H5M6.789S")
Source code in type_bridge/attribute/duration.py
value
property
¶
Get the stored duration value.
Returns:
| Type | Description |
|---|---|
Duration
|
isodate.Duration instance (zero duration if None) |
to_iso8601
¶
Convert duration to ISO 8601 string format.
Returns:
| Type | Description |
|---|---|
str
|
ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S") |
Example
duration = Duration("P1M") assert duration.to_iso8601() == "P1M"
Source code in type_bridge/attribute/duration.py
__add__
¶
Add two durations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
Another Duration to add |
required |
Returns:
| Type | Description |
|---|---|
Duration
|
New Duration with sum |
Example
d1 = Duration("P1M") d2 = Duration("P15D") result = d1 + d2 # P1M15D
Source code in type_bridge/attribute/duration.py
__radd__
¶
__sub__
¶
Subtract two durations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Any
|
Another Duration to subtract |
required |
Returns:
| Type | Description |
|---|---|
Duration
|
New Duration with difference |
Example
d1 = Duration("P1M") d2 = Duration("P15D") result = d1 - d2 # P1M-15D
Source code in type_bridge/attribute/duration.py
Integer
¶
Bases: NumericAttribute
Integer attribute type that accepts int values.
Example
class Age(Integer): pass
class Count(Integer): pass
With Literal for type safety¶
class Priority(Integer): pass
priority: Literal[1, 2, 3] | Priority
Initialize Integer attribute with an integer value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The integer value to store |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value violates range_constraint |
Source code in type_bridge/attribute/integer.py
String
¶
Bases: Attribute
String attribute type that accepts str values.
Example
class Name(String): pass
class Email(String): pass
With Literal for type safety¶
class Status(String): pass
status: Literal["active", "inactive"] | Status
Initialize String attribute with a string value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
The string value to store |
required |
Source code in type_bridge/attribute/string.py
__str__
¶
__add__
¶
Concatenate strings.
Source code in type_bridge/attribute/string.py
__radd__
¶
contains
classmethod
¶
Create contains string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
String
|
String value to search for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr contains value |
Example
Email.contains(Email("@company.com")) # email contains "@company.com"
Source code in type_bridge/attribute/string.py
like
classmethod
¶
Create regex pattern matching expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
String
|
Regex pattern to match |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like pattern |
Example
Name.like(Name("^A.*")) # name starts with 'A'
Source code in type_bridge/attribute/string.py
regex
classmethod
¶
Create regex pattern matching expression (alias for like).
Note
Automatically converts to TypeQL 'like' operator. Both 'like' and 'regex' perform regex pattern matching in TypeDB.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
String
|
Regex pattern to match |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like pattern |
Example
Email.regex(Email(".@gmail.com")) # Generates TypeQL: $email like ".@gmail.com"
Source code in type_bridge/attribute/string.py
startswith
classmethod
¶
Create startswith string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
String
|
Prefix string to check for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like "^prefix.*" |
Source code in type_bridge/attribute/string.py
endswith
classmethod
¶
Create endswith string expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suffix
|
String
|
Suffix string to check for |
required |
Returns:
| Type | Description |
|---|---|
StringExpr
|
StringExpr for attr like ".*suffix$" |
Source code in type_bridge/attribute/string.py
build_lookup
classmethod
¶
Build an expression for string-specific lookups.
Overrides base method to handle contains, regex, startswith, endswith.
Source code in type_bridge/attribute/string.py
TypeFlags
dataclass
¶
Metadata flags for Entity and Relation classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
TypeDB type name (if None, uses class name with case formatting) |
None
|
abstract
|
bool
|
Whether this is an abstract type |
False
|
base
|
bool
|
Whether this is a Python base class that should not appear in TypeDB schema |
False
|
case
|
TypeNameCase
|
Case formatting for auto-generated type names (default: CLASS_NAME) |
CLASS_NAME
|
Example
class Person(Entity): flags = TypeFlags(name="person") name: Name
class PersonName(Entity): flags = TypeFlags() # → PersonName (default CLASS_NAME) name: Name
class PersonName(Entity): flags = TypeFlags(case=TypeNameCase.SNAKE_CASE) # → person_name name: Name
class AbstractPerson(Entity): flags = TypeFlags(abstract=True) name: Name
class BaseEntity(Entity): flags = TypeFlags(base=True) # Python base class only # Children skip this in TypeDB hierarchy
Initialize TypeFlags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
TypeDB type name (if None, uses class name with case formatting) |
None
|
abstract
|
bool
|
Whether this is an abstract type |
False
|
base
|
bool
|
Whether this is a Python base class that should not appear in TypeDB schema |
False
|
case
|
TypeNameCase
|
Case formatting for auto-generated type names (default: CLASS_NAME) |
CLASS_NAME
|
Source code in type_bridge/attribute/flags.py
TypeNameCase
¶
Bases: Enum
Type name case formatting options for Entity and Relation types.
CrudEvent
¶
Bases: Enum
CRUD lifecycle events.
CrudHook
¶
Bases: Protocol
Protocol for CRUD lifecycle hooks.
Implement only the methods you need. All methods are optional —
HookRunner uses hasattr / getattr to discover them.
EntityNotFoundError
¶
Bases: NotFoundError
Raised when an entity does not exist in the database.
This exception is raised during delete or update operations when the target entity cannot be found using its @key attributes or matched attributes.
Example
try: manager.delete(nonexistent_entity) except EntityNotFoundError: print("Entity was already deleted or never existed")
HookCancelled
¶
Bases: Exception
Raise in a pre-hook to abort the operation.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
Human-readable explanation. |
|
event |
The event that was cancelled (set by HookRunner). |
|
hook |
The hook instance that raised the cancellation (set by HookRunner). |
Source code in type_bridge/crud/hooks.py
KeyAttributeError
¶
Bases: ValueError
Raised when @key attribute validation fails during update/delete.
This exception is raised when: - A @key attribute has a None value - No @key attributes are defined on the entity
Attributes:
| Name | Type | Description |
|---|---|---|
entity_type |
Name of the entity class |
|
operation |
The operation that failed ("update" or "delete") |
|
field_name |
The @key field that was None (if applicable) |
|
all_fields |
List of all defined fields (when no @key exists) |
Example
try: manager.update(entity_with_none_key) except KeyAttributeError as e: print(f"Key validation failed: {e}") print(f"Entity type: {e.entity_type}") print(f"Operation: {e.operation}")
Source code in type_bridge/crud/exceptions.py
NotUniqueError
¶
Bases: ValueError
Raised when an operation requires exactly one match but finds multiple.
This exception is raised when attempting to delete an entity without @key attributes and multiple matching records are found. Use filter().delete() for bulk deletion instead.
Example
try: manager.delete(keyless_entity) except NotUniqueError: print("Multiple entities matched - use filter().delete() for bulk deletion")
RelationNotFoundError
¶
Bases: NotFoundError
Raised when a relation does not exist in the database.
This exception is raised during delete or update operations when the target relation cannot be found using its role players' @key attributes.
Example
try: manager.delete(nonexistent_relation) except RelationNotFoundError: print("Relation was already deleted or never existed")
TypeDBManager
¶
Unified CRUD manager for TypeDB entities and relations.
Source code in type_bridge/crud/typedb_manager.py
add_hook
¶
remove_hook
¶
insert
¶
Insert a new instance and populate _iid.
For entities, uses a single roundtrip (insert + fetch combined). For relations, uses two roundtrips (insert, then fetch) because TypeDB 3.x relation inserts don't bind the variable.
Source code in type_bridge/crud/typedb_manager.py
get
¶
Get instances matching filters.
Source code in type_bridge/crud/typedb_manager.py
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | |
update
¶
Update an instance in the database.
Uses the Strategy pattern to identify the instance, then updates all non-key attributes to match the current state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
T
|
Instance with updated values |
required |
Returns:
| Type | Description |
|---|---|
T
|
The updated instance |
Source code in type_bridge/crud/typedb_manager.py
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 | |
delete
¶
Delete an instance and return it.
Source code in type_bridge/crud/typedb_manager.py
all
¶
insert_many
¶
Insert multiple instances in a single query (batched).
For entities, combines all inserts into a single query for efficiency. For relations, falls back to individual inserts (due to match clause complexity).
Source code in type_bridge/crud/typedb_manager.py
put
¶
Insert or update an instance (idempotent) and populate _iid.
Uses TypeQL's PUT clause for idempotent insertion. For entities, uses a single roundtrip. For relations, uses two.
Source code in type_bridge/crud/typedb_manager.py
delete_many
¶
Delete multiple instances.
Optimized for batch deletion: instances with IIDs are deleted in a single query using disjunctive matching (OR pattern), reducing N roundtrips to 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instances
|
list[T]
|
List of instances to delete |
required |
strict
|
bool
|
If True, raise EntityNotFoundError if any entity doesn't exist. In strict mode, checks all entities first and raises before any deletion. |
False
|
Returns:
| Type | Description |
|---|---|
list[T]
|
List of actually-deleted entities (excludes those that didn't exist) |
Source code in type_bridge/crud/typedb_manager.py
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
put_many
¶
Put multiple instances (idempotent insert/update).
Attempts batch operation first for efficiency. If a key constraint violation occurs (some entities exist with different data), falls back to individual operations which are idempotent.
For entities, uses batch PUT when possible (N→1 roundtrips). For relations, uses individual operations (match clause complexity).
Source code in type_bridge/crud/typedb_manager.py
update_many
¶
get_by_iid
¶
Fetch an instance by its internal ID with polymorphic type resolution.
Source code in type_bridge/crud/typedb_manager.py
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 | |
filter
¶
Create a chainable query with filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*expressions
|
Any
|
Expression objects (Person.age.gt(Age(30)), etc.) |
()
|
**filters
|
Any
|
Attribute filters (exact match) - age=30, name="Alice" |
{}
|
Returns:
| Type | Description |
|---|---|
TypeDBQuery[T]
|
TypeDBQuery for chaining |
Raises:
| Type | Description |
|---|---|
ValueError
|
If expressions reference attribute types not owned by the model |
Source code in type_bridge/crud/typedb_manager.py
count
¶
Count all instances of this type, optionally filtering.
Source code in type_bridge/crud/typedb_manager.py
group_by
¶
Group results by field values and compute aggregations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*fields
|
Any
|
Field descriptors to group by (e.g., Person.department) |
()
|
Returns:
| Type | Description |
|---|---|
GroupByQuery[T]
|
GroupByQuery for chained aggregations |
Example
Group by department, compute average age per department¶
result = manager.group_by(Person.department).aggregate(Person.age.avg())
Returns: {¶
"Engineering": {"avg_age": 35.5},¶
"Sales":¶
}¶
Source code in type_bridge/crud/typedb_manager.py
BreakingChangeAnalyzer
¶
Analyzes schema diffs to classify changes by severity.
Classification rules: - SAFE: Adding new types, widening role player types - WARNING: Adding required attributes to existing types - BREAKING: Removing types, narrowing role player types, removing roles
Example
analyzer = BreakingChangeAnalyzer() diff = old_schema.compare(new_schema) changes = analyzer.analyze(diff)
for change in changes: print(f"[{change.category.value}] {change.description}") print(f" Recommendation: {change.recommendation}")
analyze
¶
Classify all changes in the schema diff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
list[ClassifiedChange]
|
List of classified changes with recommendations |
Source code in type_bridge/migration/breaking.py
has_breaking_changes
¶
Quick check for any breaking changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any breaking changes exist |
Source code in type_bridge/migration/breaking.py
has_warnings
¶
Quick check for any warning-level changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any warnings exist |
Source code in type_bridge/migration/breaking.py
get_breaking_changes
¶
Get only breaking changes from the diff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
list[ClassifiedChange]
|
List of breaking changes only |
Source code in type_bridge/migration/breaking.py
summary
¶
Generate a human-readable summary of classified changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted summary string |
Source code in type_bridge/migration/breaking.py
ChangeCategory
¶
Bases: Enum
Classification of schema changes by severity.
Migration
¶
Base class for migration scripts.
Migrations define schema changes that can be applied to a TypeDB database. They can be either model-based (for initial migrations) or operation-based (for incremental changes).
Model-based Migration Example
class InitialMigration(Migration): dependencies = [] models = [Person, Company, Employment]
Operation-based Migration Example
class AddPhoneMigration(Migration): dependencies = [("myapp", "0001_initial")] operations = [ ops.AddAttribute(Phone), ops.AddOwnership(Person, Phone, optional=True), ]
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Migration name (auto-populated from filename) |
app_label |
str
|
Application label (auto-populated from directory) |
dependencies |
list[tuple[str, str]]
|
List of (app_label, migration_name) tuples |
models |
list[type[Entity | Relation]]
|
List of Entity/Relation classes for initial migrations |
operations |
list[Operation]
|
List of Operation instances for incremental migrations |
reversible |
bool
|
Whether the migration can be rolled back |
get_dependencies
¶
Get dependencies as MigrationDependency objects.
Returns:
| Type | Description |
|---|---|
list[MigrationDependency]
|
List of MigrationDependency instances |
describe
¶
Generate a human-readable description of this migration.
Returns:
| Type | Description |
|---|---|
str
|
Description string |
Source code in type_bridge/migration/base.py
MigrationError
¶
Bases: Exception
Error during migration execution.
MigrationExecutor
¶
Executes migrations against a TypeDB database.
Handles: - Applying pending migrations - Rolling back applied migrations - Previewing migration TypeQL - Listing migration status
Example
executor = MigrationExecutor(db, Path("migrations"))
Apply all pending migrations¶
results = executor.migrate()
Migrate to specific version¶
results = executor.migrate(target="0002_add_company")
Show migration status¶
status = executor.showmigrations() for name, is_applied in status: print(f"[{'X' if is_applied else ' '}] {name}")
Preview TypeQL¶
typeql = executor.sqlmigrate("0002_add_company") print(typeql)
Initialize executor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
migrations_dir
|
Path
|
Directory containing migration files |
required |
dry_run
|
bool
|
If True, preview operations without executing |
False
|
Source code in type_bridge/migration/executor.py
migrate
¶
Apply pending migrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Optional target migration name (e.g., "0002_add_company") If None, apply all pending migrations. If specified, migrate to that exact state (may rollback). |
None
|
Returns:
| Type | Description |
|---|---|
list[MigrationResult]
|
List of migration results |
Raises:
| Type | Description |
|---|---|
MigrationError
|
If migration fails |
Source code in type_bridge/migration/executor.py
showmigrations
¶
List all migrations with their applied status.
Returns:
| Type | Description |
|---|---|
list[tuple[str, bool]]
|
List of (migration_name, is_applied) tuples |
Source code in type_bridge/migration/executor.py
sqlmigrate
¶
Preview TypeQL for a migration without executing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
migration_name
|
str
|
Name of the migration |
required |
reverse
|
bool
|
If True, show rollback TypeQL |
False
|
Returns:
| Type | Description |
|---|---|
str
|
TypeQL string that would be executed |
Raises:
| Type | Description |
|---|---|
MigrationError
|
If migration not found or not reversible |
Source code in type_bridge/migration/executor.py
plan
¶
Get the migration plan without executing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Optional target migration name |
None
|
Returns:
| Type | Description |
|---|---|
MigrationPlan
|
MigrationPlan showing what would be applied/rolled back |
Source code in type_bridge/migration/executor.py
ModelRegistry
¶
Registry for tracking Entity/Relation models.
Models can be registered manually or auto-discovered from Python modules. The registry is used by the migration generator to determine which models should be tracked for schema changes.
Example - Manual registration
from type_bridge.migration import ModelRegistry from myapp.models import Person, Company
ModelRegistry.register(Person, Company)
Example - Auto-discovery
from type_bridge.migration import ModelRegistry
Discover all Entity/Relation classes in module¶
models = ModelRegistry.discover("myapp.models")
Example - In models.py (recommended pattern): from type_bridge import Entity, String, Flag, Key, TypeFlags from type_bridge.migration import ModelRegistry
class Name(String):
pass
class Person(Entity):
flags = TypeFlags(name="person")
name: Name = Flag(Key)
# Register at module load time
ModelRegistry.register(Person)
register
classmethod
¶
Register models for migration tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
type[Entity | Relation]
|
Entity or Relation classes to register |
()
|
Source code in type_bridge/migration/registry.py
unregister
classmethod
¶
clear
classmethod
¶
get_all
classmethod
¶
is_registered
classmethod
¶
Check if a model is registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type
|
Model class to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if model is registered |
discover
classmethod
¶
Auto-discover Entity/Relation classes from a module.
Imports the module and finds all Entity/Relation subclasses defined in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_path
|
str
|
Python module path (e.g., "myapp.models") |
required |
register
|
bool
|
If True, also register discovered models |
True
|
Returns:
| Type | Description |
|---|---|
list[type[Entity | Relation]]
|
List of discovered Entity/Relation classes |
Raises:
| Type | Description |
|---|---|
ImportError
|
If module cannot be imported |
Source code in type_bridge/migration/registry.py
discover_recursive
classmethod
¶
Recursively discover models from a package.
Imports all modules in the package and discovers Entity/Relation classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_path
|
str
|
Python package path (e.g., "myapp") |
required |
register
|
bool
|
If True, also register discovered models |
True
|
Returns:
| Type | Description |
|---|---|
list[type[Entity | Relation]]
|
List of discovered Entity/Relation classes |
Raises:
| Type | Description |
|---|---|
ImportError
|
If package cannot be imported |
Source code in type_bridge/migration/registry.py
RolePlayerChange
dataclass
¶
Represents a change in role player types.
Tracks when entity types are added to or removed from a role's allowed players.
Example
If a role changes from Role[Person] to Role[Person, Company]: - added_player_types = ["company"] - removed_player_types = []
SchemaConflictError
¶
Bases: Exception
Raised when there are conflicting schema changes during sync.
This exception is raised when attempting to sync a schema that has breaking changes (removed or modified types/attributes) compared to the existing database schema.
Initialize SchemaConflictError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff containing the conflicting changes |
required |
message
|
str | None
|
Optional custom error message |
None
|
Source code in type_bridge/migration/exceptions.py
has_breaking_changes
¶
Check if the diff contains breaking changes.
Breaking changes include removed or modified types/attributes.
Returns:
| Type | Description |
|---|---|
bool
|
True if there are breaking changes |
Source code in type_bridge/migration/exceptions.py
SchemaInfo
¶
Container for organized schema information.
Initialize SchemaInfo with empty collections.
Source code in type_bridge/migration/info.py
get_entity_by_name
¶
Get entity by type name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Entity type name |
required |
Returns:
| Type | Description |
|---|---|
type[Entity] | None
|
Entity class or None if not found |
Source code in type_bridge/migration/info.py
get_relation_by_name
¶
Get relation by type name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Relation type name |
required |
Returns:
| Type | Description |
|---|---|
type[Relation] | None
|
Relation class or None if not found |
Source code in type_bridge/migration/info.py
validate
¶
Validate schema definitions for TypeDB constraints.
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If schema violates TypeDB constraints |
Source code in type_bridge/migration/info.py
to_typeql
¶
Generate TypeQL schema definition from collected schema information.
Base classes (with base=True) are skipped as they don't appear in TypeDB schema.
Validates the schema before generation.
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If schema validation fails |
Source code in type_bridge/migration/info.py
compare
¶
Compare this schema with another schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
SchemaInfo
|
Another SchemaInfo to compare against |
required |
Returns:
| Type | Description |
|---|---|
SchemaDiff
|
SchemaDiff containing all differences between the schemas |
Source code in type_bridge/migration/info.py
SchemaIntrospector
¶
Introspects TypeDB database schema.
Queries the database to discover all types, attributes, ownerships, and relations defined in the schema.
Example
introspector = SchemaIntrospector(db) schema = introspector.introspect()
print(f"Found {len(schema.entities)} entities") print(f"Found {len(schema.relations)} relations") print(f"Found {len(schema.attributes)} attributes")
Initialize introspector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/introspection.py
introspect_for_models
¶
Introspect database schema for specific model types.
This is the TypeDB 3.x compatible approach that checks each model type individually instead of enumerating all types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list[type[Entity] | type[Relation]]
|
List of model classes to check |
required |
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with info about existing types |
Source code in type_bridge/migration/introspection.py
introspect
¶
Query TypeDB schema and return structured info.
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with all discovered types |
Source code in type_bridge/migration/introspection.py
SchemaManager
¶
Manager for database schema operations.
Initialize schema manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/schema_manager.py
register
¶
Register model classes for schema management.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
type[Entity | Relation]
|
Model classes to register |
()
|
Source code in type_bridge/migration/schema_manager.py
collect_schema_info
¶
Collect schema information from registered models.
Returns:
| Type | Description |
|---|---|
SchemaInfo
|
SchemaInfo with entities, relations, and attributes |
Source code in type_bridge/migration/schema_manager.py
generate_schema
¶
Generate complete TypeQL schema definition.
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Source code in type_bridge/migration/schema_manager.py
has_existing_schema
¶
Check if database has existing schema defined.
Returns:
| Type | Description |
|---|---|
bool
|
True if database exists and has custom schema beyond built-in types |
Source code in type_bridge/migration/schema_manager.py
introspect_current_schema_info
¶
Introspect current database schema and build SchemaInfo.
Note: This is a best-effort attempt. It cannot perfectly reconstruct Python class hierarchies from TypeDB schema.
Returns:
| Type | Description |
|---|---|
SchemaInfo | None
|
SchemaInfo with current schema, or None if database doesn't exist |
Source code in type_bridge/migration/schema_manager.py
verify_compatibility
¶
Verify that new schema is compatible with old schema.
Checks for breaking changes (removed or modified types/attributes) and raises SchemaConflictError if found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_schema_info
|
SchemaInfo
|
The previous schema to compare against |
required |
Raises:
| Type | Description |
|---|---|
SchemaConflictError
|
If breaking changes are detected |
Source code in type_bridge/migration/schema_manager.py
sync_schema
¶
Synchronize database schema with registered models.
Automatically checks for existing schema in the database and raises SchemaConflictError if schema already exists and might conflict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
If True, recreate database from scratch, ignoring conflicts |
False
|
skip_if_exists
|
bool
|
If True, skip conflict checks when types already exist. Use this for idempotent deployments where you want to ensure the schema is in place without recreating the database. TypeDB 3.x's define statement is idempotent for identical definitions. |
False
|
Raises:
| Type | Description |
|---|---|
SchemaConflictError
|
If database has existing schema and force=False and skip_if_exists=False |
Source code in type_bridge/migration/schema_manager.py
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 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
drop_schema
¶
Drop all schema definitions.
Source code in type_bridge/migration/schema_manager.py
introspect_schema
¶
Introspect current database schema.
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
Dictionary of schema information |
Source code in type_bridge/migration/schema_manager.py
SchemaValidationError
¶
Bases: Exception
Raised when schema validation fails during schema generation.
This exception is raised when the Python model definitions violate TypeDB constraints or best practices.
MigrationManager
¶
Manager for schema migrations.
Initialize migration manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/simple_migration.py
add_migration
¶
Add a migration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Migration name |
required |
schema
|
str
|
TypeQL schema definition |
required |
Source code in type_bridge/migration/simple_migration.py
apply_migrations
¶
Apply all pending migrations.
Source code in type_bridge/migration/simple_migration.py
create_attribute_migration
¶
Create a migration to add an attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_name
|
str
|
Attribute name |
required |
value_type
|
str
|
Value type |
required |
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.py
create_entity_migration
¶
Create a migration to add an entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_name
|
str
|
Entity name |
required |
attributes
|
list[str]
|
List of attribute names |
required |
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.py
create_relation_migration
¶
Create a migration to add a relation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relation_name
|
str
|
Relation name |
required |
roles
|
list[tuple[str, str]]
|
List of (role_name, player_type) tuples |
required |
attributes
|
list[str] | None
|
Optional list of attribute names |
None
|
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.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
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
ProxyDatabase
¶
Drop-in replacement for Database that routes queries through a type-bridge proxy server.
Instead of connecting directly to TypeDB, all queries are sent as HTTP requests to the proxy server's REST API. The proxy handles validation, interceptors (audit log, etc.), and forwarding to TypeDB.
Source code in type_bridge/proxy.py
connect
¶
Verify the proxy server is reachable via health check.
Source code in type_bridge/proxy.py
close
¶
transaction
¶
Create a proxy transaction context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction_type
|
Any
|
Transaction type string ("read", "write", "schema") or TransactionType enum value. |
'read'
|
Source code in type_bridge/proxy.py
execute_query
¶
Execute a query through the proxy and return results.
Source code in type_bridge/proxy.py
get_schema
¶
ProxyError
¶
Query
¶
Builder for TypeQL queries.
Initialize query builder.
Source code in type_bridge/query/__init__.py
match
¶
Add a match clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL match pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
fetch
¶
Add variables and attributes to fetch.
In TypeQL 3.x, fetch uses the syntax: fetch { $e.* } (fetch all attributes)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable
|
str
|
Variable name to fetch (e.g., "$e") |
required |
attributes
|
str
|
Not used in TypeQL 3.x (kept for API compatibility) |
()
|
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Example
query.fetch("$e") # Fetches all attributes
Source code in type_bridge/query/__init__.py
delete
¶
Add a delete clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL delete pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
insert
¶
Add an insert clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL insert pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
limit
¶
Set query limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum number of results |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
offset
¶
Set query offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
int
|
Number of results to skip |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
sort
¶
Add sorting to the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable
|
str
|
Variable to sort by |
required |
direction
|
str
|
Sort direction ("asc" or "desc") |
'asc'
|
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Example
Query().match("$p isa person").fetch("$p").sort("$p", "asc")
Source code in type_bridge/query/__init__.py
build
¶
Build the final TypeQL query string.
Returns:
| Type | Description |
|---|---|
str
|
Complete TypeQL query |
Source code in type_bridge/query/__init__.py
QueryBuilder
¶
Helper class for building queries with model classes.
match_entity
staticmethod
¶
Create a match query for an entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
type[Entity]
|
The entity model class |
required |
var
|
str
|
Variable name to use |
'$e'
|
filters
|
Any
|
Attribute filters (field_name: value) |
{}
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Source code in type_bridge/query/__init__.py
insert_entity
staticmethod
¶
Create an insert query for an entity instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
Entity
|
Entity instance |
required |
var
|
str
|
Variable name to use |
'$e'
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Source code in type_bridge/query/__init__.py
match_relation
staticmethod
¶
Create a match query for a relation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
type[Relation]
|
The relation model class |
required |
var
|
str
|
Variable name to use |
'$r'
|
role_players
|
dict[str, str] | None
|
Dict mapping role names to player variables |
None
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a role name is not defined in the model |
Source code in type_bridge/query/__init__.py
Database
¶
Main database connection and session manager.
Initialize database connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
TypeDB server address |
'localhost:1729'
|
database
|
str
|
Database name |
'typedb'
|
username
|
str | None
|
Optional username for authentication |
None
|
password
|
str | None
|
Optional password for authentication |
None
|
driver
|
Driver | None
|
Optional pre-existing Driver instance to use. If provided, the Database will use this driver instead of creating a new one. The caller retains ownership and is responsible for closing it. |
None
|
Source code in type_bridge/session.py
connect
¶
Connect to TypeDB server.
If a driver was injected via init, this method does nothing (the driver is already connected). Otherwise, creates a new driver.
Source code in type_bridge/session.py
close
¶
Close connection to TypeDB server.
If the driver was injected via init, this method only clears the reference without closing the driver (the caller retains ownership). If the driver was created internally, it will be closed.
Source code in type_bridge/session.py
__enter__
¶
__exit__
¶
__del__
¶
Destructor that warns if driver was not properly closed.
Source code in type_bridge/session.py
create_database
¶
Create the database if it doesn't exist.
Source code in type_bridge/session.py
delete_database
¶
Delete the database.
Source code in type_bridge/session.py
database_exists
¶
transaction
¶
transaction(transaction_type: TransactionType) -> TransactionContext
transaction(transaction_type: str = 'read') -> TransactionContext
Create a transaction context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction_type
|
TransactionType | str
|
TransactionType or string ("read", "write", "schema") |
'read'
|
Returns:
| Type | Description |
|---|---|
TransactionContext
|
TransactionContext for use as a context manager |
Source code in type_bridge/session.py
execute_query
¶
Execute a query and return results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
TypeQL query string |
required |
transaction_type
|
str
|
Type of transaction ("read", "write", or "schema") |
'read'
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of result dictionaries |
Source code in type_bridge/session.py
get_schema
¶
Get the schema definition for this database.
Source code in type_bridge/session.py
TransactionContext
¶
Context manager for sharing a TypeDB transaction across operations.
Source code in type_bridge/session.py
execute
¶
commit
¶
rollback
¶
manager
¶
Get a TypeDBManager bound to this transaction.
Source code in type_bridge/session.py
Flag
¶
Create attribute flags for Key, Unique, and Card markers.
Usage
field: Type = Flag(Key) # @key (implies @card(1..1)) field: Type = Flag(Unique) # @unique @card(1..1) field: list[Type] = Flag(Card(min=2)) # @card(2..) field: list[Type] = Flag(Card(1, 5)) # @card(1..5) field: Type = Flag(Key, Unique) # @key @unique field: list[Type] = Flag(Key, Card(min=1)) # @key @card(1..)
For optional single values, use Optional[Type] instead: field: Optional[Type] # @card(0..1) - no Flag needed
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*annotations
|
Any
|
Variable number of Key, Unique, or Card marker instances |
()
|
Returns:
| Type | Description |
|---|---|
Annotated[Any, AttributeFlags]
|
AttributeFlags instance with the specified flags |
Example
class Person(Entity): flags = TypeFlags(name="person") name: Name = Flag(Key) # @key (implies @card(1..1)) email: Email = Flag(Key, Unique) # @key @unique age: Optional[Age] # @card(0..1) tags: list[Tag] = Flag(Card(min=2)) # @card(2..) jobs: list[Job] = Flag(Card(1, 5)) # @card(1..5)