Persistence and migrations standard¶
This page sets the rules for persistence code and schema migrations in ConnectSoft services. It is written for engineers who add or change entities, mappings, repositories and migrations, for their reviewers, and for AI agents that work in service repositories. The concepts are explained in NHibernate and Database Migrations.
Two phases of a service's schema¶
A service's schema goes through two phases, and the migration rules differ between them:
- Before release: no environment holds data that must survive. Databases are recreated from the migrations whenever the schema changes, and the baseline migration is the schema.
- After release: at least one environment holds data that must survive, for example production or a customer's acceptance environment. Every schema change is a new migration that the existing databases can apply.
The service records the switch between the phases, with the date and the environment that triggered it, in its README or in an ADR.
Rules¶
CS-PER-001: Use NHibernate, FluentNHibernate and FluentMigrator by default¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
The templates, the persistence extensions, the unit of work and the mapping tests are built for NHibernate with FluentNHibernate ClassMap mappings and FluentMigrator migrations. A service on another stack loses those, and reviewers cannot tell a deliberate choice from drift. The default is settled by ADR-0106 §7.
Do¶
- Map relational entities with FluentNHibernate
ClassMap<T>classes. - Write schema changes as FluentMigrator migrations.
- Use Dapper for read paths that need hand-written SQL.
- Use MongoDB, through the template's MongoDB option, for document storage.
- Record the reason when a service uses Entity Framework Core, for example a client mandate or a third-party component that requires it.
Don't¶
- Add Entity Framework Core to a service without a recorded reason.
- Mix mapping styles, such as mapping by code, with
ClassMapin one service.
How to check¶
- A new reference to
Microsoft.EntityFrameworkCorein a service comes with a recorded reason. - The change adds no mapping by code (
ClassMapping<T>) or other mapping style to a service that maps withClassMap<T>.
CS-PER-002: Fold schema changes into the baseline migration before release¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Before release nobody needs an upgrade path, and every incremental migration adds a file, a test and a Down() that only ever runs against a database that is recreated anyway. Folding keeps one readable baseline that describes the whole schema. Databases are recreated, not upgraded.
Do¶
- While the service is before release, add a new table, column or index to the baseline migration and delete the incremental migration that added it.
- Recreate the affected databases after the change. An agent only reports which databases need it; see CS-PER-005.
- Add or update a test that runs the migrations up from an empty database and asserts the folded table or column.
- Keep a
Down()in the baseline that reverses everything itsUp()creates, including the folded objects. Every migration has aDown(), before the switch as well as after it.
Don't¶
- Add new guards to
Down()for folded tables. A database built by an earlier baseline is recreated, not migrated down. Guards that are already in a baseline stay unless the owner asks to remove them. - Fold a migration after the service has recorded its switch to the after-release phase.
How to check¶
- The service has not recorded the switch to the after-release phase.
- A migration test runs from an empty database and asserts each folded object.
- The test catalog does not still hold the object from an earlier run, which would make the test pass without proving anything.
- The baseline
Down()removes every object folded into itsUp(), and the change adds no new guards toDown().
CS-PER-003: Keep migrations immutable and additive after release¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A database that has applied migration N never runs it again. After release, an edit to an applied migration never reaches the existing databases, so they drift from the code without any error.
Do¶
- After the switch, write every schema change as a new migration with the next number.
- Make each change additive where possible: add nullable columns or columns with defaults, and remove a column only in a later migration after no code reads it.
- Implement
Down()for each new migration, or state in the migration why it cannot be reversed.
Don't¶
- Edit or delete a migration that an after-release environment has applied.
How to check¶
- The change adds migrations and does not modify existing ones, once the service has recorded its switch.
- Each new migration implements
Down(), or states in the migration why it cannot be reversed.
CS-PER-004: Seed lookup tables from the enumeration in the baseline¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Smart enumerations (Enumeration subclasses) are mapped to lookup tables with a foreign key. The baseline migration inserts one row per member from Enumeration.GetAll<T>(), so a new member already gets its row on every database created from scratch. A second migration that inserts the same row fails with a primary-key violation on every fresh database.
Do¶
- To add a lookup value, add the member to the enumeration class, and stop there.
- After release, when an existing database must receive the new row, write a migration that inserts it only if it does not exist.
Don't¶
- Write an unguarded seed migration for a value that the baseline seeds from the enumeration.
How to check¶
- A change that adds an enumeration member adds no seed migration before release.
- After release, a seed migration for a lookup value is guarded with a "not exists" check.
CS-PER-005: Never drop, recreate or alter a database that was not named¶
Severity: blocker · Applies to: service, template, docs · Enforced by: manual · Status: active
Why¶
Services in one environment share data across their databases. Recreating one database leaves the others holding references to rows that no longer exist, so a "local" recreate degrades its neighbours. The data and the running processes belong to the environment's owner. ADR-0103 §7 already keeps database runs with the owner.
Do¶
- When a change needs a schema refresh, say so and list the databases that lack the change and the steps to refresh them.
- Let the owner of the environment run the refresh.
- State this rule in the
AGENTS.mdof every service and template repository.
Don't¶
- Drop, recreate or alter a database, or stop a service to reach its database, unless the owner named that database and asked for it.
- Run tests that write to a shared database without the owner's permission.
How to check¶
- An agent's report lists the databases that need a refresh instead of refreshing them.
AGENTS.mdcontains the rule.
CS-PER-006: Change data through repositories inside the unit of work¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
The unit of work opens the session, installs the interceptors that decide between insert and update, and commits or rolls back as one transaction. Code that opens its own session or transaction bypasses them and behaves differently from the rest of the service.
Do¶
- Read through repositories and specifications.
- Write inside
ExecuteTransactionalorExecuteTransactionalAsyncin the domain service.
Don't¶
- Open an
ISessionor a database transaction directly in a domain service, a controller or a handler.
How to check¶
Changed code outside the persistence model does not reference ISession, ISessionSource or DbConnection.
CS-PER-007: Flush between closing and opening rows under a filtered unique index¶
Severity: major · Applies to: service · Enforced by: manual · Status: active
Why¶
NHibernate runs all inserts before all updates when it flushes. In a "close the current row, open a new one" swap guarded by a filtered unique index, such as one open assignment per order, the new open row is inserted while the old row is still open. The index rejects the insert, although the object graph is correct.
Do¶
- Call
Flush()on the unit of work after closing the outgoing row and before adding the incoming row, inside the same transaction.
Don't¶
- Rely on the order of statements in C# to set the order of SQL statements in one flush.
How to check¶
Each close-then-open swap under a filtered unique index has an intermediate flush and a persistence test that performs the swap.
CS-PER-008: Re-parent a child by setting its parent reference¶
Severity: blocker · Applies to: service · Enforced by: manual · Status: active
Why¶
Child collections of an aggregate are mapped inverse with delete-orphan cascade. Removing the child from the old parent's collection marks it as an orphan, and NHibernate deletes the row, even when the same unit of work adds it to a new parent. Unit tests with in-memory fakes do not show this.
Do¶
- Move a child by adding it to the new parent through the parent's method, which sets the child's parent reference.
Don't¶
- Call
Remove()on the old parent's collection when the child is moving, not being deleted.
How to check¶
An operation that moves a child has an end-to-end or persistence test that asserts the child still exists under the new parent.
CS-PER-009: Test persistence the way production runs it¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Insert or update for an entity with an assigned id is decided by an interceptor that only the unit of work installs. A test on a raw session, or one that saves where production merges, issues an update for a new row and fails, or passes for the wrong reason. Mapping tests that commit their rows leave data behind, so a fixed value in a unique column fails on the next run.
Do¶
- Open sessions in persistence tests with
IUnitOfWorkFactory.BeginUnitOfWork(). - Persist an aggregate with new children through the same call production uses, for example
Merge. - Give unique columns a value that is distinct per run, for example with a
Guidsuffix.
Don't¶
- Test persistence on a session from
ISessionSource.CreateSession(). - Use fixed values in unique columns in tests that commit.
How to check¶
Persistence tests in the change use the unit-of-work factory and per-run values for unique columns.
CS-PER-010: Apply a command's effective date to every record it writes¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
Users often record a change after it happened. A command that carries an effective date but applies it to only one of the records it writes leaves the others dated at the moment of entry. The result is gaps or overlaps between periods, and history that disagrees with the period shown beside it.
Do¶
- Give an entity whose state changes take effect on a date its own effective-date field, separate from its creation time.
- Apply the command's effective date to every record the command creates, closes or appends to history.
- Sort lists of past events by the date the event took effect, and keep planned future dates out of them or in a separate list.
Don't¶
- Use the creation time, or the current time, as the effective date of a change that the command dates explicitly.
How to check¶
A test records a change dated in the past and asserts that every record the command wrote carries that date.
CS-PER-011: Match search text word by word across the searched columns¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A search box labelled with "name" invites a full name. A predicate that compares the whole text with each column separately never finds a value that spans two columns, such as a first and a last name, so the search fails exactly for the input its label suggests.
Do¶
- Split the search text into words, and require each word to match at least one of the searched columns.
- Keep twin specifications, such as keyed and unkeyed variants, on one shared predicate.
- Test each kind of input the search box label promises.
Don't¶
- Compare the whole search text with each column separately when the label promises values that span columns.
How to check¶
A search test finds a record by its full name in both orders, by one word and by its id.
CS-PER-012: Keep SQL echo off in deployed configurations and batch-fetch the collections that list reads touch¶
Severity: major · Applies to: service, template · Enforced by: manual (target: ENF-068) · Status: active
Why¶
show_sql writes every statement synchronously to the console, and a list that touches lazy collections for each row issues one query per row and collection. Together they make a list read grow linearly with the page size, while the database itself is idle. Statement echo is useful on a developer's machine, but it costs every request in an environment that serves real load.
Do¶
- Set
show_sqlandformat_sqlto false in every ORM configuration that a deployed environment loads. - Keep statement echo, where you want it, in configurations used only for local development, such as a Development or local Docker configuration.
- Set a default batch size for collections and lazy references, or fetch the collections a list mapping uses in the query.
- Keep a test that asserts the number of queries for one page stays constant as the page size grows.
- Apply this to each configuration that a change adds or edits. Existing base configurations that still set
show_sqlto true are tracked as ENF-068 and change when they are next touched.
Don't¶
- Ship
show_sqlorformat_sqlset to true to a deployed environment. - Map a list item by walking lazy collections without batch fetching.
How to check¶
- The ORM configuration that deployed environments load sets
show_sqlto false and a batch size. - List endpoints have a query-count test.