sql.ts 17.9 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
import { View } from "../core/view";
30
import { Tsort } from "../util/tsort";
31

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

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

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

66 67 68 69 70
/** Dictonary indexed by view name, that returns the QueryAndName object. */
interface QNMap {
    [key: string]: QueryAndName;
}

71 72 73 74 75
/**
 * 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.
 */
76
interface DimAndNameMap {
77
    /** Dictionary indexed by dimension name that returns DimInfo */
78
    dimensions: {[key: string]: DimInfo};
79 80 81 82 83
    /**
     * Dictionary indexed by dimension name that returns
     * a view where this dimension is. Used as right side
     * of a join clause.
     */
84 85 86
    views: {[key: string]: View};
}

87 88 89 90 91 92
/**
 * 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.
 */
93
export abstract class SQLAdapter extends Adapter {
94 95 96 97
    /**
     * Translate a view to a SQL query.
     * @param view - View to be translated.
     */
98
    public getQueryFromView(view: View): string {
99 100 101 102 103
        const map = this.buildPartials(view);
        const topSort = Tsort.view(view);
        const partials = topSort.map((i) => {
            return (map[i]) ? map[i] : {query : "", name: i};
        }).filter((i) => {
104 105 106
            return i.query !== "";
        }).map((i) => {
            return i.name + " AS (" + i.query + ")";
107 108
        });

109 110 111
        let withClause = "";
        if (partials.length > 0) {
            withClause =  "WITH "  + partials.join(", ") + " ";
112 113
        }

114 115 116 117 118 119
        let sort = "";
        if (view.sort.length > 0) {
            // Sorting
            const order = view.sort.map((item) => {
                return "\"" + item.name + "\"";
            }).join(",");
120

121 122
            sort = " ORDER BY " + order;
        }
123

Rafael Dias's avatar
Rafael Dias committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        const dimensions = view.dimensions.map((item) => {
            return "\"" + item.name + "\"";
        }).join(",");

        const metrics = view.metrics.map((item) => {
            return "\"" + item.name + "\"";
        }).join(",");

        let attributes = "";
        if (dimensions.length > 0) {
            if (metrics.length > 0) {
                attributes = dimensions + "," + metrics;
            }

            else {
                attributes = dimensions;
            }
        }

        else {
            attributes = metrics;
        }

        return withClause + "SELECT " + attributes + " FROM " + view.name + sort + ";";
148
    }
149

150 151 152 153 154 155 156
    /**
     * 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.
     */
157
    private buildPartials(view: View): QNMap {
158 159
        let op = view.operation;
        let queue: View[] = op.values.map((i) => i);
160 161
        const output: QNMap = {};
        output[view.name] = {
162
            query: this.operation(op, view),
163 164
            name: view.name
        };
165 166 167 168 169 170 171 172 173

        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;
174 175 176 177 178 179
                    if (!output[partial.name]) {
                        output[partial.name] = {
                            query: query,
                            name: partial.name
                        };
                    }
180
                    queue = queue.concat(partial.operation.values);
181 182
                }
            }
183
        }
184

185 186
        return output;
    }
187

188 189 190 191 192
    /**
     * 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.
     */
193 194 195 196 197 198 199 200 201 202 203 204
    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 "";
        }
    }
205

206 207 208 209 210 211
    /**
     * 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.
     */
212 213 214 215 216 217 218 219 220 221 222 223
    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;
224
            }
225 226 227 228
            const sourceView = mapping.views[dim.name];
            return this.translateDimension(dimension, dim, sourceView);
        });
        const projElem = dimensions.map((i) => i.aliased).concat(metrics);
229

230 231 232 233
        // Grouping
        const grouped = dimensions.map((item) => {
            return (item.expanded) ? item.alias : item.noalias;
        });
234

235 236 237 238 239 240 241 242 243
        // 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 + ")");
            }
        }
244

245 246 247 248 249 250 251
        // 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;
252
                    const leftSide = this.buildColumn(dim, views.shift().name);
253
                    while (views.length > 0) {
254
                        const rightSide = this.buildColumn(dim, views.shift().name);
255
                        conds.push("(" + leftSide + "=" + rightSide + ")");
256 257 258 259 260
                    }
                }
            }
        }

261 262
        // Assembly
        const projection = "SELECT " + projElem.join(", ");
263
        const sources = "FROM " + partials.map((i) => (i.name)).join(", ");
264
        const selection = (conds.length > 0) ? " WHERE " + conds.join(" AND ") : "";
265

266 267 268
        let grouping = "";
        if (grouped.length > 0) {
            grouping = " GROUP BY " + grouped.join(",");
269 270
        }

