Browse Source

fix problem with initialization & refactor types

sql-absurd-sql
Trent Larson 2 weeks ago
parent
commit
a3bdcfd168
  1. 4
      src/interfaces/database.ts
  2. 6
      src/services/database.ts
  3. 17
      src/services/migrationService.ts

4
src/interfaces/database.ts

@ -9,6 +9,6 @@ export interface DatabaseService {
initialize(): Promise<void>;
query(sql: string, params?: any[]): Promise<QueryExecResult[]>;
run(sql: string, params?: any[]): Promise<{ changes: number; lastId?: number }>;
get(sql: string, params?: any[]): Promise<any[] | undefined>;
all(sql: string, params?: any[]): Promise<any[][]>;
getOneRow(sql: string, params?: any[]): Promise<any[] | undefined>;
getAll(sql: string, params?: any[]): Promise<any[][]>;
}

6
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<QueryExecResult[]>;
@ -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<QueryExecResult[]> {
this.ensureInitialized();
return this.db!.exec(sql, params);
}
async get(sql: string, params: any[] = []): Promise<any[] | undefined> {
async getOneRow(sql: string, params: any[] = []): Promise<any[] | undefined> {
this.ensureInitialized();
const result = await this.db!.exec(sql, params);
return result[0]?.values[0];

17
src/services/migrationService.ts

@ -1,9 +1,4 @@
type SqlValue = string | number | null | Uint8Array;
export interface QueryExecResult {
columns: Array<string>;
values: Array<Array<SqlValue>>;
}
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 result: QueryExecResult[] = await sqlExec('SELECT name FROM migrations;');
let executedMigrations: Set<string> = 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];
const executedMigrations = new Set(singleResult.values.map(row => row[0]));
executedMigrations = new Set(singleResult.values.map((row: any[]) => row[0]));
}
// Run pending migrations in order
for (const migration of this.migrations) {

Loading…
Cancel
Save