-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite.ts
More file actions
71 lines (65 loc) · 2.79 KB
/
sqlite.ts
File metadata and controls
71 lines (65 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { QueryResult, SqlExecutor } from "../types";
import { SQLKITException } from "../exceptions";
export class SQLiteAdapter implements SqlExecutor {
constructor(private sqliteDb: any) {}
async executeSQL<T>(sql: string, values: any[]): Promise<QueryResult<T>> {
return new Promise((resolve, reject) => {
try {
if (this.sqliteDb.prepare) {
// better-sqlite3 prepared statements
console.log('Original SQL:', sql);
console.log('Original values:', values);
// Convert PostgreSQL-style placeholders ($1, $2, etc.) to SQLite-style (?)
let sqliteQuery = sql.replace(/\$\d+/g, '?');
// Determine if this is a SELECT statement or a modification statement
const trimmedSql = sql.trim().toUpperCase();
const isSelectStatement = trimmedSql.startsWith('SELECT') ||
trimmedSql.startsWith('WITH') ||
(trimmedSql.startsWith('PRAGMA') && trimmedSql.includes('=')); // Some PRAGMA statements return data
// SQLite doesn't support RETURNING clause in INSERT, UPDATE, DELETE statements
// Strip RETURNING clause for modification statements
if (!isSelectStatement && sqliteQuery.toUpperCase().includes('RETURNING')) {
sqliteQuery = sqliteQuery.replace(/\s+RETURNING\s+[\s\S]*?;?\s*$/i, ';');
}
const stmt = this.sqliteDb.prepare(sqliteQuery);
if (isSelectStatement) {
// Use .all() for SELECT statements
const rows = stmt.all(values) as T[];
resolve({
rows: rows || [],
rowCount: rows?.length || 0
});
} else {
// Use .run() for INSERT, UPDATE, DELETE, CREATE, DROP, etc.
const result = stmt.run(values);
if (sqliteQuery.toUpperCase().includes('UPDATE')) {
console.log('UPDATE query:', sqliteQuery);
console.log('UPDATE values:', values);
console.log('UPDATE result:', result);
}
resolve({
rows: [] as T[],
rowCount: result.changes || 0
});
}
} else if (this.sqliteDb.all) {
// node-sqlite3 callback-based API
this.sqliteDb.all(sql, values, (err: any, rows: T[]) => {
if (err) {
reject(new SQLKITException(err.message));
} else {
resolve({
rows: rows || [],
rowCount: rows?.length || 0
});
}
});
} else {
reject(new SQLKITException("Unsupported SQLite database interface"));
}
} catch (err: any) {
reject(new SQLKITException(err.message));
}
});
}
}