Skip to content

Commit

Permalink
🔨 use migrate function in db migration
Browse files Browse the repository at this point in the history
  • Loading branch information
sophiamersmann committed Oct 5, 2024
1 parent 588d8f7 commit a6d1c3f
Showing 1 changed file with 35 additions and 16 deletions.
51 changes: 35 additions & 16 deletions db/migration/1726588731621-MigrateOutdatedConfigsToLatestVersion.ts
Original file line number Diff line number Diff line change
@@ -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<string, any>): 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<void> {
// 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<void> {
Expand Down

0 comments on commit a6d1c3f

Please sign in to comment.