@@ -21,14 +21,51 @@ 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 ( `Importing data for model: ${ modelName } ` ) ;
28+ await model . bulkCreate ( modelRecords , {
2729 transaction,
2830 } ) ;
2931 logger . info (
30- `Records to save for model: ${ modelName } = ${ modelRecords . length } ` ,
32+ `Records imported for model: ${ modelName } = ${ modelRecords . length } ` ,
3133 ) ;
34+
35+ // Set autoincrement sequencers in the database to be set to max of the autoincrement column,
36+ // so that, when next insertions don't provide value of autoincrement column, as in case of using APIs,
37+ // it should be set automatically based on last value of sequencers.
38+ const modelAttributes = Object . keys ( model . rawAttributes ) ;
39+ const tableName = model . getTableName ( ) ;
40+ /* eslint-disable no-await-in-loop */
41+ for (
42+ let attributeIndex = 0 ;
43+ attributeIndex < modelAttributes . length ;
44+ attributeIndex += 1
45+ ) {
46+ const field = modelAttributes [ attributeIndex ] ;
47+ const fieldInfo = model . rawAttributes [ field ] ;
48+ if ( fieldInfo . autoIncrement ) {
49+ // Get sequence name corresponding to automincrment column in a table
50+ const selectSequenceQuery = `SELECT pg_get_serial_sequence('${ tableName } ', '${ field } ')` ;
51+ const sequenceName = (
52+ await models . sequelize . query ( selectSequenceQuery , {
53+ transaction,
54+ } )
55+ ) [ 0 ] [ 0 ] . pg_get_serial_sequence ;
56+
57+ // update sequence value to be set to max value of the autoincrement column in the table
58+ const query = `SELECT setval('${ sequenceName } ', (SELECT MAX(${ field } ) FROM ${ tableName } ))` ;
59+ const setValue = (
60+ await models . sequelize . query ( query , {
61+ transaction,
62+ } )
63+ ) [ 0 ] [ 0 ] . setval ;
64+ logger . info (
65+ `Updated autoIncrement for ${ modelName } .${ field } with max value = ${ setValue } ` ,
66+ ) ;
67+ }
68+ }
3269 } else {
3370 logger . info ( `No records to save for model: ${ modelName } ` ) ;
3471 }
0 commit comments