Project Oxygen & Ideo-LabIDEO LAB Dashboard 2026

Guide complet — installation, audit, réparation, cron et production

Migration Repair Doctor v1.5 — réparer les migrations Django partiellement appliquées

Ce guide explique comment installer et utiliser migration_repair_doctor, une commande Django conçue pour comparer l’état des modèles Django, les fichiers de migrations, la table django_migrations et le schéma réel MySQL/MariaDB. La version 1.5 ajoute le mode central --repair-partial, qui enchaîne automatiquement nettoyage de migration cible, fake-record contrôlé, génération d’une migration follow-up, migration et vérification finale.

Command: migration_repair_doctor Version: v1.5 ⬇ Télécharger le script

1. Le problème que ce cron résout

Les migrations Django sont fiables quand tout se passe parfaitement. Elles deviennent beaucoup plus pénibles quand une migration est partiellement exécutée : une table a été créée, quelques colonnes aussi, un ou deux index ont échoué, mais la migration n’a pas été enregistrée dans django_migrations. Au run suivant, Django retente toute la migration et plante.

Tables déjà créées

Le SQL a matérialisé des tables, mais Django pense que la migration n’est pas appliquée.

Colonnes partielles

Certaines colonnes existent, d’autres manquent encore, notamment des FK ajoutées après CreateModel.

Index trop longs

MySQL/MariaDB refuse les index sur VARCHAR/TEXT trop longs, typiquement avec utf8mb4.

models.pymigration filesdjango_migrationsinformation_schemarepair planfollow-up migration
But v1.5 : ne plus faire une séquence de 4 commandes à la main. Le mode --repair-partial encapsule le scénario complet : détection, nettoyage, fake-record, génération de migration corrective, migration réelle et verify final.

Ce que le script sait faire

FonctionOptionUtilité
Vérifier l’état DB vs models.py--verifyListe les colonnes, index ou tables manquantes, et peut générer une migration follow-up.
Scanner les migrations--scan / --exploreTrouve la migration la plus probablement cassée avec un scoring.
Nettoyer une migration cible--clean-target-migrationRéécrit la migration avec les opérations réellement matérialisées en DB.
Marquer appliqué--fake-recordInsère l’entrée dans django_migrations après nettoyage contrôlé.
Réparation complète--repair-partialWorkflow automatisé en 5 étapes pour migrations partiellement appliquées.
Exporter les diagnostics--export excel / --export pdfProduit un rapport exploitable pour audit, support ou historique.

2. Installation

2.1 Télécharger le script

Le fichier publié est disponible ici :

Download URL
/static/toolbox/migrationrepair_doctor.py

⬇ Télécharger migrationrepair_doctor.py

Nom du fichier côté Django : pour obtenir la commande python manage.py migration_repair_doctor, le fichier doit être installé sous le nom migration_repair_doctor.py dans un dossier management/commands/. Le nom de téléchargement public peut être différent, mais le nom de commande Django dépend du nom du fichier Python installé.

2.2 Installer dans une app Django

Arborescence attendue
your_app/
    management/
        __init__.py
        commands/
            __init__.py
            migration_repair_doctor.py

2.3 Dépendances Python

Le script utilise Django, openpyxl pour l’export Excel et reportlab pour l’export PDF.

Installation dépendances
pip install openpyxl reportlab

2.4 Vérifier que Django voit la commande

Vérification commande
python manage.py help migration_repair_doctor
python manage.py migration_repair_doctor --help

2.5 Premier test sans risque

Par défaut, si ni --execute ni --simulation ne sont fournis, le script bascule en simulation.

Premier test
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --verify \
  --verbose

2.6 Checklist avant production

Backup Git

Les fichiers de migration peuvent être réécrits. Commit ou backup obligatoire avant execute.

Backup SQL

Le script ne fait pas de dump SQL complet. Fais-le côté infrastructure si tu es en production.

Permissions

L’utilisateur Django doit pouvoir lire information_schema et modifier django_migrations.

Chemin backup

Par défaut : C:/temp/migration_repair_doctor_backups sous Windows, /tmp/migration_repair_doctor_backups sous Linux.

3. Commandes rapides à retenir

Cette section est le mémo opérationnel. Pour une migration cassée partiellement, la commande à retenir est maintenant --repair-partial.

3.1 Vérifier une app

Verify read-only
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --verify \
  --verbose

3.2 Générer une migration follow-up si verify détecte des colonnes/champs manquants

