dbHandler.ts 17.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * form-creator-api. RESTful API to manage and answer forms.
 * Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
 *
 * This file is part of form-creator-api.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

22
import { eachOfSeries, eachSeries , map, waterfall } from "async";
23
import { Pool, PoolConfig, QueryResult } from "pg";
24 25 26
import { Form } from "../core/form";
import { Input, Validation } from "../core/input";
import { EnumHandler, InputType, ValidationType } from "./enumHandler";
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

/**
 * Class of the SGBD from the Form Creator Api perspective. Used to
 * perform all the operations into the database that the Form Creator Api
 * requires. This operations include read and write data.
 */

export class DbHandler {

    /** Information used to connect with a PostgreSQL database. */
    private pool: Pool;

    /**
     * Creates a new adapter with the database connection configuration.
     * @param config - The information required to create a connection with
     * the database.
     */
    constructor(config: PoolConfig) {
        this.pool = new Pool(config);
    }

    /**
     * Asynchronously executes a query and get its result.
     * @param query - Query (SQL format) to be executed.
     * @param cb - Callback function which contains the data read.
52
     * @param cb.err - Error information when the method fails.
53 54 55 56 57 58
     * @param cb.result - Query result.
     */

    public executeQuery(query: string, cb: (err: Error, result?: QueryResult) =>  void): void{

        this.pool.connect((err, client, done) => {
59

60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
            if (err) {
                cb(err);
                return;
            }

            client.query(query, [], (error, result) => {
            // call 'done()' to release client back to pool
                done();
                cb(error, (result) ? result : null);
            });
        });
    }

    /**
     * Asynchronously ends a transaction
     */
    public commit(cb: (err: Error, result?: QueryResult) =>  void){
        this.executeQuery("COMMIT;", cb);
    }
79 80 81 82 83 84
    /**
     * Asynchronously rollback a transaction
     */
    public rollback(cb: (err: Error, result?: QueryResult) =>  void){
        this.executeQuery("ROLLBACK;", cb);
    }
85 86 87 88 89 90 91 92

    /**
     * Asynchronously starts a transaction
     */
    public begin(cb: (err: Error, result?: QueryResult) =>  void){
        this.executeQuery("BEGIN;", cb);
    }

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
    /**
     * Asynchronously list all forms in database.
     * @param cb - Callback function which contains the data read.
     * @param cb.err - Error information when the method fails.
     * @param cb.form - list of form or a empty list if there is no form on database.
     */
     public listForms(cb: (err: Error, forms?: Form[]) =>  void){
         const query: string = "SELECT id, title, description FROM form;";
         const forms: Form[] = [];

         this.executeQuery(query, (err: Error, result?: QueryResult) => {
             if (err) {
                 cb(err);
                 return;
             }

             for (const row of result.rows){
                 const inputs: Input[] = [];
                 const formTmp = new Form (
                                 row["title"],
                                 row["description"],
                                 inputs,
                                 row["id"]
                                );

                 forms.push(formTmp);
             }
             cb(err, forms);
         });
     }

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
    /**
     * Asynchronously executes a query and get a Form.
     * @param id - Form identifier to be founded.
     * @param cb - Callback function which contains the data read.
     * @param cb.err - Error information when the method fails.
     * @param cb.form - Form or null if form not exists.
     */
    public readForm(id: number, cb: (err: Error, form?: Form) =>  void){
        const query: string = "SELECT id, title, description FROM form WHERE id=" + id + ";";

        waterfall([
             (callback: (err: Error, result?: QueryResult) =>  void) => {
                 this.begin(callback);
             },
             (result: QueryResult, callback: (err: Error, result?: QueryResult) =>  void) => {
                this.executeQuery(query, callback);
             },
             (result: QueryResult, callback: (err: Error, form?: Form) =>  void) => {

                 if (result.rowCount !== 1){
                     callback(new Error("Bad number of ids returned: found '" + result.rowCount + "' should be 1"));
                     return;
                 }
                 this.readInputWithFormId(id, (error: Error, inputs: Input[]) => {
                     const formTmp = new Form (
                                     result.rows[0]["title"],
                                     result.rows[0]["description"],
                                     inputs,
                                     result.rows[0]["id"]
                                    );
                     callback(error, formTmp);
                 });
             },
             (form: Form, callback: (err: Error, form?: Form) =>  void) => {

                 this.commit((error: Error, result?: QueryResult) => {
                     callback(error, form);
                 });
             }
         ], (err, result: Form) => {

             if (err){
                 this.rollback( (error: Error, results?: QueryResult) => {
                     cb(err);
                     return;
                 });
                 return;
             }
             cb(err, result);

         });

    }

