Created
September 30, 2021 18:27
-
-
Save SidneyAllen/b23e8b3803a779cdf9b2841b787ed8c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const COLUMNS_TO_CHANGE = [ | |
['table1',json_col], | |
[table2,json_col], | |
[table3,json_col], | |
[table4,json_col], | |
]; | |
const limit = 2500; | |
function revertRows (Knex, table, json_col, jsonb_col) { | |
return Knex.raw(` | |
UPDATE ${table} | |
SET | |
${json_col} = ${jsonb_col}::json | |
WHERE id IN ( | |
SELECT id | |
FROM ${table} | |
WHERE ${json_col} IS NULL | |
AND ${jsonb_col} is NOT NULL | |
LIMIT ${limit} | |
) | |
`) | |
} | |
exports.up = async (Knex) => { | |
for (const tableColumnPair of COLUMNS_TO_CHANGE) { | |
await Knex.schema.table(tableColumnPair[0], (table) => { | |
table.dropColumn(tableColumnPair[1]); | |
}); | |
await Knex.schema.table(tableColumnPair[0], (table) => { | |
table.renameColumn(tableColumnPair[1] + '_jsonb', tableColumnPair[1]); | |
}); | |
} | |
} | |
exports.down = async (Knex) => { | |
for (const tableColumnPair of COLUMNS_TO_CHANGE) { | |
await Knex.schema.table(tableColumnPair[0], (table) => { | |
table.renameColumn(tableColumnPair[1], tableColumnPair[1] + '_jsonb'); | |
}); | |
await Knex.schema.table(tableColumnPair[0], (table) => { | |
table.json(tableColumnPair[1]); | |
}); | |
} | |
for (const tableColumnPair of COLUMNS_TO_CHANGE) { | |
let rowCount = limit; | |
do { | |
let response = await revertRows(Knex, tableColumnPair[0], tableColumnPair[1], tableColumnPair[1] + '_jsonb'); | |
rowCount = response.rowCount; | |
} while (rowCount === limit) | |
} | |
} | |
exports.config = { | |
transaction: true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment