Skip to content

Commit

Permalink
Make tableName configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
Rajesh Gollapudi committed Dec 10, 2024
1 parent 76e6df2 commit 619eaea
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions packages/openauth/src/storage/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,40 @@ import Database from "libsql";

export interface SqliteStorageOptions {
persist?: string;
tableName?: string;
}

export function SQLiteStorage(input?: SqliteStorageOptions): StorageAdapter {
// initialize sqlite database and create the necessary table structure
const db = new Database(input?.persist || ":memory:");
const db = new Database(input?.persist ?? ":memory:");
const TABLE_NAME = input?.tableName ?? "__openauth__kv_storage";

db.exec(
"CREATE TABLE IF NOT EXISTS storage (key TEXT PRIMARY KEY, value TEXT, ttl INTEGER)"
`CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (key TEXT PRIMARY KEY, value TEXT, ttl INTEGER)`
);

return {
async get(key: string[]) {
const joined = joinKey(key);
const row = db
.prepare("SELECT value FROM storage WHERE key = ?")
.prepare(`SELECT value FROM ${TABLE_NAME} WHERE key = ?`)
.get(joined) as { value: string } | undefined;
return row ? JSON.parse(row.value) : undefined;
},
async set(key: string[], value: any, ttl?: number) {
const joined = joinKey(key);
db.prepare(
"INSERT OR REPLACE INTO storage (key, value, ttl) VALUES (?, ?, ?)"
`INSERT OR REPLACE INTO ${TABLE_NAME} (key, value, ttl) VALUES (?, ?, ?)`
).run(joined, JSON.stringify(value), ttl);
},
async remove(key: string[]) {
const joined = joinKey(key);
db.prepare("DELETE FROM storage WHERE key = ?").run(joined);
db.prepare(`DELETE FROM ${TABLE_NAME} WHERE key = ?`).run(joined);
},
async *scan(prefix: string[]) {
const joined = joinKey(prefix);
const rows = db
.prepare("SELECT key, value, ttl FROM storage WHERE key LIKE ?")
.prepare(`SELECT key, value, ttl FROM ${TABLE_NAME} WHERE key LIKE ?`)
.all(joined + "%") as { key: string; value: string; ttl: number }[];

for (const row of rows) {
Expand Down

0 comments on commit 619eaea

Please sign in to comment.