Verify execute follow-up
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --verify \
  --execute \
  --verbose

python manage.py migrate tech_glossary

python manage.py migration_repair_doctor \
  --app tech_glossary \
  --verify \
  --verbose

3.3 Réparer une migration partiellement appliquée en simulation

Repair partial simulation
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --repair-partial \
  --simulation \
  --verbose

3.4 Réparer réellement une migration partiellement appliquée

Repair partial execute
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --repair-partial \
  --execute \
  --verbose

3.5 Réparer une migration précise

Repair partial target
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --target 0014 \
  --repair-partial \
  --execute \
  --verbose

3.6 Exporter un rapport Excel ou PDF

Export report
python manage.py migration_repair_doctor \
  --app tech_glossary \
  --scan \
  --export excel \
  --open-export \
  --verbose

4. Mode indispensable : --repair-partial

C’est le mode à utiliser quand une migration a été interrompue pendant son exécution. Exemple : MySQL a créé une table, puis a échoué sur un index trop long. Django n’a pas enregistré la migration, donc au prochain run il retente de créer la table et casse.

Ne pas lancer migrate brut en boucle. Quand tu vois une migration partiellement appliquée, stoppe les relances de python manage.py migrate. Commence par --repair-partial --simulation.

4.1 Workflow interne en 5 étapes

1
Scan ou targetLe script choisit la migration cassée via --scan si aucun --target n’est fourni, ou utilise la migration précise demandée.
2
Clean target migrationIl reconstruit une migration d’état contenant uniquement ce qui est déjà matérialisé en DB selon models.py et information_schema.
3
Fake-recordIl insère la migration nettoyée dans django_migrations, sauf si elle est déjà marquée appliquée.
4
Follow-up sync migrationIl relance --verify --execute pour générer une migration complémentaire avec les colonnes/champs manquants.
5
Migrate puis verify finalIl applique la migration follow-up puis vérifie que DB et models.py sont synchronisés.

4.2 Commande standard

Commande standard
python manage.py migration_repair_doctor \
  --app your_app \
  --repair-partial \
  --execute \
  --verbose

4.3 Commande prudente avec target

Commande ciblée
python manage.py migration_repair_doctor \
  --app your_app \
  --target 0050 \
  --repair-partial \
  --execute \
  --verbose

4.4 Résultat attendu

Sortie attendue
REPAIR PARTIAL MIGRATION WORKFLOW
App: your_app
Mode: EXECUTE

STEP 1/5 - Clean target migration
Backup created: ...
Rewritten cleaned migration: ...

STEP 2/5 - Fake-record cleaned migration
Recorded migration as applied: your_app.0050_...

STEP 3/5 - Generate follow-up sync migration
Generated migration: 0051_your_app_manual_field_sync.py
Verification failed as expected before follow-up migration is applied.

STEP 4/5 - Run migrate
Applying your_app.0051_your_app_manual_field_sync... OK

STEP 5/5 - Final verification
Errors count      : 0
Pending AddField  : 0
Pending AlterField: 0
Pending AddIndex  : 0
Pending CreateModel: 0
Status: OK

REPAIR PARTIAL WORKFLOW COMPLETED

5. Référence CLI des options importantes

OptionTypeDescriptionExemple
--apprequiredApp Django à inspecter.--app tech_glossary
--targetsafePréfixe ou nom exact de migration.--target 0014
--lastsafeUtilise la dernière migration sur disque.--last
--scan / --exploresafeScanne et score les migrations suspectes.--scan --verbose
--verifysafeVérifie DB vs models.py. Avec --execute, génère une migration follow-up.--verify --execute
--clean-target-migrationmutateRéécrit la migration cible nettoyée.--target 0050 --clean-target-migration --execute
--fake-recordmutateEnregistre la migration cible dans django_migrations.--fake-record --execute
--repair-partialworkflowRéparation complète des migrations partiellement appliquées.--repair-partial --execute
--safe-thresholdsafeLongueur maximale sûre pour index CharField MySQL/MariaDB. Défaut : 191.--safe-threshold 191
--exportsafeExporte rapport en Excel, PDF ou les deux.--export both --open-export
--backup-dirsafeDossier de backup des migrations réécrites.--backup-dir C:\temp\mr_backups
--simulationsafeAffiche ce qui serait fait sans modifier disque/DB.--repair-partial --simulation
--executemutateAutorise les écritures disque/DB.--execute
Règle pratique : --verify, --scan, --presim sont des modes d’analyse. --execute déclenche les écritures. --repair-partial est un workflow complet.

