Skip to content

Instantly share code, notes, and snippets.

@jmbrito01
Created August 9, 2016 18:49
Show Gist options
  • Save jmbrito01/eef692162698c6c12a6ccf781359c89d to your computer and use it in GitHub Desktop.
Save jmbrito01/eef692162698c6c12a6ccf781359c89d to your computer and use it in GitHub Desktop.
Postgres <> json migration
'use strict';
var pg = require('pg');
var async = require('async');
var grab = require('ps-grab');
var faculdades = require('./faculdades.json');
var cursos = require('./cursos.json');
console.log(grab('--user'));
console.log('Initializing connection');
var config = {
user: grab('--user'),
database: grab('--db'),
password: grab('--password'),
port: grab('--port') || 5432,
max: 10,
idleTimeoutMillis: 30000,
};
var client = new pg.Pool(config);
console.log('Connecting...');
client.connect(function(err) {
if (err) throw err;
async.parallel([
function(cb) {
if (!process.env.skipUniversities) {
console.log('Starting to write universities');
faculdades.forEach(function(each, idx) {
if (each['NO_IES'].indexOf('´') !== -1) {
each['NO_IES'].replace('´', '');
}
client.query(`INSERT INTO universities_mec(name, short_name, state, city) VALUES('${each['NO_IES']}', '${each['SGL_IES']}', '${each['SGL_UF_IES']}', '${each['NO_MUNICIPIO_IES']}')`, function(err, result) {
if (err) {
console.log(`ERROR ON `);
console.log(each);
throw err;
} else console.log(`${each['SGL_IES']} added to the database`);
if (idx + 1 === faculdades.length) {
client.query('INSERT INTO ')
console.log(`Finished writing universities`);
}
});
});
}
},
function(cb) {
console.log('Started writing courses');
cursos.forEach(function(each, idx) {
let name = each['NO_IES'];
if (name.indexOf("'") !== -1) {
name.replace("'", '');
}
client.query(`SELECT * FROM universities_mec WHERE name= '${name}'`, function(err, university) {
if (err) throw err;
if (university.rows.length === 0) return console.log(`${name} não é uma faculdade conhecida`);
let university_id = university.rows[0].id;
client.query(`INSERT INTO courses_mec(name, university_id) VALUES('${each['NO_CURSO']}', ${university_id})`, function(err, result) {
if (err) {
console.log('ERROR ON');
console.log(each);
throw err;
}
console.log(`${each['NO_CURSO']} da faculdade ${each['NO_IES']} criado.`);
if (idx + 1 === cursos.length) {
console.log('Finished writing.');
}
});
})
//client.query(`INSERT INTO cursos_mec(name, university)`)
});
}
])
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment