diff --git a/lib/cartodb/models/dataview/formula.js b/lib/cartodb/models/dataview/formula.js index 7ec356b7..6781fba3 100644 --- a/lib/cartodb/models/dataview/formula.js +++ b/lib/cartodb/models/dataview/formula.js @@ -1,26 +1,35 @@ var _ = require('underscore'); -var BaseWidget = require('./base'); +var BaseDataview = require('./base'); var debug = require('debug')('windshaft:widget:formula'); -var dot = require('dot'); -dot.templateSettings.strip = false; +const countInfinitiesQueryTpl = ctx => ` + SELECT count(1) FROM (${ctx._query}) __cdb_formula_infinities + WHERE ${ctx._column} = 'infinity'::float OR ${ctx._column} = '-infinity'::float +`; -var formulaQueryTpl = dot.template([ - 'SELECT', - ' {{=it._operation}}({{=it._column}}) AS result,', - ' (SELECT count(1) FROM ({{=it._query}}) _cdb_formula_nulls WHERE {{=it._column}} IS NULL) AS nulls_count', - ' {{?it._isFloatColumn}},(SELECT count(1) FROM ({{=it._query}}) _cdb_formula_nulls', - ' WHERE {{=it._column}} = \'infinity\'::float OR {{=it._column}} = \'-infinity\'::float) AS infinities_count', - ' ,(SELECT count(1) FROM ({{=it._query}}) _cdb_formula_nulls', - ' WHERE {{=it._column}} = \'NaN\'::float) AS nans_count{{?}}', - 'FROM ({{=it._query}}) _cdb_formula', - '{{?it._isFloatColumn && it._operation !== \'count\'}}WHERE', - ' {{=it._column}} != \'infinity\'::float', - 'AND', - ' {{=it._column}} != \'-infinity\'::float', - 'AND', - ' {{=it._column}} != \'NaN\'::float{{?}}' -].join('\n')); +const countNansQueryTpl = ctx => ` + SELECT count(1) FROM (${ctx._query}) __cdb_formula_nans + WHERE ${ctx._column} = 'NaN'::float +`; + +const filterOutSpecialNumericValuesTpl = ctx => ` + WHERE + ${ctx._column} != 'infinity'::float + AND + ${ctx._column} != '-infinity'::float + AND + ${ctx._column} != 'NaN'::float +`; + +const formulaQueryTpl = ctx => ` + SELECT + ${ctx._operation}(${ctx._column}) AS result, + (SELECT count(1) FROM (${ctx._query}) _cdb_formula_nulls WHERE ${ctx._column} IS NULL) AS nulls_count + ${ctx._isFloatColumn ? `,(${countInfinitiesQueryTpl(ctx)}) AS infinities_count` : ''} + ${ctx._isFloatColumn ? `,(${countNansQueryTpl(ctx)}) AS nans_count` : ''} + FROM (${ctx._query}) __cdb_formula + ${ctx._isFloatColumn && ctx._operation !== 'count' ? `${filterOutSpecialNumericValuesTpl(ctx)}` : ''} +`; var VALID_OPERATIONS = { count: true, @@ -54,7 +63,7 @@ function Formula(query, options, queries) { throw new Error('Formula expects `column` in widget options'); } - BaseWidget.apply(this); + BaseDataview.apply(this); this.query = query; this.queries = queries; @@ -63,7 +72,7 @@ function Formula(query, options, queries) { this._isFloatColumn = null; } -Formula.prototype = new BaseWidget(); +Formula.prototype = new BaseDataview(); Formula.prototype.constructor = Formula; module.exports = Formula;