Skip to content

Instantly share code, notes, and snippets.

@yanmendes
Created September 29, 2017 18:19
Show Gist options
  • Save yanmendes/828f9b764954e04ca4885ab5ebc11952 to your computer and use it in GitHub Desktop.
Save yanmendes/828f9b764954e04ca4885ab5ebc11952 to your computer and use it in GitHub Desktop.
models.Traffic.destroy({
where: {}
}).then(function () {
return models.TrafficFull.destroy({where: {}});
}).then(function () {
return new Promise(function(resolve, reject) {
var since = new Date(req.body.since);
var to = new Date(req.body.to);
var pad = '00';
var subqueries = [];
for (var d = since; d <= to; d.setDate(d.getDate() + 1)){
subqueries.push(sprintf('(SELECT procplaca AS plate, array_length(procleituras, 1) AS doubt, ' +
'CASE WHEN procfaixacod = 1 THEN 1' + //HU entrada
' WHEN procfaixacod = 2 THEN -1' + //HU saída
' WHEN procfaixacod = 3 THEN 2' + //Engenharia entrada
' WHEN procfaixacod = 4 THEN -2' + //Engenharia saída
' WHEN procfaixacod IN (5,6) THEN 3' + //Portão sul entrada
' WHEN procfaixacod IN (7,8) THEN -3' + //Portão sul saída
' WHEN procfaixacod = 9 THEN 4' + //Portão norte entrada
' WHEN procfaixacod IN (10,11) THEN -4' + //Portão norte saída
" END AS gate, procdhcaptura - interval '3 hours' AS time, " +
"proctipoveiculo AS cartype FROM %s WHERE procleituras IS NOT NULL)",
'tb_proc_' + d.getFullYear() + '_' + (pad + (d.getMonth() + 1)).slice(-pad.length) + '_' + (pad + d.getDate()).slice(-pad.length)));
}
const client = new pg.Client(pgsqlConf);
client.connect();
client.query(sprintf('select * from (%s) AS tb1', subqueries.join(' UNION ALL ')), function(err, data){
if(err)
return reject(err);
return resolve(data);
});
});
}).then(function (data) {
console.log('cau')
return models.Traffic.bulkCreate(_.map(data.rows, processData));
}).then(function () {
console.log('caeu')
return models.sequelize.query('INSERT INTO "TrafficFulls" SELECT * FROM "Traffic";',
{
type: models.sequelize.QueryTypes.INSERT,
raw: true
});
}).then(function () {
return models.sequelize.query(
'DELETE FROM "Traffic" WHERE id IN ' +
'(SELECT ' +
' t2.id ' +
' FROM ' +
' "Traffic" t1, '+
' "Traffic" t2 ' +
' WHERE ' +
' t1.plate = t2.plate ' +
' AND t1.gate = t2.gate ' +
' AND t1.id != t2.id ' +
' AND CAST(EXTRACT(EPOCH FROM t2.time - t1.time) AS integer) BETWEEN 0 AND 60 ' +
' AND t2.time > t1.time);',
{
type: models.sequelize.QueryTypes.DELETE,
raw: true
});
}).then(function () {
res.send({
success: true,
message: 'Dados inseridos com sucesso'
});
}).catch(function (err) {
return next (err, req, res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment