|
| 1 | +import * as fs from 'fs'; |
| 2 | +import models from '../../../src/models'; |
| 3 | +import { dataModels, validateDataModels } from '../dataModels'; |
| 4 | +import { indexMetadata, indexProjectsRange } from '../../../src/utils/es'; |
| 5 | + |
| 6 | +/** |
| 7 | + * import data from json file to database |
| 8 | + * @param {string} filePath path of file where to save data |
| 9 | + * @param {object} logger logger instance |
| 10 | + * @return {Promise} Returns a promise |
| 11 | + */ |
| 12 | +async function writeDataToDatabase(filePath, logger) { |
| 13 | + let transaction = null; |
| 14 | + let currentModelName = null; |
| 15 | + try { |
| 16 | + // Start a transaction |
| 17 | + transaction = await models.sequelize.transaction(); |
| 18 | + const jsonData = JSON.parse(fs.readFileSync(filePath).toString()); |
| 19 | + // we disable no-await-in-loop because we need to run insert operations sequentially to avoid FK constraints errors |
| 20 | + /* eslint-disable no-await-in-loop */ |
| 21 | + for (let index = 0; index < dataModels.length; index += 1) { |
| 22 | + const modelName = dataModels[index]; |
| 23 | + currentModelName = modelName; |
| 24 | + const model = models[modelName]; |
| 25 | + const modelRecords = jsonData[modelName]; |
| 26 | + if (modelRecords && modelRecords.length > 0) { |
| 27 | + logger.info(`Importing data for model: ${modelName}`); |
| 28 | + await model.bulkCreate(modelRecords, { |
| 29 | + transaction, |
| 30 | + }); |
| 31 | + logger.info( |
| 32 | + `Records imported for model: ${modelName} = ${modelRecords.length}`, |
| 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. |
| 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.debug( |
| 65 | + `Updated autoIncrement for ${modelName}.${field} with max value = ${setValue}`, |
| 66 | + ); |
| 67 | + } |
| 68 | + } |
| 69 | + } else { |
| 70 | + logger.info(`No records to import for model: ${modelName}`); |
| 71 | + } |
| 72 | + } |
| 73 | + // commit transaction only if all things went ok |
| 74 | + logger.info('committing transaction to database...'); |
| 75 | + await transaction.commit(); |
| 76 | + } catch (error) { |
| 77 | + logger.error('Error while writing data of model:', currentModelName); |
| 78 | + // rollback all insert operations |
| 79 | + if (transaction) { |
| 80 | + logger.info('rollback database transaction...'); |
| 81 | + transaction.rollback(); |
| 82 | + } |
| 83 | + if (error.name && error.errors && error.fields) { |
| 84 | + // For sequelize validation errors, we throw only fields with data that helps in debugging error, |
| 85 | + // because the error object has many fields that contains very big sql query for the insert bulk operation |
| 86 | + throw new Error( |
| 87 | + JSON.stringify({ |
| 88 | + modelName: currentModelName, |
| 89 | + name: error.name, |
| 90 | + errors: error.errors, |
| 91 | + fields: error.fields, |
| 92 | + }), |
| 93 | + ); |
| 94 | + } else { |
| 95 | + throw error; |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +/** |
| 101 | + * index imported data to Elasticsearch |
| 102 | + * @param {object} logger logger instance |
| 103 | + * @return {Promise} Returns a promise |
| 104 | + */ |
| 105 | +async function indexDataToES(logger) { |
| 106 | + logger.info('Indexing metatdata...'); |
| 107 | + await indexMetadata(); |
| 108 | + |
| 109 | + logger.info('Indexing projects data...'); |
| 110 | + const req = { |
| 111 | + logger, |
| 112 | + projectIdStart: 1, |
| 113 | + projectIdEnd: Number.MAX_SAFE_INTEGER, |
| 114 | + indexName: null, |
| 115 | + docType: null, |
| 116 | + fields: null, |
| 117 | + id: 0, |
| 118 | + }; |
| 119 | + await indexProjectsRange(req); |
| 120 | +} |
| 121 | + |
| 122 | +/** |
| 123 | + * import data from json file to database and index it to Elasticsearch |
| 124 | + * @param {string} filePath path of file where to save data |
| 125 | + * @param {object} logger logger instance |
| 126 | + * @return {Promise} Returns a promise |
| 127 | + */ |
| 128 | +async function importData(filePath, logger) { |
| 129 | + validateDataModels(logger); |
| 130 | + await writeDataToDatabase(filePath, logger); |
| 131 | + await indexDataToES(logger); |
| 132 | +} |
| 133 | +module.exports = { |
| 134 | + importData, |
| 135 | +}; |
0 commit comments