@tomei/product
Version:
NestJS package for product module
69 lines (58 loc) • 2.74 kB
JavaScript
;
module.exports = {
async up(queryInterface) {
// Because Previously we use Composite Primary Key (Code, ProductId), we need
// to remove first the old composite primary key, and because the composite PK
// we used is also a Foreign Key, we need to also drop the foreign key
// this function will find all the fk then drop the constraint
const refFK = await queryInterface.getForeignKeyReferencesForTable(
'product_ProductGroup',
);
refFK.forEach(async (fk) => {
await queryInterface.sequelize.query(
`Alter table product_ProductGroup drop FOREIGN KEY ${fk.constraint_name}`,
);
});
// after all the FK is drop then we can safely drop the PK
await queryInterface.sequelize.query(
'Alter table product_ProductGroup DROP PRIMARY KEY',
);
// Create ProductGroupId column without PK constraint first
await queryInterface.sequelize.query(
'ALTER TABLE product_ProductGroup ADD ProductGroupId VARCHAR(30)',
);
// We cannot add ProductGroupId PK constraint if previous data is null, so
// we UPDATING a combination of CODE + productId in previously empty ProductGroupId
await queryInterface.sequelize.query(
"UPDATE product_ProductGroup SET ProductGroupId = SUBSTRING(CONCAT(code, ProductId),1,30) WHERE ProductGroupId IS NULL OR ProductGroupId = ''",
);
// Check if new primary key is not null an unique
await queryInterface.sequelize.query(
'ALTER TABLE product_ProductGroup MODIFY COLUMN ProductGroupId VARCHAR(30) NOT NULL UNIQUE',
);
// Adding PK constraint to ProductGroupId
await queryInterface.sequelize.query(
'ALTER TABLE product_ProductGroup ADD PRIMARY KEY (ProductGroupId)',
);
// After the primary key column is created, we need to re-adding the previous dropped FK
refFK.forEach(async (fk) => {
await queryInterface.sequelize.query(
`ALTER TABLE product_ProductGroup ADD CONSTRAINT ${fk.constraint_name} FOREIGN KEY (${fk.columnName}) REFERENCES ${fk.referencedTableName}(${fk.referencedColumnName})`,
);
});
},
async down(queryInterface) {
// Remove Primary Key first from the table
await queryInterface.sequelize.query(
'Alter table product_ProductGroup DROP PRIMARY KEY',
);
// Remove ProductGroupId from the table
await queryInterface.sequelize.query(
'Alter table product_ProductGroup DROP COLUMN ProductGroupId',
);
// Create a new Composite PK from Code and ProductId
await queryInterface.sequelize.query(
'ALTER TABLE product_ProductGroup ADD PRIMARY KEY (Code, ProductId)',
);
},
};