Windshaft-cartodb/lib/models/mapconfig/adapter/analysis-mapconfig-adapter.js

362 lines
12 KiB
JavaScript
Raw Normal View History

'use strict';
var queue = require('queue-async');
var debug = require('debug')('windshaft:analysis');
var camshaft = require('camshaft');
2019-11-25 20:36:56 +08:00
const queryUtils = require('../../../../lib/utils/query-utils');
var dot = require('dot');
dot.templateSettings.strip = false;
2019-10-22 01:07:24 +08:00
function AnalysisMapConfigAdapter (analysisBackend) {
this.analysisBackend = analysisBackend;
}
2016-03-14 18:50:52 +08:00
module.exports = AnalysisMapConfigAdapter;
2019-10-22 01:07:24 +08:00
AnalysisMapConfigAdapter.prototype.getMapConfig = function (user, requestMapConfig, params, context, callback) {
var self = this;
if (!shouldAdaptLayers(requestMapConfig)) {
return callback(null, requestMapConfig);
}
2016-05-23 22:44:14 +08:00
var analysisConfiguration = context.analysisConfiguration;
var filters = {};
if (params.filters) {
try {
filters = JSON.parse(params.filters);
} catch (e) {
// ignore
}
}
var dataviewsFilters = filters.dataviews || {};
debug(dataviewsFilters);
var dataviews = requestMapConfig.dataviews || {};
var errors = getDataviewsErrors(dataviews);
if (errors.length > 0) {
return callback(errors);
}
2019-10-22 01:07:24 +08:00
var dataviewsFiltersBySourceId = Object.keys(dataviewsFilters).reduce(function (bySourceId, dataviewName) {
var dataview = dataviews[dataviewName];
if (dataview) {
var sourceId = dataview.source.id;
if (!Object.prototype.hasOwnProperty.call(bySourceId, sourceId)) {
bySourceId[sourceId] = {};
}
2016-03-22 19:22:04 +08:00
bySourceId[sourceId][dataviewName] = getFilter(dataview, dataviewsFilters[dataviewName]);
}
return bySourceId;
}, {});
debug(dataviewsFiltersBySourceId);
debug('mapconfig input', JSON.stringify(requestMapConfig, null, 4));
requestMapConfig = appendFiltersToNodes(requestMapConfig, dataviewsFiltersBySourceId);
// Expected format for analyses filters
// filters = {analyses: {
// a1: [{min, max}, {accept, reject}],
// b1: [{range, column, min, max}, {category, column, accept, reject}]
// }}
requestMapConfig = appendFiltersToNodes(requestMapConfig, filters.analyses);
2019-10-22 01:07:24 +08:00
function createAnalysis (analysisDefinition, done) {
self.analysisBackend.create(analysisConfiguration, analysisDefinition, function (err, analysis) {
if (err) {
var error = new Error(err.message);
error.type = 'analysis';
error.analysis = {
id: analysisDefinition.id,
node_id: err.node_id,
type: analysisDefinition.type
};
return done(error);
}
done(null, analysis);
});
}
2016-07-07 06:36:59 +08:00
var analysesQueue = queue(1);
2019-10-22 01:07:24 +08:00
requestMapConfig.analyses.forEach(function (analysis) {
analysesQueue.defer(createAnalysis, analysis);
});
2019-10-22 01:07:24 +08:00
analysesQueue.awaitAll(function (err, analysesResults) {
if (err) {
return callback(err);
}
2019-10-22 01:07:24 +08:00
var sourceId2Node = analysesResults.reduce(function (sourceId2Query, analysis) {
var rootNode = analysis.getRoot();
if (rootNode.params && rootNode.params.id) {
sourceId2Query[rootNode.params.id] = rootNode;
}
2019-10-22 01:07:24 +08:00
analysis.getNodes().forEach(function (node) {
if (node.params && node.params.id) {
sourceId2Query[node.params.id] = node;
}
});
return sourceId2Query;
}, {});
var analysesErrors = [];
2019-10-22 01:07:24 +08:00
requestMapConfig.layers = requestMapConfig.layers.map(function (layer, layerIndex) {
if (getLayerSourceId(layer)) {
var layerSourceId = getLayerSourceId(layer);
var layerNode = sourceId2Node[layerSourceId];
if (layerNode) {
try {
var analysisSql;
// it might throw error: Range filter from camshaft, for instance.
analysisSql = layerQuery(layerNode);
var sqlQueryWrap = layer.options.sql_wrap;
if (sqlQueryWrap) {
layer.options.sql_raw = analysisSql;
analysisSql = sqlQueryWrap.replace(/<%=\s*sql\s*%>/g, analysisSql);
}
layer.options.sql = analysisSql;
layer.options.columns = getDataviewsColumns(getLayerDataviews(layer, dataviews));
layer.options.affected_tables = getAllAffectedTablesFromSourceNodes(layerNode);
} catch (error) {
analysesErrors.push(error);
}
} else {
analysesErrors.push(
2019-10-22 01:07:24 +08:00
new Error('Missing analysis node.id="' + layerSourceId + '" for layer=' + layerIndex)
);
}
}
return layer;
});
var missingDataviewsNodesErrors = getMissingDataviewsSourceIds(dataviews, sourceId2Node);
if (analysesErrors.length > 0 || missingDataviewsNodesErrors.length > 0) {
return callback(analysesErrors.concat(missingDataviewsNodesErrors));
}
// Augment dataviews with sql from analyses
2019-10-22 01:07:24 +08:00
Object.keys(dataviews).forEach(function (dataviewName) {
var dataview = requestMapConfig.dataviews[dataviewName];
var dataviewSourceId = dataview.source.id;
var dataviewNode = sourceId2Node[dataviewSourceId];
dataview.node = {
type: dataviewNode.type,
filters: dataviewNode.getFilters()
};
dataview.sql = {
own_filter_on: dataviewQuery(dataviewNode, dataviewName, true),
own_filter_off: dataviewQuery(dataviewNode, dataviewName, false),
no_filters: dataviewNode.getQuery(Object.keys(dataviewNode.getFilters())
2019-10-22 01:07:24 +08:00
.reduce(function (applyFilters, filterId) {
applyFilters[filterId] = false;
return applyFilters;
}, {})
)
};
});
if (Object.keys(dataviews).length > 0) {
requestMapConfig.dataviews = dataviews;
}
debug('mapconfig output', JSON.stringify(requestMapConfig, null, 4));
2016-05-24 00:59:23 +08:00
context.analysesResults = analysesResults;
return callback(null, requestMapConfig);
});
};
2016-05-25 23:24:28 +08:00
var SKIP_COLUMNS = {
2019-10-22 01:07:24 +08:00
the_geom: true,
the_geom_webmercator: true
2016-05-25 23:24:28 +08:00
};
2019-10-22 01:07:24 +08:00
function skipColumns (columnNames) {
2016-05-25 23:24:28 +08:00
return columnNames
2019-11-25 20:36:56 +08:00
.filter(function (columnName) { return !SKIP_COLUMNS[queryUtils.stripQuotes(columnName)]; });
2016-05-25 23:24:28 +08:00
}
var wrappedQueryTpl = dot.template([
2016-05-25 23:24:28 +08:00
'SELECT {{=it._columns}}',
'FROM ({{=it._query}}) _cdb_analysis_query'
].join('\n'));
2019-10-22 01:07:24 +08:00
function layerQuery (node) {
2016-05-25 23:24:28 +08:00
if (node.type === 'source') {
return node.getQuery();
}
var _columns = ['ST_Transform(the_geom, 3857) the_geom_webmercator'].concat(skipColumns(node.getColumns()));
return wrappedQueryTpl({ _query: node.getQuery(), _columns: _columns.join(', ') });
}
2019-10-22 01:07:24 +08:00
function dataviewQuery (node, dataviewName, ownFilter) {
var applyFilters = {};
if (!ownFilter) {
applyFilters[dataviewName] = false;
}
if (node.type === 'source') {
return node.getQuery(applyFilters);
}
var _columns = ['ST_Transform(the_geom, 3857) the_geom_webmercator'].concat(skipColumns(node.getColumns()));
return wrappedQueryTpl({ _query: node.getQuery(applyFilters), _columns: _columns.join(', ') });
2016-05-25 23:24:28 +08:00
}
2019-10-22 01:07:24 +08:00
function appendFiltersToNodes (requestMapConfig, dataviewsFiltersBySourceId) {
2016-05-25 23:24:28 +08:00
var analyses = requestMapConfig.analyses || [];
dataviewsFiltersBySourceId = dataviewsFiltersBySourceId || {};
2016-05-25 23:24:28 +08:00
2019-10-22 01:07:24 +08:00
requestMapConfig.analyses = analyses.map(function (analysisDefinition) {
2016-05-25 23:24:28 +08:00
var analysisGraph = new camshaft.reference.AnalysisGraph(analysisDefinition);
var definition = analysisDefinition;
2019-10-22 01:07:24 +08:00
Object.keys(dataviewsFiltersBySourceId).forEach(function (sourceId) {
definition = analysisGraph.getDefinitionWith(sourceId, { filters: dataviewsFiltersBySourceId[sourceId] });
2016-05-25 23:24:28 +08:00
});
return definition;
});
return requestMapConfig;
}
2019-10-22 01:07:24 +08:00
function shouldAdaptLayers (requestMapConfig) {
2019-11-06 20:56:59 +08:00
return (Array.isArray(requestMapConfig.layers) && requestMapConfig.layers.some(getLayerSourceId)) ||
(Array.isArray(requestMapConfig.analyses) && requestMapConfig.analyses.length > 0) ||
requestMapConfig.dataviews;
2016-05-25 23:24:28 +08:00
}
var DATAVIEW_TYPE_2_FILTER_TYPE = {
aggregation: 'category',
histogram: 'range'
};
2019-10-22 01:07:24 +08:00
function getFilter (dataview, params) {
2016-05-25 23:24:28 +08:00
var type = dataview.type;
return {
type: DATAVIEW_TYPE_2_FILTER_TYPE[type],
column: dataview.options.column,
params: params
};
}
2019-10-22 01:07:24 +08:00
function getLayerSourceId (layer) {
return layer.options.source && layer.options.source.id;
}
2019-10-22 01:07:24 +08:00
function getDataviewSourceId (dataview) {
return dataview.source && dataview.source.id;
}
2019-10-22 01:07:24 +08:00
function getLayerDataviews (layer, dataviews) {
var layerDataviews = [];
var layerSourceId = getLayerSourceId(layer);
if (layerSourceId) {
var dataviewsList = getDataviewsList(dataviews);
2019-10-22 01:07:24 +08:00
dataviewsList.forEach(function (dataview) {
if (getDataviewSourceId(dataview) === layerSourceId) {
layerDataviews.push(dataview);
}
});
}
return layerDataviews;
}
2019-10-22 01:07:24 +08:00
function getDataviewsColumns (dataviews) {
return Object.keys(dataviews.reduce(function (columnsDict, dataview) {
getDataviewColumns(dataview).forEach(function (columnName) {
if (columnName) {
columnsDict[columnName] = true;
}
});
return columnsDict;
}, {}));
}
2019-10-22 01:07:24 +08:00
function getDataviewColumns (dataview) {
var columns = [];
var options = dataview.options;
2019-10-22 01:07:24 +08:00
['column', 'aggregationColumn'].forEach(function (opt) {
if (Object.prototype.hasOwnProperty.call(options, opt) && !!options[opt]) {
columns.push(options[opt]);
}
});
return columns;
}
2019-10-22 01:07:24 +08:00
function getDataviewsList (dataviews) {
return Object.keys(dataviews).map(function (dataviewKey) { return dataviews[dataviewKey]; });
}
2019-10-22 01:07:24 +08:00
function getDataviewsErrors (dataviews) {
var dataviewType = typeof dataviews;
if (dataviewType !== 'object') {
return [new Error('"dataviews" must be a valid JSON object: "' + dataviewType + '" type found')];
}
if (Array.isArray(dataviews)) {
return [new Error('"dataviews" must be a valid JSON object: "array" type found')];
}
var errors = [];
2019-10-22 01:07:24 +08:00
Object.keys(dataviews).forEach(function (dataviewName) {
var dataview = dataviews[dataviewName];
if (!Object.prototype.hasOwnProperty.call(dataview, 'source') || !dataview.source.id) {
errors.push(new Error('Dataview "' + dataviewName + '" is missing `source.id` attribute'));
}
if (!dataview.type) {
errors.push(new Error('Dataview "' + dataviewName + '" is missing `type` attribute'));
}
});
return errors;
}
2019-10-22 01:07:24 +08:00
function getMissingDataviewsSourceIds (dataviews, sourceId2Node) {
var missingDataviewsSourceIds = [];
2019-10-22 01:07:24 +08:00
Object.keys(dataviews).forEach(function (dataviewName) {
var dataview = dataviews[dataviewName];
var dataviewSourceId = getDataviewSourceId(dataview);
if (!Object.prototype.hasOwnProperty.call(sourceId2Node, dataviewSourceId)) {
2019-10-22 01:07:24 +08:00
missingDataviewsSourceIds.push(new AnalysisError('Node with `source.id="' + dataviewSourceId + '"`' +
' not found in analyses for dataview "' + dataviewName + '"'));
}
});
return missingDataviewsSourceIds;
}
2019-10-22 01:07:24 +08:00
function AnalysisError (message) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.type = 'analysis';
this.message = message;
}
2019-10-22 01:07:24 +08:00
function getAllAffectedTablesFromSourceNodes (node) {
var affectedTables = node.getAllInputNodes(function (node) {
return node.getType() === 'source';
2019-10-22 01:07:24 +08:00
}).reduce(function (list, node) {
return list.concat(node.getAffectedTables());
2019-10-22 01:07:24 +08:00
}, []);
return affectedTables;
}
require('util').inherits(AnalysisError, Error);