diff --git a/backend/database/core.ts b/backend/database/core.ts index d6782bbb..b2630801 100644 --- a/backend/database/core.ts +++ b/backend/database/core.ts @@ -29,7 +29,7 @@ import { ColumnDiff, FieldValueMap, GetQueryBuilderOptions } from './types'; * * 1. Init core: `const db = new DatabaseCore(dbPath)`. * 2. Connect db: `db.connect()`. This will allow for raw queries to be executed. - * 3. Set schemas: `bb.setSchemaMap(schemaMap)`. This will allow for ORM functions to be executed. + * 3. Set schemas: `db.setSchemaMap(schemaMap)`. This will allow for ORM functions to be executed. * 4. Migrate: `await db.migrate()`. This will create absent tables and update the tables' shape. * 5. ORM function execution: `db.get(...)`, `db.insert(...)`, etc. * 6. Close connection: `await db.close()`. @@ -65,6 +65,29 @@ export default class DatabaseCore extends DatabaseBase { }; } + static async getCountryCode(dbPath: string): Promise { + let countryCode = 'in'; + const db = new DatabaseCore(dbPath); + db.connect(); + + let query: { countryCode: string }[] = []; + try { + query = await db.knex!('SingleValue').where({ + fieldname: 'countryCode', + parent: 'SystemSettings', + }); + } catch { + // Database not inialized and no countryCode passed + } + + if (query.length > 0) { + countryCode = query[0].countryCode as string; + } + + await db.close(); + return countryCode; + } + setSchemaMap(schemaMap: SchemaMap) { this.schemaMap = schemaMap; } diff --git a/backend/database/manager.ts b/backend/database/manager.ts index edf9d5c3..084c13ba 100644 --- a/backend/database/manager.ts +++ b/backend/database/manager.ts @@ -25,10 +25,11 @@ export class DatabaseManager extends DatabaseDemuxBase { } async connectToDatabase(dbPath: string, countryCode?: string) { + countryCode ??= await DatabaseCore.getCountryCode(dbPath); + this.db = new DatabaseCore(dbPath); this.db.connect(); - countryCode ??= await this.#getCountryCode(); const schemaMap = getSchemas(countryCode); this.db.setSchemaMap(schemaMap); @@ -102,28 +103,6 @@ export class DatabaseManager extends DatabaseDemuxBase { return patches.filter((p) => !executedPatches.includes(p.name)); } - async #getCountryCode(): Promise { - if (this.db === undefined) { - return undefined; - } - - let query: { countryCode: string }[] = []; - try { - query = await this.db.knex!('SingleValue').where({ - fieldname: 'countryCode', - parent: 'SystemSettings', - }); - } catch { - // Database not inialized and no countryCode passed - } - - if (query.length > 0) { - return query[0].countryCode as string; - } - - return undefined; - } - async #unlinkIfExists(dbPath: string) { try { fs.unlink(dbPath);