93 lines
2.9 KiB
JavaScript
93 lines
2.9 KiB
JavaScript
'use strict';
|
||
|
||
const TABLE_NAME = 'wms_order_delivery';
|
||
const TABLE_LIKE_PATTERN = 'wms_order_delivery\\_%';
|
||
const COLUMN_NAME = 'order_flag';
|
||
const UP_COLUMN_DDL = "LONGTEXT NULL COMMENT '订单标记'";
|
||
const DOWN_COLUMN_DDL = "VARCHAR(200) NULL COMMENT '订单标记'";
|
||
|
||
/**
|
||
* 获取发货单主表及所有分表名称。
|
||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||
* @return {Promise<Array<Object>>} 表名查询结果。
|
||
*/
|
||
async function getOrderDeliveryTables(queryInterface) {
|
||
const [ tables ] = await queryInterface.sequelize.query(`
|
||
SELECT TABLE_NAME
|
||
FROM INFORMATION_SCHEMA.TABLES
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND (TABLE_NAME = '${TABLE_NAME}' OR TABLE_NAME LIKE '${TABLE_LIKE_PATTERN}')
|
||
`);
|
||
|
||
return tables;
|
||
}
|
||
|
||
/**
|
||
* 判断表中是否存在指定字段。
|
||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||
* @param {string} tableName 表名。
|
||
* @param {string} columnName 字段名。
|
||
* @return {Promise<boolean>} 是否存在字段。
|
||
*/
|
||
async function hasColumn(queryInterface, tableName, columnName) {
|
||
const [ columns ] = await queryInterface.sequelize.query(
|
||
`
|
||
SELECT COLUMN_NAME
|
||
FROM INFORMATION_SCHEMA.COLUMNS
|
||
WHERE TABLE_SCHEMA = DATABASE()
|
||
AND TABLE_NAME = :tableName
|
||
AND COLUMN_NAME = :columnName
|
||
`,
|
||
{ replacements: { tableName, columnName } }
|
||
);
|
||
|
||
return columns.length > 0;
|
||
}
|
||
|
||
module.exports = {
|
||
/**
|
||
* 将发货单主表及分表的 `order_flag` 调整为 LONGTEXT。
|
||
* 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。
|
||
*
|
||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async up(queryInterface) {
|
||
const tables = await getOrderDeliveryTables(queryInterface);
|
||
|
||
for (const row of tables) {
|
||
const tableName = row.TABLE_NAME;
|
||
|
||
if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) {
|
||
continue;
|
||
}
|
||
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${UP_COLUMN_DDL}`
|
||
);
|
||
}
|
||
},
|
||
|
||
/**
|
||
* 将发货单主表及分表的 `order_flag` 回滚为 VARCHAR(200)。
|
||
* 仅在目标表存在且字段存在时执行 MODIFY COLUMN,保证幂等。
|
||
*
|
||
* @param {import('sequelize').QueryInterface} queryInterface Sequelize 查询接口。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async down(queryInterface) {
|
||
const tables = await getOrderDeliveryTables(queryInterface);
|
||
|
||
for (const row of tables) {
|
||
const tableName = row.TABLE_NAME;
|
||
|
||
if (!(await hasColumn(queryInterface, tableName, COLUMN_NAME))) {
|
||
continue;
|
||
}
|
||
|
||
await queryInterface.sequelize.query(
|
||
`ALTER TABLE \`${tableName}\` MODIFY COLUMN \`${COLUMN_NAME}\` ${DOWN_COLUMN_DDL}`
|
||
);
|
||
}
|
||
},
|
||
}; |