WIP Added model, migration and bulk upsert fnc.

This commit is contained in:
Naida Vatric
2020-01-21 16:28:47 +01:00
parent 42eddb3aa5
commit 8d3f001678
5 changed files with 65 additions and 22 deletions

View File

@@ -14,9 +14,16 @@ class PostgresSaver {
const savedRecords = await bulkUpsertRealEstates(results);
//Extruding data for price history table
const resultPrices = savedRecords.map(realEstate => {
//Null values canot be recognized by ignore duplicates in sequalize
//Value price = 0 indicates 'cijena na upit'
const priceTmp =
realEstate.dataValues.price === null ? 0 : realEstate.dataValues.price;
return {
realEstateId: realEstate.dataValues.id,
price: realEstate.dataValues.price
price: priceTmp,
createdAt: realEstate.dataValues.createdAt,
updatedAt: realEstate.dataValues.updatedAt
};
});
const savedPrices = await bulkUpsertPriceHistory(resultPrices);

View File

@@ -7,7 +7,8 @@ const bulkUpsertPriceHistory = async priceHistoryData => {
const order = [["realEstateId", "desc"]];
return await db.PriceHistory.bulkCreate(priceHistoryData, {
order
order,
ignoreDuplicates: true
});
} catch (e) {
console.log("Error bulk upserting priceHistory : ", e);

View File

@@ -0,0 +1,10 @@
"use strict";
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.addConstraint("PriceHistory", ["realEstateId", "price"], {
type: "unique",
name: "uniquePriceRealEstate"
}),
down: queryInterface =>
queryInterface.removeConstraint("PriceHistory", "uniquePriceRealEstate")
};

View File

@@ -1,29 +1,35 @@
"use strict";
module.exports = (sequalize, DataTypes) => {
const PriceHistory = sequalize.define("PriceHistory", {
id: {
type: DataTypes.BIGINT,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
realEstateId: {
type: DataTypes.BIGINT,
allowNull: false,
unique: "uniquePriceRealEstate",
references: {
model: "RealEstates",
key: "id"
const PriceHistory = sequalize.define(
"PriceHistory",
{
id: {
type: DataTypes.BIGINT,
autoIncrement: true,
primaryKey: true,
allowNull: false
},
onUpdate: "CASCADE",
onDelete: "SET NULL"
realEstateId: {
type: DataTypes.BIGINT,
allowNull: false,
unique: "uniquePriceRealEstate",
references: {
model: "RealEstates",
key: "id"
},
onUpdate: "CASCADE",
onDelete: "SET NULL"
},
price: {
type: DataTypes.REAL,
unique: "uniquePriceRealEstate"
}
},
price: {
type: DataTypes.REAL,
unique: "uniquePriceRealEstate"
{
freezeTableName: true
}
});
);
PriceHistory.associate = models => {
PriceHistory.hasMany(models.RealEstate, {

View File

@@ -0,0 +1,19 @@
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
// ??
const realEstateInitialData = await queryInterface.Sequelize.findall ();
const priceHistoryInitialData = realEstateInitialData.map ();
return queryInterface.bulkInsert(
"PriceHistory",
priceHistoryInitialData,
{}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete("PriceHistory", null, {});
}
};