Skip to content

type_bridge.fields

fields

Field reference system for type-safe query building.

This module provides field descriptors and references that enable type-safe query expressions like Person.age.gt(Age(30)) and Employment.employee.age.gt(Age(30)).

FieldDescriptor

FieldDescriptor(field_name, attr_type)

Descriptor for entity fields that supports dual behavior: - Class-level access: Returns FieldRef[T] for query building - Instance-level access: Returns T (the attribute value)

Create a field descriptor.

Parameters:

Name Type Description Default
field_name str

Python field name

required
attr_type type[T]

Attribute type class

required
Source code in type_bridge/fields/base.py
def __init__(self, field_name: str, attr_type: type[T]):
    """Create a field descriptor.

    Args:
        field_name: Python field name
        attr_type: Attribute type class
    """
    self.field_name = field_name
    self.attr_type = attr_type

__get__

__get__(instance: None, owner: Any) -> FieldRef[T]
__get__(instance: Entity, owner: Any) -> T | None
__get__(instance, owner)

Get field value or field reference.

Parameters:

Name Type Description Default
instance Entity | None

Entity instance (None for class-level access)

required
owner Any

Entity class

required

Returns:

Type Description
FieldRef[T] | T | None

FieldRef[T] for class-level access, T | None for instance-level access

Source code in type_bridge/fields/base.py
def __get__(self, instance: "Entity | None", owner: Any) -> "FieldRef[T] | T | None":
    """Get field value or field reference.

    Args:
        instance: Entity instance (None for class-level access)
        owner: Entity class

    Returns:
        FieldRef[T] for class-level access, T | None for instance-level access
    """
    if instance is None:
        # Class-level access: return FieldRef for query building
        return self._make_field_ref(owner)
    # Instance-level access: return attribute value from Pydantic model
    # Pydantic stores field values in instance.__dict__
    return instance.__dict__.get(self.field_name)

__set__

__set__(instance, value)

Set field value on instance.

Parameters:

Name Type Description Default
instance Entity

Entity instance

required
value T

Attribute value to set

required
Source code in type_bridge/fields/base.py
def __set__(self, instance: "Entity", value: T) -> None:
    """Set field value on instance.

    Args:
        instance: Entity instance
        value: Attribute value to set
    """
    # Store directly in instance __dict__
    # Note: We don't call validate_assignment() here because:
    # 1. The model_validator _wrap_raw_values already handles attribute wrapping
    # 2. Calling validate_assignment triggers the model validator which would
    #    call object.__setattr__ and trigger this __set__ again (infinite recursion)
    # Cast needed because pyright sees __dict__ as potentially MappingProxyType
    inst_dict = cast(dict[str, Any], instance.__dict__)
    inst_dict[self.field_name] = value

FieldRef

FieldRef(field_name, attr_type, entity_type)

Type-safe reference to an entity field.

Returned when accessing entity class attributes (e.g., Person.age). Provides query methods like .gt(), .lt(), etc. that return typed expressions.

Create a field reference.

Parameters:

Name Type Description Default
field_name str

Python field name

required
attr_type type[T]

Attribute type class

required
entity_type Any

Entity type that owns this field

required
Source code in type_bridge/fields/base.py
def __init__(self, field_name: str, attr_type: type[T], entity_type: Any):
    """Create a field reference.

    Args:
        field_name: Python field name
        attr_type: Attribute type class
        entity_type: Entity type that owns this field
    """
    self.field_name = field_name
    self.attr_type = attr_type
    self.entity_type: Any = entity_type

lt

lt(value)

Create a less-than comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field < value

Source code in type_bridge/fields/base.py
def lt(self, value: T) -> "ComparisonExpr[T]":
    """Create a less-than comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field < value
    """
    # Delegate to attribute class method
    return self.attr_type.lt(value)

gt

gt(value)

Create a greater-than comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field > value

