forked from OpenTreeMap/otm-tiler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filtersToTables.js
79 lines (65 loc) · 2.46 KB
/
filtersToTables.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"use strict";
var _ = require('underscore');
var config = require('./config');
var utils = require("./filterObjectUtils");
exports = module.exports = function (filterObject, displayFilters, isPolygonRequest, isUtfGridRequest) {
if (_.isUndefined(filterObject) || _.isNull(filterObject)) {
throw new Error('A null or undefined filter object cannot be converted to SQL');
}
var models = getModelsForFilterObject(filterObject);
if ((!isPolygonRequest && !isUtfGridRequest) ||
(displayFilters && utils.isTreeInDisplayFilters(displayFilters))) {
models = _.union(models, ['tree']);
}
if (models.length === 0) {
models = [config.sqlForMapFeatures.basePointModel];
}
if (isPolygonRequest) {
models = _.union(models, [config.sqlForMapFeatures.basePolygonModel]);
}
return getSqlAndModels(models);
};
function getSqlAndModels(models) {
var sql = [];
var modelsAdded = [];
_.each(models, function addModelToSql(model) {
if (! _.contains(modelsAdded, model)) {
var depends = config.sqlForMapFeatures.tables[model].depends;
depends = _.without(depends, modelsAdded);
if (depends.length > 0) {
_.each(depends, addModelToSql);
}
var template = config.sqlForMapFeatures.tables[model].sqlTemplate;
if (_.isUndefined(template)) {
sql.push(config.sqlForMapFeatures.tables[model].sql);
}
modelsAdded.push(model);
}
});
return {
sql: sql.join(" "),
models: modelsAdded
};
}
// `getModelsForFilterObject` looks at a nested filterObject with
// clauses and produces a flat list of models to use in FROM/JOIN
// clauses.
function getModelsForFilterObject(object) {
function fieldNameToModel(fieldName) {
var model;
if (fieldName.indexOf('udf:') === 0) {
model = utils.parseUdfCollectionFieldName(fieldName).modelName;
if (model === "tree") {
return ["tree", "udf"];
}
return ["udf"];
}
model = fieldName.split('.')[0];
if (!config.modelMapping[model]) {
throw new Error('The model name must be one of the following: ' +
Object.keys(config.modelMapping).join(', ') + '. Not ' + model);
}
return [model];
}
return _.uniq(_.flatten(_.map(utils.filterObjectKeys(object), fieldNameToModel)));
}