Skip to content

type_bridge.expressions

expressions

Type-safe query expression system for TypeBridge.

This module provides expression classes for building type-safe TypeQL queries.

AggregateExpr

AggregateExpr(attr_type=None, function='count', field_name=None)

Bases: Expression

Type-safe aggregate expression for database-side calculations.

Represents aggregations like sum(age), avg(score), count(*), etc.

Create an aggregate expression.

Parameters:

Name Type Description Default
attr_type type[T] | None

Attribute type to aggregate (None for count)

None
function Literal['sum', 'mean', 'max', 'min', 'count', 'median', 'std']

Aggregation function (use 'mean' for TypeDB 3.x, not 'avg')

'count'
field_name str | None

Python field name (used for result keys, e.g., 'salary' → 'avg_salary')

None
Note

The user-facing avg() method automatically converts to 'mean'. TypeDB 3.x uses 'mean' instead of 'avg'.

Source code in type_bridge/expressions/aggregate.py
def __init__(
    self,
    attr_type: type[T] | None = None,
    function: Literal["sum", "mean", "max", "min", "count", "median", "std"] = "count",
    field_name: str | None = None,
):
    """Create an aggregate expression.

    Args:
        attr_type: Attribute type to aggregate (None for count)
        function: Aggregation function (use 'mean' for TypeDB 3.x, not 'avg')
        field_name: Python field name (used for result keys, e.g., 'salary' → 'avg_salary')

    Note:
        The user-facing avg() method automatically converts to 'mean'.
        TypeDB 3.x uses 'mean' instead of 'avg'.
    """
    self.attr_type = attr_type
    self.function = function
    self.field_name = field_name

    # Validate attr_type requirement
    if function != "count" and attr_type is None:
        raise ValueError(f"{function.upper()} requires an attribute type")

to_value_ast

to_value_ast(var=None)

Convert to AST FunctionCallValue.

Parameters:

Name Type Description Default
var str | None

Variable name required for aggregate expressions (e.g., "$e")

None

Raises:

Type Description
ValueError

If var is not provided (aggregates require context)

Source code in type_bridge/expressions/aggregate.py
def to_value_ast(self, var: str | None = None) -> "Value":
    """Convert to AST FunctionCallValue.

    Args:
        var: Variable name required for aggregate expressions (e.g., "$e")

    Raises:
        ValueError: If var is not provided (aggregates require context)
    """
    from type_bridge.query.ast import FunctionCallValue

    if var is None:
        raise ValueError("AggregateExpr.to_value_ast() requires a variable name")

    if self.function == "count":
        return FunctionCallValue(function="count", args=[var])

    assert self.attr_type is not None
    from type_bridge.expressions.utils import generate_attr_var

    attr_var = generate_attr_var(var, self.attr_type)
    return FunctionCallValue(function=self.function, args=[attr_var])

to_typeql

to_typeql(var)

Deprecated: Generate TypeQL pattern for this aggregation.

Source code in type_bridge/expressions/aggregate.py
def to_typeql(self, var: str) -> str:
    """Deprecated: Generate TypeQL pattern for this aggregation."""
    if self.function == "count":
        return f"count({var})"

    assert self.attr_type is not None
    from type_bridge.expressions.utils import generate_attr_var

    attr_var = generate_attr_var(var, self.attr_type)
    return f"{self.function}({attr_var})"

get_fetch_key

get_fetch_key()

Get the key to use in fetch results.

Note

AUTOMATIC CONVERSION: TypeQL 'mean' → result key 'avg' For user-facing consistency, result keys use 'avg' even though TypeDB internally uses 'mean'. This matches the method name.

Returns:

Type Description
str

String key for accessing aggregate result

Example

Person.salary.avg() generates TypeQL 'mean($personsalary)' but result key is 'avg_salary' (using field name, not attribute type name)

Source code in type_bridge/expressions/aggregate.py
def get_fetch_key(self) -> str:
    """Get the key to use in fetch results.

    Note:
        AUTOMATIC CONVERSION: TypeQL 'mean' → result key 'avg'
        For user-facing consistency, result keys use 'avg' even though
        TypeDB internally uses 'mean'. This matches the method name.

    Returns:
        String key for accessing aggregate result

    Example:
        Person.salary.avg() generates TypeQL 'mean($personsalary)'
        but result key is 'avg_salary' (using field name, not attribute type name)
    """
    if self.function == "count":
        return "count"

    assert self.attr_type is not None
    # AUTOMATIC CONVERSION: Map 'mean' back to 'avg' for user-facing API
    func_name = "avg" if self.function == "mean" else self.function

    # Use field_name if available (from FieldRef), otherwise fall back to attribute type name
    if self.field_name:
        return f"{func_name}_{self.field_name}"
    else:
        attr_type_name = self.attr_type.get_attribute_name()
        return f"{func_name}_{attr_type_name.lower()}"

ArithmeticExpr dataclass

ArithmeticExpr(left, operator, right)

Bases: Expression

Binary arithmetic expression for TypeQL queries.

Represents an infix operation like $x + $y or $price * 1.1.

Example

expr = ArithmeticExpr("$x", "+", "$y") expr.to_typeql("$unused") '($x + $y)'

In a let assignment:

let $total = ($price * $quantity);

to_ast

to_ast(var)

Arithmetic expressions are values, not match patterns.

Source code in type_bridge/expressions/arithmetic.py
def to_ast(self, var: str) -> list[Pattern]:
    """Arithmetic expressions are values, not match patterns."""
    return []