6. Cas d’usage et séquences exactes

Cas A — erreur MySQL 1071 : clé trop longue

Symptôme : MariaDB/MySQL refuse un index sur un champ long, souvent CharField(260), URLField ou TextField.

Cas A
python manage.py migration_repair_doctor \
  --app your_app \
  --repair-partial \
  --simulation \
  --verbose

python manage.py migration_repair_doctor \
  --app your_app \
  --repair-partial \
  --execute \
  --verbose
Après réparation, corrige le modèle : ne mets pas d’index direct sur VARCHAR/TEXT longs. Utilise un champ hash court ou un index partiel géré manuellement si nécessaire.

Cas B — tables créées mais migration non appliquée

Cas B
python manage.py migration_repair_doctor \
  --app your_app \
  --scan \
  --verbose

python manage.py migration_repair_doctor \
  --app your_app \
  --repair-partial \
  --execute \
  --verbose

Cas C — colonnes FK manquantes après fake-record

Ce cas arrive quand la migration a été marquée appliquée alors que certaines colonnes n’existent pas encore.

Cas C
python manage.py migration_repair_doctor \
  --app your_app \
  --verify \
  --execute \
  --verbose

python manage.py migrate your_app

python manage.py migration_repair_doctor \
  --app your_app \
  --verify \
  --verbose

Cas D — diagnostic seulement, aucun changement

Cas D
python manage.py migration_repair_doctor \
  --app your_app \
  --scan \
  --export excel \
  --open-export \
  --verbose

Cas E — migration précise connue

Cas E
python manage.py migration_repair_doctor \
  --app your_app \
  --target 0050 \
  --clean-target-migration \
  --fake-record \
  --execute \
  --verbose

python manage.py migration_repair_doctor \
  --app your_app \
  --verify \
  --execute \
  --verbose

python manage.py migrate your_app

7. Cron, CI et exploitation

7.1 Cron quotidien de vérification

Cron verify
# Tous les jours à 03:20
20 3 * * * cd /var/www/ideo_lab && /opt/venv/bin/python manage.py migration_repair_doctor --app tech_glossary --verify --verbose >> /var/log/ideo_lab/migration_repair_doctor.log 2>&1

7.2 CI avant déploiement

CI gate
python manage.py migration_repair_doctor --app tech_glossary --verify --verbose
python manage.py showmigrations tech_glossary

7.3 Runbook production en cas d’incident

1
Stopper les relances migrateNe pas relancer 10 fois la même migration cassée.
2
Faire un backup SQLmysqldump, snapshot RDS, dump MariaDB, selon l’environnement.
3
Simulation--repair-partial --simulation --verbose
4
Exécution--repair-partial --execute --verbose
5
Contrôle final--verify --verbose doit terminer avec Status: OK.

8. Dépannage

Erreur : Use either --simulation or --execute, not both

Le script refuse les modes ambigus. Garde un seul des deux flags.

Correction
# Bon
python manage.py migration_repair_doctor --app your_app --repair-partial --simulation

# Bon
python manage.py migration_repair_doctor --app your_app --repair-partial --execute

Erreur : No materialized operations detected

Le script ne voit aucune table/colonne réellement présente pour construire une migration nettoyée. Soit la mauvaise migration est ciblée, soit la DB n’a rien matérialisé.

Diagnostic
python manage.py migration_repair_doctor --app your_app --scan --verbose
python manage.py showmigrations your_app

Verify affiche des warnings d’index manquants mais Status: OK

Ce n’est pas bloquant si les erreurs sont à zéro. Les warnings signalent des index déclarés côté modèle mais non présents côté DB, ou renommés par MySQL.

Le follow-up est généré mais migrate échoue

Lis la migration générée, puis vérifie si le champ ajouté est nullable, a une default, ou référence une table absente.

Contrôle follow-up
python manage.py showmigrations your_app
python manage.py sqlmigrate your_app 0051
python manage.py migrate your_app

Règles MySQL/MariaDB à garder

ChampIndex direct ?Conseil
CharField <= 191OuiOK en utf8mb4.
CharField 220/260/500NonUtiliser hash court ou index applicatif.
TextFieldNonJamais d’index BTree direct standard.
URLField longNonIndexer un hash ou une clé courte.
ForeignKeyOuiIndex automatique généralement créé par Django/MySQL.