All files / src DatabaseConnection.ts

93.75% Statements 45/48
86.67% Branches 13/15
100% Functions 14/14
93.75% Lines 45/48

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 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                              1x           1x     1x 1x               1x                 82x 82x 82x 82x   82x 82x 1x     82x       1x       7x                 2x       103x 21x     103x 1x                 26x                 16x                 10x 1x     9x               24x                       20x   20x 20x 16x 16x     4x 4x     20x                     3x 3x 3x         3x 3x   3x                         18x       18x 18x 18x             20x                                                                                                                                                              
// 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 {
    getApplicationLogger,
    getInstance
} from './instance';
import {Readable} from 'stream';
import {IDatabaseConnection} from './IDatabaseConnection';
import {Query} from './Query';
import { IQueryParameters } from './IQueryParameters';
 
export const LINGER_WARNING: number = 10000;
export const DEFAULT_QUERY_TIMEOUT: number = 3600000;
 
/**
 * Do not call `new Database` directly. Use `Database.getConnection` to create a `DatabaseConnection` object.
 * @abstract
 * @implements `IDatabaseConnection`
 * @class
 */
export abstract class DatabaseConnection implements IDatabaseConnection {
    private api: any;
    private readOnly: boolean;
    private _timeout: number;
    private _lingerTimer: NodeJS.Timer;
    private _instantiationStack: string;
    private _open: boolean;
 
    public constructor(api: any, isReadOnly: boolean, instantiationStack: string) {
        this.api = api;
        this.readOnly = isReadOnly;
        this._instantiationStack = (instantiationStack || '').replace(/Error:/, 'Warning:');
        this._open = true;
 
        this._timeout = getInstance().getConfig().query_timeout;
        if (isNaN(this._timeout)) {
            this._timeout = DEFAULT_QUERY_TIMEOUT;
        }
 
        this._armLingerWarning();
    }
 
    private _triggerLingerWarning(): void {
        getApplicationLogger().warn(`Database connection has lingered for ${LINGER_WARNING}ms of inactivity.\n\n${this._instantiationStack}`);
    }
 
    public setInstantiationStack(stack: string): void {
        this._instantiationStack = stack;
    }
 
    /**
     * Gets the callback stacktrace to determine what opened
     * this connection. Useful for debugging lingering connections.
     * @returns string - A stacktrace
     */
    public getInstantiationStack(): string {
        return this._instantiationStack;
    }
 
    private _armLingerWarning() {
        if (this._lingerTimer) {
            clearTimeout(this._lingerTimer);
        }
 
        this._lingerTimer = setTimeout(() => {
            this._triggerLingerWarning();
        }, LINGER_WARNING);
    }
 
    /**
     * Gets the underlying Database API
     * @returns any
     */
    public getAPI(): any {
        return this.api;
    }
 
    /**
     * Returns true if connection was created without
     * write access
     * @returns boolean
     */
    public isReadOnly(): boolean {
        return this.readOnly;
    }
 
    /**
     * Sets the timeout of this connectino
     * 
     * @param timeout in milliseconds
     */
    public setTimeout(timeout: number): void {
        if (isNaN(timeout)) {
            throw new TypeError('setTimeout expects a number in parameter 1.');
        }
 
        this._timeout = timeout;
    }
 
    /**
     * Returns the current timeout setting
     * @returns number in milliseconds
     */
    public getTimeout(): number {
        return this._timeout;
    }
 
    /**
     * Queries the database for a dataset.
     * 
    * @param {Query} query The database query
     * @param {IQueryParameters} params Parameters for the query
     * @async
     * @returns Promise<any>
     */
    public query(query: string | Query, params?: IQueryParameters): Promise<any> {
        this._armLingerWarning();
        
        let queryStr: string = null;
        if (query instanceof Query) {
            queryStr = query.getQuery();
            params = query.getParameters();
        }
        else {
            getInstance().getLogger().deprecateParameterType(1, 'string', 'Query instance');
            queryStr = query;
        }
 
        return this._query(queryStr, params);
    }
 
    /**
     * 
     * @param query The database query
     * @param params Parameters for the query
     * @param streamOptions Stream options
     * @returns Readable
     */
    public stream(query: string | Query, params?: any, streamOptions?: any): Readable {
        this._armLingerWarning();
        let queryStr: string = null;
        Iif (query instanceof Query) {
            queryStr = query.getQuery();
            params = query.getParameters();
        }
        else {
            getInstance().getLogger().deprecateParameterType(1, 'string', 'Query instance');
            queryStr = query;
        }
        return this._stream(queryStr, params, streamOptions);
    }
 
    /**
     * Closes the connection. May error if connection has an active transaction.
     * if `forceClose` boolean is true, it will force close the connection, regardless
     * of transaction state.
     * 
     * @param forceClose optional boolean
     * @async
     * @returns Promise<void>
     */
    public close(forceClose: boolean = false): Promise<void> {
        Iif (this.isClosed()) {
            return Promise.resolve();
        }
        
        this._open = false;
        clearTimeout(this._lingerTimer);
        return this._close(forceClose);
    }
 
    /**
     * Returns true if the connection has been closed.
     */
    public isClosed(): boolean {
        return !this._open;
    }
 
    /**
     * Implementation method to start a transaction.
     * 
     * @abstract
     * @async
     * @returns Promise<void>
     */
    public abstract startTransaction(): Promise<void>;
 
    /**
     * Implementation method to determine if the connection is in an active transaction.
     * 
     * @abstract
     * @returns boolean
     */
    public abstract isTransaction(): boolean;
 
    /**
     * Ends a transaction. if `requiresRollback` is `true`, then `rollback()` is invoked. Otherwise, `commit()` is invoked.
     * 
     * @abstract
     * @async
     * @param requiresRollback optional boolean
     * @returns Promise<void>
     */
    public abstract endTransaction(requiresRollback?: boolean): Promise<void>;
    
    /**
     * Commits a transaction. This will end a transaction.
     * 
     * @abstract
     * @async
     * @returns Promise<void>
     */
    public abstract commit(): Promise<void>;
 
    /**
     * Rollsback a transaction. This will end a transaction.
     * 
     * @abstract
     * @async
     * @returns Promise<void>
     */
    public abstract rollback(): Promise<void>;
 
    /**
     * Implementation to close the connection, if `forceClose` is true, close the connection no matter what.
     * Silently error if it means the connection is closed.
     * 
     * @param forceClose boolean, if `true`, should close the connection no matter what.
     * @async
     * @returns Promise<void>
     */
    protected abstract _close(forceClose: boolean): Promise<void>;
    
    /**
     * Implementation method to return a dataset from the database
     * 
     * @param query The database query
     * @param params The query parameters
     * @async
     * @returns Promise
     */
    protected abstract _query(query: string, params?: any): Promise<any>;
 
    /**
     * Implementation method to return a dataset from the database like `query()`,
     * but returns a `Readable` stream instead.
     * 
     * @param query The database query
     * @param params The query parameters
     * @param streamOptions `Readable` stream options
     * @returns `Readable`
     */
    protected abstract _stream(query: string, params?: any, streamOptions?: any): Readable;
}