Skip to content

Commit 8037d7a

Browse files
committed
update database sequencers, after importing, to be set to max(autoincrement column) from table, so that when next insertions don't provide value of autoincrement column, as in case of using APIs, it should be set automatically based on lastvalue of sequencers.
1 parent b2e4357 commit 8037d7a

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

scripts/data/import/importData.js

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,32 @@ async function writeDataToDatabase(filePath, logger) {
2121
for (let index = 0; index < dataModels.length; index += 1) {
2222
const modelName = dataModels[index];
2323
currentModelName = modelName;
24+
const model = models[modelName];
2425
const modelRecords = jsonData[modelName];
2526
if (modelRecords && modelRecords.length > 0) {
26-
await models[modelName].bulkCreate(modelRecords, {
27+
logger.info(
28+
`Importing data for model: ${modelName}`,
29+
);
30+
await model.bulkCreate(modelRecords, {
2731
transaction,
2832
});
2933
logger.info(
30-
`Records to save for model: ${modelName} = ${modelRecords.length}`,
34+
`Records imported for model: ${modelName} = ${modelRecords.length}`,
3135
);
36+
const modelAttributes = Object.keys(model.rawAttributes);
37+
const tableName = model.getTableName();
38+
/* eslint-disable no-await-in-loop */
39+
for (let attributeIndex = 0; attributeIndex < modelAttributes.length; attributeIndex += 1) {
40+
const field = modelAttributes[attributeIndex];
41+
const fieldInfo = model.rawAttributes[field];
42+
if (fieldInfo.autoIncrement) {
43+
const query = `SELECT setval('${tableName}_${field}_seq', (SELECT MAX(${field}) FROM ${tableName}))`;
44+
const setValue = (await models.sequelize.query(query, {
45+
transaction,
46+
}))[0][0].setval;
47+
logger.info(`Updated autoIncrement for ${modelName}.${field} with max value = ${setValue}`);
48+
}
49+
}
3250
} else {
3351
logger.info(`No records to save for model: ${modelName}`);
3452
}

0 commit comments

Comments
 (0)