@tomei/product
Version:
NestJS package for product module
69 lines (58 loc) • 2.79 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_productcollection',
);
refFK.forEach(async (fk) => {
await queryInterface.sequelize.query(
`Alter table product_productcollection 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_productcollection DROP PRIMARY KEY',
);
// Create ProductCollectionId column without PK constraint first
await queryInterface.sequelize.query(
'ALTER TABLE product_productcollection ADD ProductCollectionId VARCHAR(30)',
);
// We cannot add ProductCollectionId PK constraint if previous data is null, so
// we UPDATING a combination of CODE + productId in previously empty ProductCollectionId
await queryInterface.sequelize.query(
"UPDATE product_productcollection SET ProductCollectionId = SUBSTRING(CONCAT(code, ProductId),1,30) WHERE ProductCollectionId IS NULL OR ProductCollectionId = ''",
);
// Check if new primary key is not null an unique
await queryInterface.sequelize.query(
'ALTER TABLE product_productcollection MODIFY COLUMN ProductCollectionId VARCHAR(30) NOT NULL UNIQUE',
);
// Adding PK constraint to ProductCollectionId
await queryInterface.sequelize.query(
'ALTER TABLE product_productcollection ADD PRIMARY KEY (ProductCollectionId)',
);
// 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_productcollection 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_productcollection DROP PRIMARY KEY',
);
// Remove ProductCollectionId from the table
await queryInterface.sequelize.query(
'Alter table product_productcollection DROP COLUMN ProductCollectionId',
);
// Create a new Composite PK from Code and ProductId
await queryInterface.sequelize.query(
'ALTER TABLE product_productcollection ADD PRIMARY KEY (Code, ProductId)',
);
},
};