temps-add-migration-and-entity
Skill949 starsChanged 24 days agoApache-2.0View on GitHub
Add a database migration in crates/temps-migrations and the matching Sea-ORM entity in crates/temps-entities - file naming (the file is the registration), up/down, TimescaleDB and Postgres specifics, encrypted columns and migration tests. Use whenever a change adds or alters a table, column, index, constraint or hypertable, or adds a per-record setting.
In this repository23 other files it gives its agents.
- AGENTS.mdAGENTS.md
- web/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- web/CLAUDE.mdCLAUDE.md
- start-temps-clusterSkill
- start-tempsSkill
- temps-add-handlerSkill
- temps-add-pluginSkill
- temps-design-systemSkill
- temps-split-moduleSkill
- add-custom-domainSkill
- add-error-trackingSkill
- add-node-sdkSkill
- add-react-analyticsSkill
- add-session-recordingSkill
- deploy-to-tempsSkill
- estimate-temps-savingsSkill
- temps-best-practicesSkill
- temps-cliSkill
- temps-mcp-setupSkill
- temps-platform-setupSkill
- temps-pluginSkill
- tempsSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
13 rules. About 0 are common, 2 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 17
Read first: AGENTS.md (NEVER list, "Configuration is a column", "Data, logging and secrets"), REVIEW.md → "Migrations and the database".
- Very specific: line 38
Only drop or rename a column after the code has stopped reading it in an earlier release.
- Very specific: line 93
Always write a real down. If the data cannot be restored, say so in the module doc and make down restore the shape (as the drop-column …
- Very specific: line 95
If down would destroy live user data, refuse with an error instead (see the Bunny delivery downgrade test in …
- Very specific: line 106
time_bucket: never cast it at the same query level as GROUP BY. - Very specific: line 113
Backfills: add the column first, then backfill in committed batches.
- Very specific: line 127
Keep only migration files in src/migration/.
- Very specific: line 130
Never add a block to order_exceptions.txt for a new migration, and never edit, reorder or remove an existing block or rename a migration …
- Very specific: line 162
When altering an existing table, update its entity in the same PR and grep for struct literals of that Model (tests build them by hand) so …
- Very specific: line 167
Every schema change ships a test (AGENTS.md, REVIEW.md).
- Very specific: line 171
Up/down against a real database: add a #[tokio::test] to crates/temps-migrations/tests/migration_tests.rs.
- Distinctive: line 181
When you change a column default, grep the existing tests for the old default.
- Distinctive: line 196
Run the migration test with Docker available: a skipped test proves nothing.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!--
SPDX-FileCopyrightText: 2024-2026 Temps Contributors
SPDX-License-Identifier: MIT OR Apache-2.0
-->Add a migration and its entity
A schema change in Temps is always two pieces in one PR: a new migration file
(adding the file registers it in Migrator) and the entity (new or changed) that
reads the table. A test proves the migration applies to an existing database and, where it
matters, that down restores the previous state.
Read first: AGENTS.md (NEVER list, "Configuration is a column", "Data, logging and secrets"), REVIEW.md → "Migrations and the
database".
1. Decide what the change is
- Runtime configuration is a column, never an env var. A new knob belongs on
the row it configures (
oidc_providers.trust_idp_email,project_analytics_settings.exclude_datacenter_traffic), so it can be changed per record through the API, gets audit logging, and needs no restart. Env vars are only for bootstrap values needed before the database exists. - Sensitive values are encrypted at rest. Name the column
<thing>_encrypted(TEXT), write it withEncryptionService::encrypt_stringand read it withdecrypt_string(crates/temps-core/src/encryption.rs). Responses expose a boolean such ashas_secret, never the value. Worked example:crates/temps-revenue/src/service/integration.rs. - A shipped migration is never edited. Once a migration has been released,
its name is recorded in
seaql_migrationson users' databases and it never runs again. Fix or extend it with a new migration. - Stay compatible with the previous binary.
crates/temps-schema/src/schema_guard.rslets an operator roll the binary back after an upgrade with the newer schema in place. Prefer additive changes (new nullable or defaulted column, new table). Only drop or rename a column after the code has stopped reading it in an earlier release; seem20261105_000002_drop_webhook_deliveries_response_body.rs.
2. Create the migration file
Location: crates/temps-migrations/src/migration/.
Name: mYYYYMMDD_NNNNNN_<snake_case_description>.rs (lowercase letters, digits
and _). The stamp must sort after every existing migration file: use today's
date and the next free sequence number, unless a file already carries a later
date, in which case use that date with the next free sequence number. File-name
order is run order, so an earlier stamp would run your migration in the middle of
shipped history (the registry test rejects it). DeriveMigrationName turns the
file name into the persisted migration name, so it must be unique.
Shape (mirrors m20261104_000002_create_project_analytics_settings.rs):
// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Why this table/column exists, what the default means for existing rows,
//! and whether a backfill is needed.
use sea_orm_migration::prelude::*;
#[derive(DeriveMigrationName)]
pub struct Migration;
#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.get_connection()
.execute_unprepared(
"ALTER TABLE things ADD COLUMN IF NOT EXISTS enabled boolean NOT NULL DEFAULT true",
)
.await?;
Ok(())
}
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.get_connection()
.execute_unprepared("ALTER TABLE things DROP COLUMN IF EXISTS enabled")
.await?;
Ok(())
}
}Rules:
- Raw SQL through
execute_unpreparedis the dominant style; keep statements idempotent (IF NOT EXISTS,IF EXISTS). - Always write a real
down. If the data cannot be restored, say so in the module doc and makedownrestore the shape (as the drop-column example above does). Ifdownwould destroy live user data, refuse with an error instead (see the Bunny delivery downgrade test incrates/temps-migrations/tests/migration_tests.rs). - Timestamps are
timestamptz, normallyNOT NULL DEFAULT now(). - Foreign keys state their
ON DELETEbehaviour explicitly. - The module doc comment explains the why: defaults for existing rows, backfill, and why a table rather than a column (or the reverse).
Postgres and TimescaleDB specifics
- Hypertables:
SELECT create_hypertable('<table>', '<time column>', ..., if_not_exists => TRUE). Example:m20260225_000001_create_otel_tables.rs. time_bucket: never cast it at the same query level asGROUP BY; bucket in a subquery.- Large or hot tables: a plain
CREATE INDEXblocks writes for the whole scan. Build such indexesCONCURRENTLYafter boot throughrun_post_migration_indexesincrates/temps-schema/src/maintenance.rs(seeREFERENCE_INDEXES, andFK_INDEXESexported fromm20261105_000001_project_data_purges.rs), not inside the migration. - Backfills: add the column first, then backfill in committed batches. Do not
rewrite every row while
ALTER TABLEstill holds its exclusive lock. - Uniqueness claims (hostnames, ports, slugs) are enforced with a unique index, not with read-then-write in the service.
3. Registration is automatic
There is no list to edit. crates/temps-migrations/build.rs reads
src/migration/, declares one pub mod per file and generates
Migrator::migrations(): the file names sorted, then the blocks of
src/migration/order_exceptions.txt applied (shipped history that does not
follow file-name order; rules in src/migration_order.rs). mod.rs only
include!s the result. Every file must define pub struct Migration.
- Keep only migration files in
src/migration/. The build fails, naming the file or line, on a badly named file, a directory, or a malformed exceptions block. - Never add a block to
order_exceptions.txtfor a new migration, and never edit, reorder or remove an existing block or rename a migration file: either changes the order or names existing databases recorded. A wrong stamp is fixed by renaming the new file before it ships. - To expose a migration's SQL or struct to another crate or an integration
test,
pub useit fromcrates/temps-migrations/src/lib.rs, asNormalizedManagedDomainIndexMigrationis.
registry_tests at the bottom of mod.rs asserts that names are unique, that
every file is registered, and that the generated list starts with exactly the
shipped history in crates/temps-migrations/tests/fixtures/migration_order.txt.
That fixture is append-only: never edit, reorder or remove a line.
4. Add or update the entity
Location: crates/temps-entities/src/<table_name>.rs, declared with
pub mod <table_name>; in crates/temps-entities/src/lib.rs (alphabetical).
Adding it to crates/temps-entities/src/prelude.rs is optional.
Mirror crates/temps-entities/src/project_analytics_settings.rs:
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]and#[sea_orm(table_name = "...")].- Timestamps are
temps_core::DBDateTime(an alias forchrono::DateTime<Utc>, serialised with aZsuffix). NeverNaiveDateTime. - Nullable columns are
Option<T>; column types match the SQL exactly. A mismatch fails at decode time, not at compile time. Relation+Relatedfor every foreign key you will join on (JOINs, not N+1).ActiveModelBehavior::before_savesetscreated_at/updated_atwhen the table has them.- Doc-comment each setting column with what it does and its default.
When altering an existing table, update its entity in the same PR and grep for
struct literals of that Model (tests build them by hand) so they still compile.
5. Test it
Every schema change ships a test (AGENTS.md, REVIEW.md).
- Registry:
cargo test --lib -p temps-migrationsrunsregistry_testsand the order rules' tests insrc/migration_order.rs. - Up/down against a real database: add a
#[tokio::test]tocrates/temps-migrations/tests/migration_tests.rs. Follow its pattern: starttimescale/timescaledb-ha:pg18throughtestcontainers, skip with a message when Docker is unavailable orexternal_db_configured(), migrate to just before your migration, insert representative rows, runMigrator::up(&db, Some(1)), assert, thenMigrator::downand assert again. Use thesteps_back_to(name)helper rather than a hard-coded step count. Never mark it#[ignore]. - Service-level tests on the new schema:
TestDatabase::with_migrations()fromcrates/temps-test-utils/src/lib.rs, skipping when it returnsErr(seetry_test_dbincrates/temps-revenue/tests/end_to_end.rs). - When you change a column default, grep the existing tests for the old default.
Verification
cargo check --lib -p temps-migrations
cargo check --lib -p temps-entities
cargo test --lib -p temps-migrations
cargo test -p temps-migrations --test migration_tests <your_test_name>
cargo clippy -p temps-migrations -p temps-entities --all-targets -- -D warnings
python3 scripts/rule_drift.py
python3 scripts/source_attribution.py checkAlso cargo check --lib for every crate whose code uses the changed entity.
Run the migration test with Docker available: a skipped test proves nothing.
Commit
- New
.rsfiles carry the SPDX header (python3 scripts/source_attribution.py annotate <file>). - Conventional Commits with DCO:
git commit -s -m "feat(<area>): add <column> to <table>". - A new entity column usually means an API change: follow the
temps-add-handlerskill to expose it and regenerate the OpenAPI clients.
Checklist
- New file, never an edit to a shipped migration
- File named
mYYYYMMDD_NNNNNN_description.rs, stamped after every existing migration; no edit tomod.rsororder_exceptions.txt - Working
down, or an explicit refusal when it would destroy user data - Additive and compatible with the previous binary
- No blocking index build or locked backfill on a large table
- Config is a column; secrets are
*_encryptedviaEncryptionService - Entity uses
DBDateTime,Option<T>for nullable, relations for joins - Migration test added and run with Docker available
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

