0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-02-24 23:48:13 -05:00

🐛 Added migration to update empty strings to null (#10428)

closes #10388

This migration finds all tables with nullable columns, it then loops through the tables and their nullable columns, updating each column to a null when its current value is an empty string.
This commit is contained in:
Fabien O'Carroll 2019-01-28 19:00:29 +01:00 committed by GitHub
parent e20537e2bf
commit 0edacf3fc1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -0,0 +1,81 @@
const Promise = require('bluebird');
const common = require('../../../../lib/common');
const schema = require('../../../schema');
/*
* [{
* tableName: 'posts',
* columns: ['custom_excerpt', 'description', 'etc...']
* }]
* */
const tablesToUpdate = Object.keys(schema.tables).reduce((tablesToUpdate, tableName) => {
const table = schema.tables[tableName];
const columns = Object.keys(table).filter((columnName) => {
const column = table[columnName];
return column.nullable && ['string', 'text'].includes(column.type);
});
if (!columns.length) {
return tablesToUpdate;
}
return tablesToUpdate.concat({
tableName,
columns
});
}, []);
const createReplace = (connection, from, to) => (tableName, columnName) => {
return connection.schema.hasTable(tableName)
.then((tableExists) => {
if (!tableExists) {
common.logging.warn(
`Table ${tableName} does not exist`
);
return;
}
return connection.schema.hasColumn(tableName, columnName)
.then((columnExists) => {
if (!columnExists) {
common.logging.warn(
`Table '${tableName}' does not have column '${columnName}'`
);
return;
}
common.logging.info(
`Updating ${tableName}, setting '${from}' in ${columnName} to '${to}'`
);
return connection(tableName)
.where(columnName, from)
.update(columnName, to);
});
});
};
module.exports.up = ({transacting}) => {
const replaceEmptyStringWithNull = createReplace(transacting, '', null);
return Promise.all(
tablesToUpdate.map(({tableName, columns}) => Promise.all(
columns.map(
columnName => replaceEmptyStringWithNull(tableName, columnName)
)
))
);
};
module.exports.down = ({connection}) => {
const replaceNullWithEmptyString = createReplace(connection, null, '');
return Promise.all(
tablesToUpdate.map(({tableName, columns}) => Promise.all(
columns.map(
columnName => replaceNullWithEmptyString(tableName, columnName)
)
))
);
};
module.exports.config = {
transaction: true
};