|
1 | | -import { createClient, type LibsqlError } from '@libsql/client' |
2 | 1 | import type { Arrayed } from '$lib/commons/types' |
3 | | -import { CATDAT_DB_AUTH_TOKEN, CATDAT_DB_URL } from '$env/static/private' |
| 2 | +import Database, { SqliteError } from 'better-sqlite3' |
| 3 | +import { join } from 'node:path' |
4 | 4 |
|
5 | | -const db = createClient({ |
6 | | - url: CATDAT_DB_URL, |
7 | | - authToken: CATDAT_DB_AUTH_TOKEN, |
8 | | -}) |
| 5 | +const db_path = join(process.cwd(), 'databases', 'catdat', 'catdat.db') |
9 | 6 |
|
10 | | -db.execute('PRAGMA foreign_keys = ON') |
| 7 | +const db = new Database(db_path, { readonly: true }) |
| 8 | + |
| 9 | +db.exec('PRAGMA foreign_keys = ON') |
11 | 10 |
|
12 | 11 | /** |
13 | | - * Small wrapper around db.execute to handle errors, |
| 12 | + * Small wrapper around db.prepare.all to handle errors, |
14 | 13 | * use sql templates, and specify the type of the result. |
15 | 14 | */ |
16 | | -export async function query<T>(stmt: { sql: string; values: any[] }) { |
| 15 | +export function query<T>(stmt: { sql: string; values: any[] }) { |
17 | 16 | try { |
18 | | - const { rows } = await db.execute(stmt.sql, stmt.values) |
| 17 | + const rows = db.prepare(stmt.sql).all(...stmt.values) |
19 | 18 | return { rows: rows as T[], err: null } |
20 | 19 | } catch (err) { |
21 | 20 | console.error(err) |
22 | | - return { rows: null, err: err as LibsqlError } |
| 21 | + return { rows: null, err: err as SqliteError } |
23 | 22 | } |
24 | 23 | } |
25 | 24 |
|
26 | 25 | /** |
27 | | - * Small wrapper around db.batch to handle errors |
| 26 | + * Small wrapper around db.transaction to handle errors |
28 | 27 | * use sql templates, and specify the type of the result. |
29 | 28 | */ |
30 | | -export async function batch<T extends any[]>(queries: { sql: string; values: any[] }[]) { |
| 29 | +export function batch<T extends any[]>(queries: { sql: string; values: any[] }[]) { |
31 | 30 | try { |
32 | | - const results = await db.batch( |
33 | | - queries.map((query) => ({ |
34 | | - sql: query.sql, |
35 | | - args: query.values, |
36 | | - })), |
37 | | - ) |
38 | | - return { results: results.map(({ rows }) => rows) as Arrayed<T>, err: null } |
| 31 | + const run_batch = db.transaction(() => { |
| 32 | + const results = [] |
| 33 | + |
| 34 | + for (const query of queries) { |
| 35 | + const result = db.prepare(query.sql).all(...query.values) |
| 36 | + results.push(result) |
| 37 | + } |
| 38 | + |
| 39 | + return results |
| 40 | + }) |
| 41 | + |
| 42 | + const results = run_batch() as Arrayed<T> |
| 43 | + return { results, err: null } |
39 | 44 | } catch (err) { |
40 | 45 | console.error(err) |
41 | | - return { results: null, err: err as LibsqlError } |
| 46 | + return { rows: null, err: err as SqliteError } |
42 | 47 | } |
43 | 48 | } |
0 commit comments