All files Query.ts

12.5% Statements 3/24
0% Branches 0/5
0% Functions 0/10
12.5% Lines 3/24

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                                1x       1x                                                   1x                                                                                                                                                                          
/*
   Copyright 2022 Total Pave Inc.
 
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
 
       http://www.apache.org/licenses/LICENSE-2.0
 
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
 
import {SERVICE_NAME} from './SQLite';
import { SQLiteParams } from './SQLiteTypes';
import {IDatabaseHandle} from './IDatabaseHandle';
import {IError} from './IError';
import {SQLiteParamAdapter} from './SQLiteParamAdapter';
 
/**
 * Before v0.2.0 TParams can hold anything, as long as you filtered out
 * non-query parameters inside _getParameters.
 * 
 * @since v0.2.0
 * 
 * TParams must only contain query parameters. Additional query options can be passed
 * as an another argument if desired. Implementing _getParameters is now optional
 * and the default implementation of it will automatically convert several
 * well known types into the appropriate SQLite type.
 * 
 * Custom type adaptions can be implemented by providing a custom SQLiteParamAdapter.
 * 
 * If you can guarentee that the TParams consists of only valid SQLite Types, then
 * the overriding _getParameters can be used to skip the adaption step, which might be
 * a significant performance gain on large param queries, such as bulk inserts.
 * 
 * @example
 * ```typescript
 * protected override _getParameters(params: TParams): SQLiteParams {
 *  return <SQLiteParams><unknown>params;
 * }
 * ```
 */
export abstract class Query<TParams, TResponse> {
    private $params: TParams;
    private $paramAdapter: SQLiteParamAdapter;
 
    public constructor(params: TParams) {
        this.$params = params;
        this.$paramAdapter = this._createParamAdapter();
    }
 
    /**
     * @since v0.2.0
     * @returns 
     */
    protected _createParamAdapter(): SQLiteParamAdapter {
        return new SQLiteParamAdapter();
    }
 
    protected _validateParameterNames(params: SQLiteParams) {
        for (let key in params) {
            Iif (!(/^([a-zA-Z])+([a-zA-Z0-9_]+)/.test(key))) {
                throw new Error(`Query parameter "${key}" contains an invalid character. Parameter name should only contain alphanumeric or underscore characters. The first charater must be an alphebetical letter.`);
            }
        }
    }
 
    public abstract getQuery(): string;
 
    /**
     * Returns the parameters as given to the Query
     * @returns 
     */
    public getParams(): TParams {
        return this.$params;
    }
 
    /**
     * Implement to translate unknown parameter types into valid SQL data types
     * @param params 
     * @returns 
     */
    protected async _getParameters(params: TParams): Promise<SQLiteParams> {
        Iif (!params) {
            return null;
        }
 
        let out: SQLiteParams;
        if (params instanceof Array) {
            out = await this.$paramAdapter.processArray(params);
        }
        else Iif (typeof params === 'object') {
            out = await this.$paramAdapter.processKWargs(<Record<string, unknown>>params);
        }
 
        return out;
    }
 
    /**
     * @internal function that controls which native API to call. Don't touch this.
     */
     protected _getNativeMethod(): string {
        return 'query';
    }
 
    public async execute(db: IDatabaseHandle): Promise<TResponse> {
        let params: SQLiteParams = await this._getParameters(this.$params);
        this._validateParameterNames(params); // _getParameters is able to create or remove parameter keys. As a result, we must validate the returned value of _getParameters.
        return new Promise<TResponse>((resolve, reject) => {
            cordova.exec(
                (data: any) => {
                    resolve(data);
                },
                (error: IError) => {
                    reject(error);
                },
                SERVICE_NAME,
                this._getNativeMethod(),
                [
                    {dbHandle: db.getHandle()},
                    this.getQuery(),
                    params
                ]
            );
        });
    }
}