    /**
     * A private method to asynchronously executes a query and get a list of Inputs.
     * @param id - Form identifier which inputs are linked to.
     * @param cb - Callback function which contains the data read.
     * @param cb.err - Error information when the method fails.
     * @param cb.inputs - Input array or an empty list if there is no input linked to form.
     */
    private readInputWithFormId(id: number, cb: (err: Error, inputs?: Input[]) =>  void){
        const query: string = "SELECT id, placement, input_type, question, description FROM input WHERE id_form=" + id + ";";

        this.executeQuery(query, (err: Error, result?: QueryResult) => {
            map(result.rows, (innerResult, callback) => {
                this.readInputValidationWithInputId(innerResult["id"], (error: Error, validation: Validation[]) => {
                    const inputTmp = new Input (
                                      innerResult["placement"],
                                      innerResult["description"],
                                      innerResult["question"],
                                      EnumHandler.parseInputType(innerResult["input_type"]),
                                      validation,
                                      innerResult["id"]);
                    callback(error, inputTmp);
                });
            }, (errors, inputs: Input[]) => {

                if (errors){
                    this.rollback( (error: Error, results?: QueryResult) => {
                        cb(errors);
                        return;
                    });
                    return;
                }

                const sortedInputs: Input[] = this.sortByPlacement(inputs);

                cb(errors, sortedInputs);
            });
        });
    }

    /**
     * A private method to asynchronously executes a query and get a list of Validations based on a Input id.
     * @param id - Input identifier which validations are linked to.
     * @param cb - Callback function which contains the data read.
     * @param cb.err - Error information when the method fails.
     * @param cb.validations - Validation array or an empty list if there is no validation for selected input.
     */
    private readInputValidationWithInputId(id: number, cb: (err: Error, validations?: Validation[]) =>  void){
        const query: string = "SELECT id, validation_type FROM input_validation WHERE id_input=" + id + ";";

        this.executeQuery(query, (err: Error, result?: QueryResult) => {
            map(result.rows, (innerResult, callback) => {
                this.readInputValidationArgumentWithInputValidationId(innerResult["id"], (error, argumentsArray) => {
                    const validationTmp: Validation = {
                        type:  EnumHandler.parseValidationType(innerResult["validation_type"]),
                        arguments: argumentsArray
                    };
                    callback(error, validationTmp);
                });
            }, (errors, validation: Validation[]) => {
                cb(errors, validation);
            });
        });

    }

    /**
     * A private method to asynchronously executes a query and get a list of Validation Argument based on a Validation id.
     * @param id - Validation identifier which Validation Arguments are linked to.
     * @param cb - Callback function which contains the data read.
     * @param cb.err - Error information when the method fails.
     * @param cb.argumentsArray - Validation Arguments array or an empty list if there is no validation argument for selected input.
     */
    private readInputValidationArgumentWithInputValidationId(id: number, cb: (err: Error, argumentsArray?: any[]) =>  void){
        const query: string = "SELECT id, argument, placement FROM \
                              input_validation_argument WHERE \
                              id_input_validation=" + id + ";";

        // cb(null);

        this.executeQuery(query, (error: Error, result?: QueryResult) => {

            const sortedResult: any[] = this.sortByPlacement(result.rows);
            const argumentArrayTmp = [];
            for (const innerResult of sortedResult){
                argumentArrayTmp.push(innerResult["argument"]);
            }

            cb(error, argumentArrayTmp);
        });

    }

    /**
     * A private method to return a array sorted by placement field
     * I personally don't think that this method should be here, it is quite weird to have a sort method on database handler
     * @param array - Array with objects that have placement field
     * @returns - A sorted array by placement
     */
    private sortByPlacement(array: any[]): any[] {

        const sortedArray: any[] = array.sort((obj1, obj2) => {
            if (obj1["placement"] > obj2["placement"]) {
                return 1;
            }

            if (obj1["placement"] < obj2["placement"]) {
                return -1;
            }

            return 0;
        });

        return sortedArray;
    }

    /**
     * Asynchronously insert a form on Database and return it.
     * @param form - Form to be inserted.
     * @param cb - Callback function which contains the inserted data.
     * @param cb.err - Error information when the method fails.
     * @param cb.formResult - Form or null if form any error occurs.
     */

    public writeForm(form: Form, cb: (err: Error, formResult?: Form) =>  void){
        const query: string = "INSERT INTO form (title, description) VALUES\
                              ( \'" + form.title + "\', \'" +
                              form.description + "\' ) RETURNING id;";

        waterfall([
            (callback: (err: Error, result?: QueryResult) =>  void) => {
                this.begin(callback);
            },
            (result: QueryResult, callback: (err: Error, result?: QueryResult) =>  void) => {
               this.executeQuery(query, callback);
            },
            (result: QueryResult, callback: (err: Error, formId?: number) =>  void) => {
                if (result.rowCount !== 1){
                    callback(new Error("Form not inserted"));
                    return;
                }
                eachSeries(form.inputs, (input: Input, innerCallback) => {
                    this.writeInputWithFormId(result.rows[0]["id"], input, innerCallback);
                }, (error) => {
                    if (error){
                        callback(error);
                        return;

                    }
                    callback(error, result.rows[0]["id"]);

                });
            },
            (formId: number, callback: (err: Error, formId?: number) =>  void) => {

                this.commit((error: Error, result?: QueryResult) => {
                    callback(error, formId);
                });
            },
            (formId: number, callback: (err: Error, formResult?: Form) =>  void) => {

                this.readForm(formId, callback);

            }
        ], (err, result: Form) => {

            if (err){
                this.rollback( (error: Error, results?: QueryResult) => {
                    cb(err);
                    return;
                });
                return;
            }
            cb(err, result);

        });
    }

    /**
     * Asynchronously insert a form on Database and return it.
     * @param formId - Form identifier to relate with Input.
     * @param input - Input to be inserted.
     * @param cb - Callback function.
     * @param cb.err - Error information when the method fails.
     */
    private writeInputWithFormId(formId: number, input: Input, cb: (err: Error) =>  void){
        const query: string = "INSERT INTO input (\
             id_form, placement, input_type, question, description)\
             VALUES ( " + formId + ", " + input.placement +
             ", \'" + EnumHandler.stringfyInputType(input.type) +
             "\', \'" + input.question + "\', \'" + input.description +
             "\' ) RETURNING id;";

        this.executeQuery(query, (err: Error, result?: QueryResult) => {
                    if (err){
                        cb(err);
                        return;
                    }

                    if (result.rowCount !== 1){
                        cb(new Error("Input not Inserted"));
                        return;
                    }

                    eachSeries(input.validation, (validation: Validation, callback) => {

                        this.writeValidationWithInputId(result.rows[0]["id"], validation, callback);

                    }, (error) => {

                        cb(error);

                    });
                });

    }
    /**
     * Asynchronously insert a form on Database and return it.
     * @param inputId - Input id to relate with Validation.
     * @param validation - Validation to be inserted.
     * @param cb - Callback function.
     * @param cb.err - Error information when the method fails.
     */
    private writeValidationWithInputId(inputId: number, validation: Validation, cb: (err: Error) =>  void){
        const query: string = "INSERT INTO input_validation ( id_input, \
                               validation_type) VALUES ( " + inputId + ", \'" +
                               EnumHandler.stringfyValidationType(validation.type) +
                               "\' ) RETURNING id;";

        this.executeQuery(query, (err: Error, result?: QueryResult) => {

            if (err){
                cb(err);
                return;
            }

            if (result.rowCount !== 1){
                cb(new Error("Validation not Inserted"));
                return;
            }

            eachOfSeries(validation.arguments, (argument, placement: number, callback) => {

                this.writeValidationArgumentWithInputIdAndPlacement(result.rows[0]["id"], argument, placement, callback);
            }, (error) => {
                cb(error);
            });

        });

    }

    /**
     * Asynchronously insert a form on Database and return it.
     * @param validationId - Validation identifier to relate with Argument.
     * @param argument - Argument to be inserted.
     * @param placement - placement where argument should be.
     * @param cb - Callback function.
     * @param cb.err - Error information when the method fails.
     */
     private writeValidationArgumentWithInputIdAndPlacement(validationId: number, argument: any, placement: number, cb: (err: Error) =>  void){
         const query: string = "INSERT INTO input_validation_argument \
                                ( id_input_validation, argument, placement )\
                                VALUES (  \'" + validationId + "\', \'" +
                                argument + "\', \'" + placement + "\' ) RETURNING id;";

         this.executeQuery(query, (err: Error, result?: QueryResult) => {

             if (err){
                 cb(err);
                 return;
             }

             if (result.rowCount !== 1){
                 cb(new Error("Validation Argument not Inserted"));
                 return;
             }

             cb(err);

         });

     }
460
}