From cc5689eaf4f7cfa158e31107906434da9aed62bf Mon Sep 17 00:00:00 2001 From: lonkaars Date: Thu, 29 Jun 2023 23:25:01 +0200 Subject: WIP examples + change `.prepare()` to `await .ready` --- db/db.ts | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) (limited to 'db') diff --git a/db/db.ts b/db/db.ts index d5a2b76..5605f40 100644 --- a/db/db.ts +++ b/db/db.ts @@ -3,7 +3,6 @@ import * as path from 'https://deno.land/std@0.102.0/path/mod.ts'; import { TokenTags } from "../language/tags.ts"; import "../util/string.ts"; -import YomikunError from "../util/error.ts"; export interface DBDictInfo { id: number; @@ -49,14 +48,15 @@ interface DBFindResult { */ export default class DB { private connection: Database; - public ready: boolean = false; + public ready: Promise; + private here = path.dirname(path.fromFileUrl(import.meta.url)); private paths = { db: { - dict: path.resolve('db', 'dict.db'), - user: path.resolve('db', 'user.db'), + dict: path.resolve(this.here, 'dict.db'), + user: path.resolve(this.here, 'user.db'), }, query: { - find: path.resolve('db', 'find.sql'), + find: path.resolve(this.here, 'find.sql'), }, } as const; private statement: { @@ -68,25 +68,23 @@ export default class DB { this.connection = new Database(":memory:", { create: false }); this.statement = { attach: this.connection.prepare("attach database ? as ?"), - queryTerm: this.connection.prepare(""), // initialized in prepare() + queryTerm: this.connection.prepare(""), }; this.attach(this.paths.db.dict, 'dict'); this.attach(this.paths.db.user, 'user'); + this.ready = new Promise(async resolve => { + const statement = await Deno.readTextFile(this.paths.query.find); + this.statement.queryTerm = this.connection.prepare(statement); + resolve(); + }); } private attach(dbPath: string, alias?: string) { this.statement.attach.run(dbPath, alias); } - async prepare() { - const statement = await Deno.readTextFile(this.paths.query.find); - this.statement.queryTerm = this.connection.prepare(statement); - this.ready = true; - } - - findTerm(term: string): FindResult[] { - if (!this.ready) throw new YomikunError("DB not ready yet, call `async DB::prepare()` first"); - + async findTerm(term: string): Promise { + await this.ready; var results = this.statement.queryTerm.all({ term }) as unknown as DBFindResult[]; var terms: FindResult[] = results?.map(term => { if (term.rules == null) term.rules = ""; -- cgit v1.2.3