all files / models/data-source/ data-source.js

65.86% Statements 218/331
57.21% Branches 123/215
66.67% Functions 34/51
65.94% Lines 213/323
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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527                                  17× 17× 30× 30×   30× 30×     17× 17× 22× 22×   22× 22×     20× 20× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19× 19×   45×                               17× 17× 17× 17×   17× 17×         17×         17×         17×         17× 17×     17× 17× 17×     17× 17×   17× 17× 17× 30× 22× 17×           17×                                           17×     17×                                                 13×             26× 14×               13× 13× 13×   13× 13×   13×   13×       40×       40×                                           19× 19× 18×                                                                                             16× 16× 16×                                                       24×                 59× 64×                                                                                                                                                          
"use strict";
var Q = require('q');
var immutable_1 = require('immutable');
var immutable_class_1 = require('immutable-class');
var chronoshift_1 = require('chronoshift');
var plywood_1 = require('plywood');
var general_1 = require('../../utils/general/general');
var dimension_1 = require('../dimension/dimension');
var measure_1 = require('../measure/measure');
var filter_1 = require('../filter/filter');
var max_time_1 = require('../max-time/max-time');
var refresh_rule_1 = require('../refresh-rule/refresh-rule');
function formatTimeDiff(diff) {
    diff = Math.round(Math.abs(diff) / 1000); // turn to seconds
    if (diff < 60)
        return 'less than 1 minute';
    diff = Math.floor(diff / 60); // turn to minutes
    if (diff === 1)
        return '1 minute';
    if (diff < 60)
        return diff + ' minutes';
    diff = Math.floor(diff / 60); // turn to hours
    if (diff === 1)
        return '1 hour';
    if (diff <= 24)
        return diff + ' hours';
    diff = Math.floor(diff / 24); // turn to days
    return diff + ' days';
}
function makeUniqueDimensionList(dimensions) {
    var seen = {};
    return immutable_1.List(dimensions.filter(function (dimension) {
        var dimensionName = dimension.name.toLowerCase();
        Iif (seen[dimensionName])
            return false;
        seen[dimensionName] = 1;
        return true;
    }));
}
function makeUniqueMeasureList(measures) {
    var seen = {};
    return immutable_1.List(measures.filter(function (measure) {
        var measureName = measure.name.toLowerCase();
        Iif (seen[measureName])
            return false;
        seen[measureName] = 1;
        return true;
    }));
}
var check;
var DataSource = (function () {
    function DataSource(parameters) {
        var name = parameters.name;
        general_1.verifyUrlSafeName(name);
        this.name = name;
        this.title = parameters.title || general_1.makeTitle(name);
        this.engine = parameters.engine;
        this.source = parameters.source;
        this.subsetFilter = parameters.subsetFilter;
        this.options = parameters.options || {};
        this.introspection = parameters.introspection || DataSource.DEFAULT_INTROSPECTION;
        this.attributes = parameters.attributes || [];
        this.attributeOverrides = parameters.attributeOverrides || [];
        this.dimensions = parameters.dimensions || immutable_1.List([]);
        this.measures = parameters.measures || immutable_1.List([]);
        this.timeAttribute = parameters.timeAttribute;
        this.defaultTimezone = parameters.defaultTimezone;
        this.defaultFilter = parameters.defaultFilter;
        this.defaultDuration = parameters.defaultDuration;
        this.defaultSortMeasure = parameters.defaultSortMeasure;
        this.defaultPinnedDimensions = parameters.defaultPinnedDimensions;
        this.refreshRule = parameters.refreshRule;
        this.maxTime = parameters.maxTime;
        this.executor = parameters.executor;
        this._validateDefaults();
    }
    DataSource.isDataSource = function (candidate) {
        return immutable_class_1.isInstanceOf(candidate, DataSource);
    };
    DataSource.updateMaxTime = function (dataSource) {
        if (!dataSource.shouldUpdateMaxTime())
            return Q(dataSource);
        if (dataSource.refreshRule.isRealtime()) {
            return Q(dataSource.changeMaxTime(max_time_1.MaxTime.fromNow()));
        }
        var ex = plywood_1.ply().apply('maxTime', plywood_1.$('main').max(dataSource.timeAttribute));
        return dataSource.executor(ex).then(function (dataset) {
            var maxTimeDate = dataset.data[0]['maxTime'];
            if (!isNaN(maxTimeDate)) {
                return dataSource.changeMaxTime(max_time_1.MaxTime.fromDate(maxTimeDate));
            }
            return dataSource;
        });
    };
    DataSource.fromJS = function (parameters, executor) {
        Eif (executor === void 0) { executor = null; }
        var engine = parameters.engine;
        var introspection = parameters.introspection;
        var attributeOverrideJSs = parameters.attributeOverrides;
        // Back compat.
        var options = parameters.options || {};
        Iif (options.skipIntrospection) {
            if (!introspection)
                introspection = 'none';
            delete options.skipIntrospection;
        }
        Iif (options.disableAutofill) {
            if (!introspection)
                introspection = 'no-autofill';
            delete options.disableAutofill;
        }
        Iif (options.attributeOverrides) {
            if (!attributeOverrideJSs)
                attributeOverrideJSs = options.attributeOverrides;
            delete options.attributeOverrides;
        }
        Iif (options.defaultSplitDimension) {
            options.defaultSplits = options.defaultSplitDimension;
            delete options.defaultSplitDimension;
        }
        // End Back compat.
        introspection = introspection || DataSource.DEFAULT_INTROSPECTION;
        Iif (DataSource.INTROSPECTION_VALUES.indexOf(introspection) === -1) {
            throw new Error("invalid introspection value " + introspection + ", must be one of " + DataSource.INTROSPECTION_VALUES.join(', '));
        }
        var refreshRule = parameters.refreshRule ? refresh_rule_1.RefreshRule.fromJS(parameters.refreshRule) : refresh_rule_1.RefreshRule.query();
        var maxTime = parameters.maxTime ? max_time_1.MaxTime.fromJS(parameters.maxTime) : null;
        Iif (!maxTime && refreshRule.isRealtime()) {
            maxTime = max_time_1.MaxTime.fromNow();
        }
        var timeAttributeName = parameters.timeAttribute;
        if (engine === 'druid' && !timeAttributeName) {
            timeAttributeName = '__time';
        }
        var timeAttribute = timeAttributeName ? plywood_1.$(timeAttributeName) : null;
        var attributeOverrides = plywood_1.AttributeInfo.fromJSs(attributeOverrideJSs || []);
        var attributes = plywood_1.AttributeInfo.fromJSs(parameters.attributes || []);
        var dimensions = makeUniqueDimensionList((parameters.dimensions || []).map(function (d) { return dimension_1.Dimension.fromJS(d); }));
        var measures = makeUniqueMeasureList((parameters.measures || []).map(function (m) { return measure_1.Measure.fromJS(m); }));
        if (timeAttribute && !dimension_1.Dimension.getDimensionByExpression(dimensions, timeAttribute)) {
            dimensions = dimensions.unshift(new dimension_1.Dimension({
                name: timeAttributeName,
                expression: timeAttribute,
                kind: 'time'
            }));
        }
        var value = {
            executor: null,
            name: parameters.name,
            title: parameters.title,
            engine: engine,
            source: parameters.source,
            subsetFilter: parameters.subsetFilter ? plywood_1.Expression.fromJSLoose(parameters.subsetFilter) : null,
            options: options,
            introspection: introspection,
            attributeOverrides: attributeOverrides,
            attributes: attributes,
            dimensions: dimensions,
            measures: measures,
            timeAttribute: timeAttribute,
            defaultTimezone: parameters.defaultTimezone ? chronoshift_1.Timezone.fromJS(parameters.defaultTimezone) : DataSource.DEFAULT_TIMEZONE,
            defaultFilter: parameters.defaultFilter ? filter_1.Filter.fromJS(parameters.defaultFilter) : filter_1.Filter.EMPTY,
            defaultDuration: parameters.defaultDuration ? chronoshift_1.Duration.fromJS(parameters.defaultDuration) : DataSource.DEFAULT_DURATION,
            defaultSortMeasure: parameters.defaultSortMeasure || (measures.size ? measures.first().name : null),
            defaultPinnedDimensions: immutable_1.OrderedSet(parameters.defaultPinnedDimensions || []),
            refreshRule: refreshRule,
            maxTime: maxTime
        };
        Iif (executor) {
            value.executor = executor;
        }
        return new DataSource(value);
    };
    DataSource.prototype.valueOf = function () {
        var value = {
            name: this.name,
            title: this.title,
            engine: this.engine,
            source: this.source,
            subsetFilter: this.subsetFilter,
            options: this.options,
            introspection: this.introspection,
            attributeOverrides: this.attributeOverrides,
            attributes: this.attributes,
            dimensions: this.dimensions,
            measures: this.measures,
            timeAttribute: this.timeAttribute,
            defaultTimezone: this.defaultTimezone,
            defaultFilter: this.defaultFilter,
            defaultDuration: this.defaultDuration,
            defaultSortMeasure: this.defaultSortMeasure,
            defaultPinnedDimensions: this.defaultPinnedDimensions,
            refreshRule: this.refreshRule,
            maxTime: this.maxTime
        };
        Iif (this.executor) {
            value.executor = this.executor;
        }
        return value;
    };
    DataSource.prototype.toJS = function () {
        var js = {
            name: this.name,
            title: this.title,
            engine: this.engine,
            source: this.source,
            subsetFilter: this.subsetFilter ? this.subsetFilter.toJS() : null,
            introspection: this.introspection,
            dimensions: this.dimensions.toArray().map(function (dimension) { return dimension.toJS(); }),
            measures: this.measures.toArray().map(function (measure) { return measure.toJS(); }),
            defaultTimezone: this.defaultTimezone.toJS(),
            defaultFilter: this.defaultFilter.toJS(),
            defaultDuration: this.defaultDuration.toJS(),
            defaultSortMeasure: this.defaultSortMeasure,
            defaultPinnedDimensions: this.defaultPinnedDimensions.toArray(),
            refreshRule: this.refreshRule.toJS()
        };
        Eif (this.timeAttribute)
            js.timeAttribute = this.timeAttribute.name;
        Iif (this.attributeOverrides.length)
            js.attributeOverrides = plywood_1.AttributeInfo.toJSs(this.attributeOverrides);
        if (this.attributes.length)
            js.attributes = plywood_1.AttributeInfo.toJSs(this.attributes);
        Iif (Object.keys(this.options).length)
            js.options = this.options;
        Iif (this.maxTime)
            js.maxTime = this.maxTime.toJS();
        return js;
    };
    DataSource.prototype.toJSON = function () {
        return this.toJS();
    };
    DataSource.prototype.toString = function () {
        return "[DataSource: " + this.name + "]";
    };
    DataSource.prototype.equals = function (other) {
        return this.equalsWithoutMaxTime(other) &&
            Boolean(this.maxTime) === Boolean(other.maxTime) &&
            (!this.maxTime || this.maxTime.equals(other.maxTime));
    };
    DataSource.prototype.equalsWithoutMaxTime = function (other) {
        return DataSource.isDataSource(other) &&
            this.name === other.name &&
            this.title === other.title &&
            this.engine === other.engine &&
            this.source === other.source &&
            Boolean(this.subsetFilter) === Boolean(other.subsetFilter) &&
            (!this.subsetFilter || this.subsetFilter.equals(other.subsetFilter)) &&
            JSON.stringify(this.options) === JSON.stringify(other.options) &&
            this.introspection === other.introspection &&
            immutable_class_1.arraysEqual(this.attributeOverrides, other.attributeOverrides) &&
            immutable_class_1.arraysEqual(this.attributes, other.attributes) &&
            general_1.listsEqual(this.dimensions, other.dimensions) &&
            general_1.listsEqual(this.measures, other.measures) &&
            Boolean(this.timeAttribute) === Boolean(other.timeAttribute) &&
            (!this.timeAttribute || this.timeAttribute.equals(other.timeAttribute)) &&
            this.defaultTimezone.equals(other.defaultTimezone) &&
            this.defaultFilter.equals(other.defaultFilter) &&
            this.defaultDuration.equals(other.defaultDuration) &&
            this.defaultSortMeasure === other.defaultSortMeasure &&
            this.defaultPinnedDimensions.equals(other.defaultPinnedDimensions) &&
            this.refreshRule.equals(other.refreshRule);
    };
    DataSource.prototype._validateDefaults = function () {
        var _a = this, measures = _a.measures, defaultSortMeasure = _a.defaultSortMeasure;
        if (defaultSortMeasure) {
            if (!measures.find(function (measure) { return measure.name === defaultSortMeasure; })) {
                throw new Error("can not find defaultSortMeasure '" + defaultSortMeasure + "' in data source '" + this.name + "'");
            }
        }
    };
    DataSource.prototype.getMainTypeContext = function () {
        var attributes = this.attributes;
        Iif (!attributes)
            return null;
        var datasetType = {};
        for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) {
            var attribute = attributes_1[_i];
            datasetType[attribute.name] = attribute;
        }
        return {
            type: 'DATASET',
            datasetType: datasetType
        };
    };
    DataSource.prototype.getIssues = function () {
        var _a = this, dimensions = _a.dimensions, measures = _a.measures;
        var mainTypeContext = this.getMainTypeContext();
        var issues = [];
        dimensions.forEach(function (dimension) {
            try {
                dimension.expression.referenceCheckInTypeContext(mainTypeContext);
            }
            catch (e) {
                issues.push("failed to validate dimension '" + dimension.name + "': " + e.message);
            }
        });
        var measureTypeContext = {
            type: 'DATASET',
            datasetType: {
                main: mainTypeContext
            }
        };
        measures.forEach(function (measure) {
            try {
                measure.expression.referenceCheckInTypeContext(measureTypeContext);
            }
            catch (e) {
                var message = e.message;
                // If we get here it is possible that the user has misunderstood what the meaning of a measure is and have tried
                // to do something like $volume / $volume. We detect this here by checking for a reference to $main
                // If there is no main reference raise a more informative issue.
                if (measure.expression.getFreeReferences().indexOf('main') === -1) {
                    message = 'measure must contain a $main reference';
                }
                issues.push("failed to validate measure '" + measure.name + "': " + message);
            }
        });
        return issues;
    };
    DataSource.prototype.attachExecutor = function (executor) {
        var value = this.valueOf();
        value.executor = executor;
        return new DataSource(value);
    };
    DataSource.prototype.toClientDataSource = function () {
        var value = this.valueOf();
        // Do not reveal the subset filter to the client
        value.subsetFilter = null;
        // No need for any introspection on the client
        value.introspection = 'none';
        // No point sending over the maxTime
        if (this.refreshRule.isRealtime()) {
            value.maxTime = null;
        }
        // No need for the overrides
        value.attributeOverrides = null;
        return new DataSource(value);
    };
    DataSource.prototype.isQueryable = function () {
        return Boolean(this.executor);
    };
    DataSource.prototype.getMaxTimeDate = function () {
        var refreshRule = this.refreshRule;
        Eif (refreshRule.isFixed())
            return refreshRule.time;
        // refreshRule is query or realtime
        var maxTime = this.maxTime;
        if (!maxTime)
            return null;
        return chronoshift_1.second.ceil(maxTime.time, chronoshift_1.Timezone.UTC);
    };
    DataSource.prototype.updatedText = function () {
        var refreshRule = this.refreshRule;
        if (refreshRule.isRealtime()) {
            return 'Updated: ~1 second ago';
        }
        else if (refreshRule.isFixed()) {
            return "Fixed to: " + formatTimeDiff(Date.now() - refreshRule.time.valueOf());
        }
        else {
            var maxTime = this.maxTime;
            if (maxTime) {
                return "Updated: " + formatTimeDiff(Date.now() - maxTime.time.valueOf()) + " ago";
            }
            else {
                return null;
            }
        }
    };
    DataSource.prototype.shouldUpdateMaxTime = function () {
        if (!this.refreshRule.shouldUpdate(this.maxTime))
            return false;
        return Boolean(this.executor) || this.refreshRule.isRealtime();
    };
    DataSource.prototype.getDimension = function (dimensionName) {
        return dimension_1.Dimension.getDimension(this.dimensions, dimensionName);
    };
    DataSource.prototype.getDimensionByExpression = function (expression) {
        return dimension_1.Dimension.getDimensionByExpression(this.dimensions, expression);
    };
    DataSource.prototype.getDimensionByKind = function (kind) {
        return this.dimensions.filter(function (d) { return d.kind === kind; });
    };
    DataSource.prototype.getTimeDimension = function () {
        return this.getDimensionByExpression(this.timeAttribute);
    };
    DataSource.prototype.isTimeAttribute = function (ex) {
        return ex.equals(this.timeAttribute);
    };
    DataSource.prototype.getMeasure = function (measureName) {
        measureName = measureName.toLowerCase(); // Case insensitive
        return this.measures.find(function (measure) { return measure.name.toLowerCase() === measureName; });
    };
    DataSource.prototype.getMeasureByExpression = function (expression) {
        return this.measures.find(function (measure) { return measure.expression.equals(expression); });
    };
    DataSource.prototype.changeDimensions = function (dimensions) {
        var value = this.valueOf();
        value.dimensions = dimensions;
        return new DataSource(value);
    };
    DataSource.prototype.rolledUp = function () {
        return this.engine === 'druid';
    };
    DataSource.prototype.setAttributes = function (attributes) {
        var _this = this;
        var _a = this, introspection = _a.introspection, dimensions = _a.dimensions, measures = _a.measures;
        Iif (introspection === 'none')
            return this;
        var autofillDimensions = introspection === 'autofill-dimensions-only' || introspection === 'autofill-all';
        var autofillMeasures = introspection === 'autofill-measures-only' || introspection === 'autofill-all';
        var $main = plywood_1.$('main');
        for (var _i = 0, attributes_2 = attributes; _i < attributes_2.length; _i++) {
            var attribute = attributes_2[_i];
            var name = attribute.name, type = attribute.type;
            var expression;
            switch (type) {
                case 'TIME':
                    Iif (!autofillDimensions)
                        continue;
                    expression = plywood_1.$(name);
                    Eif (this.getDimensionByExpression(expression))
                        continue;
                    // Add to the start
                    dimensions = dimensions.unshift(new dimension_1.Dimension({
                        name: name,
                        kind: 'time'
                    }));
                    break;
                case 'STRING':
                    if (attribute.special === 'unique') {
                        Iif (!autofillMeasures)
                            continue;
                        var newMeasures = measure_1.Measure.measuresFromAttributeInfo(attribute);
                        newMeasures.forEach(function (newMeasure) {
                            Iif (_this.getMeasureByExpression(newMeasure.expression))
                                return;
                            measures = measures.push(newMeasure);
                        });
                    }
                    else {
                        Iif (!autofillDimensions)
                            continue;
                        expression = plywood_1.$(name);
                        Iif (this.getDimensionByExpression(expression))
                            continue;
                        dimensions = dimensions.push(new dimension_1.Dimension({
                            name: name
                        }));
                    }
                    break;
                case 'SET/STRING':
                    if (!autofillDimensions)
                        continue;
                    expression = plywood_1.$(name);
                    if (this.getDimensionByExpression(expression))
                        continue;
                    dimensions = dimensions.push(new dimension_1.Dimension({
                        name: name
                    }));
                    break;
                case 'BOOLEAN':
                    if (!autofillDimensions)
                        continue;
                    expression = plywood_1.$(name);
                    if (this.getDimensionByExpression(expression))
                        continue;
                    dimensions = dimensions.push(new dimension_1.Dimension({
                        name: name,
                        kind: 'boolean'
                    }));
                    break;
                case 'NUMBER':
                    Iif (!autofillMeasures)
                        continue;
                    var newMeasures = measure_1.Measure.measuresFromAttributeInfo(attribute);
                    newMeasures.forEach(function (newMeasure) {
                        Iif (_this.getMeasureByExpression(newMeasure.expression))
                            return;
                        measures = (name === 'count') ? measures.unshift(newMeasure) : measures.push(newMeasure);
                    });
                    break;
                default:
                    throw new Error('unsupported type ' + type);
            }
        }
        Iif (!this.rolledUp() && !measures.find(function (m) { return m.name === 'count'; })) {
            measures = measures.unshift(new measure_1.Measure({
                name: 'count',
                expression: $main.count()
            }));
        }
        var value = this.valueOf();
        value.introspection = 'no-autofill';
        value.attributes = attributes;
        value.dimensions = dimensions;
        value.measures = measures;
        Eif (!value.defaultSortMeasure) {
            value.defaultSortMeasure = measures.size ? measures.first().name : null;
        }
        // ToDo: remove this when Pivot can handle it
        Iif (!value.timeAttribute && dimensions.first().kind === 'time') {
            value.timeAttribute = dimensions.first().expression;
        }
        return new DataSource(value);
    };
    DataSource.prototype.changeMaxTime = function (maxTime) {
        var value = this.valueOf();
        value.maxTime = maxTime;
        return new DataSource(value);
    };
    DataSource.prototype.getDefaultSortAction = function () {
        return new plywood_1.SortAction({
            expression: plywood_1.$(this.defaultSortMeasure),
            direction: plywood_1.SortAction.DESCENDING
        });
    };
    DataSource.DEFAULT_INTROSPECTION = 'autofill-all';
    DataSource.INTROSPECTION_VALUES = ['none', 'no-autofill', 'autofill-dimensions-only', 'autofill-measures-only', 'autofill-all'];
    DataSource.DEFAULT_TIMEZONE = chronoshift_1.Timezone.UTC;
    DataSource.DEFAULT_DURATION = chronoshift_1.Duration.fromJS('P1D');
    return DataSource;
}());
exports.DataSource = DataSource;
check = DataSource;