to_value_ast

to_value_ast(var=None)

Convert to an ArithmeticValue AST node.

Source code in type_bridge/expressions/arithmetic.py
def to_value_ast(self, var: str | None = None) -> Value:
    """Convert to an ArithmeticValue AST node."""
    from type_bridge.query.ast import ArithmeticValue

    left: Value | str = self.left
    right: Value | str = self.right

    # If either operand is itself an ArithmeticExpr (nested), recurse
    # For now, operands are always strings (variables or literals)
    return ArithmeticValue(left=left, operator=self.operator, right=right)

to_typeql

to_typeql(var)

Generate parenthesized TypeQL arithmetic expression.

Parameters:

Name Type Description Default
var str

Ignored (arithmetic expressions use their own operands)

required

Returns:

Type Description
str

Parenthesized TypeQL expression, e.g. "($x + $y)"

Source code in type_bridge/expressions/arithmetic.py
def to_typeql(self, var: str) -> str:
    """Generate parenthesized TypeQL arithmetic expression.

    Args:
        var: Ignored (arithmetic expressions use their own operands)

    Returns:
        Parenthesized TypeQL expression, e.g. "($x + $y)"
    """
    return f"({self.left} {self.operator} {self.right})"

get_attribute_types

get_attribute_types()

Arithmetic expressions don't reference attribute types directly.

Source code in type_bridge/expressions/arithmetic.py
def get_attribute_types(self) -> set[type[Attribute]]:
    """Arithmetic expressions don't reference attribute types directly."""
    return set()

Expression

Bases: ABC

Base class for all query expressions.

Expressions represent query constraints that can be composed using boolean operators and converted to TypeQL patterns.

to_ast abstractmethod

to_ast(var)

Convert this expression to AST patterns.

Parameters:

Name Type Description Default
var str

The variable name to use in the pattern (e.g., "$e")

required

Returns:

Type Description
list[Pattern]

List of AST patterns

Source code in type_bridge/expressions/base.py
@abstractmethod
def to_ast(self, var: str) -> list["Pattern"]:
    """Convert this expression to AST patterns.

    Args:
        var: The variable name to use in the pattern (e.g., "$e")

    Returns:
        List of AST patterns
    """
    ...

to_value_ast

to_value_ast(var=None)

Convert this expression to an AST Value (if applicable).

Most expressions are patterns (filters) and cannot be converted to values. FunctionCall expressions and Literal wrappers are values.

Parameters:

Name Type Description Default
var str | None

Optional variable name for aggregate expressions that need context.

None

Raises:

Type Description
NotImplementedError

If expression cannot be converted to a value.

Source code in type_bridge/expressions/base.py
def to_value_ast(self, var: str | None = None) -> "Value":
    """Convert this expression to an AST Value (if applicable).

    Most expressions are patterns (filters) and cannot be converted to values.
    FunctionCall expressions and Literal wrappers are values.

    Args:
        var: Optional variable name for aggregate expressions that need context.

    Raises:
        NotImplementedError: If expression cannot be converted to a value.
    """
    raise NotImplementedError(f"{type(self).__name__} cannot be converted to an AST Value.")

to_typeql

to_typeql(var)

Deprecated: Use to_ast() instead.

Source code in type_bridge/expressions/base.py
def to_typeql(self, var: str) -> str:
    """Deprecated: Use to_ast() instead."""
    from type_bridge.query.compiler import QueryCompiler

    compiler = QueryCompiler()
    patterns = self.to_ast(var)
    # We need to compile each pattern and join them?
    # Compiler has _compile_pattern.
    # But _compile_pattern is private.
    # compiler.compile() takes a Clause.
    # We can create a temporary MatchClause?
    from type_bridge.query.ast import MatchClause

    return compiler.compile(MatchClause(patterns=patterns)).replace("match\n", "").strip(";")

get_attribute_types

get_attribute_types()

Get all attribute types referenced by this expression.

Returns:

Type Description
set[type[Attribute]]

Set of attribute types used in this expression

Note

Default implementation returns attr_type if present. BooleanExpr overrides to recursively collect from operands.

Source code in type_bridge/expressions/base.py
def get_attribute_types(self) -> set[type["Attribute"]]:
    """Get all attribute types referenced by this expression.

    Returns:
        Set of attribute types used in this expression

    Note:
        Default implementation returns attr_type if present.
        BooleanExpr overrides to recursively collect from operands.
    """
    # Check if this expression has attr_type attribute
    attr_type = getattr(self, "attr_type", None)
    if attr_type is not None:
        return {attr_type}
    return set()

and_

and_(other)

Combine this expression with another using AND logic.

Parameters:

Name Type Description Default
other Expression

Another expression to AND with this one

required

Returns:

Type Description
BooleanExpr

BooleanExpr representing the conjunction

Source code in type_bridge/expressions/base.py
def and_(self, other: "Expression") -> "BooleanExpr":
    """Combine this expression with another using AND logic.

    Args:
        other: Another expression to AND with this one

    Returns:
        BooleanExpr representing the conjunction
    """
    from type_bridge.expressions.boolean import BooleanExpr

    return BooleanExpr(operation="and", operands=[self, other])

or_

or_(other)

Combine this expression with another using OR logic.

Parameters:

Name Type Description Default
other Expression

Another expression to OR with this one

required

Returns:

Type Description
BooleanExpr

BooleanExpr representing the disjunction

Source code in type_bridge/expressions/base.py
def or_(self, other: "Expression") -> "BooleanExpr":
    """Combine this expression with another using OR logic.

    Args:
        other: Another expression to OR with this one

    Returns:
        BooleanExpr representing the disjunction
    """
    from type_bridge.expressions.boolean import BooleanExpr

    return BooleanExpr(operation="or", operands=[self, other])

not_

not_()

Negate this expression using NOT logic.

Returns:

Type Description
BooleanExpr

BooleanExpr representing the negation

Source code in type_bridge/expressions/base.py
def not_(self) -> "BooleanExpr":
    """Negate this expression using NOT logic.

    Returns:
        BooleanExpr representing the negation
    """
    from type_bridge.expressions.boolean import BooleanExpr

    return BooleanExpr(operation="not", operands=[self])

BooleanExpr

BooleanExpr(operation, operands)

Bases: Expression

Boolean expression for combining other expressions with AND, OR, NOT.

Represents logical combinations of query constraints.

Create a boolean expression.

Parameters:

Name Type Description Default
operation Literal['and', 'or', 'not']

Boolean operation type

required
operands list[Expression]

List of expressions to combine

required
Source code in type_bridge/expressions/boolean.py
def __init__(
    self,
    operation: Literal["and", "or", "not"],
    operands: list[Expression],
):
    """Create a boolean expression.

    Args:
        operation: Boolean operation type
        operands: List of expressions to combine
    """
    self.operation = operation
    self.operands = operands

    # Validate operand count
    if operation == "not" and len(operands) != 1:
        raise ValueError("NOT operation requires exactly 1 operand")
    if operation in ("and", "or") and len(operands) < 2:
        raise ValueError(f"{operation.upper()} operation requires at least 2 operands")

get_attribute_types

get_attribute_types()

Get all attribute types referenced by this boolean expression.

Recursively collects attribute types from all operands.

Returns:

Type Description
set[type[Attribute]]

Set of attribute types used in this expression and its operands

Source code in type_bridge/expressions/boolean.py
def get_attribute_types(self) -> set[type[Attribute]]:
    """Get all attribute types referenced by this boolean expression.

    Recursively collects attribute types from all operands.

    Returns:
        Set of attribute types used in this expression and its operands
    """
    result = set()
    for operand in self.operands:
        result.update(operand.get_attribute_types())
    return result

to_ast

to_ast(var)

Generate AST patterns for this boolean expression.

Source code in type_bridge/expressions/boolean.py
def to_ast(self, var: str) -> list[Pattern]:
    """Generate AST patterns for this boolean expression."""
    from type_bridge.query.ast import NotPattern, OrPattern

    if self.operation == "and":
        # Flatten all patterns from operands
        all_patterns = []
        for op in self.operands:
            all_patterns.extend(op.to_ast(var))
        return all_patterns

    if self.operation == "or":
        # Operands define alternatives
        # Each operand produces a list of patterns (a conjunction block)
        alternatives = [op.to_ast(var) for op in self.operands]
        return [OrPattern(alternatives=alternatives)]

    if self.operation == "not":
        # Negate the conjunction of the operand's patterns
        # Typically NOT applies to a block
        operand_patterns = self.operands[0].to_ast(var)
        return [NotPattern(patterns=operand_patterns)]

    raise ValueError(f"Unknown boolean operation: {self.operation}")

and_

and_(other)

Combine with another expression using AND, flattening if possible.

If this is already an AND expression, adds the new operand to create a flat structure instead of a nested binary tree.

Parameters:

Name Type Description Default
other Expression

Another expression to AND with this one

required

Returns:

Type Description
BooleanExpr

BooleanExpr with flattened operands

Source code in type_bridge/expressions/boolean.py
def and_(self, other: Expression) -> BooleanExpr:
    """Combine with another expression using AND, flattening if possible.

    If this is already an AND expression, adds the new operand to create
    a flat structure instead of a nested binary tree.

    Args:
        other: Another expression to AND with this one

    Returns:
        BooleanExpr with flattened operands
    """
    if self.operation == "and":
        # Flatten: (a AND b).and_(c) -> (a AND b AND c)
        return BooleanExpr("and", [*self.operands, other])
    # Different operation, must wrap
    return BooleanExpr("and", [self, other])

or_

or_(other)

Combine with another expression using OR, flattening if possible.

If this is already an OR expression, adds the new operand to create a flat structure instead of a nested binary tree. This is critical for avoiding TypeDB query planner stack overflow with many values.

Parameters:

Name Type Description Default
other Expression

Another expression to OR with this one

required

Returns:

Type Description
BooleanExpr

BooleanExpr with flattened operands

Source code in type_bridge/expressions/boolean.py
def or_(self, other: Expression) -> BooleanExpr:
    """Combine with another expression using OR, flattening if possible.

    If this is already an OR expression, adds the new operand to create
    a flat structure instead of a nested binary tree. This is critical
    for avoiding TypeDB query planner stack overflow with many values.

    Args:
        other: Another expression to OR with this one

    Returns:
        BooleanExpr with flattened operands
    """
    if self.operation == "or":
        # Flatten: (a OR b).or_(c) -> (a OR b OR c)
        return BooleanExpr("or", [*self.operands, other])
    # Different operation, must wrap
    return BooleanExpr("or", [self, other])

BuiltinFunctionExpr dataclass

BuiltinFunctionExpr(name, *args)

Bases: Expression

Expression for TypeQL built-in functions.

Built-in functions can be used in fetch clauses, let assignments, and other expression contexts.

