@@ -24,29 +24,48 @@ async function writeDataToDatabase(filePath, logger) {
24
24
const model = models [ modelName ] ;
25
25
const modelRecords = jsonData [ modelName ] ;
26
26
if ( modelRecords && modelRecords . length > 0 ) {
27
- logger . info (
28
- `Importing data for model: ${ modelName } ` ,
29
- ) ;
27
+ logger . info ( `Importing data for model: ${ modelName } ` ) ;
30
28
await model . bulkCreate ( modelRecords , {
31
29
transaction,
32
30
} ) ;
33
31
logger . info (
34
32
`Records imported for model: ${ modelName } = ${ modelRecords . length } ` ,
35
33
) ;
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.
36
38
const modelAttributes = Object . keys ( model . rawAttributes ) ;
37
39
const tableName = model . getTableName ( ) ;
38
40
/* 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
+ ) {
40
46
const field = modelAttributes [ attributeIndex ] ;
41
47
const fieldInfo = model . rawAttributes [ field ] ;
42
48
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
+ }
48
68
}
49
- }
50
69
} else {
51
70
logger . info ( `No records to save for model: ${ modelName } ` ) ;
52
71
}
0 commit comments