sql.ts 17.2 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
/*
 * Copyright (C) 2016 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of blend.
 *
 * blend 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.
 *
 * blend 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 blend.  If not, see <http://www.gnu.org/licenses/>.
 */

import { Adapter } from "../core/adapter";
import { Metric } from "../core/metric";
Rafael Dias's avatar
Rafael Dias committed
23
import { Source } from "../core/source";
24 25 26
import { Dimension } from "../core/dimension";
import { Clause } from "../core/clause";
import { Filter, FilterOperator } from "../core/filter";
27
import { AggregationType, RelationType, DataType } from "../common/types";
28
import { Operation, Opcode } from "../common/expression";
29 30
import { View } from "../core/view";

31 32 33 34
/**
 * Information required to make a join clause.
 * The dimension and views that contain this dimension.
 */
35
interface DimInfo {
36
    /** Dimension object. */
37
    dim: Dimension;
38
    /** Set of views that contain the dimension. */
39
    views: View[];
40 41
}

42 43 44 45
/**
 * Several translations of a dimension that will be used in different
 * parts of a query
 */
46
interface DimTranslation {
47
    /** Translation with the AS clause. Used on SELECT clause. */
48
    aliased: string;
49
    /** Translation without the AS clause. USED on GROUP BY clause. */
50
    noalias: string;
51
    /** The alias of the dimension. The quoted name. */
52
    alias: string;
53
    /** Expansion of a sub dimension. */
54 55 56
    expanded: boolean;
}

57
/** Translated view, the query which gets all data and its name */
58
interface QueryAndName {
59
    /** Query that returns all the data of a view. */
60
    query: string;
61
    /** The view name. */
62 63 64
    name: string;
}

65 66 67 68 69
/**
 * Two Dictionaries, both indexed with a dimension name.
 * Used to get the views where a dimension is.
 * The dimensions also have the Dimension object inside.
 */
70
interface DimAndNameMap {
71
    /** Dictionary indexed by dimension name that returns DimInfo */
72
    dimensions: {[key: string]: DimInfo};
73 74 75 76 77
    /**
     * Dictionary indexed by dimension name that returns
     * a view where this dimension is. Used as right side
     * of a join clause.
     */
78 79 80
    views: {[key: string]: View};
}

81 82 83 84 85 86
/**
 * Generic SQL adapter.
 * Contains most implementation to perform a SQL query.
 * However, which database has its peculiarities, so this
 * adapter must be extended to each SGBD.
 */
