configParser.ts 9.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright (C) 2017 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of blendb.
 *
 * blendb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * blendb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with blendb.  If not, see <http://www.gnu.org/licenses/>.
 */

import { Metric, MetricOptions } from "../core/metric";
import { Dimension, DimensionOptions } from "../core/dimension";
import { View, ViewOptions, LoadView } from "../core/view";
24
import { AggregationType, RelationType } from "../common/types";
25 26
import { Filter } from "../core/filter";
import { Clause } from "../core/clause";
27 28 29 30 31 32 33
import { PoolConfig } from "pg";
import * as fs from "fs";
import * as yaml from "js-yaml";

export interface ViewParsingOptions {
    alias: string;
    data: string;
34
    file?: string;
35
    origin?: boolean;
36 37
    dimensions: string[];
    metrics: string[];
38
    clauses?: string[];
39
    keys?: string[];
40 41
}

42 43 44 45 46 47
interface MetricStrOptions {
    name: string;
    aggregation: string;
    dataType: string;
}

48
export interface DimensionStrOptions {
49 50 51 52 53 54
    name: string;
    dataType: string;
    parent?: string;
    relation?: string;
}

55 56
interface ConfigSchema {
    views: ViewParsingOptions[];
57 58
    metrics: MetricStrOptions[];
    dimensions: DimensionStrOptions[];
59 60 61 62 63 64 65 66
}

interface ConfigFile {
    connection: PoolConfig;
    struct: LoadStruct;
    schema: ConfigSchema;
}

67 68 69 70 71 72
interface BuildView {
    view: View;
    file: string;
    alias: string;
}

73 74 75 76 77 78 79 80 81 82 83 84
export interface LoadStruct{
    create: boolean;
    insert: boolean;
}

export interface ParsedConfig {
    connection: PoolConfig;
    views: View[];
    metrics: Metric[];
    dimensions: Dimension[];
    struct: LoadStruct;
    loadViews: LoadView[];
85
    buildViews: BuildView[];
86 87
}

88 89 90 91 92 93 94 95
interface DimensionMap {
    [key: string]: Dimension;
}

interface MetricMap {
    [key: string]: Metric;
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
export class ConfigParser {
    public static parse(configPath: string): ParsedConfig {
        let config: ConfigFile = yaml.safeLoad(fs.readFileSync(configPath, {
            encoding: "utf-8"
        }));

        let metricsOpts = config.schema.metrics;
        let viewsOpts = config.schema.views;
        let dimensionsOpts = config.schema.dimensions;
        let parsed: ParsedConfig = {
            connection: config.connection,
            views: [],
            metrics: [],
            dimensions: [],
            struct: config.struct,
111 112
            loadViews: [],
            buildViews: []
113 114
        };

115 116
        let metMap: MetricMap = {};
        let dimMap: DimensionMap = {};
117 118

        for (let i = 0; i < metricsOpts.length; ++i) {
119
            let met = new Metric(this.parseMetOpts(metricsOpts[i]));
120
            parsed.metrics.push(met);
121
            metMap[met.name] = met;
122 123 124
        }

        for (let i = 0; i < dimensionsOpts.length; ++i) {
125
            let dim = new Dimension(this.parseDimOpts(dimensionsOpts[i], parsed.dimensions));
126
            parsed.dimensions.push(dim);
127
            dimMap[dim.name] = dim;
128 129 130
        }

        for (let i = 0; i < viewsOpts.length; ++i) {
131 132 133
            if (!viewsOpts[i].metrics) {
                viewsOpts[i].metrics = [];
            }
134 135 136 137 138
            let viewOpts = ConfigParser.parseViewOpt(viewsOpts[i], metMap, dimMap);
            let view = new View(viewOpts);
            parsed.views.push(view);
            let loadView: LoadView = {view: view, data: viewsOpts[i].data};
            parsed.loadViews.push(loadView);
139 140 141 142 143 144
            const buildView: BuildView = {
                view: view,
                file: viewsOpts[i].file,
                alias: viewsOpts[i].alias
            };
            parsed.buildViews.push(buildView);
145 146 147 148 149 150
        }

        return parsed;
    }

