fixture.ts 4.98 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 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
/*
 * Copyright (C) 2017 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 { Client, PoolConfig } from "pg";
import { View, LoadView } from "../../src/core/view";
import { each, series } from "async";
import * as fs from "fs";

interface TransSet {
    init: string;
    data: string[];
}

export interface Schema {
    alias?: string;
    query?: string;
    data?: string;
    fields: any[];
}

export class Fixture {
    private database: string;
    private config: PoolConfig;

    constructor(config: PoolConfig) {
        this.config = config;
        this.database = config.database;
    }

    public load(schemas: LoadView[], create: boolean, cb: (err: Error) => void) {
        let client = new Client(this.config);

        /*
            Loading data has 2 steps:
            1 - Create a table or truncate a existing one.
                Create or truncate dependes from a parameter in the configure
                file, this parameter reaches this function as the create
                parameter.
            2 - Insert data.
        */
        let init: string[] = [];
        let data: string[] = [];
        for (let i = 0; i < schemas.length; ++i) {
            let table: TransSet = this.createTransSet(schemas[i].view, schemas[i].data, create);
            init.push(table.init);
            data = data.concat(table.data);
        }

        client.connect((error) => {
            if (error) {
                cb(error);
                return;
            }

            /*
                Tables must be creates before data could be inserted, so the
                queries that create and insert are splited in 2 arrays.
                To garantee that tables exists before start insert data, series
                is used. Inside series each query is executed, using each;
            */
78
            series([(callback: (err: Error) => void) => {
79 80 81
                each(init, (query, cback) => {
                    return client.query(query, [], (err: Error) => cback(err));
                }, (errQuery: Error) => callback(errQuery));
82
            }, (callback: (err: Error) => void) => {
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
                each(data, (query, cback) => {
                    return client.query(query, [], (err: Error) => cback(err));
                }, (errQuery: Error) => callback(errQuery));
            }], (errQuery: Error) => {
                if (errQuery) {
                    client.end();
                    cb(errQuery);
                }
                client.end((err) => {
                    cb(err);
                });
            });

        });
    }

    private typeConvertion(t: string) {
        switch (t) {
            case "integer":
                return "INTEGER";
            case "date":
                return "DATE";
            case "string":
                return "TEXT";
            case "boolean":
                return "BOOLEAN";
            default:
                return "";
        }
    }

    private createTransSet(view: View, filePath: string, create: boolean) {
        let props = [];

        for (let i = 0; i < view.metrics.length; ++i) {
            let met = view.metrics[i];
            props.push("\"" + met.name + "\" " + this.typeConvertion(met.dataType));
        }

        for (let i = 0; i < view.dimensions.length; ++i) {
            let dim = view.dimensions[i];
            props.push("\"" + dim.name + "\" " + this.typeConvertion(dim.dataType));
        }

        let name = "view_" + view.id;
        let transaction: TransSet = {init: "", data: []};
        if (create) {
            transaction.init = "CREATE TABLE " + name + "(" + props.join(", ") + ")";
        }
        else {
            transaction.init = "TRUNCATE TABLE " + name;
        }

        transaction.data = [];
        let rows = JSON.parse(fs.readFileSync(filePath, {encoding : "utf8"}));
        for (let i = 0; i < rows.length; ++i) {
            let values = [];
            let keys = [];
141
            for (let key of Object.keys(rows[i])) {
142 143 144 145 146 147 148 149 150 151
                keys.push("\"" + key + "\"");
                values.push("'" + rows[i][key] + "'");
            }
            transaction.data.push("INSERT INTO " + name +
                                    "(" + keys.join(", ") + ") " +
                                    "VALUES (" + values.join(", ") + ")");
        }
        return transaction;
    }
}