All files / src/engines sqlite3-engine.ts

100% Statements 16/16
50% Branches 2/4
100% Functions 12/12
100% Lines 14/14
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      1x   1x       17x       55x 55x 55x           44x 44x 44x           3x 3x 3x 3x           73x    
import { DatabaseEngine } from "../database-engine";
import { Database } from "sqlite3";
import { DatabaseType, KeyedDatabaseResult } from "../base-model";
import SQLGrammarCompiler from "../query/compiler";
 
export default class Sqlite3Engine implements DatabaseEngine {
    private connection: Database;
 
    constructor(connection: Database) {
        this.connection = connection;
    }
 
    query(sql: string, params: DatabaseType[]): Promise<void> {
        return new Promise<void>((resolve, reject) => {
            this.connection.run(sql, params, err => {
                err ? reject(err) : resolve();
            });
        });
    }
 
    get(sql: string, params: DatabaseType[]): Promise<KeyedDatabaseResult[]> {
        return new Promise((resolve, reject) => {
            this.connection.all(sql, params, (err, row) => {
                err ? reject(err) : resolve(row);
            });
        });
    }
 
    insertAndGetId(table: string, sql: string, params: DatabaseType[]): Promise<number> {
        return new Promise((resolve, reject) => {
            this.connection.serialize(async () => {
                await this.query(sql, params);
                this.get("SELECT last_insert_rowid() AS id FROM " + table, []).then(x => <number>x[0]["id"]).then(resolve, reject);
            });
        });
    }
 
    getGrammarCompiler(): SQLGrammarCompiler {
        return new SQLGrammarCompiler();
    }
}