Example

expr = BuiltinFunctionExpr("iid", "$e") expr.to_typeql("$e") 'iid($e)'

In a fetch clause:

fetch

Create a built-in function expression.

Parameters:

Name Type Description Default
name str

Function name (iid, label, abs, ceil, floor, round, len, max, min)

required
*args str

Variable names or literal values as arguments

()
Source code in type_bridge/expressions/builtin.py
def __init__(self, name: str, *args: str):
    """Create a built-in function expression.

    Args:
        name: Function name (iid, label, abs, ceil, floor, round, len, max, min)
        *args: Variable names or literal values as arguments
    """
    self.name = name
    self.args = args

to_ast

to_ast(var)

Built-in functions are values, not patterns.

Use to_value_ast() instead for AST representation.

Source code in type_bridge/expressions/builtin.py
def to_ast(self, var: str) -> list[Pattern]:
    """Built-in functions are values, not patterns.

    Use to_value_ast() instead for AST representation.
    """
    # Return empty list since built-in functions don't produce match patterns
    return []

to_typeql

to_typeql(var)

Generate TypeQL for this built-in function call.

Parameters:

Name Type Description Default
var str

Ignored (built-in functions use their own args)

required

Returns:

Type Description
str

TypeQL function call string (e.g., "iid($e)")

Source code in type_bridge/expressions/builtin.py
def to_typeql(self, var: str) -> str:
    """Generate TypeQL for this built-in function call.

    Args:
        var: Ignored (built-in functions use their own args)

    Returns:
        TypeQL function call string (e.g., "iid($e)")
    """
    args_str = ", ".join(self.args)
    return f"{self.name}({args_str})"

to_value_ast

to_value_ast(var=None)

Convert to AST FunctionCallValue.

Source code in type_bridge/expressions/builtin.py
def to_value_ast(self, var: str | None = None) -> Value:
    """Convert to AST FunctionCallValue."""
    from type_bridge.query.ast import FunctionCallValue

    return FunctionCallValue(function=self.name, args=list(self.args))

get_attribute_types

get_attribute_types()

Built-in functions don't reference attribute types.

Source code in type_bridge/expressions/builtin.py
def get_attribute_types(self) -> set[type[Attribute]]:
    """Built-in functions don't reference attribute types."""
    return set()

AttributeExistsExpr

AttributeExistsExpr(attr_type, present)

Bases: Expression

Attribute presence/absence check expression.

Source code in type_bridge/expressions/comparison.py
def __init__(self, attr_type: type[T], present: bool):
    self.attr_type = attr_type
    self.present = present

ComparisonExpr

ComparisonExpr(attr_type, operator, value)

Bases: Expression

Type-safe comparison expression for filtering by attribute values.

Represents comparisons like age > 30, score <= 100, etc.

Create a comparison expression.

Parameters:

Name Type Description Default
attr_type type[T]

Attribute type to filter on

required
operator Literal['>', '<', '>=', '<=', '==', '!=']

Comparison operator

required
value T

Value to compare against

required
Source code in type_bridge/expressions/comparison.py
def __init__(
    self,
    attr_type: type[T],
    operator: Literal[">", "<", ">=", "<=", "==", "!="],
    value: T,
):
    """Create a comparison expression.

    Args:
        attr_type: Attribute type to filter on
        operator: Comparison operator
        value: Value to compare against
    """
    self.attr_type = attr_type
    self.operator = operator
    self.value = value

to_ast

to_ast(var)

Generate AST patterns for this comparison.

Example: "$e has age $e_age; $e_age > 30"

Source code in type_bridge/expressions/comparison.py
def to_ast(self, var: str) -> list["Pattern"]:
    """Generate AST patterns for this comparison.

    Example: "$e has age $e_age; $e_age > 30"
    """
    from type_bridge.crud.patterns import _get_literal_type
    from type_bridge.query.ast import (
        HasPattern,
        LiteralValue,
        ValueComparisonPattern,
    )

    attr_type_name = self.attr_type.get_attribute_name()
    attr_var = generate_attr_var(var, self.attr_type)

    # Unwrap value from Attribute wrapper if needed
    raw_value = self.value.value if hasattr(self.value, "value") else self.value
    literal_type = _get_literal_type(raw_value)

    return [
        HasPattern(thing_var=var, attr_type=attr_type_name, attr_var=attr_var),
        ValueComparisonPattern(
            var=attr_var,
            operator=self.operator,
            value=LiteralValue(value=raw_value, value_type=literal_type),
        ),
    ]

FunctionCallExpr dataclass

FunctionCallExpr(name, args)

Bases: Expression

Represents a call to a TypeDB function.

to_value_ast

to_value_ast(var=None)

Convert to AST FunctionCallValue.

Source code in type_bridge/expressions/functions.py
def to_value_ast(self, var: str | None = None) -> Value:
    """Convert to AST FunctionCallValue."""
    from type_bridge.query.ast import FunctionCallValue, LiteralValue

    ast_args: list[Value | str] = []
    for arg in self.args:
        if isinstance(arg, Expression):
            ast_args.append(arg.to_value_ast(var))
        elif isinstance(arg, bool):
            ast_args.append(LiteralValue(arg, "boolean"))
        elif isinstance(arg, int):
            ast_args.append(LiteralValue(arg, "long"))
        elif isinstance(arg, float):
            ast_args.append(LiteralValue(arg, "double"))
        elif isinstance(arg, str):
            # Variables pass through as-is
            if arg.startswith("$"):
                ast_args.append(arg)
            else:
                ast_args.append(LiteralValue(arg, "string"))
        else:
            # Unknown types default to string
            ast_args.append(LiteralValue(arg, "string"))

    return FunctionCallValue(function=self.name, args=ast_args)

