"""Maintenance : colonnes d'observation corrompues par l'ancien bug positionnel. ``record_observations`` écrivait le **prix** dans ``published_at`` et la date déclarée par la station dans ``fetched_at``. Ce script remet ces colonnes dans leur sens : - ``published_at`` : une valeur numérique est effacée (aucune date de publication n'existe pour le flux instantané) ; - ``fetched_at`` : une valeur égale à ``source_updated`` est notre erreur d'écriture, elle est remplacée par ``collected_at``, qui portait déjà l'heure réelle de collecte. Aucun prix ni aucune autre donnée n'est supprimé. Le nombre de lignes touchées est journalisé dans ``db_maintenance``. Usage : ``python3 repair_columns.py --apply`` (sans option : simulation). """ from __future__ import annotations import argparse import json import re import storage NUMERIC = re.compile(r"[-+]?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?") def survey(now=None): with storage.connect() as db: numeric = db.execute( "SELECT count(*) FROM observations WHERE published_at IS NOT NULL" ).fetchone()[0] bad_published = db.execute( "SELECT count(*) FROM observations WHERE published_at IS NOT NULL AND (" "length(published_at) < 10 OR published_at NOT LIKE '____-__-__%')" ).fetchone()[0] swapped_fetch = db.execute( "SELECT count(*) FROM observations WHERE fetched_at IS NOT NULL" " AND fetched_at = source_updated" ).fetchone()[0] missing_fetch = db.execute( "SELECT count(*) FROM observations WHERE fetched_at IS NULL" ).fetchone()[0] other = db.execute( "SELECT count(*) FROM observations WHERE typeof(price) <> 'real'" " OR price IS NULL OR price <= 0 OR day NOT LIKE '____-__-__'" ).fetchone()[0] return dict( published_at_renseignes=numeric, published_at_non_dates=bad_published, fetched_at_permute=swapped_fetch, fetched_at_absent=missing_fetch, lignes_incoherentes=other, ) def repair(apply=False, now=None): before = survey(now) if not apply: return dict(applied=False, avant=before) with storage.connect() as db: cleared = db.execute( "UPDATE observations SET published_at=NULL WHERE published_at IS NOT NULL AND (" "length(published_at) < 10 OR published_at NOT LIKE '____-__-__%')" ).rowcount fixed = db.execute( "UPDATE observations SET fetched_at=collected_at WHERE fetched_at IS NOT NULL" " AND fetched_at = source_updated AND collected_at IS NOT NULL" ).rowcount storage.record_maintenance( "repair_observation_columns", int(cleared) + int(fixed), f"published_at remis a NULL: {cleared} ; fetched_at restaure depuis collected_at: {fixed}", now=now, ) after = survey(now) return dict(applied=True, cleared_published_at=cleared, restored_fetched_at=fixed, avant=before, apres=after) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--apply", action="store_true", help="écrire les corrections") args = parser.parse_args() print(json.dumps(repair(apply=args.apply), ensure_ascii=False, indent=2))