    public static parseViewOpt(opts: ViewParsingOptions,
151 152
                               metMap: MetricMap,
                               dimMap: DimensionMap): ViewOptions {
153 154 155 156 157

        let viewOpt: ViewOptions = {
            metrics: [],
            dimensions: [],
            materialized: true,
158
            origin: opts.origin,
159
            childViews: [],
160 161
            clauses: [],
            keys: []
162 163
        };

164 165
        const keys = (opts.keys) ? opts.keys : [];

166
        for (let i = 0; i < opts.metrics.length; ++i) {
167 168
            if (metMap[opts.metrics[i]]) {
                viewOpt.metrics.push(metMap[opts.metrics[i]]);
169 170 171 172 173 174 175 176
            }

            else {
                throw new Error("[Parsing error] Non exist metric set to view " + opts.alias);
            }
        }

        for (let i = 0; i < opts.dimensions.length; ++i) {
177 178
            if (dimMap[opts.dimensions[i]]) {
                viewOpt.dimensions.push(dimMap[opts.dimensions[i]]);
179 180 181 182 183 184
            }

            else {
                throw new Error("[Parsing error] Non exist dimension set to view " + opts.alias);
            }
        }
185

186 187
        for (let i = 0; i < keys.length; ++i) {
            if (dimMap[keys[i]]) {
188
                viewOpt.keys.push(dimMap[opts.keys[i]]);
189 190 191 192 193 194 195
            }

            else {
                throw new Error("[Parsing error] Non exist key set to view " + opts.alias);
            }
        }

196 197 198 199 200 201 202 203 204 205 206 207 208
        if (opts.clauses) {
            for (let i = 0; i < opts.clauses.length; ++i) {
                const clause = this.parseClause(opts.clauses[i], metMap, dimMap);
                if (clause) {
                    viewOpt.clauses.push(clause);
                }
                else {
                    throw new Error("[Parsing error] Bad formed clause: on view \"" +
                                    opts.alias + "\" the clause \"" + opts.clauses[i] +
                                    "\" could not be created");
                }
            }
        }
209 210
        return viewOpt;
    }
211

212
    public static parseDimOpts (opts: DimensionStrOptions, dims: Dimension[]): DimensionOptions {
213
        if (opts.parent || opts.relation) {
214 215 216 217 218 219 220 221 222 223 224 225
            for (let i = 0; i < dims.length; ++i) {
                if (dims[i].name === opts.parent) {
                    return {
                        name: opts.name,
                        dataType: opts.dataType,
                        parent: dims[i],
                        relation: this.strToRelationType(opts.relation)
                    };
                }
            }

            throw new Error("[Parsing error] Parent for subdimension " + opts.name + "  not found");
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
        }
        return {
            name: opts.name,
            dataType: opts.dataType,
            parent: null,
            relation: RelationType.NONE
        };
    }

    private static parseMetOpts (opts: MetricStrOptions): MetricOptions {
        return {
            name: opts.name,
            aggregation: this.strToAggregationType(opts.aggregation),
            dataType : opts.dataType
        };
    }

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
    private static parseClause (opts: string, metMap: MetricMap, dimMap: DimensionMap): Clause {
        const strFilters = opts.split(",");
        const filters: Filter[] = strFilters.map((item) => {
            return this.parseFilter(item, metMap, dimMap);
        });

        for (let i = 0; i < filters.length; ++i) {
            if (!filters[i] || !filters[i].isValid) {
                return null;
            }
        }

        return new Clause ({filters: filters});
    }

    private static parseFilter (opts: string, metMap: MetricMap, dimMap: DimensionMap): Filter {
        const strFilter = Filter.segment(opts);
        if (!strFilter) {
            return null;
        }
        let target: Metric|Dimension = dimMap[strFilter.target];
        if (!target) {
            target = metMap[strFilter.target];
            if (!target) {
                return null;
            }
        }

        const operator = Filter.parseOperator(strFilter.operator);

        return new Filter({
            target: target,
            operator: operator,
            value: strFilter.value
        });
    }

280 281 282 283 284 285 286 287
    private static strToAggregationType (str: string): AggregationType {
        switch (str) {
            case "sum":
                return AggregationType.SUM;
            case "avg":
                return AggregationType.AVG;
            case "count":
                return AggregationType.COUNT;
288 289 290 291
            case "min":
                return AggregationType.MIN;
            case "max":
                return AggregationType.MAX;
292 293 294 295
            default:
                return AggregationType.NONE;
        }
    }
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

    private static strToRelationType (str: string): RelationType {
        switch (str) {
            case "day":
                return RelationType.DAY;
            case "month":
                return RelationType.MONTH;
            case "year":
                return RelationType.YEAR;
            case "dayofweek":
                return RelationType.DAYOFWEEK;
            default:
                return RelationType.NONE;
        }
    }
311
}