All files / src MySQLConnection.ts

92.5% Statements 74/80
83.33% Branches 25/30
92.31% Functions 24/26
93.67% Lines 74/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 78 79 80 81 82 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 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                              1x 1x 1x       1x 1x 1x   1x   1x 1x 1x   1x         39x   39x 39x   39x                           31x       1x       18x 18x       18x 5x     13x   18x         2x 1x     2x 2x     2x         2x   2x       12x 1x     11x 1x     10x   10x 10x 9x   1x 1x 1x           2x       5x 1x     4x 4x 2x 2x   2x 2x           3x 1x     2x 2x 1x 1x   1x 1x           5x 1x     4x   4x 4x 4x 3x 2x     1x       1x     4x 3x 3x   1x 1x 1x          
// Copyright (C) 2017  Norman Breau
 
// This program 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.
 
// 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 General Public License for more details.
 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
import {DatabaseConnection} from './DatabaseConnection';
import {DatabaseQueryError} from './DatabaseQueryError';
import {getInstance, getApplicationLogger} from './instance';
import * as MySQL from 'mysql';
import {Readable} from 'stream';
import {Query} from './Query';
import { StartTransactionQuery } from './private/StartTransactionQuery';
import { CommitQuery } from './private/CommitQuery';
import { RollbackQuery } from './private/RollbackQuery';
 
const DEFAULT_HIGH_WATERMARK: number = 512; // in number of result objects
 
const startTransactionQuery: Query = new StartTransactionQuery();
const commitQuery: Query = new CommitQuery();
const rollbackQuery: Query = new RollbackQuery();
 
export class MySQLConnection extends DatabaseConnection {
    private transaction: boolean;
    private _opened: boolean;
 
    public constructor(connection: MySQL.PoolConnection, instantiationStack: string, isReadOnly: boolean = true) {
        super(connection, isReadOnly, instantiationStack);
 
        this._opened = true;
        this.transaction = false;
 
        connection.config.queryFormat = function(query: string, values: any) {
            if (!values) return query;
 
            return query.replace(/:(\w+)/g, function(this: any, txt: string, key: string): string {
                // eslint-disable-next-line no-prototype-builtins
                if (values.hasOwnProperty(key)) {
                    return this.escape(values[key]);
                }
                return txt;
            }.bind(this));
        };
    }
 
    public isTransaction(): boolean {
        return this.transaction;
    }
 
    public isOpen(): boolean {
        return this._opened;
    }
 
    protected _query(query: string, params?: any): Promise<any> {
        return new Promise((resolve, reject) => {
            let queryObject: MySQL.Query = this.getAPI().query({
                sql: query,
                timeout: this.getTimeout()
            }, params, (error: MySQL.MysqlError, results: any) => {
                if (error) {
                    return reject(new DatabaseQueryError(queryObject.sql, error));
                }
 
                return resolve(results);
            });
            getApplicationLogger().trace(queryObject.sql);
        });
    }
 
    protected _stream(query: string, params?: any, streamOptions?: any): Readable {
        if (!streamOptions) {
            streamOptions = {};
        }
 
        Eif (!streamOptions.highWatermark) {
            streamOptions.highWatermark = DEFAULT_HIGH_WATERMARK;
        }
 
        const queryObject: MySQL.Query = this.getAPI().query({
            sql: query,
            timeout: this.getTimeout()
        }, params);
 
        getApplicationLogger().trace(queryObject.sql);
 
        return queryObject.stream(streamOptions);
    }
 
    public startTransaction(): Promise<void> {
        if (this.isReadOnly()) {
            return Promise.reject(new Error('A readonly connection cannot start a transaction.'));
        }
 
        if (this.isTransaction()) {
            return Promise.reject(new Error('Connection is already in a transaction.'));
        }
 
        this.transaction = true;
 
        return new Promise<void>((resolve, reject) => {
            this.query(startTransactionQuery).then(() => {
                resolve();
            }).catch((ex) => {
                this.transaction = false;
                getApplicationLogger().error(ex);
                reject(ex);
            });
        });
    }
 
    public endTransaction(requiresRollback: boolean = false): Promise<void> {
        return (requiresRollback) ? this.rollback() : this.commit();
    }
 
    public rollback(): Promise<void> {
        if (!this.isTransaction()) {
            return Promise.reject(new Error('Cannot rollback when there is no active transaction.'));
        }
 
        return new Promise<void>((resolve, reject) => {
            this.query(rollbackQuery).then(() => {
                this.transaction = false
                resolve();
            }).catch((ex: any) => {
                getApplicationLogger().error(ex);
                reject(ex);
            });
        });
    }
 
    public commit(): Promise<void> {
        if (!this.isTransaction()) {
            return Promise.reject(new Error('Cannot commit when there is no active transaction.'));
        }
 
        return new Promise<void>((resolve, reject) => {
            this.query(commitQuery).then(() => {
                this.transaction = false;
                resolve();
            }).catch((ex: any) => {
                getApplicationLogger().error(ex);
                reject(ex);
            });
        });
    }
 
    protected _close(forceClose: boolean): Promise<void> {
        if (!forceClose && this.isTransaction()) {
            return Promise.reject(new Error('Cannot close a connection while there is an active transaction. Use commit or rollback first.'));
        }
 
        this._opened = false;
        
        return new Promise<void>((resolve, reject) => {
            let rollbackPromise: Promise<void> = null;
            if (forceClose) {
                if (this.isTransaction()) {
                    rollbackPromise = this.rollback();
                }
                else {
                    rollbackPromise = Promise.resolve();
                }
            }
            else {
                rollbackPromise = Promise.resolve();
            }
 
            rollbackPromise.then(() => {
                this.getAPI().release();
                resolve();
            }).catch((error: any) => {
                getInstance().getLogger().error(error);
                this.getAPI().release();
                resolve();
            });
        });
    }
}