@@ -24,29 +24,48 @@ async function writeDataToDatabase(filePath, logger) {
2424 const model = models [ modelName ] ;
2525 const modelRecords = jsonData [ modelName ] ;
2626 if ( modelRecords && modelRecords . length > 0 ) {
27- logger . info (
28- `Importing data for model: ${ modelName } ` ,
29- ) ;
27+ logger . info ( `Importing data for model: ${ modelName } ` ) ;
3028 await model . bulkCreate ( modelRecords , {
3129 transaction,
3230 } ) ;
3331 logger . info (
3432 `Records imported for model: ${ modelName } = ${ modelRecords . length } ` ,
3533 ) ;
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.
3638 const modelAttributes = Object . keys ( model . rawAttributes ) ;
3739 const tableName = model . getTableName ( ) ;
3840 /* eslint-disable no-await-in-loop */
39- for ( let attributeIndex = 0 ; attributeIndex < modelAttributes . length ; attributeIndex += 1 ) {
41+ for (
42+ let attributeIndex = 0 ;
43+ attributeIndex < modelAttributes . length ;
44+ attributeIndex += 1
45+ ) {
4046 const field = modelAttributes [ attributeIndex ] ;
4147 const fieldInfo = model . rawAttributes [ field ] ;
4248 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 } ` ) ;
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+ }
4868 }
49- }
5069 } else {
5170 logger . info ( `No records to save for model: ${ modelName } ` ) ;
5271 }
0 commit comments