Évolution du schéma SQLAlchemy et Alembic

VérifiéSûr

Gérer les changements de modèles SQLAlchemy, contraintes, index et révisions Alembic : générer, revoir, tester migrations et transformations de données en sécurité.

Spar Skills Guide Bot
DeveloppementAvancé
1018/10/2026
Claude CodeCursorCodex
#sqlalchemy#alembic#database-migrations#schema-evolution#backend

Recommandé pour

Notre avis

Cadre l'évolution du schéma de base de données : modèles SQLAlchemy, contraintes, index, révisions Alembic et transformations de données existantes.

Points forts

  • Couvre la chaîne complète : génération de la migration, revue du SQL et de l'ordre des clés étrangères, tests sur base vide et sur révision précédente, parité modèle/schéma.
  • Impose des garde-fous concrets : vérification de la tête Alembic intégrée, assertions de préservation des données, refus de considérer l'autogénération ou create_all comme preuve.
  • Détaille les conventions du projet (identifiants de révision YYYYMMDD_NNNNNN, nommage explicite des contraintes, exclusion des tables directus_*).
  • Articule le changement avec les skills voisins (openapi-sync, backend-architecture, validate-change) et prévoit des phases de déploiement compatibles.

Limites

  • Très lié à une organisation de projet précise (recettes `just backend`, chemins backend/src/common/database/) et peu réutilisable tel quel ailleurs.
  • Suppose une maîtrise préalable d'Alembic et de SQLAlchemy ; les étapes restent procédurales et peu guidées pour un débutant.
  • N'aborde pas les stratégies de rollback destructives ni les migrations multi-bases au-delà de ce que le profil de projet décrit.
Quand l'utiliser

À utiliser dès qu'un changement ajoute ou modifie des tables, colonnes, relations, contraintes, index ou données stockées dans une base SQLAlchemy/Alembic.

Quand l'éviter

À ne pas utiliser pour des modifications limitées aux DTO, schémas Pydantic ou zod, ou pour du code qui ne touche ni au schéma ni aux données persistées.

Analyse de sécurité

Sûr
Score qualité92/100

The skill provides structured guidance for database schema changes using project-specific 'just' commands and Alembic workflows. It does not instruct destructive, exfiltrating, obfuscated, or safety-disabling actions. The referenced commands operate on disposable databases and owned resources only, with explicit warnings against unsafe downgrades and stale migrations.

Aucun point d'attention détecté

Exemples

Add a column with a unique constraint
Add a nullable stripe_customer_id column with a unique constraint to the customers table, update the SQLAlchemy model, and generate plus review the Alembic revision.
Merge conflicting migration heads
We have two Alembic heads after the last merge; collapse them into a single integrated head, renumber the revisions to the next global sequence, and verify with just backend check-migrations.
Backfill data in a migration
Write a migration that backfills the new plan_tier column from the legacy subscription field, and add assertions that existing values are preserved on the previous revision.

name: schema-change description: Evolve SQLAlchemy models, constraints, indexes, Alembic revisions or data transformations. Use when a change adds or alters tables, columns, relationships, migrations or stored data. DTO, Pydantic or zod-only edits do not activate this workflow.

schema-change

Read the project profile, affected data criteria, central ORM models (backend/src/common/database/models/) and the Alembic graph. Coordinate with backend-change and consumers when HTTP contracts change.

Steps

  1. Generate with just backend new-migration "description" when appropriate, then deliberately review SQL, FK ordering, constraints and data transforms. Merge conflicting revisions through Alembic's graph workflow.
  2. Test an empty database and the supported previous revision with representative data. Use just backend check-migrations; it owns disposable databases, upgrades and drift checks. Add data-preservation assertions when a migration transforms existing values.
  3. Confirm an unambiguous integrated head, model parity and preserved data. Plan compatible deployment phases when API, frontend and schema do not update simultaneously. When the change reaches DTOs or routes, refresh the API snapshot with openapi-sync. Place shared domain models as backend-architecture describes.
  4. Record the structural decision in an ADR and the technical evidence on the exact integrated revision. Return findings to the implementer; validate-change checks evolution and compatibility acceptance. Clean only owned resources.

Gotchas

  • Autogeneration is a starting point, not a reviewed migration.
  • metadata.create_all and migrate-current are not migration evidence.
  • Do not require a destructive downgrade by default.
  • Run just backend migrate before just backend new-migration; autogenerate diffs against the local database, so a stale database yields a wrong revision.
  • Base.metadata has no naming_convention: name new constraints and indexes explicitly (name="uq_<table>_<cols>", ix_..., fk_...) so later revisions can drop them deterministically.
  • Revision ids follow YYYYMMDD_NNNNNN (date plus a global sequence, e.g. 20260907_000002) with files named <revision>_<slug>.py in backend/src/common/database/versions/. The recipe's file_template produces a timestamped name with a random hex id, so set revision and rename the file to the next sequence before review.
  • env.py include_object skips directus_* tables; never write migrations for them, and do not read their absence from autogenerate as drift.
Skills similaires