Make tests pass running with postgres

This commit is contained in:
Ajay Ramachandran
2021-03-07 00:21:56 -05:00
parent 3fe7501802
commit 8729796e87
22 changed files with 208 additions and 173 deletions

View File

@@ -1,5 +1,5 @@
export interface IDatabase {
init(): void;
async init(): Promise<void>;
prepare(type: QueryType, query: string, params?: any[]): Promise<any | any[] | void>;
}

View File

@@ -9,7 +9,7 @@ export class Mysql implements IDatabase {
constructor(private config: any) {
}
init(): void {
async init(): Promise<void> {
this.connection = new MysqlInterface(this.config);
}

View File

@@ -1,6 +1,6 @@
import { Logger } from '../utils/logger';
import { IDatabase, QueryType } from './IDatabase';
import { Pool } from 'pg';
import { Client, Pool } from 'pg';
import fs from "fs";
@@ -13,6 +13,10 @@ export class Postgres implements IDatabase {
this.pool = new Pool(this.config.postgres);
if (!this.config.readOnly) {
if (this.config.createDbIfNotExists) {
await this.createDB();
}
if (this.config.createDbIfNotExists && !this.config.readOnly && fs.existsSync(this.config.dbSchemaFileName)) {
await this.pool.query(this.processUpgradeQuery(fs.readFileSync(this.config.dbSchemaFileName).toString()));
}
@@ -74,6 +78,29 @@ export class Postgres implements IDatabase {
}
}
private async createDB() {
const client = new Client({
...this.config.postgres,
database: "postgres"
});
await client.connect();
if ((await client.query(`SELECT * FROM pg_database WHERE datname = '${this.config.postgres.database}'`)).rowCount == 0) {
await client.query(`CREATE DATABASE "${this.config.postgres.database}"
WITH
OWNER = ${this.config.postgres.user}
ENCODING = 'UTF8'
LC_COLLATE = 'en_US.utf8'
LC_CTYPE = 'en_US.utf8'
TABLESPACE = pg_default
CONNECTION LIMIT = -1;`
);
}
client.end();
}
private async upgradeDB(fileNamePrefix: string, schemaFolder: string) {
const versionCodeInfo = await this.pool.query("SELECT value FROM config WHERE key = 'version'");
let versionCode = versionCodeInfo.rows[0] ? versionCodeInfo.rows[0].value : 0;

View File

@@ -30,7 +30,7 @@ export class Sqlite implements IDatabase {
}
}
init() {
async init() {
// Make dirs if required
if (!fs.existsSync(path.join(this.config.dbPath, "../"))) {
fs.mkdirSync(path.join(this.config.dbPath, "../"));

View File

@@ -60,9 +60,9 @@ if (config.mysql) {
enableWalCheckpointNumber: false
});
}
function initDb() {
db.init();
privateDB.init();
async function initDb() {
await db.init();
await privateDB.init();
if (db instanceof Sqlite) {
// Attach private db to main db