271
        return projection + sources + selection + grouping;
272 273
    }

274 275 276 277 278
    /**
     * Constructs and returns the dictionaries which inform
     * in which views a given dimension is.
     * @param views - Set of views to be scored.
     */
279
    private buildMaps(views: View[]): DimAndNameMap {
280
        let dimMap: {[key: string]: DimInfo} = {};
281
        let nameMap: {[key: string]: View} = {};
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

        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]);
                }
            }
        }

308 309 310 311 312
        return {
            dimensions: dimMap,
            views: nameMap
        };
    }
313

314 315 316 317 318 319 320
    /**
     * 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.
     */
321 322 323 324
    private orphanClauses(view: View, partials: View[]): Clause[] {
        let parentClauses: Clause[] = [];
        for (let i = 0; i < partials.length; ++i) {
            parentClauses = parentClauses.concat(partials[i].clauses);
325 326
        }

327 328
        // return clauses that does not exist in the partials
        return view.clauses.filter((i) => !parentClauses.some((j) => j.id === i.id));
329 330
    }

331 332 333 334 335 336
    /**
     * 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 ?
     */
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    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  "";
        }

    }

355 356 357 358 359 360
    /**
     * 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.
     */
361 362 363 364 365 366 367 368 369 370 371 372 373 374
    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 "";
        }

    }

375 376 377 378 379 380
    /**
     * Generic translate a SQL function to a query
     * @param name - Function name.
     * @param args - Function argument names.
     * @param values - Function argument values.
     */
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    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(",") + ")";
    }

399 400 401
    /**
     * Add quotes and the proper view name to a attribute in a SQL query.
     * @param item - Attribute to get the name quoted.
402
     * @param viewName - View name used to build the view name.
403
     */
404
    private buildColumn (item: Metric|Dimension, viewName: string): string {
405
        const quotedName = "\"" + item.name + "\"";
406
        return viewName + "." + quotedName;
407 408
    }

409 410 411 412 413 414
    /**
     * Translate Clause object into a SQL query condition.
     * @param clause - Clause to be translated.
     * @param map - Dictionary indexed bu attributes name
     * containing its locations.
     */
415
    private translateClause(clause: Clause, map: {[key: string]: View}): string {
416 417 418 419 420 421 422 423
        const r = clause.filters.map((item) => {
            return this.translateFilter(item, map);
        }).filter((item) => {
            return item !== "";
        });
        return r.join(" OR ");
    }

424 425 426 427 428 429
    /**
     * Translate Filter object into a SQL query condition.
     * @param filter - Filter to be translated.
     * @param map - Dictionary indexed bu attributes name
     * containing its locations.
     */
430
    private translateFilter(filter: Filter, map: {[key: string]: View}): string {
431 432 433 434
        if (!map[filter.target.name]) {
            return "";
        }

435 436
        const viewName = map[filter.target.name].name;
        const leftSide = this.buildColumn(filter.target, viewName);
437 438 439 440 441
        const quotedValue = "'" + filter.value + "'";
        const castedValue = this.typeCast(quotedValue, filter.target.dataType);
        return this.applyOperator(leftSide, castedValue, filter.operator);
    }

442 443 444 445 446
    /**
     * 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
     */
447
    private translateMetric(metric: Metric, view: View): string {
448 449
        const func = this.getAggregateFunction(metric.aggregation, view.origin);
        const quotedName = "\"" + metric.name + "\"";
450
        const extMetric = func + "(" + this.buildColumn(metric, view.name) + ")";
451 452 453
        return extMetric + " AS " + quotedName;
    }

454 455 456 457 458 459 460
    /**
     * 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.
     */
461 462
    private translateDimension(dimension: Dimension,
                               ancestor: Dimension,
463
                               view: View): DimTranslation {
464
        const quotedName = "\"" + dimension.name + "\"";
465
        let extDimension = this.buildColumn(ancestor, view.name);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        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
        };
    }

481 482 483 484 485
    /**
     * 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
486 487 488 489 490 491 492 493 494 495 496 497 498
    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("' , '"));
499
        consult = consult.concat("')");
Rafael Dias's avatar
Rafael Dias committed
500 501 502

        return consult;
    }
503

504 505 506 507 508 509
    /**
     * 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.
     */
510
    protected abstract applyOperator(leftSide: string, rightSide: string, op: FilterOperator): string;
511 512 513 514 515
    /**
     * Cast BlenDB types to proper database types.
     * @param quotedValue - SQL query attribute wrapped by quotes.
     * @param dt - Attribute data type.
     */
516
    protected abstract typeCast(quotedValue: string, dt: DataType): string;
517
}