|
| 1 | +const Promise = require('bluebird'); |
| 2 | +const common = require('../../../../lib/common'); |
| 3 | +const schema = require('../../../schema'); |
| 4 | + |
| 5 | +/* |
| 6 | + * [{ |
| 7 | + * tableName: 'posts', |
| 8 | + * columns: ['custom_excerpt', 'description', 'etc...'] |
| 9 | + * }] |
| 10 | + * */ |
| 11 | +const tablesToUpdate = Object.keys(schema.tables).reduce((tablesToUpdate, tableName) => { |
| 12 | + const table = schema.tables[tableName]; |
| 13 | + const columns = Object.keys(table).filter((columnName) => { |
| 14 | + const column = table[columnName]; |
| 15 | + return column.nullable && ['string', 'text'].includes(column.type); |
| 16 | + }); |
| 17 | + if (!columns.length) { |
| 18 | + return tablesToUpdate; |
| 19 | + } |
| 20 | + return tablesToUpdate.concat({ |
| 21 | + tableName, |
| 22 | + columns |
| 23 | + }); |
| 24 | +}, []); |
| 25 | + |
| 26 | +const createReplace = (connection, from, to) => (tableName, columnName) => { |
| 27 | + return connection.schema.hasTable(tableName) |
| 28 | + .then((tableExists) => { |
| 29 | + if (!tableExists) { |
| 30 | + common.logging.warn( |
| 31 | + `Table ${tableName} does not exist` |
| 32 | + ); |
| 33 | + return; |
| 34 | + } |
| 35 | + return connection.schema.hasColumn(tableName, columnName) |
| 36 | + .then((columnExists) => { |
| 37 | + if (!columnExists) { |
| 38 | + common.logging.warn( |
| 39 | + `Table '${tableName}' does not have column '${columnName}'` |
| 40 | + ); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + common.logging.info( |
| 45 | + `Updating ${tableName}, setting '${from}' in ${columnName} to '${to}'` |
| 46 | + ); |
| 47 | + |
| 48 | + return connection(tableName) |
| 49 | + .where(columnName, from) |
| 50 | + .update(columnName, to); |
| 51 | + }); |
| 52 | + }); |
| 53 | +}; |
| 54 | + |
| 55 | +module.exports.up = ({transacting}) => { |
| 56 | + const replaceEmptyStringWithNull = createReplace(transacting, '', null); |
| 57 | + |
| 58 | + return Promise.all( |
| 59 | + tablesToUpdate.map(({tableName, columns}) => Promise.all( |
| 60 | + columns.map( |
| 61 | + columnName => replaceEmptyStringWithNull(tableName, columnName) |
| 62 | + ) |
| 63 | + )) |
| 64 | + ); |
| 65 | +}; |
| 66 | + |
| 67 | +module.exports.down = ({connection}) => { |
| 68 | + const replaceNullWithEmptyString = createReplace(connection, null, ''); |
| 69 | + |
| 70 | + return Promise.all( |
| 71 | + tablesToUpdate.map(({tableName, columns}) => Promise.all( |
| 72 | + columns.map( |
| 73 | + columnName => replaceNullWithEmptyString(tableName, columnName) |
| 74 | + ) |
| 75 | + )) |
| 76 | + ); |
| 77 | +}; |
| 78 | + |
| 79 | +module.exports.config = { |
| 80 | + transaction: true |
| 81 | +}; |
0 commit comments