From 48c999e1b6db41ec27cd1deb7f56edf8ada8dd9b Mon Sep 17 00:00:00 2001
From: Vytor Calixto <vytorcalixto@gmail.com>
Date: Thu, 23 Mar 2017 10:14:04 -0300
Subject: [PATCH] Fix SQL in /spatial

---
 src/libs/routes/spatial.js | 93 ++++++++++++++++++--------------------
 1 file changed, 43 insertions(+), 50 deletions(-)

diff --git a/src/libs/routes/spatial.js b/src/libs/routes/spatial.js
index f8a56213..58473b0e 100644
--- a/src/libs/routes/spatial.js
+++ b/src/libs/routes/spatial.js
@@ -12,34 +12,13 @@ const sqlQuery = require(`${libs}/db/query_exec`);
 
 const response = require(`${libs}/middlewares/response`);
 
-const spatialApp = express();
-
 const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);
 
-let rqf = new ReqQueryFields();
-
-function locationIdToStr(locationId) {
-    let locationStr = 'Total';
-    switch(locationId) {
-        case 1:
-            locationStr = 'Urbana';                         break;
-        case 2:
-            locationStr = 'Rural';                          break;
-        case 3:
-            locationStr = 'Área de assentamento';           break;
-        case 4:
-            locationStr = 'Terra indígena';                 break;
-        case 5:
-            locationStr = 'Área remanescente de quilombos'; break;
-        case 6:
-            locationStr = 'Unidade de uso sustentável';     break;
+const spatialApp = express();
 
-    }
-    return locationStr;
-}
+let rqf = new ReqQueryFields();
 
