type_bridge¶
type_bridge
¶
Python SDK for generated TypeBridge applications and retained query APIs.
ProxyDatabase
¶
Drop-in replacement for Database that routes queries through a type-bridge proxy server.
Instead of connecting directly to TypeDB, all queries are sent as HTTP requests to the proxy server's REST API. The proxy handles validation, interceptors (audit log, etc.), and forwarding to TypeDB.
Source code in type_bridge/proxy.py
connect
¶
Verify the proxy server is reachable via health check.
Source code in type_bridge/proxy.py
close
¶
transaction
¶
Create a proxy transaction context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction_type
|
Any
|
Transaction type string ("read", "write", "schema") or TransactionType enum value. |
'read'
|
Source code in type_bridge/proxy.py
execute_query
¶
Execute a query through the proxy and return results.
Source code in type_bridge/proxy.py
get_schema
¶
ProxyError
¶
Query
¶
Builder for TypeQL queries.
Initialize query builder.
Source code in type_bridge/query/__init__.py
match
¶
Add a match clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL match pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
fetch
¶
Add variables and attributes to fetch.
In TypeQL 3.x, fetch uses the syntax: fetch { $e.* } (fetch all attributes)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable
|
str
|
Variable name to fetch (e.g., "$e") |
required |
attributes
|
str
|
Not used in TypeQL 3.x (kept for API compatibility) |
()
|
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Example
query.fetch("$e") # Fetches all attributes
Source code in type_bridge/query/__init__.py
delete
¶
Add a delete clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL delete pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
insert
¶
Add an insert clause.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
TypeQL insert pattern |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Source code in type_bridge/query/__init__.py
limit
¶
Set query limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum number of results |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
offset
¶
Set query offset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
offset
|
int
|
Number of results to skip |
required |
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
sort
¶
Add sorting to the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variable
|
str
|
Variable to sort by |
required |
direction
|
str
|
Sort direction ("asc" or "desc") |
'asc'
|
Returns:
| Type | Description |
|---|---|
Query
|
Self for chaining |
Example
Query().match("$p isa person").fetch("$p").sort("$p", "asc")
Source code in type_bridge/query/__init__.py
build
¶
Build the final TypeQL query string.
Returns:
| Type | Description |
|---|---|
str
|
Complete TypeQL query |
Source code in type_bridge/query/__init__.py
QueryBuilder
¶
Helper class for building raw TypeQL from installed generated models.
match_entity
staticmethod
¶
Create a match query for an entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
type[GeneratedEntityProjection]
|
An exact class from an installed generated projection |
required |
var
|
str
|
Variable name to use |
'$e'
|
filters
|
Any
|
Attribute filters (field_name: value) |
{}
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Source code in type_bridge/query/__init__.py
insert_entity
staticmethod
¶
Create an insert query for an entity instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance
|
GeneratedEntityProjection
|
An exact value from an installed generated projection |
required |
var
|
str
|
Variable name to use |
'$e'
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Source code in type_bridge/query/__init__.py
match_relation
staticmethod
¶
Create a match query for a relation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_class
|
type[GeneratedRelationProjection]
|
An exact class from an installed generated projection |
required |
var
|
str
|
Variable name to use |
'$r'
|
role_players
|
dict[str, str] | None
|
Dict mapping role names to player variables |
None
|
Returns:
| Type | Description |
|---|---|
Query
|
Query object |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a role name is not defined in the model |
Source code in type_bridge/query/__init__.py
Database
¶
Database(address='localhost:1729', database='typedb', username=None, password=None, driver=None, *, http_port=DEFAULT_HTTP_PORT, server_version=None, tls=None, tls_root_ca=None)
Main database connection and session manager.
Initialize database connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
str
|
TypeDB server address |
'localhost:1729'
|
database
|
str
|
Database name |
'typedb'
|
username
|
str | None
|
Optional username for authentication |
None
|
password
|
str | None
|
Optional password for authentication |
None
|
driver
|
Driver | None
|
Optional pre-existing Driver instance to use. If provided, the Database will use this driver instead of creating a new one. The caller retains ownership and is responsible for closing it. |
None
|
http_port
|
int
|
TypeDB HTTP API port used by the connect-time version gate probe (default 8000). |
DEFAULT_HTTP_PORT
|
server_version
|
str | None
|
Exact TypeDB server version to use for connect-time validation instead of probing the HTTP API. Use this for gRPC-only deployments with the HTTP API disabled. |
None
|
tls
|
bool | None
|
Explicit TLS policy. |
None
|
tls_root_ca
|
str | PathLike[str] | None
|
PEM root-CA path for an explicitly enabled TLS connection. A root path never enables TLS implicitly. |
None
|
Source code in type_bridge/session.py
connect
¶
Connect to TypeDB server through the Rust runtime.
If a driver was injected via init, this method does nothing
(the driver is already connected). Otherwise, initializes the cached
Rust database handle. Direct access to the external Python TypeDB
driver remains available through the driver property.
Source code in type_bridge/session.py
close
¶
Close connection to TypeDB server.
If the driver was injected via init, this method only clears the
reference without closing the driver (the caller retains ownership).
If the driver was created internally, the owned Python driver closes
first. If that close fails, the complete
transport remains attached for a released-style retry. After it
succeeds, embedded-Rust and snapshot cleanup are attempted. A Rust
close failure is logged and masked to preserve the released Python
Database.close() contract; snapshot failures retain their normal
error behavior.
Source code in type_bridge/session.py
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
__getstate__
¶
Preserve released pickling for pristine connection configs.
Source code in type_bridge/session.py
__enter__
¶
__exit__
¶
__del__
¶
Destructor that warns if driver was not properly closed.
Source code in type_bridge/session.py
create_database
¶
create_database_outcome
¶
Create the bound database and return a race-normalized outcome.
Source code in type_bridge/session.py
delete_database
¶
delete_database_outcome
¶
Delete the bound database and return a race-normalized outcome.
Source code in type_bridge/session.py
database_exists
¶
Check if database exists.
Source code in type_bridge/session.py
inspect_database_pair
¶
Inspect the managed database and its package-owned journal as one pair.
Source code in type_bridge/session.py
inspect_database_pair_controlled
¶
Inspect the managed database pair under explicit execution controls.
Source code in type_bridge/session.py
plan_database_delete
¶
Create a single-use, pair-aware managed database deletion plan.
plan_database_delete_controlled
¶
Create a managed deletion plan under explicit execution controls.
Source code in type_bridge/session.py
transaction
¶
transaction(transaction_type: Enum) -> TransactionContext
transaction(transaction_type: str = 'read') -> TransactionContext
Create a transaction context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transaction_type
|
Enum | str
|
TransactionType or string ("read", "write", "schema") |
'read'
|
Returns:
| Type | Description |
|---|---|
TransactionContext
|
TransactionContext for use as a context manager |
Source code in type_bridge/session.py
execute_query
¶
Execute a query and return results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
TypeQL query string |
required |
transaction_type
|
str
|
Type of transaction ("read", "write", or "schema") |
'read'
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of result dictionaries |
Source code in type_bridge/session.py
detected_server_version
¶
The server version detected by the connect-time version gate.
Returns the version string (e.g. "3.12.3") when known. None
means the negotiated connection path produced no authoritative server
identity; supply server_version= at construction when strict
identity validation is required.
Source code in type_bridge/session.py
check_schema_annotation_support
¶
Version-gate schema DDL that uses @doc/@meta annotations.
Raises the versioned error when the TypeQL uses schema annotations (TypeDB 3.12+) and the detected server version predates 3.12. When the server version is unknown, the DDL is sent as-is and the server decides.
Source code in type_bridge/session.py
supports_given_stage
¶
Whether given rows can execute on the active connection.
This requires both TypeDB 3.12+ syntax support and a negotiated band-9
provider. It remains False when the server version is unknown or
when a 3.12 server stays on the safe band-8 discovery connection after
a band-9 upgrade failure. Bulk operations consult this before dispatch
and use their per-row fallback when it is False.
Source code in type_bridge/session.py
execute_with_rows
¶
Execute a given-stage TypeQL query over input rows.
One compiled pipeline runs over every input row; the rows travel through the driver API instead of being interpolated into the query string, so user-supplied values never touch TypeQL text. Requires a TypeDB 3.12+ server; on older servers this raises the versioned error from the feature gate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
TypeQL starting with a |
required |
transaction_type
|
str
|
"read", "write", or "schema" |
required |
variables
|
list[str]
|
given variable names without the |
required |
column_types
|
list[str]
|
TypeQL value type names aligned with |
required |
rows
|
list[list[Any]]
|
input rows, each a list of primitives in column order (temporal values as ISO-8601 strings) |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of result dictionaries (one per pipeline output row). |
Source code in type_bridge/session.py
get_schema
¶
Get the schema definition for this database.
Source code in type_bridge/session.py
TransactionContext
¶
Context manager for sharing a TypeDB transaction across operations.
Source code in type_bridge/session.py
execute
¶
Execute a query within the active transaction.
execute_with_rows
¶
Execute a given-stage query with input rows in this transaction.
See :meth:Database.execute_with_rows for the argument contract.
Requires the Rust backend on a TypeDB 3.12+ connection.
Source code in type_bridge/session.py
commit
¶
rollback
¶
TransactionType
¶
Bases: Enum
Rust-safe fallback transaction type for the default backend.
EntityNotFoundError
¶
Bases: NotFoundError
Raised when an entity does not exist in the database.
This exception is raised during delete or update operations when the target entity cannot be found using its @key attributes or matched attributes.
Example
try: manager.delete(nonexistent_entity) except EntityNotFoundError: print("Entity was already deleted or never existed")
KeyAttributeError
¶
Bases: ValueError
Raised when @key attribute validation fails during update/delete.
This exception is raised when: - A @key attribute has a None value - No @key attributes are defined on the entity
Attributes:
| Name | Type | Description |
|---|---|---|
entity_type |
Name of the entity class |
|
operation |
The operation that failed ("update" or "delete") |
|
field_name |
The @key field that was None (if applicable) |
|
all_fields |
List of all defined fields (when no @key exists) |
Example
try: manager.update(entity_with_none_key) except KeyAttributeError as e: print(f"Key validation failed: {e}") print(f"Entity type: {e.entity_type}") print(f"Operation: {e.operation}")
Source code in type_bridge/crud/exceptions.py
NotUniqueError
¶
Bases: ValueError
Raised when an operation requires exactly one match but finds multiple.
This exception is raised when attempting to delete an entity without @key attributes and multiple matching records are found. Use filter().delete() for bulk deletion instead.
Example
try: manager.delete(keyless_entity) except NotUniqueError: print("Multiple entities matched - use filter().delete() for bulk deletion")
RelationNotFoundError
¶
Bases: NotFoundError
Raised when a relation does not exist in the database.
This exception is raised during delete or update operations when the target relation cannot be found using its role players' @key attributes.
Example
try: manager.delete(nonexistent_relation) except RelationNotFoundError: print("Relation was already deleted or never existed")
CrudEvent
¶
Bases: Enum
CRUD lifecycle events.
CrudHook
¶
Bases: Protocol
Protocol for CRUD lifecycle hooks.
Implement only the methods you need. All methods are optional —
HookRunner uses hasattr / getattr to discover them.
HookCancelled
¶
Bases: Exception
Raise in a pre-hook to abort the operation.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
Human-readable explanation. |
|
event |
The event that was cancelled (set by HookRunner). |
|
hook |
The hook instance that raised the cancellation (set by HookRunner). |
Source code in type_bridge/crud/hooks.py
SchemaConflictError
¶
Bases: Exception
A retained conflict diagnostic for existing compatibility callers.
Source code in type_bridge/migration/exceptions.py
has_breaking_changes
¶
Report whether the supplied historical diff has breaking members.
Source code in type_bridge/migration/exceptions.py
SchemaValidationError
¶
Bases: Exception
A retained schema-validation diagnostic.
SchemaIntrospector
¶
Introspects TypeDB database schema.
Queries the database to discover all types, attributes, ownerships, and relations defined in the schema.
Example
introspector = SchemaIntrospector(db) schema = introspector.introspect()
print(f"Found {len(schema.entities)} entities") print(f"Found {len(schema.relations)} relations") print(f"Found {len(schema.attributes)} attributes")
Initialize introspector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/introspection.py
introspect_for_models
¶
Introspect database schema for specific model types.
This is the TypeDB 3.x compatible approach that checks each model type individually instead of enumerating all types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list[type[_QueryEntity] | type[_QueryRelation]]
|
List of model classes to check |
required |
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with info about existing types |
Source code in type_bridge/migration/introspection.py
introspect
¶
Query TypeDB schema and return structured info.
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with all discovered types |
Source code in type_bridge/migration/introspection.py
create_driver_options
¶
Create TypeDB driver options for the retained driver lines.
The same band map that drives the version gate drives option construction.
Supported 3.11 and 3.12 drivers both use the positional
DriverOptions(tls_config) form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
is_tls_enabled
|
bool
|
Whether to enable TLS for the driver connection. |
False
|
tls_root_ca
|
str | PathLike[str] | None
|
Optional PEM root-CA path for an enabled TLS connection. |
None
|
Returns:
| Type | Description |
|---|---|
DriverOptions
|
Configured |
Raises:
| Type | Description |
|---|---|
UnsupportedVersionError
|
When the installed driver version is outside the supported range (no known band). |
ValueError
|
When a root path is supplied while TLS is disabled or the root path is empty. |
Source code in type_bridge/typedb_driver.py
__getattr__
¶
Load retained compatibility identities without importing authoring eagerly.