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
¶
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
¶
Represents changes to an entity type.
RelationChanges
dataclass
¶
RelationChanges(added_roles=list(), removed_roles=list(), modified_role_players=list(), modified_role_cardinality=list(), added_attributes=list(), removed_attributes=list(), modified_attributes=list())
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_entities=dict(), modified_relations=dict())
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
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 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 | |
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
|
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 |
MigrationGenerator
¶
Generates migration files from model changes.
Compares current models against the last migration state and generates appropriate operations for the detected changes.
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
IntrospectedAttribute
dataclass
¶
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.
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.
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) |
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.
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
162 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 | |
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.
Initialize migration manager.
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.
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.
State is stored in TypeDB as type_bridge_migration entities.
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 migration tracking schema exists in TypeDB.
Creates the type_bridge_migration entity type if it doesn't exist.
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
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
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