diff --git a/src/interfaces/database.ts b/src/interfaces/database.ts index ad61521e..f828eb00 100644 --- a/src/interfaces/database.ts +++ b/src/interfaces/database.ts @@ -9,6 +9,6 @@ export interface DatabaseService { initialize(): Promise; query(sql: string, params?: any[]): Promise; run(sql: string, params?: any[]): Promise<{ changes: number; lastId?: number }>; - get(sql: string, params?: any[]): Promise; - all(sql: string, params?: any[]): Promise; -} \ No newline at end of file + getOneRow(sql: string, params?: any[]): Promise; + getAll(sql: string, params?: any[]): Promise; +} diff --git a/src/services/database.ts b/src/services/database.ts index c87d1edf..74da316d 100644 --- a/src/services/database.ts +++ b/src/services/database.ts @@ -6,8 +6,9 @@ declare module 'absurd-sql/dist/indexeddb-backend'; import initSqlJs from '@jlongster/sql.js'; import { SQLiteFS } from 'absurd-sql'; import IndexedDBBackend from 'absurd-sql/dist/indexeddb-backend'; + import { runMigrations } from '../db-sql/migration'; -import { QueryExecResult } from './migrationService'; +import type { QueryExecResult } from '../interfaces/database'; interface SQLDatabase { exec: (sql: string, params?: any[]) => Promise; @@ -73,12 +74,13 @@ class DatabaseService { return this.db!.run(sql, params); } + // Note that the resulting array may be empty if there are no results from the query async query(sql: string, params: any[] = []): Promise { this.ensureInitialized(); return this.db!.exec(sql, params); } - async get(sql: string, params: any[] = []): Promise { + async getOneRow(sql: string, params: any[] = []): Promise { this.ensureInitialized(); const result = await this.db!.exec(sql, params); return result[0]?.values[0]; diff --git a/src/services/migrationService.ts b/src/services/migrationService.ts index 106d06d3..ca640694 100644 --- a/src/services/migrationService.ts +++ b/src/services/migrationService.ts @@ -1,9 +1,4 @@ -type SqlValue = string | number | null | Uint8Array; - -export interface QueryExecResult { - columns: Array; - values: Array>; -} +import { QueryExecResult } from '../interfaces/database'; interface Migration { name: string; @@ -36,13 +31,17 @@ export class MigrationService { id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP - ) + ); `); // Get list of executed migrations - const result = await sqlExec('SELECT name FROM migrations'); - const singleResult = result[0]; - const executedMigrations = new Set(singleResult.values.map(row => row[0])); + const result: QueryExecResult[] = await sqlExec('SELECT name FROM migrations;'); + let executedMigrations: Set = new Set(); + // Even with that query, the QueryExecResult may be [] (which doesn't make sense to me). + if (result.length > 0) { + const singleResult = result[0]; + executedMigrations = new Set(singleResult.values.map((row: any[]) => row[0])); + } // Run pending migrations in order for (const migration of this.migrations) {