All files / src ManagedDatabaseConnection.ts

96.15% Statements 75/78
93.55% Branches 29/31
97.06% Functions 33/34
96.15% Lines 75/78

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 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                                1x       1x                         32x 32x 32x       21x       3x 3x 2x 2x 2x 1x   1x 1x       1x       21x 21x       2x       33x       44x                         2x 1x     1x         3x 1x     2x         8x 8x         2x 1x     1x         1x 1x 1x           1x       32x 32x 7x 7x 7x 7x       25x           2x 2x 2x 1x     1x             3x 2x     1x         2x 2x 2x 1x     1x             2x 2x 2x 1x     1x             15x 15x 15x 15x 7x 7x     8x     15x 15x 7x   15x 15x           2x 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 {IDatabaseConnection} from './IDatabaseConnection';
import {getInstance} from './instance';
import {Readable} from 'stream';
import { Query } from './Query';
 
export class ManagedDatabaseConnection implements IDatabaseConnection {
    private _connection: IDatabaseConnection;
    /**
     * When true, this class will not close the connection or
     * allow transaction starts or ends. Methods for these actions
     * will be a no-op.
     */
    private _managed: boolean;
 
    private _requiresWrite: boolean;
    private _instantionStack: string;
 
    public constructor(requiresWrite: boolean = false) {
        this._managed = false;
        this._requiresWrite = requiresWrite;
        this._instantionStack = new Error().stack;
    }
 
    public setConnection(connection: IDatabaseConnection): void {
        if (this._connection) {
            // Store original connection because of async,
            // but we don't really need to wait for the async operations
            // to complete to set the new connection object.
            const oldConnection: IDatabaseConnection = this._connection;
            if (oldConnection.isTransaction()) {
                getInstance().getLogger().warn('Rolling back a transaction because setConnection was called on a ManagedDatabaseConnection in a transaction in progress.');
                getInstance().getLogger().trace(new Error('Stacktrace'));
                oldConnection.rollback().then(() => {
                    oldConnection.close();
                }).catch((error: any) => {
                    getInstance().getLogger().error(error);
                    oldConnection.close(true);
                });
            }
            else {
                oldConnection.close();
            }
        }
 
        this._connection = connection;
        this._managed = true;
    }
 
    public isWriteRequired(): boolean {
        return this._requiresWrite;
    }
 
    public isManaged(): boolean {
        return this._managed;
    }
 
    public hasConnection(): boolean {
        return !!this._connection;
    }
 
    public setInstantiationStack(stack: string): void {
        if (this.hasConnection()) {
            this._connection.setInstantiationStack(stack);
        }
        else {
            this._instantionStack = stack;
        }
    }
 
    public getInstantiationStack(): string {
        if (this.hasConnection()) {
            return this._connection.getInstantiationStack();
        }
        else {
            return this._instantionStack;
        }
    }
 
    public isReadOnly(): boolean {
        if (this.hasConnection()) {
            return this._connection.isReadOnly();
        }
        else {
            return true;
        }
    }
 
    public setTimeout(timeout: number): void {
        this._getConnection().then((connection: IDatabaseConnection) => {
            connection.setTimeout(timeout);
        });
    }
 
    public getTimeout(): number {
        if (this.hasConnection()) {
            return this._connection.getTimeout();
        }
        else {
            return null;
        }
    }
 
    public query(query: string | Query, params?: any): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            this._getConnection().then((connection: IDatabaseConnection) => {
                connection.query(query, params).then(resolve).catch(reject);
            }).catch(reject);
        })
    }
 
    public stream(query: string | Query, params?: any, streamOptions?: any): Readable {
        throw new Error('stream is not supported on Managed Connections');
    }
 
    public close(forceClose?: boolean): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            if (this.hasConnection() && !this.isManaged()) {
                this._connection.close(forceClose).then(() => {
                    this._connection = null;
                    this._managed = false;
                    resolve();
                }).catch(reject);
            }
            else {
                resolve();
            }
        });
    }
 
    public startTransaction(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this._getConnection().then((connection: IDatabaseConnection) => {
                if (!this.isManaged()) {
                    connection.startTransaction().then(resolve).catch(reject);
                }
                else {
                    resolve();
                }
            }).catch(reject);
        });
    }
 
    public isTransaction(): boolean {
        if (this.hasConnection()) {
            return this._connection.isTransaction();
        }
        else {
            return false;
        }
    }
 
    public commit(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this._getConnection().then((connection: IDatabaseConnection) => {
                if (!this.isManaged()) {
                    connection.commit().then(resolve).catch(reject);
                }
                else {
                    resolve();
                }
            }).catch(reject);
        });
    }
 
    public rollback(): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this._getConnection().then((connection: IDatabaseConnection) => {
                if (!this.isManaged()) {
                    connection.rollback().then(resolve).catch(reject);
                }
                else {
                    resolve();
                }
            }).catch(reject);
        });
    }
 
    private _getConnection(): Promise<IDatabaseConnection> {
        return new Promise<IDatabaseConnection>((resolve, reject) => {
            let promise: Promise<IDatabaseConnection> = null;
            let setInstantationStack: boolean = false;
            if (!this._connection) {
                promise = getInstance().getDB().getConnection(this._requiresWrite);
                setInstantationStack = true;
            }
            else {
                promise = Promise.resolve(this._connection);
            }
 
            promise.then((connection: IDatabaseConnection) => {
                if (setInstantationStack) {
                    connection.setInstantiationStack(this._instantionStack);
                }
                this._connection = connection;
                resolve(this._connection);
            }).catch(reject);
        });
    }
 
    public getAPI(): any {
        if (this.hasConnection()) {
            return this._connection.getAPI();
        }
        else {
            return null;
        }
    }
}