From 86cfc336e7a0d9dbc19595cfcd4eade0a2e65e49 Mon Sep 17 00:00:00 2001 From: Guangcong Luo Date: Fri, 1 Dec 2023 08:04:08 -0600 Subject: [PATCH] Database: Support null primaryKeyName Some tables don't have a single primary key, so primaryKeyName should be null in those cases. --- src/database.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/database.ts b/src/database.ts index 7b4fc53..a9b4e50 100644 --- a/src/database.ts +++ b/src/database.ts @@ -161,11 +161,11 @@ type PartialOrSQL = { export class DatabaseTable { db: Database; name: string; - primaryKeyName: keyof Row & string; + primaryKeyName: keyof Row & string | null; constructor( db: Database, name: string, - primaryKeyName: keyof Row & string + primaryKeyName: keyof Row & string | null = null ) { this.db = db; this.name = db.prefix + name; @@ -256,6 +256,7 @@ export class DatabaseTable { } } set(primaryKey: BasicSQLValue, partialRow: PartialOrSQL, where?: SQLStatement) { + if (!this.primaryKeyName) throw new Error(`Cannot set() without a single-column primary key`); partialRow[this.primaryKeyName] = primaryKey as any; return this.replace(partialRow, where); } @@ -263,12 +264,15 @@ export class DatabaseTable { return this.queryExec()`REPLACE INTO "${this.name}" (${partialRow as SQLValue}) ${where}`; } get(primaryKey: BasicSQLValue, entries?: (keyof Row & string)[] | SQLStatement) { + if (!this.primaryKeyName) throw new Error(`Cannot get() without a single-column primary key`); return this.selectOne(entries)`WHERE "${this.primaryKeyName}" = ${primaryKey}`; } delete(primaryKey: BasicSQLValue) { + if (!this.primaryKeyName) throw new Error(`Cannot delete() without a single-column primary key`); return this.deleteAll()`WHERE "${this.primaryKeyName}" = ${primaryKey} LIMIT 1`; } update(primaryKey: BasicSQLValue, data: PartialOrSQL) { + if (!this.primaryKeyName) throw new Error(`Cannot update() without a single-column primary key`); return this.updateAll(data)`WHERE "${this.primaryKeyName}" = ${primaryKey} LIMIT 1`; } }