--- name: temps-add-migration-and-entity description: 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. --- # 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 `_encrypted` (`TEXT`), write it with `EncryptionService::encrypt_string` and read it with `decrypt_string` (`crates/temps-core/src/encryption.rs`). Responses expose a boolean such as `has_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_migrations` on 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.rs` lets 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; see `m20261105_000002_drop_webhook_deliveries_response_body.rs`. ## 2. Create the migration file Location: `crates/temps-migrations/src/migration/`. Name: `mYYYYMMDD_NNNNNN_.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`): ```rust // 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_unprepared` is 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 make `down` restore the shape (as the drop-column example above does). If `down` would destroy live user data, refuse with an error instead (see the Bunny delivery downgrade test in `crates/temps-migrations/tests/migration_tests.rs`). - Timestamps are `timestamptz`, normally `NOT NULL DEFAULT now()`. - Foreign keys state their `ON DELETE` behaviour 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('', '
"`. - A new entity column usually means an API change: follow the `temps-add-handler` skill 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 to `mod.rs` or `order_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 `*_encrypted` via `EncryptionService` - [ ] Entity uses `DBDateTime`, `Option` for nullable, relations for joins - [ ] Migration test added and run with Docker available