// massive-of-json-to-db
var oracledb = require('oracledb'); // To DB
var moment = require('moment');
const fs = require("fs"); // FS
var FILEIN = 'avgprice_bd-prepared.json';
var YEAR = 2019;
var QUARTERNUMBER = 1;
var locationId;
var fileContent = fs.readFileSync(FILEIN, "utf8"); // File with massive of objects
var maxId = 0; // !!
// Date-time locale initial
moment.locale('ru');
var dateOptions = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
// Check hyphen, replace to null
var replaceHyphen = (element) => ( element == '-'? null : element );
////////////////////////////////////////////
oracledb.getConnection(
{
user : "system",
password : "test",
connectString : "localhost/test"
},
function(err, connection) {
if (err) {
console.error(err.message);
return;
}
var arr = fileStringToMassiveOfObjects(fileContent);
// Passage through the array
arr.forEach(function(item, i, arr) {
var now = new Date();
if (i<100) {
var d = moment().format('L');
d += " " + moment().format('LTS');
console.log(`d = ${d}`);
connection.execute(
`INSERT INTO TEMP_AVG_PRICE (ID_CRE_RECORD, DATETIME, QUARTER, "YEAR", state, locality
) VALUES
(:id, TO_timestamp(:dt, 'DD.MM.YYYY HH24:MI:SS'), :qu, :y, :st, :loc
)`,
{ id: maxId+1, dt: d, qu: QUARTERNUMBER, y: YEAR,
st: replaceHyphen(arr[i]['Регион (субъект РФ)']),
loc: replaceHyphen(arr[i]['Населенный пункт (район)'])
},
// {autoCommit: true},
function(err, result) {
if (err) {
//console.error(err.message);
//console.error('Error?');
doRelease(connection);
return;
};
console.log("Rows inserted " + result.rowsAffected);
connection.commit();
//console.log(result.rows);
doRelease(connection);
});
maxId++;
};
});
connection.commit();
doRelease(connection);
});
function doRelease(connection) {
connection.close(
function(err) {
if (err)
console.error(err.message);
});
};
// From file-string to massive of objects
function fileStringToMassiveOfObjects(fileContent){
var arr = fileContent.split('},');
arr[0] = arr[0].substr(1); // Del first char [
arr[arr.length - 1] = arr[arr.length - 1].slice(0, -1); // Del end char ]
arr.forEach(function(item, i, arr) {
if (i != (arr.length - 1)){
item += '}'; // Add char } to the end of element
};
arr[i] = JSON.parse(item);
});
return arr;
};