Entity-First Workflow & Schema Registry
Relevant source files
The following files were used as context for generating this wiki page:
The Entity-First Workflow in SeaORM 2.0 allows developers to define the database schema directly through Rust entity definitions. By using the Schema Registry, the system automatically detects changes in entities—such as new tables, columns, unique keys, or foreign keys—and synchronizes these changes with the underlying database. This approach contrasts with migration-first workflows by treating the Rust code as the primary source of truth for the database structure.
Sources: README.md:144-150, sea-orm-sync/src/lib.rs:163-172, CLAUDE.md:104-108
Core Architecture and Components
The workflow relies on several internal modules to transform Rust structs into database-agnostic schema statements and then into database-specific SQL.
Key Components
| Component | Description |
|---|---|
SchemaBuilder | The primary orchestrator that registers entities and synchronizes them with the database. |
Schema | A helper that generates TableCreateStatement, TypeCreateStatement (for enums), and IndexCreateStatement from an entity. |
EntitySchemaInfo | A container for the schema information of a specific entity, used for diffing and synchronization. |
DiscoveredSchema | Represents the current state of the database as discovered via sea-schema. |
TopologicalSort | Ensures tables are created in the correct order based on foreign key dependencies. |
Sources: src/schema/builder.rs:8-33, src/schema/builder.rs:240-262
Schema Builder Logic Flow
The following diagram illustrates how the SchemaBuilder processes entities to synchronize the database.
The synchronization logic is additive-only, meaning it will create missing structures but will not drop existing tables or columns to prevent accidental data loss.
Sources: src/schema/builder.rs:85-88, src/schema/builder.rs:211-235
Schema Synchronization Logic
The sync method is the heart of the Entity-First workflow. It performs a schema discovery to identify what already exists in the database and then applies only the necessary changes.
Synchronization Operations
- Table Creation: If a table is missing, it is created using the
TableCreateStatementderived from the entity. - Column Addition/Renaming: New columns are added via
TableAlterStatement. The system supports renaming columns if arenamed_fromcomment is detected. - Foreign Key Sync: Missing foreign keys are identified by comparing existing keys against the entity's requirements.
- Index/Unique Key Sync: The builder ensures unique constraints (e.g.,
#[sea_orm(unique)]) are backed by unique indexes in the database.
Sources: src/schema/builder.rs:320-370, src/schema/builder.rs:411-445
Discovery Process
The DiscoveredSchema struct caches the state of the database connection.
Sources: src/schema/builder.rs:95-140
Entity Definition (SeaORM 2.0)
For the registry to work effectively, entities must be defined using the 2.0 #[sea_orm::model] macro. This macro centralizes relations and column definitions within the Model struct.
#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "user")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
#[sea_orm(unique)]
pub email: String,
#[sea_orm(has_many)]
pub posts: HasMany<super::post::Entity>,
}
Sources: CLAUDE.md:15-30, sea-orm-codegen/src/entity/writer/dense.rs:75-125
Database Dependency Management
The SchemaBuilder uses a topological sort to resolve foreign key dependencies. This ensures that parent tables are processed before child tables that reference them.
Sources: src/schema/builder.rs:211-238
Usage and Implementation
To activate the Entity-First workflow, the entity-registry and schema-sync feature flags must be enabled in the project's Cargo.toml.
Implementation Example
// In a development or testing environment
db.get_schema_registry("my_crate::entity::*")
.sync(db)
.await?;
Sources: CLAUDE.md:104-108, README.md:144-150
Comparison of Workflows
| Feature | Entity-First | Migration-First |
|---|---|---|
| Source of Truth | Rust Entity Code | SQL/Rust Migration files |
| Schema Creation | Automatic via Registry | Manual via sea-orm-cli |
| Complexity | Lower for rapid prototyping | Higher, but more granular control |
| Sync Type | Additive-only | Multi-directional (Up/Down) |
Sources: README.md:144-150, src/schema/builder.rs:87-88
Summary
The Entity-First Workflow and Schema Registry provide a high-level abstraction for database management in SeaORM. By leveraging the SchemaBuilder and sea-schema discovery, developers can evolve their database schemas simply by updating their Rust models, while the system handles the complexities of topological sorting and additive schema diffing.