type_bridge.migration¶
migration
¶
TypeBridge Migration System.
A Django-style migration framework for TypeDB schemas with state tracking, rollback support, and CLI tools.
Example - Migration file (migrations/0001_initial.py): from typing import ClassVar from type_bridge.migration import Migration from type_bridge.models import Entity, Relation from myapp.models import Person, Company, Employment
class InitialMigration(Migration):
dependencies: ClassVar[list[tuple[str, str]]] = []
models: ClassVar[list[type[Entity | Relation]]] = [Person, Company, Employment]
Example - Operations-based migration (migrations/0002_add_phone.py): from typing import ClassVar from type_bridge.migration import Migration, operations as ops from type_bridge.migration.operations import Operation from myapp.models import Person, Phone
class AddPhoneMigration(Migration):
dependencies: ClassVar[list[tuple[str, str]]] = [("migrations", "0001_initial")]
operations: ClassVar[list[Operation]] = [
ops.AddAttribute(Phone),
ops.AddOwnership(Person, Phone, optional=True),
]
Example - Programmatic API
from pathlib import Path from type_bridge.migration import MigrationExecutor from type_bridge.session import Database
db = Database(address="localhost:1729", database="mydb") db.connect()
executor = MigrationExecutor(db, Path("migrations"))
Apply all pending migrations¶
executor.migrate()
Migrate to specific version¶
executor.migrate(target="0002_add_phone")
Show migration status¶
for name, is_applied in executor.showmigrations(): print(f"[{'X' if is_applied else ' '}] {name}")
Preview TypeQL¶
print(executor.sqlmigrate("0002_add_phone"))
CLI Usage
Apply all pending migrations¶
python -m type_bridge.migration migrate
Migrate to specific version¶
python -m type_bridge.migration migrate 0002_add_phone
Show migration status¶
python -m type_bridge.migration showmigrations
Preview TypeQL¶
python -m type_bridge.migration sqlmigrate 0002_add_phone
Generate migration from model changes¶
python -m type_bridge.migration makemigrations --name add_phone --models myapp.models
MIGRATION_STATE_SCHEMA
module-attribute
¶
MIGRATION_STATE_SCHEMA = _label_projection(migration_state_schema())
Immutable labels for all schema objects owned by TypeBridge migration state.
AuthoredMigration
¶
A complete authored migration artifact set, held in memory.
Wraps the Rust authoring result. files contains every artifact as
(relative_path, bytes) pairs; :meth:write_to persists them through
the validated all-or-nothing writer.
Source code in type_bridge/migration/author.py
write_to
¶
Write all artifacts under migrations_dir.
Existing files must be byte-identical (validate_identical) or
absent (fail); collisions and drift abort before anything is
written. Snapshots stay append-only.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written migration |
Source code in type_bridge/migration/author.py
Migration
¶
Base class for migration scripts.
Migrations define schema changes that can be applied to a TypeDB database. They can be either model-based (for initial migrations) or operation-based (for incremental changes).
Model-based Migration Example
class InitialMigration(Migration): dependencies = [] models = [Person, Company, Employment]
Operation-based Migration Example
class AddPhoneMigration(Migration): dependencies = [("myapp", "0001_initial")] operations = [ ops.AddAttribute(Phone), ops.AddOwnership(Person, Phone, optional=True), ]
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Migration name (auto-populated from filename) |
app_label |
str
|
Application label (auto-populated from directory) |
dependencies |
list[tuple[str, str]]
|
List of (app_label, migration_name) tuples |
models |
list[type[Entity | Relation]]
|
List of Entity/Relation classes for initial migrations |
operations |
list[Operation]
|
List of Operation instances for incremental migrations |
reversible |
bool
|
Whether the migration can be rolled back |
get_dependencies
¶
Get dependencies as MigrationDependency objects.
Returns:
| Type | Description |
|---|---|
list[MigrationDependency]
|
List of MigrationDependency instances |
describe
¶
Generate a human-readable description of this migration.
Returns:
| Type | Description |
|---|---|
str
|
Description string |
Source code in type_bridge/migration/base.py
MigrationDependency
dataclass
¶
Reference to another migration.
Example
dep = MigrationDependency("myapp", "0001_initial") str(dep) # "myapp.0001_initial"
BreakingChangeAnalyzer
¶
Analyzes schema diffs to classify changes by severity.
Classification rules: - SAFE: Adding new types, widening role player types - WARNING: Adding required attributes to existing types - BREAKING: Removing types, narrowing role player types, removing roles
Example
analyzer = BreakingChangeAnalyzer() diff = old_schema.compare(new_schema) changes = analyzer.analyze(diff)
for change in changes: print(f"[{change.category.value}] {change.description}") print(f" Recommendation: {change.recommendation}")
analyze
¶
Classify all changes in the schema diff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
list[ClassifiedChange]
|
List of classified changes with recommendations |
Source code in type_bridge/migration/breaking.py
has_breaking_changes
¶
Quick check for any breaking changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any breaking changes exist |
Source code in type_bridge/migration/breaking.py
has_warnings
¶
Quick check for any warning-level changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any warnings exist |
Source code in type_bridge/migration/breaking.py
get_breaking_changes
¶
Get only breaking changes from the diff.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
list[ClassifiedChange]
|
List of breaking changes only |
Source code in type_bridge/migration/breaking.py
summary
¶
Generate a human-readable summary of classified changes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff from SchemaInfo.compare() |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted summary string |
Source code in type_bridge/migration/breaking.py
ChangeCategory
¶
Bases: Enum
Classification of schema changes by severity.
ClassifiedChange
dataclass
¶
A schema change with its classification and recommendation.
AttributeFlagChange
dataclass
¶
Represents a change in attribute flags (e.g., cardinality change).
EntityChanges
dataclass
¶
EntityChanges(added_attributes=list(), removed_attributes=list(), modified_attributes=list(), doc_changed=None, meta_changed=None)
Represents changes to an entity type.
has_changes
¶
Check if there are any changes.
RelationChanges
dataclass
¶
RelationChanges(added_roles=list(), removed_roles=list(), modified_role_players=list(), modified_role_cardinality=list(), modified_role_annotations=list(), added_attributes=list(), removed_attributes=list(), modified_attributes=list(), doc_changed=None, meta_changed=None)
Represents changes to a relation type.
Tracks: - Role additions/removals - Role player type changes (which entities can play each role) - Role cardinality changes - Attribute additions/removals/modifications
has_changes
¶
Check if there are any changes.
Source code in type_bridge/migration/diff.py
RoleCardinalityChange
dataclass
¶
Represents a change in role cardinality constraints.
Tracks cardinality (min, max) changes on roles. None values indicate unbounded.
RolePlayerChange
dataclass
¶
Represents a change in role player types.
Tracks when entity types are added to or removed from a role's allowed players.
Example
If a role changes from Role[Person] to Role[Person, Company]: - added_player_types = ["company"] - removed_player_types = []
SchemaDiff
dataclass
¶
SchemaDiff(added_entities=set(), removed_entities=set(), added_relations=set(), removed_relations=set(), added_attributes=set(), removed_attributes=set(), modified_attributes=dict(), modified_entities=dict(), modified_relations=dict(), _rust_diff=None)
Container for schema comparison results.
Represents the differences between two schemas for migration planning.
has_changes
¶
Check if there are any schema differences.
Returns:
| Type | Description |
|---|---|
bool
|
True if any changes exist, False otherwise |
Source code in type_bridge/migration/diff.py
summary
¶
Generate a human-readable summary of changes.
Returns:
| Type | Description |
|---|---|
str
|
Formatted summary string |
Source code in type_bridge/migration/diff.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
to_rust_dict
¶
Serialize this public DTO to the Rust SchemaDiff dict shape.
Converts Python class-keyed sets/dicts into the string-keyed lists and nested dicts the PyO3 layer expects, reconciling field shapes as described in the module docstring.
Source code in type_bridge/migration/diff.py
SchemaConflictError
¶
Bases: Exception
Raised when there are conflicting schema changes during sync.
This exception is raised when attempting to sync a schema that has breaking changes (removed or modified types/attributes) compared to the existing database schema.
Initialize SchemaConflictError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diff
|
SchemaDiff
|
SchemaDiff containing the conflicting changes |
required |
message
|
str | None
|
Optional custom error message |
None
|
Source code in type_bridge/migration/exceptions.py
has_breaking_changes
¶
Check if the diff contains breaking changes.
Breaking changes include removed or modified types/attributes.
Returns:
| Type | Description |
|---|---|
bool
|
True if there are breaking changes |
Source code in type_bridge/migration/exceptions.py
SchemaValidationError
¶
Bases: Exception
Raised when schema validation fails during schema generation.
This exception is raised when the Python model definitions violate TypeDB constraints or best practices.
MigrationError
¶
Bases: Exception
Error during migration execution.
MigrationExecutor
¶
Executes migrations against a TypeDB database.
Handles: - Applying pending migrations - Rolling back applied migrations - Previewing migration TypeQL - Listing migration status
Example
executor = MigrationExecutor(db, Path("migrations"))
Apply all pending migrations¶
results = executor.migrate()
Migrate to specific version¶
results = executor.migrate(target="0002_add_company")
Show migration status¶
status = executor.showmigrations() for name, is_applied in status: print(f"[{'X' if is_applied else ' '}] {name}")
Preview TypeQL¶
typeql = executor.sqlmigrate("0002_add_company") print(typeql)
Initialize executor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
migrations_dir
|
Path
|
Directory containing migration files |
required |
dry_run
|
bool
|
If True, preview operations without executing |
False
|
state_manager
|
MigrationStateStore | None
|
Optional externally owned migration-state store. When supplied, Rust migration segments use the state-free executor and never create TypeBridge's ledger schema independently in the target database. The default remains TypeDB-backed. |
None
|
Source code in type_bridge/migration/executor.py
migrate
¶
Apply pending migrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Optional target migration name (e.g., "0002_add_company") If None, apply all pending migrations. If specified, migrate to that exact state (may rollback). |
None
|
Returns:
| Type | Description |
|---|---|
list[MigrationResult]
|
List of migration results |
Raises:
| Type | Description |
|---|---|
MigrationError
|
If migration fails |
Source code in type_bridge/migration/executor.py
showmigrations
¶
List all migrations with their applied status.
Returns:
| Type | Description |
|---|---|
list[tuple[str, bool]]
|
List of (migration_name, is_applied) tuples |
Source code in type_bridge/migration/executor.py
sqlmigrate
¶
Preview TypeQL for a migration without executing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
migration_name
|
str
|
Name of the migration |
required |
reverse
|
bool
|
If True, show rollback TypeQL |
False
|
Returns:
| Type | Description |
|---|---|
str
|
TypeQL string that would be executed |
Raises:
| Type | Description |
|---|---|
MigrationError
|
If migration not found or not reversible |
Source code in type_bridge/migration/executor.py
plan
¶
Get the migration plan without executing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | None
|
Optional target migration name |
None
|
Returns:
| Type | Description |
|---|---|
MigrationPlan
|
MigrationPlan showing what would be applied/rolled back |
Source code in type_bridge/migration/executor.py
MigrationPlan
dataclass
¶
Plan for migration execution.
Attributes:
| Name | Type | Description |
|---|---|---|
to_apply |
list[LoadedMigration]
|
Migrations to apply (forward) |
to_rollback |
list[LoadedMigration]
|
Migrations to rollback (reverse) |
MigrationResult
dataclass
¶
Result of a migration operation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Migration name |
action |
str
|
"applied" or "rolled_back" |
success |
bool
|
Whether the operation succeeded |
error |
str | None
|
Error message if failed |
backfill |
list[dict[str, object]] | None
|
Per-step backfill counts when the migration contained a
CopyAttribute op; |
MigrationGenerator
¶
Generates migration files from model changes.
Compares current models against the introspected database schema and delegates artifact authoring to the shared Rust core.
Example
generator = MigrationGenerator(db, Path("migrations"))
Generate migration from models¶
path = generator.generate([Person, Company, Employment], name="initial")
Creates: migrations/0001_initial.py¶
Generate empty migration for manual editing¶
path = generator.generate([], name="custom_changes", empty=True)
Initialize generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
migrations_dir
|
Path
|
Directory to write migration files |
required |
Source code in type_bridge/migration/generator.py
generate
¶
Generate a migration file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list[type[Entity | Relation]]
|
Model classes to check for changes |
required |
name
|
str
|
Migration name suffix (e.g., "initial", "add_company") |
'auto'
|
empty
|
bool
|
Create empty migration for manual editing |
False
|
Returns:
| Type | Description |
|---|---|
Path | None
|
Path to created file, or None if no changes detected |
Source code in type_bridge/migration/generator.py
SchemaInfo
¶
Container for organized schema information.
Initialize SchemaInfo with empty collections.
Source code in type_bridge/migration/info.py
get_entity_by_name
¶
Get entity by type name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Entity type name |
required |
Returns:
| Type | Description |
|---|---|
type[Entity] | None
|
Entity class or None if not found |
Source code in type_bridge/migration/info.py
get_relation_by_name
¶
Get relation by type name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Relation type name |
required |
Returns:
| Type | Description |
|---|---|
type[Relation] | None
|
Relation class or None if not found |
Source code in type_bridge/migration/info.py
validate
¶
Validate schema definitions for TypeDB constraints.
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If schema violates TypeDB constraints |
Source code in type_bridge/migration/info.py
to_typeql
¶
Generate TypeQL schema definition from collected schema information.
Base classes (with base=True) are skipped as they don't appear in TypeDB schema.
Validates the schema before generation.
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Raises:
| Type | Description |
|---|---|
SchemaValidationError
|
If schema validation fails |
Source code in type_bridge/migration/info.py
compare
¶
Compare this schema with another schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
SchemaInfo
|
Another SchemaInfo to compare against |
required |
Returns:
| Type | Description |
|---|---|
SchemaDiff
|
SchemaDiff containing all differences between the schemas |
Source code in type_bridge/migration/info.py
to_rust_schema_info
¶
Serialize this Python model schema to the Rust SchemaInfo dict shape.
Registers all non-base entity and relation descriptors into a fresh
PyDescriptorRegistry and delegates to Rust SchemaInfo::from_descriptors
for the full projection: entity/relation entries, plays_cardinalities overlays,
and foreign parent_type nulling all happen inside Rust.
The attributes section is merged on the Python side because it requires attribute-class metadata (regex, range, allowed_values, etc.) that is not represented in the descriptor layer.
Source code in type_bridge/migration/info.py
IntrospectedAttribute
dataclass
¶
IntrospectedAttribute(name, value_type, parent_type=None, is_abstract=False, is_independent=False, regex=None, allowed_values=None, range=None, doc=None, meta=dict())
An attribute type from the database schema.
IntrospectedEntity
dataclass
¶
An entity type from the database schema.
IntrospectedOwnership
dataclass
¶
An ownership relationship between a type and an attribute.
IntrospectedRelation
dataclass
¶
A relation type from the database schema.
IntrospectedRole
dataclass
¶
A role in a relation.
IntrospectedSchema
dataclass
¶
Complete introspected schema from TypeDB database.
This is a database-centric view of the schema that can be compared against Python model definitions.
is_empty
¶
Check if the schema is empty (no custom types).
Source code in type_bridge/migration/introspection.py
get_entity_names
¶
get_relation_names
¶
get_attribute_names
¶
get_ownerships_for
¶
Get all ownerships for a specific owner type.
from_rust_schema_info
classmethod
¶
Build the compatibility DTO from Rust SchemaInfo live introspection.
Source code in type_bridge/migration/introspection.py
to_rust_schema_info
¶
Serialize introspected database schema to the Rust SchemaInfo dict shape.
Source code in type_bridge/migration/introspection.py
SchemaIntrospector
¶
Introspects TypeDB database schema.
Queries the database to discover all types, attributes, ownerships, and relations defined in the schema.
Example
introspector = SchemaIntrospector(db) schema = introspector.introspect()
print(f"Found {len(schema.entities)} entities") print(f"Found {len(schema.relations)} relations") print(f"Found {len(schema.attributes)} attributes")
Initialize introspector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/introspection.py
introspect_for_models
¶
Introspect database schema for specific model types.
This is the TypeDB 3.x compatible approach that checks each model type individually instead of enumerating all types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
list[type[Entity] | type[Relation]]
|
List of model classes to check |
required |
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with info about existing types |
Source code in type_bridge/migration/introspection.py
introspect
¶
Query TypeDB schema and return structured info.
Returns:
| Type | Description |
|---|---|
IntrospectedSchema
|
IntrospectedSchema with all discovered types |
Source code in type_bridge/migration/introspection.py
LoadedMigration
dataclass
¶
A migration loaded from a file.
Attributes:
| Name | Type | Description |
|---|---|---|
migration |
Migration
|
The Migration instance |
path |
Path
|
Path to the migration file |
checksum |
str
|
SHA256 hash of file content (first 16 chars) |
execution_spec |
dict[str, Any] | None
|
Optional pre-lowered MigrationSpec dict loaded from
the JSON sidecar. Present only for generated migrations that carry
a |
MigrationLoader
¶
Loads migration files from a directory.
Migration files must follow the naming pattern: NNNN_*.py where NNNN is a 4-digit number (e.g., 0001_initial.py, 0002_add_company.py)
Example
loader = MigrationLoader(Path("migrations")) migrations = loader.discover()
for loaded in migrations: print(f"{loaded.migration.name}: {loaded.checksum}")
Initialize loader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
migrations_dir
|
Path
|
Directory containing migration files |
required |
Source code in type_bridge/migration/loader.py
discover
¶
Discover all migration files in order.
Returns:
| Type | Description |
|---|---|
list[LoadedMigration]
|
List of loaded migrations, sorted by filename |
Source code in type_bridge/migration/loader.py
get_by_name
¶
Get a specific migration by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Migration name (e.g., "0001_initial") |
required |
Returns:
| Type | Description |
|---|---|
LoadedMigration | None
|
LoadedMigration or None if not found |
Source code in type_bridge/migration/loader.py
get_by_number
¶
Get a specific migration by number.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
number
|
int
|
Migration number (e.g., 1 for 0001_initial) |
required |
Returns:
| Type | Description |
|---|---|
LoadedMigration | None
|
LoadedMigration or None if not found |
Source code in type_bridge/migration/loader.py
get_next_number
¶
Get the next available migration number.
Returns:
| Type | Description |
|---|---|
int
|
Next migration number (1 if no migrations exist) |
Source code in type_bridge/migration/loader.py
validate_dependencies
¶
Validate that all migration dependencies are satisfied.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of error messages (empty if valid) |
Source code in type_bridge/migration/loader.py
MigrationLoadError
¶
Bases: Exception
Error loading a migration file.
CopyAttribute
dataclass
¶
Bases: Operation
Copy an attribute value from source to destination on all instances of the owner type.
This is a DML (data manipulation) backfill operation that copies attribute values from one attribute to another for every instance of the owning type. The forward operation uses an insert-if-absent pattern (idempotent — safe to re-run). The reverse deletes all destination attribute values added by this operation.
No transform function is supported in v1. Use RunTypeQL for value transforms.
Example
ops.CopyAttribute( owner=Person, source="legacy-name", dest="display-name", )
Backfills: match $x isa person, has legacy-name $v;¶
not { $x has display-name $d; };¶
insert $x has display-name == $v;¶
Note: dest must already be owned by owner via a prior schema op.
to_typeql
¶
Generate insert-if-absent backfill TypeQL.
Emits a match+insert that copies source values to dest for every
owner instance that does not already have the destination attribute.
Source code in type_bridge/migration/operations.py
to_rollback_typeql
¶
Generate the inverse delete that removes all dest values added by this op.
Source code in type_bridge/migration/operations.py
RunPython
dataclass
¶
Bases: Operation
Run Python ORM code during migration execution.
RunPython is for migrations that need the normal TypeBridge ORM surface
rather than portable TypeQL, for example loading JSON/TOML data, creating
many entities/relations, or querying existing data before writing derived
values. The callable receives the migration executor's database connection,
so existing code such as User.manager(db).filter(...).execute() works.
Example
def forwards(db): users = User.manager(db).filter(name__startswith="A").execute() ...
operations = [ops.RunPython(forwards)]
ModelRegistry
¶
Registry for tracking Entity/Relation models.
Models can be registered manually or auto-discovered from Python modules. The registry is used by the migration generator to determine which models should be tracked for schema changes.
Example - Manual registration
from type_bridge.migration import ModelRegistry from myapp.models import Person, Company
ModelRegistry.register(Person, Company)
Example - Auto-discovery
from type_bridge.migration import ModelRegistry
Discover all Entity/Relation classes in module¶
models = ModelRegistry.discover("myapp.models")
Example - In models.py (recommended pattern): from type_bridge import Entity, String, Flag, Key, TypeFlags from type_bridge.migration import ModelRegistry
class Name(String):
pass
class Person(Entity):
flags = TypeFlags(name="person")
name: Name = Flag(Key)
# Register at module load time
ModelRegistry.register(Person)
register
classmethod
¶
Register models for migration tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
type[Entity | Relation]
|
Entity or Relation classes to register |
()
|
Source code in type_bridge/migration/registry.py
unregister
classmethod
¶
clear
classmethod
¶
get_all
classmethod
¶
is_registered
classmethod
¶
Check if a model is registered.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
type
|
Model class to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if model is registered |
discover
classmethod
¶
Auto-discover Entity/Relation classes from a module.
Imports the module and finds all Entity/Relation subclasses defined in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_path
|
str
|
Python module path (e.g., "myapp.models") |
required |
register
|
bool
|
If True, also register discovered models |
True
|
Returns:
| Type | Description |
|---|---|
list[type[Entity | Relation]]
|
List of discovered Entity/Relation classes |
Raises:
| Type | Description |
|---|---|
ImportError
|
If module cannot be imported |
Source code in type_bridge/migration/registry.py
discover_recursive
classmethod
¶
Recursively discover models from a package.
Imports all modules in the package and discovers Entity/Relation classes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package_path
|
str
|
Python package path (e.g., "myapp") |
required |
register
|
bool
|
If True, also register discovered models |
True
|
Returns:
| Type | Description |
|---|---|
list[type[Entity | Relation]]
|
List of discovered Entity/Relation classes |
Raises:
| Type | Description |
|---|---|
ImportError
|
If package cannot be imported |
Source code in type_bridge/migration/registry.py
SchemaManager
¶
Manager for database schema operations.
Initialize schema manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/schema_manager.py
register
¶
Register model classes for schema management.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
models
|
type[Entity | Relation]
|
Model classes to register |
()
|
Source code in type_bridge/migration/schema_manager.py
collect_schema_info
¶
Collect schema information from registered models.
Returns:
| Type | Description |
|---|---|
SchemaInfo
|
SchemaInfo with entities, relations, and attributes |
Source code in type_bridge/migration/schema_manager.py
generate_schema
¶
Generate complete TypeQL schema definition.
Returns:
| Type | Description |
|---|---|
str
|
TypeQL schema definition string |
Source code in type_bridge/migration/schema_manager.py
has_existing_schema
¶
Check if database has existing schema defined.
Returns:
| Type | Description |
|---|---|
bool
|
True if database exists and has custom schema beyond built-in types |
Source code in type_bridge/migration/schema_manager.py
introspect_current_schema_info
¶
Introspect current database schema and build SchemaInfo.
Note: This is a best-effort attempt. It cannot perfectly reconstruct Python class hierarchies from TypeDB schema.
Returns:
| Type | Description |
|---|---|
SchemaInfo | None
|
SchemaInfo with current schema, or None if database doesn't exist |
Source code in type_bridge/migration/schema_manager.py
verify_compatibility
¶
Verify that new schema is compatible with old schema.
Checks for breaking changes (removed or modified types/attributes) and raises SchemaConflictError if found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_schema_info
|
SchemaInfo
|
The previous schema to compare against |
required |
Raises:
| Type | Description |
|---|---|
SchemaConflictError
|
If breaking changes are detected |
Source code in type_bridge/migration/schema_manager.py
sync_schema
¶
Synchronize database schema with registered models.
Automatically checks for existing schema in the database and raises SchemaConflictError if schema already exists and might conflict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
If True, recreate database from scratch, ignoring conflicts |
False
|
skip_if_exists
|
bool
|
If True, skip conflict checks when types already exist. Use this for idempotent deployments where you want to ensure the schema is in place without recreating the database. TypeDB 3.x's define statement is idempotent for identical definitions. |
False
|
Raises:
| Type | Description |
|---|---|
SchemaConflictError
|
If database has existing schema and force=False and skip_if_exists=False |
Source code in type_bridge/migration/schema_manager.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
drop_schema
¶
Drop all schema definitions.
Source code in type_bridge/migration/schema_manager.py
introspect_schema
¶
Introspect current database schema.
Returns:
| Type | Description |
|---|---|
dict[str, list[str]]
|
Dictionary of schema information |
Source code in type_bridge/migration/schema_manager.py
SimpleMigrationManager
¶
Manager for schema migrations.
.. deprecated::
MigrationManager (exported as SimpleMigrationManager) is
superseded by :class:~type_bridge.migration.executor.MigrationExecutor
(for applying migrations) and
:class:~type_bridge.migration.generator.MigrationGenerator (for
generating migrations). It will be removed in a future release.
Initialize migration manager.
.. deprecated::
Use :class:~type_bridge.migration.executor.MigrationExecutor and
:class:~type_bridge.migration.generator.MigrationGenerator instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/simple_migration.py
add_migration
¶
Add a migration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Migration name |
required |
schema
|
str
|
TypeQL schema definition |
required |
Source code in type_bridge/migration/simple_migration.py
apply_migrations
¶
Apply all pending migrations.
Source code in type_bridge/migration/simple_migration.py
create_attribute_migration
¶
Create a migration to add an attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_name
|
str
|
Attribute name |
required |
value_type
|
str
|
Value type |
required |
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.py
create_entity_migration
¶
Create a migration to add an entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_name
|
str
|
Entity name |
required |
attributes
|
list[str]
|
List of attribute names |
required |
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.py
create_relation_migration
¶
Create a migration to add a relation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relation_name
|
str
|
Relation name |
required |
roles
|
list[tuple[str, str]]
|
List of (role_name, player_type) tuples |
required |
attributes
|
list[str] | None
|
Optional list of attribute names |
None
|
Returns:
| Type | Description |
|---|---|
str
|
TypeQL migration |
Source code in type_bridge/migration/simple_migration.py
MigrationRecord
dataclass
¶
Record of an applied migration.
MigrationRunRecord
dataclass
¶
MigrationRunRecord(run_id, app_label, name, checksum, direction, status, started_at, finished_at=None, error=None, executor_ip=None, executor_mac=None)
Record of one migration execution attempt.
MigrationState
dataclass
¶
Complete state of applied migrations.
is_applied
¶
Check if a migration has been applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
name
|
str
|
Migration name |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if migration has been applied |
Source code in type_bridge/migration/state.py
add
¶
Add a migration record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
MigrationRecord
|
Migration record to add |
required |
remove
¶
Remove a migration record (for rollback).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
name
|
str
|
Migration name |
required |
Source code in type_bridge/migration/state.py
get_latest
¶
Get the most recently applied migration for an app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
Returns:
| Type | Description |
|---|---|
MigrationRecord | None
|
Most recent migration record, or None |
Source code in type_bridge/migration/state.py
get_all_for_app
¶
Get all applied migrations for an app.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
Returns:
| Type | Description |
|---|---|
list[MigrationRecord]
|
List of migration records in application order |
Source code in type_bridge/migration/state.py
MigrationStateManager
¶
Manages migration state in TypeDB.
Applied state is stored in TypeDB as type_bridge_migration entities, and
execution attempts are stored as type_bridge_migration_run entities. The
storage mechanism — schema bootstrap, reads, and writes — lives in Rust
behind the MigrationStateStore seam; this class is a thin facade that
delegates to a Rust-owned PyMigrationStateManager and assembles Python
dataclasses for callers.
Example
manager = MigrationStateManager(db) state = manager.load_state()
if not state.is_applied("myapp", "0001_initial"): # Apply migration... manager.record_applied("myapp", "0001_initial", "abc123")
Initialize state manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
Source code in type_bridge/migration/state.py
ensure_schema
¶
Ensure the migration tracking schema exists in TypeDB.
Idempotent: the Rust state store no-ops when the schema is already ensured, so no second Python-side latch is kept here.
Source code in type_bridge/migration/state.py
load_state
¶
Load migration state from TypeDB.
Returns:
| Type | Description |
|---|---|
MigrationState
|
Current migration state |
Source code in type_bridge/migration/state.py
load_runs
¶
Load the migration execution run log from TypeDB.
Source code in type_bridge/migration/state.py
record_applied
¶
Record that a migration was applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
name
|
str
|
Migration name |
required |
checksum
|
str
|
Migration content hash |
required |
Source code in type_bridge/migration/state.py
record_unapplied
¶
Record that a migration was rolled back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_label
|
str
|
Application label |
required |
name
|
str
|
Migration name |
required |
Source code in type_bridge/migration/state.py
record_run_started
¶
Record that one migration execution attempt started.
Source code in type_bridge/migration/state.py
record_run_finished
¶
Record that a migration execution attempt finished.
Source code in type_bridge/migration/state.py
MigrationStateStore
¶
Bases: Protocol
State operations required by :class:MigrationExecutor.
Implement this protocol to keep applied migration state outside the target
TypeDB database. Schema bootstrap and run-log reads are intentionally not
part of the contract: the default :class:MigrationStateManager provides
those TypeDB-specific capabilities, while embedding orchestrators may own
persistence and execution-attempt logging independently.
MigrationStateSchema
dataclass
¶
Immutable label projection of the canonical migration-state schema.
Role labels are qualified as relation:role so an application relation
can use the same unqualified role name without being classified as
TypeBridge infrastructure.
author_migration
¶
author_migration(base, target, *, app_label, name, snapshot_version, dependencies=None, previous_snapshot_version=None, before_schema=None, after_schema=None, attribute_renames=None, generated_at=None)
Author the complete migration artifact set from serialized schemas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
dict[str, Any]
|
Serialized |
required |
target
|
dict[str, Any]
|
Serialized |
required |
app_label
|
str
|
Migrations package name (the migrations directory name). |
required |
name
|
str
|
Full migration stem, e.g. |
required |
snapshot_version
|
str
|
Snapshot version to generate, e.g. |
required |
dependencies
|
list[tuple[str, str]] | None
|
|
None
|
previous_snapshot_version
|
str | None
|
The prior snapshot version ( |
None
|
before_schema
|
list[dict[str, Any]] | None
|
Serialized operations executed before the schema change set (e.g. destructive data cleanup). |
None
|
after_schema
|
list[dict[str, Any]] | None
|
Serialized operations executed after the schema change set (e.g. backfills). |
None
|
attribute_renames
|
list[tuple[str, str]] | None
|
|
None
|
generated_at
|
str | None
|
Explicit timestamp text for the generated |
None
|
Returns:
| Type | Description |
|---|---|
AuthoredMigration | None
|
The authored artifact set, or |
AuthoredMigration | None
|
no explicit operations were supplied. |
Source code in type_bridge/migration/author.py
is_migration_state_type
¶
Return whether label is a TypeBridge migration-state schema object.
Role labels must use the qualified relation:role form.
Source code in type_bridge/migration/state_schema.py
migration_state_schema
¶
Return the full canonical migration-state schema descriptor from Rust.
without_migration_state_schema
¶
Return a copy of schema without TypeBridge migration-state objects.
Source code in type_bridge/migration/state_schema.py
type_exists
¶
Check if a type exists in the database schema.
Uses a simple query to check if the type name is valid in the schema. If the type doesn't exist, the query will raise an error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db
|
Database
|
Database connection |
required |
type_name
|
str
|
Name of the type to check (entity, relation, or attribute) |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if type exists in schema, False otherwise |
Example
type_exists(db, "person") True type_exists(db, "nonexistent") False