diff --git a/db/migration/1726588731621-MigrateOutdatedConfigsToLatestVersion.ts b/db/migration/1726588731621-MigrateOutdatedConfigsToLatestVersion.ts index a104f1d2872..5df7228815c 100644 --- a/db/migration/1726588731621-MigrateOutdatedConfigsToLatestVersion.ts +++ b/db/migration/1726588731621-MigrateOutdatedConfigsToLatestVersion.ts @@ -1,28 +1,47 @@ +import { migrateGrapherConfigToLatestVersion } from "@ourworldindata/grapher" +import { GrapherInterface } from "@ourworldindata/types" import { MigrationInterface, QueryRunner } from "typeorm" export class MigrateOutdatedConfigsToLatestVersion1726588731621 implements MigrationInterface { + private migrateConfig(config: Record): GrapherInterface { + try { + return migrateGrapherConfigToLatestVersion(config) + } catch { + // if the migration function throws, then the $schema field + // is either missing or invalid. when that happens, we assume + // a schema v1, and try again + config.$schema = + "https://files.ourworldindata.org/schemas/grapher-schema.001.json" + return migrateGrapherConfigToLatestVersion(config) + } + } + public async up(queryRunner: QueryRunner): Promise { - // we have v3 configs in the database; turn these into v5 configs - // by removing the `data` and `hideLinesOutsideTolerance` properties - await queryRunner.query( + const outdatedConfigs = await queryRunner.query( `-- sql - UPDATE chart_configs - SET - patch = JSON_SET( - JSON_REMOVE(patch, '$.data', '$.hideLinesOutsideTolerance'), - '$.$schema', - 'https://files.ourworldindata.org/schemas/grapher-schema.005.json' - ), - full = JSON_SET( - JSON_REMOVE(full, '$.data', '$.hideLinesOutsideTolerance'), - '$.$schema', - 'https://files.ourworldindata.org/schemas/grapher-schema.005.json' - ) - WHERE patch ->> '$.$schema' = 'https://files.ourworldindata.org/schemas/grapher-schema.003.json' + SELECT id, patch, full + FROM chart_configs + WHERE + patch ->> '$.$schema' != 'https://files.ourworldindata.org/schemas/grapher-schema.005.json' + OR full ->> '$.$schema' != 'https://files.ourworldindata.org/schemas/grapher-schema.005.json' ` ) + + for (const { id, patch, full } of outdatedConfigs) { + const updatedPatch = this.migrateConfig(JSON.parse(patch)) + const updatedFull = this.migrateConfig(JSON.parse(full)) + + await queryRunner.query( + `-- sql + UPDATE chart_configs + SET patch = ?, full = ? + WHERE id = ? + `, + [JSON.stringify(updatedPatch), JSON.stringify(updatedFull), id] + ) + } } public async down(): Promise {