87
export abstract class SQLAdapter extends Adapter {
88 89 90 91
    /**
     * Translate a view to a SQL query.
     * @param view - View to be translated.
     */
92
    public getQueryFromView(view: View): string {
93 94 95 96
        const partials = this.buildPartials(view).filter((i) => {
            return i.query !== "";
        }).map((i) => {
            return i.name + " AS (" + i.query + ")";
97 98
        });

99 100 101
        let withClause = "";
        if (partials.length > 0) {
            withClause =  "WITH "  + partials.join(", ") + " ";
102 103
        }

104 105 106 107 108 109
        let sort = "";
        if (view.sort.length > 0) {
            // Sorting
            const order = view.sort.map((item) => {
                return "\"" + item.name + "\"";
            }).join(",");
110

111 112
            sort = " ORDER BY " + order;
        }
113

114 115
        return withClause + "SELECT * FROM " + this.viewName(view) + sort + ";";
    }
116

117 118 119 120 121 122 123
    /**
     * Translates a view to a SQL sub-query. The main diffence between
     * this method and getQueryFromView is that a sub-query cannot have
     * sorting properties. Also a sub-query is called a partial and
     * partials can only have one metric.
     * @param view - View which the partial will be built.
     */
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    private buildPartials(view: View): QueryAndName[] {
        let op = view.operation;
        let queue: View[] = op.values.map((i) => i);
        const output: QueryAndName[] = [{
            query: this.operation(op, view),
            name: this.viewName(view)
        }];

        const map: {[key: string]: boolean } = {};

        while (queue.length > 0) {
            const partial = queue.shift();
            if (!map[partial.id]) {
                const query = this.operation(partial.operation, partial);
                if (query !== "") {
                    map[partial.id] = true;
                    output.unshift({
                        query: query,
                        name: this.viewName(partial)
                    });
                    queue = queue.concat(partial.operation.values);
145 146
                }
            }
147
        }
148

149 150
        return output;
    }
151

152 153 154 155
    /**
     * The translated name of a view into SQL databases.
     * @param view - View which the name will be built.
     */
156 157 158
    protected viewName(view: View): string {
        return "view_" + view.id;
    }
159

160 161 162 163 164
    /**
     * Constructs a query from a view based in a given operation
     * @param op - Operation used to construct the view.
     * @param view - View to be querified.
     */
165 166 167 168 169 170 171 172 173 174 175 176
    private operation(op: Operation, view: View): string {
        switch (op.opcode) {
            case Opcode.REDUCE:
                return this.buildOperation(view, op.values, false);
            case Opcode.JOIN:
                return this.buildOperation(view, op.values, true);
            default:
                // Is unnecessary make a push function. Push = materialized
                // No need for materialized partials
                return "";
        }
    }
177

178 179 180 181 182 183
    /**
     * Constructs a query to a expecific view, from a set of given partials.
     * @param view - View to be built.
     * @param partials - Partials (other views) required to built the view.
     * @param isJoin - Used to check if join clauses must be added.
     */
184 185 186 187 188 189 190 191 192 193 194 195
    private buildOperation(view: View, partials: View[], isJoin: boolean): string {
        // Mapping, which views the metrics and dimensions are
        const mapping = this.buildMaps(partials);
        // Projection
        const metrics = view.metrics.map((i) => {
            const sourceView = mapping.views[i.name];
            return this.translateMetric(i, sourceView);
        });
        const dimensions = view.dimensions.map((dimension) => {
            let dim = dimension;
            while (!mapping.views[dim.name]) {
                dim = dim.parent;
196
            }
197 198 199 200
            const sourceView = mapping.views[dim.name];
            return this.translateDimension(dimension, dim, sourceView);
        });
        const projElem = dimensions.map((i) => i.aliased).concat(metrics);
201

202 203 204 205
        // Grouping
        const grouped = dimensions.map((item) => {
            return (item.expanded) ? item.alias : item.noalias;
        });
206

207 208 209 210 211 212 213 214 215
        // Selection
        const conds = [];
        const clauses = this.orphanClauses(view, partials);
        for (let i = 0; i < clauses.length; ++i) {
            const trClause = this.translateClause(clauses[i], mapping.views);
            if (trClause) {
                conds.push("(" + trClause + ")");
            }
        }
216

217 218 219 220 221 222 223 224 225 226 227
        // Joinning
        if (isJoin) {
            const dimMap = mapping.dimensions;
            for (let i of Object.keys(dimMap)) {
                if (dimMap[i].views.length > 1) {
                    const views = dimMap[i].views;
                    const dim = dimMap[i].dim;
                    const leftSide = this.buildColumn(dim, views.shift().id);
                    while (views.length > 0) {
                        const rightSide = this.buildColumn(dim, views.shift().id);
                        conds.push("(" + leftSide + "=" + rightSide + ")");
228 229 230 231 232
                    }
                }
            }
        }

233 234 235 236
        // Assembly
        const projection = "SELECT " + projElem.join(", ");
        const sources = "FROM " + partials.map((i) => this.viewName(i)).join(", ");
        const selection = (conds.length > 0) ? " WHERE " + conds.join(" AND ") : "";
237

238 239 240
        let grouping = "";
        if (grouped.length > 0) {
            grouping = " GROUP BY " + grouped.join(",");
241 242
        }

243
        return projection + sources + selection + grouping;
244 245
    }

246 247 248 249 250
    /**
     * Constructs and returns the dictionaries which inform
     * in which views a given dimension is.
     * @param views - Set of views to be scored.
     */
251
    private buildMaps(views: View[]): DimAndNameMap {
252
        let dimMap: {[key: string]: DimInfo} = {};
253
        let nameMap: {[key: string]: View} = {};
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

        for (let i = 0; i < views.length; ++i) {
            const mets = views[i].metrics;
            const dims = views[i].dimensions;
            for (let j = 0; j < mets.length; ++j) {
                if (!nameMap[mets[j].name])  {
                    nameMap[mets[j].name] = views[i];
                }

            }

            for (let j = 0; j < dims.length; ++j) {
                if (!dimMap[dims[j].name])  {
                    dimMap[dims[j].name] = {
                        dim: dims[j],
                        views: [views[i]]
                    };
                    nameMap[dims[j].name] = views[i];
                }

                else {
                    dimMap[dims[j].name].views.push(views[i]);
                }
            }
        }

280 281 282 283 284
        return {
            dimensions: dimMap,
            views: nameMap
        };
    }
285

286 287 288 289 290 291 292
    /**
     * Returns a set o clauses of the given view that is not fulfilled
     * by any of the partials. In other words, clauses that has not been
     * added to the query yet.
     * @param view - View with all clauses.
     * @param partials - Views with some of the clauses.
     */
293 294 295 296
    private orphanClauses(view: View, partials: View[]): Clause[] {
        let parentClauses: Clause[] = [];
        for (let i = 0; i < partials.length; ++i) {
            parentClauses = parentClauses.concat(partials[i].clauses);
297 298
        }

299 300
        // return clauses that does not exist in the partials
        return view.clauses.filter((i) => !parentClauses.some((j) => j.id === i.id));
301 302
    }

303 304 305 306 307 308
    /**
     * Parse a BlenDB enumeration of agregation functions to a proper string
     * to be used in the SQL query.
     * @param aggrType - Aggregation function.
     * @param origin - Will be applied in a view with origin flag ?
     */
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    private getAggregateFunction(aggrType: AggregationType, origin: boolean): string {
        switch (aggrType) {
            case AggregationType.SUM:
                return "SUM";
            case AggregationType.AVG:
                return "AVG";
            case AggregationType.COUNT:
                return (origin) ? "COUNT" : "SUM";
            case AggregationType.MAX:
                return "MAX";
            case AggregationType.MIN:
                return "MIN";
            default:
                return  "";
        }

    }

327 328 329 330 331 332
    /**
     * Parse a BlenDB enumeration of relationships to a proper string
     * to be used in the SQL query.
     * @param relation - The realtion function that will be used.
     * @param arg - The attribute that is the function argument.
     */
333 334 335 336 337 338 339 340 341 342 343 344 345 346
    private translateRelation(relation: RelationType, arg: string): string {
        switch (relation) {
            case RelationType.DAY:
                return this.applyRelation("EXTRACT", ["DAY FROM "], [arg]);
            case RelationType.MONTH:
                return this.applyRelation("EXTRACT", ["MONTH FROM "], [arg]);
            case RelationType.YEAR:
                return this.applyRelation("EXTRACT", ["YEAR FROM "], [arg]);
            default:
                return "";
        }

    }

347 348 349 350 351 352
    /**
     * Generic translate a SQL function to a query
     * @param name - Function name.
     * @param args - Function argument names.
     * @param values - Function argument values.
     */
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    private applyRelation(name: string, args: string[], values: string[]): string {
        /*
            This adapter uses the concept of functions in Postgres to
            implement BLENDB sub-dimention relations, this functions
            applys the transformation to build the call of a Postgres
            funtion. Note that this function can be native from postgres,
            like EXTRACT, or even implemented on the database.
            This function is short and only used in the translateRelation
            method however is a bit complex and is possible to be used
            several times, because of that is puted appart to make easyer update
            and avoid problems
            Example
            applyRelation ("EXTRACT", "["DAY FROM"]", ["view_0.date"])
            output: EXTRACT(DAY FROM view_0.date)
        */
        return name + "(" + args.map((item, idx) => item + values[idx]).join(",") + ")";
    }

371 372 373 374 375
    /**
     * Add quotes and the proper view name to a attribute in a SQL query.
     * @param item - Attribute to get the name quoted.
     * @param id - View id used to build the view name.
     */
376 377 378 379 380
    private buildColumn (item: Metric|Dimension, id: string): string {
        const quotedName = "\"" + item.name + "\"";
        return "view_" + id + "." + quotedName;
    }

381 382 383 384 385 386
    /**
     * Translate Clause object into a SQL query condition.
     * @param clause - Clause to be translated.
     * @param map - Dictionary indexed bu attributes name
     * containing its locations.
     */
387
    private translateClause(clause: Clause, map: {[key: string]: View}): string {
388 389 390 391 392 393 394 395
        const r = clause.filters.map((item) => {
            return this.translateFilter(item, map);
        }).filter((item) => {
            return item !== "";
        });
        return r.join(" OR ");
    }

396 397 398 399 400 401
    /**
     * Translate Filter object into a SQL query condition.
     * @param filter - Filter to be translated.
     * @param map - Dictionary indexed bu attributes name
     * containing its locations.
     */
402
    private translateFilter(filter: Filter, map: {[key: string]: View}): string {
403 404 405 406 407 408 409 410 411 412 413
        if (!map[filter.target.name]) {
            return "";
        }

        const viewId = map[filter.target.name].id;
        const leftSide = this.buildColumn(filter.target, viewId);
        const quotedValue = "'" + filter.value + "'";
        const castedValue = this.typeCast(quotedValue, filter.target.dataType);
        return this.applyOperator(leftSide, castedValue, filter.operator);
    }

414 415 416 417 418
    /**
     * Translate Metric object into a SQL query attribute.
     * @param metric - Metric to be translated.
     * @param view - View which contains the metric. Used to create the name
     */
419
    private translateMetric(metric: Metric, view: View): string {
420 421 422 423 424 425
        const func = this.getAggregateFunction(metric.aggregation, view.origin);
        const quotedName = "\"" + metric.name + "\"";
        const extMetric = func + "(" + this.buildColumn(metric, view.id) + ")";
        return extMetric + " AS " + quotedName;
    }

426 427 428 429 430 431 432
    /**
     * Translate Dimension object into a SQL query attribute.
     * @param dimension - Dimension to be translated.
     * @param ancestor - Dimension ancestor found in the view
     * @param view - View which contains the dimenion/ancestor.
     *  Used to create the name.
     */
433 434
    private translateDimension(dimension: Dimension,
                               ancestor: Dimension,
435
                               view: View): DimTranslation {
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        const quotedName = "\"" + dimension.name + "\"";
        let extDimension = this.buildColumn(ancestor, view.id);
        let aux = dimension;
        let expanded = false;
        while (aux.name !== ancestor.name) {
            extDimension = this.translateRelation(aux.relation, extDimension);
            aux = aux.parent;
            expanded = true;
        }
        return {
            aliased: extDimension + " AS " + quotedName,
            noalias: extDimension,
            alias: quotedName,
            expanded: expanded
        };
    }

453 454 455 456 457
    /**
     * Generates a generic insertion query for one register.
     * @param source - Data insertion "location".
     * @param data - Data to be inserted.
     */
Rafael Dias's avatar
Rafael Dias committed
458 459 460 461 462 463 464 465 466 467 468 469 470
    public getQueryFromSource(source: Source, data: any[]): string {
        let consult: string;
        let colums: any[] = [];
        let values: string[] = [];
        let tam = Object.keys(data).length;
        colums = source.fields.map(o => o.name);
        for (let i = 0; i < tam; i++){
            values[i] = data[colums[i]];
        }
        consult = "INSERT INTO " + source.name + " (\"";
        consult = consult.concat(colums.join("\",\""));
        consult = consult.concat("\") VALUES ('");
        consult = consult.concat(values.join("' , '"));
471
        consult = consult.concat("')");
Rafael Dias's avatar
Rafael Dias committed
472 473 474

        return consult;
    }
475

476 477 478 479 480 481
    /**
     * Parse a filter operation. Varies in each database.
     * @param lSide - Operation left side operator.
     * @param rSide - Operation right side operator.
     * @param op - Operation to be performed.
     */
482
    protected abstract applyOperator(leftSide: string, rightSide: string, op: FilterOperator): string;
483 484 485 486 487
    /**
     * Cast BlenDB types to proper database types.
     * @param quotedValue - SQL query attribute wrapped by quotes.
     * @param dt - Attribute data type.
     */
488
    protected abstract typeCast(quotedValue: string, dt: DataType): string;
489
}