Source code in type_bridge/fields/base.py
def gt(self, value: T) -> "ComparisonExpr[T]":
    """Create a greater-than comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field > value
    """
    # Delegate to attribute class method
    return self.attr_type.gt(value)

lte

lte(value)

Create a less-than-or-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field <= value

Source code in type_bridge/fields/base.py
def lte(self, value: T) -> "ComparisonExpr[T]":
    """Create a less-than-or-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field <= value
    """
    # Delegate to attribute class method
    return self.attr_type.lte(value)

gte

gte(value)

Create a greater-than-or-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field >= value

Source code in type_bridge/fields/base.py
def gte(self, value: T) -> "ComparisonExpr[T]":
    """Create a greater-than-or-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field >= value
    """
    # Delegate to attribute class method
    return self.attr_type.gte(value)

eq

eq(value)

Create an equality comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field == value

Source code in type_bridge/fields/base.py
def eq(self, value: T) -> "ComparisonExpr[T]":
    """Create an equality comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field == value
    """
    # Delegate to attribute class method
    return self.attr_type.eq(value)

neq

neq(value)

Create a not-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
ComparisonExpr[T]

ComparisonExpr for this field != value

Source code in type_bridge/fields/base.py
def neq(self, value: T) -> "ComparisonExpr[T]":
    """Create a not-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        ComparisonExpr for this field != value
    """
    # Delegate to attribute class method
    return self.attr_type.neq(value)

NumericFieldRef

NumericFieldRef(field_name, attr_type, entity_type)

Bases: FieldRef[T]

Field reference for numeric attribute types.

Provides additional numeric-specific operations like sum, avg, max, min.

Source code in type_bridge/fields/base.py
def __init__(self, field_name: str, attr_type: type[T], entity_type: Any):
    """Create a field reference.

    Args:
        field_name: Python field name
        attr_type: Attribute type class
        entity_type: Entity type that owns this field
    """
    self.field_name = field_name
    self.attr_type = attr_type
    self.entity_type: Any = entity_type

sum

sum()

Create a sum aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for sum of this field

Source code in type_bridge/fields/base.py
def sum(self) -> "AggregateExpr[T]":
    """Create a sum aggregation expression.

    Returns:
        AggregateExpr for sum of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(attr_type=self.attr_type, function="sum", field_name=self.field_name)

avg

avg()

Create an average (mean) aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for average/mean of this field

Source code in type_bridge/fields/base.py
def avg(self) -> "AggregateExpr[T]":
    """Create an average (mean) aggregation expression.

    Returns:
        AggregateExpr for average/mean of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(attr_type=self.attr_type, function="mean", field_name=self.field_name)

max

max()

Create a maximum aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for maximum of this field

Source code in type_bridge/fields/base.py
def max(self) -> "AggregateExpr[T]":
    """Create a maximum aggregation expression.

    Returns:
        AggregateExpr for maximum of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(attr_type=self.attr_type, function="max", field_name=self.field_name)

min

min()

Create a minimum aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for minimum of this field

Source code in type_bridge/fields/base.py
def min(self) -> "AggregateExpr[T]":
    """Create a minimum aggregation expression.

    Returns:
        AggregateExpr for minimum of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(attr_type=self.attr_type, function="min", field_name=self.field_name)

median

median()

Create a median aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for median of this field

Source code in type_bridge/fields/base.py
def median(self) -> "AggregateExpr[T]":
    """Create a median aggregation expression.

    Returns:
        AggregateExpr for median of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(
        attr_type=self.attr_type, function="median", field_name=self.field_name
    )

std

std()

Create a standard deviation aggregation expression.

Returns:

Type Description
AggregateExpr[T]

AggregateExpr for standard deviation of this field

Source code in type_bridge/fields/base.py
def std(self) -> "AggregateExpr[T]":
    """Create a standard deviation aggregation expression.

    Returns:
        AggregateExpr for standard deviation of this field
    """
    from type_bridge.expressions import AggregateExpr

    return AggregateExpr(attr_type=self.attr_type, function="std", field_name=self.field_name)

StringFieldRef

StringFieldRef(field_name, attr_type, entity_type)

Bases: FieldRef[T]

Field reference for String attribute types.

Provides additional string-specific operations like contains, like, regex.

Source code in type_bridge/fields/base.py
def __init__(self, field_name: str, attr_type: type[T], entity_type: Any):
    """Create a field reference.

    Args:
        field_name: Python field name
        attr_type: Attribute type class
        entity_type: Entity type that owns this field
    """
    self.field_name = field_name
    self.attr_type = attr_type
    self.entity_type: Any = entity_type

contains

contains(value)

Create a string contains expression.

Parameters:

Name Type Description Default
value T

Substring to search for

required

Returns:

Type Description
StringExpr[T]

StringExpr for this field contains value

Source code in type_bridge/fields/base.py
def contains(self, value: T) -> "StringExpr[T]":
    """Create a string contains expression.

    Args:
        value: Substring to search for

    Returns:
        StringExpr for this field contains value
    """
    # Delegate to attribute class method
    return self.attr_type.contains(value)

like

like(pattern)

Create a string pattern matching expression (regex).

Parameters:

Name Type Description Default
pattern T

Regex pattern to match

required

Returns:

Type Description
StringExpr[T]

StringExpr for this field like pattern

Source code in type_bridge/fields/base.py
def like(self, pattern: T) -> "StringExpr[T]":
    """Create a string pattern matching expression (regex).

    Args:
        pattern: Regex pattern to match

    Returns:
        StringExpr for this field like pattern
    """
    # Delegate to attribute class method
    return self.attr_type.like(pattern)

regex

regex(pattern)

Create a string regex expression (alias for like).

Parameters:

Name Type Description Default
pattern T

Regex pattern to match

required

Returns:

Type Description
StringExpr[T]

StringExpr for this field matching pattern

Source code in type_bridge/fields/base.py
def regex(self, pattern: T) -> "StringExpr[T]":
    """Create a string regex expression (alias for like).

    Args:
        pattern: Regex pattern to match

    Returns:
        StringExpr for this field matching pattern
    """
    # Delegate to attribute class method
    return self.attr_type.regex(pattern)

RolePlayerFieldRef

RolePlayerFieldRef(role_name, field_name, attr_type, player_types)

Field reference for role-player attributes.

Provides comparison methods that return RolePlayerExpr instead of regular ComparisonExpr, adding role context for proper TypeQL generation.

Example

Employment.employee.age # Returns RolePlayerNumericFieldRef[Age] Employment.employee.age.gt(Age(30)) # Returns RolePlayerExpr

Create a role-player field reference.

Parameters:

Name Type Description Default
role_name str

Name of the role (e.g., "employee")

required
field_name str

Python field name on the player entity

required
attr_type type[T]

Attribute type class

required
player_types tuple[type[TypeDBType], ...]

Tuple of entity types that can play this role

required
Source code in type_bridge/fields/role.py
def __init__(
    self,
    role_name: str,
    field_name: str,
    attr_type: type[T],
    player_types: tuple[type[TypeDBType], ...],
):
    """Create a role-player field reference.

    Args:
        role_name: Name of the role (e.g., "employee")
        field_name: Python field name on the player entity
        attr_type: Attribute type class
        player_types: Tuple of entity types that can play this role
    """
    self.role_name = role_name
    self.field_name = field_name
    self.attr_type = attr_type
    self.player_types = player_types

lt

lt(value)

Create a less-than comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a less-than comparison

Source code in type_bridge/fields/role.py
def lt(self, value: T) -> RolePlayerExpr:
    """Create a less-than comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping a less-than comparison
    """
    return self._wrap_expr(self.attr_type.lt(value))

gt

gt(value)

Create a greater-than comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a greater-than comparison

Source code in type_bridge/fields/role.py
def gt(self, value: T) -> RolePlayerExpr:
    """Create a greater-than comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping a greater-than comparison
    """
    return self._wrap_expr(self.attr_type.gt(value))

lte

lte(value)

Create a less-than-or-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a less-than-or-equal comparison

Source code in type_bridge/fields/role.py
def lte(self, value: T) -> RolePlayerExpr:
    """Create a less-than-or-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping a less-than-or-equal comparison
    """
    return self._wrap_expr(self.attr_type.lte(value))

gte

gte(value)

Create a greater-than-or-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a greater-than-or-equal comparison

Source code in type_bridge/fields/role.py
def gte(self, value: T) -> RolePlayerExpr:
    """Create a greater-than-or-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping a greater-than-or-equal comparison
    """
    return self._wrap_expr(self.attr_type.gte(value))

eq

eq(value)

Create an equality comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping an equality comparison

Source code in type_bridge/fields/role.py
def eq(self, value: T) -> RolePlayerExpr:
    """Create an equality comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping an equality comparison
    """
    return self._wrap_expr(self.attr_type.eq(value))

neq

neq(value)

Create a not-equal comparison expression.

Parameters:

Name Type Description Default
value T

Value to compare against

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a not-equal comparison

Source code in type_bridge/fields/role.py
def neq(self, value: T) -> RolePlayerExpr:
    """Create a not-equal comparison expression.

    Args:
        value: Value to compare against

    Returns:
        RolePlayerExpr wrapping a not-equal comparison
    """
    return self._wrap_expr(self.attr_type.neq(value))

RolePlayerNumericFieldRef

RolePlayerNumericFieldRef(role_name, field_name, attr_type, player_types)

Bases: RolePlayerFieldRef[T]

Role-player field reference for numeric attributes.

Inherits comparison methods from RolePlayerFieldRef. Aggregation methods (sum, avg, etc.) are not supported for role-player fields as they require grouping context.

Example

Employment.employee.age # Returns RolePlayerNumericFieldRef[Age] Employment.employee.age.gt(Age(30)) # Returns RolePlayerExpr

Source code in type_bridge/fields/role.py
def __init__(
    self,
    role_name: str,
    field_name: str,
    attr_type: type[T],
    player_types: tuple[type[TypeDBType], ...],
):
    """Create a role-player field reference.

    Args:
        role_name: Name of the role (e.g., "employee")
        field_name: Python field name on the player entity
        attr_type: Attribute type class
        player_types: Tuple of entity types that can play this role
    """
    self.role_name = role_name
    self.field_name = field_name
    self.attr_type = attr_type
    self.player_types = player_types

RolePlayerStringFieldRef

RolePlayerStringFieldRef(role_name, field_name, attr_type, player_types)

Bases: RolePlayerFieldRef[T]

Role-player field reference for String attributes.

Provides additional string-specific operations like contains, like, regex, all wrapped in RolePlayerExpr for proper role context.

Example

Employment.employer.name # Returns RolePlayerStringFieldRef[Name] Employment.employer.name.contains(Name("Tech")) # Returns RolePlayerExpr

Source code in type_bridge/fields/role.py
def __init__(
    self,
    role_name: str,
    field_name: str,
    attr_type: type[T],
    player_types: tuple[type[TypeDBType], ...],
):
    """Create a role-player field reference.

    Args:
        role_name: Name of the role (e.g., "employee")
        field_name: Python field name on the player entity
        attr_type: Attribute type class
        player_types: Tuple of entity types that can play this role
    """
    self.role_name = role_name
    self.field_name = field_name
    self.attr_type = attr_type
    self.player_types = player_types

contains

contains(value)

Create a string contains expression.

Parameters:

Name Type Description Default
value T

Substring to search for

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a contains expression

Source code in type_bridge/fields/role.py
def contains(self, value: T) -> RolePlayerExpr:
    """Create a string contains expression.

    Args:
        value: Substring to search for

    Returns:
        RolePlayerExpr wrapping a contains expression
    """
    return self._wrap_expr(self.attr_type.contains(value))

like

like(pattern)

Create a string pattern matching expression.

Parameters:

Name Type Description Default
pattern T

Pattern to match (SQL LIKE style)

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a like expression

Source code in type_bridge/fields/role.py
def like(self, pattern: T) -> RolePlayerExpr:
    """Create a string pattern matching expression.

    Args:
        pattern: Pattern to match (SQL LIKE style)

    Returns:
        RolePlayerExpr wrapping a like expression
    """
    return self._wrap_expr(self.attr_type.like(pattern))

regex

regex(pattern)

Create a string regex expression.

Parameters:

Name Type Description Default
pattern T

Regex pattern to match

required

Returns:

Type Description
RolePlayerExpr

RolePlayerExpr wrapping a regex expression

Source code in type_bridge/fields/role.py
def regex(self, pattern: T) -> RolePlayerExpr:
    """Create a string regex expression.

    Args:
        pattern: Regex pattern to match

    Returns:
        RolePlayerExpr wrapping a regex expression
    """
    return self._wrap_expr(self.attr_type.regex(pattern))

RoleRef

RoleRef(role_name, player_types)

Reference to a role for type-safe attribute access.

Returned when accessing a Role descriptor from the Relation class level. Enables chained attribute access for building type-safe filter expressions.

Example

Employment.employee # Returns RoleRef[Person] Employment.employee.age # Returns RolePlayerNumericFieldRef[Age] Employment.employee.age.gt(Age(30)) # Returns RolePlayerExpr

For Role.multi() (polymorphic roles), attributes from all player types are available. If an attribute exists on at least one player type, it can be accessed.

Relations can also be role players

Permission.permitted_access # Returns RoleRef[Access] where Access is a Relation

Create a role reference.

Parameters:

Name Type Description Default
role_name str

Name of the role (e.g., "employee")

required
player_types tuple[type[T], ...]

Tuple of types (Entity or Relation) that can play this role

required
Source code in type_bridge/fields/role.py
def __init__(
    self,
    role_name: str,
    player_types: tuple[type[T], ...],
):
    """Create a role reference.

    Args:
        role_name: Name of the role (e.g., "employee")
        player_types: Tuple of types (Entity or Relation) that can play this role
    """
    self.role_name = role_name
    self.player_types = player_types
    # Cache of collected attributes from all player types
    self._player_attrs: dict[str, tuple[type, Any]] | None = None

__getattr__

__getattr__(name)

Access role-player attribute for query building.

Parameters:

Name Type Description Default
name str

Attribute name to access

required

Returns:

Type Description
RolePlayerFieldRef[Any]

Appropriate RolePlayerFieldRef subclass based on attribute type

Raises:

Type Description
AttributeError

If attribute doesn't exist on any player type

Source code in type_bridge/fields/role.py
def __getattr__(self, name: str) -> RolePlayerFieldRef[Any]:
    """Access role-player attribute for query building.

    Args:
        name: Attribute name to access

    Returns:
        Appropriate RolePlayerFieldRef subclass based on attribute type

    Raises:
        AttributeError: If attribute doesn't exist on any player type
    """
    # Avoid infinite recursion for special attributes
    if name.startswith("_"):
        raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")

    player_attrs = self._get_player_attrs()

    if name not in player_attrs:
        available = sorted(player_attrs.keys())
        raise AttributeError(
            f"Role '{self.role_name}' players do not have attribute '{name}'. "
            f"Available attributes: {available}"
        )

    attr_type, _attr_info = player_attrs[name]
    return self._make_field_ref(name, attr_type)

__dir__

__dir__()

Enable IDE autocompletion for available player attributes.

Returns:

Type Description
list[str]

List of available attribute names from all player types

Source code in type_bridge/fields/role.py
def __dir__(self) -> list[str]:
    """Enable IDE autocompletion for available player attributes.

    Returns:
        List of available attribute names from all player types
    """
    return sorted(self._get_player_attrs().keys())