to_typeql

to_typeql(var)

Deprecated: generate TypeQL function call syntax.

Source code in type_bridge/expressions/functions.py
def to_typeql(self, var: str) -> str:
    """Deprecated: generate TypeQL function call syntax."""
    arg_strs = []
    for arg in self.args:
        if isinstance(arg, Expression):
            arg_strs.append(arg.to_typeql(var))
        else:
            arg_strs.append(str(arg))

    return f"{self.name}({', '.join(arg_strs)})"

FunctionQuery dataclass

FunctionQuery(name, return_type, args=list(), docstring=None)

A TypeDB function call with query generation capabilities.

This class wraps a TypeDB schema function and provides methods to generate complete TypeQL queries for calling the function.

Attributes:

Name Type Description
name str

The TypeDB function name (e.g., "count-artifacts")

args list[tuple[str, Any]]

Ordered list of (param_name, value) tuples

return_type ReturnType

Description of what the function returns

docstring str | None

Optional documentation for the function

Example

Simple count function

fn = FunctionQuery( ... name="count-artifacts", ... return_type=ReturnType(["integer"], is_stream=False), ... ) fn.to_query() 'match let $result = count-artifacts(); fetch { "result": $result };'

Stream function with parameter

fn = FunctionQuery( ... name="get-neighbor-ids", ... args=[("$target_id", '"abc-123"')], ... return_type=ReturnType(["id"], is_stream=True), ... ) fn.to_query(limit=10) 'match let $id in get-neighbor-ids("abc-123"); limit 10; fetch { "id": $id };'

Composite return type

fn = FunctionQuery( ... name="count-artifacts-by-type", ... return_type=ReturnType(["artifact", "integer"], is_stream=True), ... ) fn.to_query() 'match let $artifact, $integer in count-artifacts-by-type(); fetch { "artifact": $artifact, "integer": $integer };'

to_call_ast

to_call_ast()

Generate AST for function call.

Source code in type_bridge/expressions/functions.py
def to_call_ast(self) -> FunctionCallValue:
    """Generate AST for function call."""
    from type_bridge.query.ast import FunctionCallValue

    ast_args = [self._format_arg_ast(v) for _, v in self.args]
    return FunctionCallValue(function=self.name, args=ast_args)

to_call

to_call()

Generate just the function call expression string.

Source code in type_bridge/expressions/functions.py
def to_call(self) -> str:
    """Generate just the function call expression string."""
    from type_bridge.query.compiler import QueryCompiler

    return QueryCompiler()._compile_value(self.to_call_ast())

to_match_let

to_match_let(result_vars=None)

Generate the match let clause string for calling this function.

Source code in type_bridge/expressions/functions.py
def to_match_let(
    self,
    result_vars: list[str] | None = None,
) -> str:
    """Generate the match let clause string for calling this function."""
    vars_list = self._get_result_vars(result_vars)
    call_ast = self.to_call_ast()
    is_stream = self.return_type.is_stream

    from type_bridge.query.ast import LetAssignment, MatchLetClause
    from type_bridge.query.compiler import QueryCompiler

    assignment = LetAssignment(variables=vars_list, expression=call_ast, is_stream=is_stream)
    clause = MatchLetClause(assignments=[assignment])
    compiler = QueryCompiler()

    return compiler.compile(clause)

to_fetch

to_fetch(result_vars=None, fetch_keys=None)

Generate the fetch clause string for the function results.

Source code in type_bridge/expressions/functions.py
def to_fetch(
    self,
    result_vars: list[str] | None = None,
    fetch_keys: list[str] | None = None,
) -> str:
    """Generate the fetch clause string for the function results."""
    from type_bridge.query.ast import FetchClause, FetchVariable
    from type_bridge.query.compiler import QueryCompiler

    vars_list = self._get_result_vars(result_vars)

    if fetch_keys:
        keys = fetch_keys
    else:
        # Use type names as keys (without $)
        keys = [v.lstrip("$") for v in vars_list]

    items = [FetchVariable(key=k, var=v) for k, v in zip(keys, vars_list, strict=True)]
    clause = FetchClause(items=cast(list["FetchItem | str"], items))
    compiler = QueryCompiler()

    return compiler.compile(clause)

to_query

to_query(result_vars=None, fetch_keys=None, limit=None, offset=None, sort_var=None, sort_order='asc')

Generate a complete TypeQL query for calling this function.

Parameters:

Name Type Description Default
result_vars list[str] | None

Optional custom variable names for results

None
fetch_keys list[str] | None

Optional custom keys for the fetch object

None
limit int | None

Optional limit on number of results

None
offset int | None

Optional offset for pagination

None
sort_var str | None

Optional variable to sort by

None
sort_order str

Sort order ("asc" or "desc")

'asc'

Returns:

Type Description
str

Complete TypeQL query string

Example

fn.to_query(limit=10, offset=5) 'match let $id in get-ids(); offset 5; limit 10; fetch { "id": $id };'

Source code in type_bridge/expressions/functions.py
def to_query(
    self,
    result_vars: list[str] | None = None,
    fetch_keys: list[str] | None = None,
    limit: int | None = None,
    offset: int | None = None,
    sort_var: str | None = None,
    sort_order: str = "asc",
) -> str:
    """Generate a complete TypeQL query for calling this function.

    Args:
        result_vars: Optional custom variable names for results
        fetch_keys: Optional custom keys for the fetch object
        limit: Optional limit on number of results
        offset: Optional offset for pagination
        sort_var: Optional variable to sort by
        sort_order: Sort order ("asc" or "desc")

    Returns:
        Complete TypeQL query string

    Example:
        >>> fn.to_query(limit=10, offset=5)
        'match let $id in get-ids(); offset 5; limit 10; fetch { "id": $id };'
    """
    parts = [self.to_match_let(result_vars)]

    # Add sort if specified (must come before offset/limit)
    if sort_var:
        var = sort_var if sort_var.startswith("$") else f"${sort_var}"
        parts.append(f"sort {var} {sort_order};")

    # Add offset before limit (TypeQL order)
    if offset is not None:
        parts.append(f"offset {offset};")

    if limit is not None:
        parts.append(f"limit {limit};")

    parts.append(self.to_fetch(result_vars, fetch_keys))

    return "\n".join(parts)

to_reduce_query

to_reduce_query(result_vars=None)

Generate a query that returns the raw reduce result.

Useful for single-value functions like count() where you just want the number without fetch overhead.

Returns:

Type Description
str

Query using reduce syntax

Source code in type_bridge/expressions/functions.py
def to_reduce_query(
    self,
    result_vars: list[str] | None = None,
) -> str:
    """Generate a query that returns the raw reduce result.

    Useful for single-value functions like count() where you just
    want the number without fetch overhead.

    Returns:
        Query using reduce syntax
    """
    if self.return_type.is_stream:
        raise ValueError("Cannot use to_reduce_query with stream functions")

    return self.to_match_let(result_vars)

with_args

with_args(**kwargs)

Create a new FunctionQuery with the given arguments.

This is useful for parameterized functions where you want to create a bound version with specific argument values.

Parameters:

Name Type Description Default
**kwargs Any

Argument values keyed by parameter name (without $)

{}

Returns:

Type Description
FunctionQuery[T]

New FunctionQuery with the arguments set

Example

fn = get_neighbor_ids.with_args(target_id="abc-123") fn.to_query()

Source code in type_bridge/expressions/functions.py
def with_args(self, **kwargs: Any) -> FunctionQuery[T]:
    """Create a new FunctionQuery with the given arguments.

    This is useful for parameterized functions where you want to
    create a bound version with specific argument values.

    Args:
        **kwargs: Argument values keyed by parameter name (without $)

    Returns:
        New FunctionQuery with the arguments set

    Example:
        >>> fn = get_neighbor_ids.with_args(target_id="abc-123")
        >>> fn.to_query()
    """
    # Map kwargs to our args format
    new_args = []
    for param_name, _ in self.args:
        clean_name = param_name.lstrip("$").replace("-", "_")
        if clean_name in kwargs:
            new_args.append((param_name, kwargs[clean_name]))
        else:
            new_args.append((param_name, None))

    return FunctionQuery(
        name=self.name,
        return_type=self.return_type,
        args=new_args,
        docstring=self.docstring,
    )

ReturnType dataclass

ReturnType(types, is_stream=False, is_optional=list())

Describes the return type of a TypeDB function.

Attributes:

Name Type Description
types list[str]

List of type names (e.g., ["integer"] or ["artifact", "integer"])

is_stream bool

True if function returns multiple rows (uses { } syntax)

is_optional list[bool]

List of booleans indicating if each type is optional

is_composite property

is_composite

True if function returns multiple values per row (tuple).

is_single_value property

is_single_value

True if function returns exactly one value (not a stream).

IidExpr

IidExpr(iid)

Bases: Expression

Expression for matching entity by IID (Internal ID).

Generates TypeQL pattern: $var iid 0x...

Example

expr = IidExpr("0x1a2b3c4d") expr.to_typeql("$e") # -> "$e iid 0x1a2b3c4d"

Create an IID expression.

Parameters:

Name Type Description Default
iid str

TypeDB internal ID (format: 0x followed by hex digits)

required

Raises:

Type Description
ValueError

If IID format is invalid

Source code in type_bridge/expressions/iid.py
def __init__(self, iid: str):
    """Create an IID expression.

    Args:
        iid: TypeDB internal ID (format: 0x followed by hex digits)

    Raises:
        ValueError: If IID format is invalid
    """
    validate_iid(iid)
    self.iid = iid

to_ast

to_ast(var)

Generate AST patterns for IID match.

Returns:

Type Description
list[Pattern]

List containing one IidPattern.

Source code in type_bridge/expressions/iid.py
def to_ast(self, var: str) -> list[Pattern]:
    """Generate AST patterns for IID match.

    Returns:
        List containing one IidPattern.
    """
    from type_bridge.query.ast import IidPattern

    return [IidPattern(variable=var, iid=self.iid)]

get_attribute_types

get_attribute_types()

IID is not an attribute, so return empty set.

Source code in type_bridge/expressions/iid.py
def get_attribute_types(self) -> set[type[Attribute]]:
    """IID is not an attribute, so return empty set."""
    return set()

RolePlayerExpr

RolePlayerExpr(role_name, inner_expr, player_types)

Bases: Expression

Type-safe expression for filtering role players by their attributes.

Wraps an attribute expression and associates it with a specific role, ensuring type safety and proper TypeQL variable scoping.

TypeDB 3.x Note: Variable names are prefixed with the entity variable to avoid collisions. Using the same variable twice creates an implicit equality constraint.

Example

If both actor and target have 'name' attribute:

$actor has name $actor_name; $actor_name contains "Bot"; $target has name $target_name; $target_name == "Resource1";

Parameters:

Name Type Description Default
role_name str

The role name (e.g., "employee", "employer", "actor")

required
inner_expr Expression

The attribute expression to apply (e.g., Age.gt(Age(30)))

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

Tuple of allowed entity types that can play this role

required
Example

expr = RolePlayerExpr("employee", Age.gt(Age(30)), (Person,)) expr.to_typeql("$employee") '$employee has age $employee_age; $employee_age > 30'

Initialize a role player expression.

Parameters:

Name Type Description Default
role_name str

Name of the role being filtered

required
inner_expr Expression

Attribute expression to apply to the role player

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

Tuple of entity types allowed to play this role

required
Source code in type_bridge/expressions/role_player.py
def __init__(
    self,
    role_name: str,
    inner_expr: Expression,
    player_types: tuple[type[T], ...],
):
    """Initialize a role player expression.

    Args:
        role_name: Name of the role being filtered
        inner_expr: Attribute expression to apply to the role player
        player_types: Tuple of entity types allowed to play this role
    """
    self.role_name = role_name
    self.inner_expr = inner_expr
    self.player_types = player_types

to_ast

to_ast(var)

Generate AST patterns using role-prefixed variable names.

Delegates to the inner expression with role variable.

Source code in type_bridge/expressions/role_player.py
def to_ast(self, var: str) -> list[Pattern]:
    """Generate AST patterns using role-prefixed variable names.

    Delegates to the inner expression with role variable.
    """
    return self.inner_expr.to_ast(var)

get_attribute_types

get_attribute_types()

Get all attribute types referenced by this expression.

Delegates to the inner expression.

Returns:

Type Description
set[type[Attribute]]

Set of attribute types used in this expression

Source code in type_bridge/expressions/role_player.py
def get_attribute_types(self) -> set[type[Attribute]]:
    """Get all attribute types referenced by this expression.

    Delegates to the inner expression.

    Returns:
        Set of attribute types used in this expression
    """
    return self.inner_expr.get_attribute_types()

__repr__

__repr__()

Return string representation for debugging.

Source code in type_bridge/expressions/role_player.py
def __repr__(self) -> str:
    """Return string representation for debugging."""
    return (
        f"RolePlayerExpr(role_name={self.role_name!r}, "
        f"inner_expr={self.inner_expr!r}, "
        f"player_types={self.player_types!r})"
    )

StringExpr

StringExpr(attr_type, operation, pattern)

Bases: Expression

Type-safe string expression for text-based filtering.

Represents string operations like contains, like (regex), etc.

Create a string expression.

Parameters:

Name Type Description Default
attr_type type[T]

String attribute type to filter on

required
operation Literal['contains', 'like', 'regex']

String operation type

required
pattern T

Pattern to match

required
Source code in type_bridge/expressions/string.py
def __init__(
    self,
    attr_type: type[T],
    operation: Literal["contains", "like", "regex"],
    pattern: T,
):
    """Create a string expression.

    Args:
        attr_type: String attribute type to filter on
        operation: String operation type
        pattern: Pattern to match
    """
    self.attr_type = attr_type
    self.operation = operation
    self.pattern = pattern

to_ast

to_ast(var)

Generate AST patterns for this string operation.

Example: "$e has Name $e_name; $e_name contains 'Alice'"

Parameters:

Name Type Description Default
var str

Entity variable name (e.g., "$e", "$actor")

required

Returns:

Type Description
list[Pattern]

List of AST patterns

Source code in type_bridge/expressions/string.py
def to_ast(self, var: str) -> list["Pattern"]:
    """Generate AST patterns for this string operation.

    Example: "$e has Name $e_name; $e_name contains 'Alice'"

    Args:
        var: Entity variable name (e.g., "$e", "$actor")

    Returns:
        List of AST patterns
    """
    from type_bridge.query.ast import (
        HasPattern,
        LiteralValue,
        ValueComparisonPattern,
    )

    attr_type_name = self.attr_type.get_attribute_name()
    attr_var = generate_attr_var(var, self.attr_type)

    # Map operation to TypeQL keyword
    # AUTOMATIC CONVERSION: regex() → 'like' in TypeQL
    typeql_op = "like" if self.operation == "regex" else self.operation

    return [
        HasPattern(thing_var=var, attr_type=attr_type_name, attr_var=attr_var),
        ValueComparisonPattern(
            var=attr_var,
            operator=typeql_op,
            value=LiteralValue(value=self.pattern.value, value_type="string"),
        ),
    ]

add

add(left, right)

Create an addition expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left + right

Example

add("x", "y").to_typeql("") '($x + $y)' add("price", 10).to_typeql("") '($price + 10)'

