-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite-connection.ts
More file actions
298 lines (263 loc) · 8.46 KB
/
Copy pathsqlite-connection.ts
File metadata and controls
298 lines (263 loc) · 8.46 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import { Temporal } from "temporal-polyfill";
import type { Queryable } from "./absurd";
import type {
SQLiteColumnDefinition,
SQLiteDatabase,
SQLiteStatement,
SQLiteVerboseLog,
SQLiteBindValue,
} from "./sqlite-types";
/**
* Hooks for encoding parameters and decoding query results.
* Useful when SQLite drivers expose different value representations.
*/
export interface SQLiteValueCodec {
encodeParam?: (value: SQLiteBindValue) => SQLiteBindValue;
decodeColumn?: (args: {
value: unknown;
columnName: string;
columnType: string | null;
verbose?: SQLiteVerboseLog;
}) => unknown;
decodeRow?: (args: {
row: Record<string, unknown>;
columns: SQLiteColumnDefinition[];
decodeColumn: NonNullable<SQLiteValueCodec["decodeColumn"]>;
verbose?: SQLiteVerboseLog;
}) => Record<string, unknown>;
}
/**
* Configuration options for SQLiteConnection.
*/
export interface SQLiteConnectionOptions {
valueCodec?: SQLiteValueCodec;
verbose?: SQLiteVerboseLog;
}
/**
* SQLite adapter that rewrites Absurd's SQL to SQLite syntax and handles retries.
*/
export class SQLiteConnection implements Queryable {
private readonly db: SQLiteDatabase;
private readonly maxRetries = 5;
private readonly baseRetryDelayMs = 50;
private readonly codec: Required<Pick<SQLiteValueCodec, "encodeParam" | "decodeColumn">> &
Pick<SQLiteValueCodec, "decodeRow">;
private readonly verbose?: SQLiteVerboseLog;
constructor(db: SQLiteDatabase, options: SQLiteConnectionOptions = {}) {
this.db = db;
this.codec = {
encodeParam: options.valueCodec?.encodeParam ?? encodeColumnValue,
decodeColumn: options.valueCodec?.decodeColumn ?? decodeColumnValue,
decodeRow: options.valueCodec?.decodeRow,
};
this.verbose = options.verbose;
}
async query<R extends object = Record<string, any>>(
sql: string,
params?: unknown[] | Record<string, unknown>
): Promise<{ rows: R[] }> {
const sqliteQuery = rewritePostgresQuery(sql);
const sqliteParams = rewritePostgresParams(params, this.codec.encodeParam);
const statement = this.db.prepare(sqliteQuery);
if (!statement.readonly) {
// this indicates `return_data` is false
// https://github.com/WiseLibs/better-sqlite3/blob/6209be238d6a1b181f516e4e636986604b0f62e1/src/objects/statement.cpp#L134C83-L134C95
throw new Error("The query() method is only statements that return data");
}
const rowsDecoded = await this.runWithRetry(() => {
const rows = statement.all(sqliteParams);
return rows.map((row) =>
decodeRowValues(statement, row, this.codec, this.verbose)
);
});
return { rows: rowsDecoded };
}
async exec(
sql: string,
params?: unknown[] | Record<string, unknown>
): Promise<void> {
const sqliteQuery = rewritePostgresQuery(sql);
const sqliteParams = rewritePostgresParams(params, this.codec.encodeParam);
const statement = this.db.prepare(sqliteQuery);
await this.runWithRetry(() => statement.run(sqliteParams));
}
close(): void {
this.db.close();
}
private async runWithRetry<T>(operation: () => T): Promise<T> {
let attempt = 0;
while (true) {
try {
return operation();
} catch (err) {
if (!isRetryableSQLiteError(err) || attempt >= this.maxRetries) {
throw err;
}
attempt++;
await delay(this.baseRetryDelayMs * attempt);
}
}
}
}
const namedParamPrefix = "p";
function rewritePostgresQuery(text: string): string {
return text
.replace(/\$(\d+)/g, `:${namedParamPrefix}$1`)
.replace(/absurd\.(\w+)/g, "absurd_$1");
}
function rewritePostgresParams(
params: unknown[] | Record<string, unknown> | undefined,
encodeParam: (value: SQLiteBindValue) => SQLiteBindValue
): Record<string, SQLiteBindValue> {
if (!params) {
return {};
}
const rewrittenParams: Record<string, SQLiteBindValue> = {};
if (Array.isArray(params)) {
params.forEach((value, index) => {
const paramKey = `${namedParamPrefix}${index + 1}`;
const encodedParamValue = encodeParam(value as SQLiteBindValue);
rewrittenParams[paramKey] = encodedParamValue;
});
return rewrittenParams;
}
for (const [key, value] of Object.entries(params)) {
rewrittenParams[key] = encodeParam(value as SQLiteBindValue);
}
return rewrittenParams;
}
function decodeRowValues<U extends object, R extends object = any>(
statement: SQLiteStatement,
row: U,
codec: Required<Pick<SQLiteValueCodec, "decodeColumn">> &
Pick<SQLiteValueCodec, "decodeRow">,
verbose?: SQLiteVerboseLog
): R {
const columns = statement.columns();
const rowRecord = row as Record<string, unknown>;
if (codec.decodeRow) {
return codec.decodeRow({
row: rowRecord,
columns,
decodeColumn: codec.decodeColumn,
verbose,
}) as R;
}
const decodedRow: any = {};
for (const column of columns) {
const columnName = column.name;
const columnType = column.type;
const rawValue = rowRecord[columnName];
const decodedValue = codec.decodeColumn({
value: rawValue,
columnName,
columnType,
verbose,
});
decodedRow[columnName] = decodedValue;
}
return decodedRow as R;
}
function decodeColumnValue<V = any>(args: {
value: unknown | V;
columnName: string;
columnType: string | null;
verbose?: SQLiteVerboseLog;
}): V | null {
const { value, columnName, columnType, verbose } = args;
if (value === null || value === undefined) {
return null;
}
if (columnType === null) {
if (typeof value === "string") {
// When column type is not known but the value is string
// try parse it as JSON -- for cases where the column is computed
// e.g. `SELECT json(x) as y from ....`
// FIXME: better type detection
let rv: V;
let isValidJSON = false;
try {
rv = JSON.parse(value) as V;
isValidJSON = true;
} catch (e) {
verbose?.(`Failed to decode string column ${columnName} as JSON`, e);
rv = value as V;
}
if (isValidJSON) {
verbose?.(`Decoded column ${columnName} with null as JSON`);
}
return rv;
}
verbose?.(`Column ${columnName} has null type, returning raw value`);
return value as V;
}
const columnTypeName = columnType.toLowerCase();
if (columnTypeName === "blob") {
// BLOB values are JSON string decoded from JSONB
try {
return JSON.parse(value.toString()) as V;
} catch (e) {
verbose?.(`Failed to decode BLOB column ${columnName} as JSON`, e);
throw e;
}
}
if (columnTypeName === "datetime") {
// SQLite stores datetimes as strings but may return them in different formats
// depending on how they were inserted. Support both ISO strings (from
// Temporal.Instant.toString() or Date.toISOString()) and epoch milliseconds
// (from numeric timestamps).
if (typeof value === "string") {
// Handle ISO string format (e.g., "2024-01-01T00:00:00Z")
return Temporal.Instant.from(value) as V;
}
if (typeof value === "number") {
// Handle epoch milliseconds format
return Temporal.Instant.fromEpochMilliseconds(value) as V;
}
throw new Error(
`Expected datetime column ${columnName} to be a string or number, got ${typeof value}`
);
}
// For other types, return as is
return value as V;
}
function encodeColumnValue(value: any): any {
// Encode Temporal types to ISO string format for SQLite storage
if (value instanceof Temporal.Instant) {
return value.toString();
}
if (value instanceof Temporal.Duration) {
return value.toString();
}
// Legacy support for Date objects
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === "number" && Number.isInteger(value)) {
return value.toString();
}
return value;
}
const sqliteRetryableErrorCodes = new Set(["SQLITE_BUSY", "SQLITE_LOCKED"]);
const sqliteRetryableErrnos = new Set([5, 6]);
function isRetryableSQLiteError(err: unknown): boolean {
if (!err || typeof err !== "object") {
return false;
}
const code = (err as any).code;
if (typeof code === "string") {
for (const retryableCode of sqliteRetryableErrorCodes) {
if (code.startsWith(retryableCode)) {
return true;
}
}
}
const errno = (err as any).errno;
if (typeof errno === "number" && sqliteRetryableErrnos.has(errno)) {
return true;
}
return false;
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}