-function schoolYearIdToStr(schoolYearId)
-{
+function schoolYearIdToStr(schoolYearId) {
     let schoolYearStr;
     switch(schoolYearId) {
         case 11:
@@ -160,7 +139,7 @@ rqf.addField({
     name: 'state',
     table: 'estado',
     tableField: 'nome',
-    resultField: 'estado_name',
+    resultField: 'state_name',
     where: {
         relation: '=',
         type: 'integer',
@@ -184,6 +163,16 @@ rqf.addField({
         primary: 'id',
         foreign: 'municipio_id'
     }
+}).addValue({
+    name: 'school',
+    table: 'escola',
+    tableField: 'nome_escola',
+    resultField: 'school_name',
+    where: {
+        relation: '=',
+        type: 'integer',
+        field: 'id'
+    }
 });
 
 spatialApp.get('/sociodemographic', rqf.parse(), rqf.build(), (req, res, next) => {
@@ -268,31 +257,36 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => {
 
     const totalSchoolsQry = req.sql.clone()
         .field('\'Brasil\'', 'name')
-        .field('0', 'location')
+        .field('\'Total\'', 'location_name')
         .field('COUNT(DISTINCT(escola.id))', 'total')
         .field('escola.ano_censo', 'census_year')
         .from('escola')
-        .join('turma', null, 'turma.ano_censo=escola.ano_censo AND turma.escola_id = escola.id')
+        .from('turma')
+        .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id')
         .where(`escola.ano_censo IN (${censusYearQry})`)
         .where('turma.tipo_turma_id = 0')
         .group('escola.ano_censo');
 
     const schoolsPerLocationQry = req.sql.clone()
         .field('\'Brasil\'', 'name')
-        .field('escola.cod_localizacao', 'location')
         .field('COUNT(DISTINCT(escola.id))', 'total')
         .field('escola.ano_censo', 'census_year')
+        .field('localizacao.descricao', 'location_name')
         .from('escola')
-        .join('turma', null, 'turma.ano_censo=escola.ano_censo AND turma.escola_id=escola.id')
+        .from('localizacao')
+        .where('escola.cod_localizacao=localizacao.id')
+        .from('turma')
+        .where('escola.ano_censo=turma.ano_censo AND escola.id=turma.escola_id')
         .where(`escola.ano_censo IN (${censusYearQry})`)
         .where('turma.tipo_turma_id = 0')
         .group('escola.cod_localizacao')
         .group('escola.ano_censo')
-        .order('escola.cod_localizacao');
+        .group('localizacao.descricao')
+        .order('localizacao.descricao');
 
     const schoolClassYearQry = squel.select()
-        .field('MAX(matricula.ano_censo)')
-        .from('matricula')
+        .field('MAX(turma.ano_censo)')
+        .from('turma')
         .toString();
 
     const enrollmentsQry = req.sql.clone()
@@ -301,34 +295,37 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => {
         .field('matricula.ano_censo', 'census_year')
         .from('matricula')
         .where(`matricula.ano_censo IN (${schoolClassYearQry})`)
-        .where('matricula.tipo <= 3')
+        .where('matricula.tipo<=3')
         .group('matricula.ano_censo');
 
-    const enrollmentsPerAdmDepQry = squel.select()
+    const enrollmentsPerAdmDepQry = req.sql.clone()
         .field('\'Brasil\'', 'name')
         .field('COALESCE(COUNT(matricula.id), 0)', 'total')
         .field('matricula.ano_censo', 'census_year')
         .field('dependencia_adm.nome', 'adm_dependency_name')
         .from('matricula')
-        .join('dependencia_adm', null, 'matricula.dependencia_adm_id=dependencia_adm.id')
+        .from('dependencia_adm')
+        .where('matricula.dependencia_adm_id=dependencia_adm.id')
         .where('matricula.tipo <= 3')
         .where(`matricula.ano_censo IN (${schoolClassYearQry})`)
         .group('matricula.ano_censo')
         .group('dependencia_adm.nome')
         .order('dependencia_adm.nome');
 
-    const enrollmentsPerSchoolLevelQry = squel.select()
+    const enrollmentsPerSchoolLevelQry = req.sql.clone()
         .field('\'Brasil\'', 'name')
-        .field('COALESCE(SUM(matricula.id), 0)', 'total')
+        .field('COALESCE(COUNT(matricula.id), 0)', 'total')
         .field('matricula.ano_censo', 'census_year')
         .field('etapa_ensino.desc_etapa', 'school_level_name')
         .from('matricula')
-        .join('etapa_ensino', null, 'matricula.etapa_ensino_id=etapa_ensino.id')
+        .from('etapa_ensino')
+        .where('matricula.etapa_ensino_id=etapa_ensino.id')
         .where('matricula.tipo <= 3')
         .where(`matricula.ano_censo IN (${schoolClassYearQry})`)
         .group('matricula.ano_censo')
         .group('etapa_ensino.desc_etapa')
-        .order('etapa_ensino.desc_etapa');
+        .group('etapa_ensino.id')
+        .order('etapa_ensino.id');
 
     const queryLabels = [ "school", "school_per_location", "enrollment", "enrollment_per_adm_dep",
         "enrollment_per_school_level" ];
@@ -337,13 +334,6 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => {
     // wait until all queries finish or one of them fail
     Promise.all(dbExecAll(querySet)).then((queryResults) => {
         req.result = processResultSet(queryResults, queryLabels);
-        for(let label in req.result) {
-            for(let row of req.result[label]) {
-                if (row.hasOwnProperty('location')) {
-                    row.location = locationIdToStr(row.location);
-                }
-            }
-        }
         next();
     }).catch((error) => {
         log.error(`[SQL query error] ${error}`);
@@ -351,23 +341,26 @@ spatialApp.get('/educational', rqf.parse(), rqf.build(), (req, res, next) => {
     });
 }, response('spatial'));
 
-spatialApp.get('/educational/school_level', rqf.parse(), rqf.build(), (req, res, next) => {
+spatialApp.get('/educational/school_level', (req, res, next) => {
     const enrollmentsPerSchoolLevelYearQry = squel.select()
         .field('MAX(matricula.ano_censo)', 'census_year')
         .from('matricula');
 
-    const enrollmentsPerSchoolLevelQry = req.sql.clone()
+    const enrollmentsPerSchoolLevelQry = squel.select()
         .field('COALESCE(COUNT(matricula.id), 0)', 'total')
         .field('matricula.ano_censo', 'census_year')
         .field('matricula.serie_ano_id', 'school_year')
-        .field('etapa_ensino.desc_etapa', 'school_level_name')
+        .field('etapa_ensino.desc_etapa', 'school_level')
         .from('matricula')
-        .join('etapa_ensino', null, 'matricula.etapa_ensino_id=etapa_ensino.id')
+        .from('etapa_ensino')
         .where(`matricula.ano_censo IN (${enrollmentsPerSchoolLevelYearQry.toString()})`)
+        .where('matricula.etapa_ensino_id = etapa_ensino.id')
         .where('matricula.tipo <= 3')
         .group('etapa_ensino.desc_etapa')
+        .group('etapa_ensino.id')
         .group('matricula.serie_ano_id')
         .group('matricula.ano_censo')
+        .order('etapa_ensino.id')
         .order('matricula.serie_ano_id')
         .order('matricula.ano_censo');
 
-- 
GitLab