type_bridge.expressions¶
expressions
¶
Type-safe query expression system for TypeBridge.
This module provides expression classes for building type-safe TypeQL queries.
AggregateExpr
¶
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
to_value_ast
¶
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
to_typeql
¶
Deprecated: Generate TypeQL pattern for this aggregation.
Source code in type_bridge/expressions/aggregate.py
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
ArithmeticExpr
dataclass
¶
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_value_ast
¶
Convert to an ArithmeticValue AST node.
Source code in type_bridge/expressions/arithmetic.py
to_typeql
¶
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
get_attribute_types
¶
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
¶
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 |
to_value_ast
¶
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
to_typeql
¶
Deprecated: Use to_ast() instead.
Source code in type_bridge/expressions/base.py
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
and_
¶
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
or_
¶
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
not_
¶
Negate this expression using NOT logic.
Returns:
| Type | Description |
|---|---|
BooleanExpr
|
BooleanExpr representing the negation |
Source code in type_bridge/expressions/base.py
BooleanExpr
¶
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
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
to_ast
¶
Generate AST patterns for this boolean expression.
Source code in type_bridge/expressions/boolean.py
and_
¶
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
or_
¶
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
BuiltinFunctionExpr
dataclass
¶
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
to_ast
¶
Built-in functions are values, not patterns.
Use to_value_ast() instead for AST representation.
Source code in type_bridge/expressions/builtin.py
to_typeql
¶
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
to_value_ast
¶
Convert to AST FunctionCallValue.
AttributeExistsExpr
¶
Bases: Expression
Attribute presence/absence check expression.
Source code in type_bridge/expressions/comparison.py
ComparisonExpr
¶
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
to_ast
¶
Generate AST patterns for this comparison.
Example: "$e has age $e_age; $e_age > 30"
Source code in type_bridge/expressions/comparison.py
FunctionCallExpr
dataclass
¶
Bases: Expression
Represents a call to a TypeDB function.
to_value_ast
¶
Convert to AST FunctionCallValue.
Source code in type_bridge/expressions/functions.py
to_typeql
¶
Deprecated: generate TypeQL function call syntax.
Source code in type_bridge/expressions/functions.py
FunctionQuery
dataclass
¶
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
¶
Generate AST for function call.
Source code in type_bridge/expressions/functions.py
to_call
¶
Generate just the function call expression string.
to_match_let
¶
Generate the match let clause string for calling this function.
Source code in type_bridge/expressions/functions.py
to_fetch
¶
Generate the fetch clause string for the function results.
Source code in type_bridge/expressions/functions.py
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
to_reduce_query
¶
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
with_args
¶
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
ReturnType
dataclass
¶
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 |
IidExpr
¶
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
RolePlayerExpr
¶
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
to_ast
¶
Generate AST patterns using role-prefixed variable names.
Delegates to the inner expression with role variable.
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
__repr__
¶
Return string representation for debugging.
StringExpr
¶
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
to_ast
¶
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
add
¶
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 |
Example
add("x", "y").to_typeql("") '($x + $y)' add("price", 10).to_typeql("") '($price + 10)'
Source code in type_bridge/expressions/arithmetic.py
div
¶
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 |
Source code in type_bridge/expressions/arithmetic.py
mod
¶
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 |
Source code in type_bridge/expressions/arithmetic.py
mul
¶
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 |
Source code in type_bridge/expressions/arithmetic.py
pow_
¶
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 |
Source code in type_bridge/expressions/arithmetic.py
sub
¶
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 |
Source code in type_bridge/expressions/arithmetic.py
abs_
¶
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
ceil
¶
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
floor
¶
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
label
¶
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
len_
¶
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
max_
¶
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
min_
¶
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
round_
¶
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)" |