Source code in type_bridge/expressions/arithmetic.py
def add(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create an addition expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left + right``

    Example:
        >>> add("x", "y").to_typeql("")
        '($x + $y)'
        >>> add("price", 10).to_typeql("")
        '($price + 10)'
    """
    return ArithmeticExpr(_normalize_operand(left), "+", _normalize_operand(right))

div

div(left, right)

Create a division expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left / right

Source code in type_bridge/expressions/arithmetic.py
def div(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create a division expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left / right``
    """
    return ArithmeticExpr(_normalize_operand(left), "/", _normalize_operand(right))

mod

mod(left, right)

Create a modulo expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left % right

Source code in type_bridge/expressions/arithmetic.py
def mod(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create a modulo expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left % right``
    """
    return ArithmeticExpr(_normalize_operand(left), "%", _normalize_operand(right))

mul

mul(left, right)

Create a multiplication expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left * right

Source code in type_bridge/expressions/arithmetic.py
def mul(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create a multiplication expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left * right``
    """
    return ArithmeticExpr(_normalize_operand(left), "*", _normalize_operand(right))

pow_

pow_(left, right)

Create an exponentiation expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left ^ right

Source code in type_bridge/expressions/arithmetic.py
def pow_(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create an exponentiation expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left ^ right``
    """
    return ArithmeticExpr(_normalize_operand(left), "^", _normalize_operand(right))

sub

sub(left, right)

Create a subtraction expression.

Parameters:

Name Type Description Default
left str | int | float

Variable name or numeric literal

required
right str | int | float

Variable name or numeric literal

required

Returns:

Type Description
ArithmeticExpr

ArithmeticExpr representing left - right

Source code in type_bridge/expressions/arithmetic.py
def sub(left: str | int | float, right: str | int | float) -> ArithmeticExpr:
    """Create a subtraction expression.

    Args:
        left: Variable name or numeric literal
        right: Variable name or numeric literal

    Returns:
        ArithmeticExpr representing ``left - right``
    """
    return ArithmeticExpr(_normalize_operand(left), "-", _normalize_operand(right))

abs_

abs_(var)

Get the absolute value of a number.

Parameters:

Name Type Description Default
var str

Variable name or numeric expression

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "abs($var)"

Source code in type_bridge/expressions/builtin.py
def abs_(var: str) -> BuiltinFunctionExpr:
    """Get the absolute value of a number.

    Args:
        var: Variable name or numeric expression

    Returns:
        Expression that generates "abs($var)"
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("abs", var)

ceil

ceil(var)

Round up to nearest integer.

Parameters:

Name Type Description Default
var str

Variable name or numeric expression

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "ceil($var)"

Source code in type_bridge/expressions/builtin.py
def ceil(var: str) -> BuiltinFunctionExpr:
    """Round up to nearest integer.

    Args:
        var: Variable name or numeric expression

    Returns:
        Expression that generates "ceil($var)"
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("ceil", var)

floor

floor(var)

Round down to nearest integer.

Parameters:

Name Type Description Default
var str

Variable name or numeric expression

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "floor($var)"

Source code in type_bridge/expressions/builtin.py
def floor(var: str) -> BuiltinFunctionExpr:
    """Round down to nearest integer.

    Args:
        var: Variable name or numeric expression

    Returns:
        Expression that generates "floor($var)"
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("floor", var)

label

label(var)

Get the type label of a thing.

Parameters:

Name Type Description Default
var str

Variable name (e.g., "$e" or "e")

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "label($var)"

Example

label("$e").to_typeql("") 'label($e)'

Use in fetch: fetch

Source code in type_bridge/expressions/builtin.py
def label(var: str) -> BuiltinFunctionExpr:
    """Get the type label of a thing.

    Args:
        var: Variable name (e.g., "$e" or "e")

    Returns:
        Expression that generates "label($var)"

    Example:
        >>> label("$e").to_typeql("")
        'label($e)'

        >>> # Use in fetch: fetch { "_type": label($e) }
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("label", var)

len_

len_(var)

Get length of a list.

Parameters:

Name Type Description Default
var str

Variable name of a list

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "len($var)"

Source code in type_bridge/expressions/builtin.py
def len_(var: str) -> BuiltinFunctionExpr:
    """Get length of a list.

    Args:
        var: Variable name of a list

    Returns:
        Expression that generates "len($var)"
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("len", var)

max_

max_(*args)

Get maximum value.

Parameters:

Name Type Description Default
*args str

Variable names or values to compare

()

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "max($a, $b, ...)"

Source code in type_bridge/expressions/builtin.py
def max_(*args: str) -> BuiltinFunctionExpr:
    """Get maximum value.

    Args:
        *args: Variable names or values to compare

    Returns:
        Expression that generates "max($a, $b, ...)"
    """
    normalized = tuple(f"${a}" if not a.startswith("$") else a for a in args)
    return BuiltinFunctionExpr("max", *normalized)

min_

min_(*args)

Get minimum value.

Parameters:

Name Type Description Default
*args str

Variable names or values to compare

()

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "min($a, $b, ...)"

Source code in type_bridge/expressions/builtin.py
def min_(*args: str) -> BuiltinFunctionExpr:
    """Get minimum value.

    Args:
        *args: Variable names or values to compare

    Returns:
        Expression that generates "min($a, $b, ...)"
    """
    normalized = tuple(f"${a}" if not a.startswith("$") else a for a in args)
    return BuiltinFunctionExpr("min", *normalized)

round_

round_(var)

Round to nearest integer.

Parameters:

Name Type Description Default
var str

Variable name or numeric expression

required

Returns:

Type Description
BuiltinFunctionExpr

Expression that generates "round($var)"

Source code in type_bridge/expressions/builtin.py
def round_(var: str) -> BuiltinFunctionExpr:
    """Round to nearest integer.

    Args:
        var: Variable name or numeric expression

    Returns:
        Expression that generates "round($var)"
    """
    if not var.startswith("$"):
        var = f"${var}"
    return BuiltinFunctionExpr("round", var)