-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathhrana.ts
More file actions
431 lines (388 loc) · 15.2 KB
/
hrana.ts
File metadata and controls
431 lines (388 loc) · 15.2 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import * as hrana from "@libsql/hrana-client";
import type {
InStatement,
ResultSet,
Transaction,
TransactionMode,
InArgs,
} from "@libsql/core/api";
import { LibsqlError, LibsqlBatchError } from "@libsql/core/api";
import type { SqlCache } from "./sql_cache.js";
import { transactionModeToBegin, ResultSetImpl } from "@libsql/core/util";
export abstract class HranaTransaction implements Transaction {
#mode: TransactionMode;
#version: hrana.ProtocolVersion;
// Promise that is resolved when the BEGIN statement completes, or `undefined` if we haven't executed the
// BEGIN statement yet.
#started: Promise<void> | undefined;
/** @private */
constructor(mode: TransactionMode, version: hrana.ProtocolVersion) {
this.#mode = mode;
this.#version = version;
this.#started = undefined;
}
/** @private */
abstract _getStream(): hrana.Stream;
/** @private */
abstract _getSqlCache(): SqlCache;
abstract close(): void;
abstract get closed(): boolean;
execute(stmt: InStatement): Promise<ResultSet> {
return this.batch([stmt]).then((results) => results[0]);
}
async batch(stmts: Array<InStatement>): Promise<Array<ResultSet>> {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError(
"Cannot execute statements because the transaction is closed",
"TRANSACTION_CLOSED",
);
}
try {
const hranaStmts = stmts.map(stmtToHrana);
let rowsPromises: Array<Promise<hrana.RowsResult | undefined>>;
if (this.#started === undefined) {
// The transaction hasn't started yet, so we need to send the BEGIN statement in a batch with
// `hranaStmts`.
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
const beginStep = batch.step();
const beginPromise = beginStep.run(
transactionModeToBegin(this.#mode),
);
// Execute the `hranaStmts` only if the BEGIN succeeded, to make sure that we don't execute it
// outside of a transaction.
let lastStep = beginStep;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch
.step()
.condition(hrana.BatchCond.ok(lastStep));
if (this.#version >= 3) {
// If the Hrana version supports it, make sure that we are still in a transaction
stmtStep.condition(
hrana.BatchCond.not(
hrana.BatchCond.isAutocommit(batch),
),
);
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
// `this.#started` is resolved successfully only if the batch and the BEGIN statement inside
// of the batch are both successful.
this.#started = batch
.execute()
.then(() => beginPromise)
.then(() => undefined);
try {
await this.#started;
} catch (e) {
// If the BEGIN failed, the transaction is unusable and we must close it. However, if the
// BEGIN suceeds and `hranaStmts` fail, the transaction is _not_ closed.
this.close();
throw e;
}
} else {
if (this.#version < 3) {
// The transaction has started, so we must wait until the BEGIN statement completed to make
// sure that we don't execute `hranaStmts` outside of a transaction.
await this.#started;
} else {
// The transaction has started, but we will use `hrana.BatchCond.isAutocommit()` to make
// sure that we don't execute `hranaStmts` outside of a transaction, so we don't have to
// wait for `this.#started`
}
this._getSqlCache().apply(hranaStmts);
const batch = stream.batch(this.#version >= 3);
let lastStep: hrana.BatchStep | undefined = undefined;
rowsPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step();
if (lastStep !== undefined) {
stmtStep.condition(hrana.BatchCond.ok(lastStep));
}
if (this.#version >= 3) {
stmtStep.condition(
hrana.BatchCond.not(
hrana.BatchCond.isAutocommit(batch),
),
);
}
const rowsPromise = stmtStep.query(hranaStmt);
rowsPromise.catch(() => undefined); // silence Node warning
lastStep = stmtStep;
return rowsPromise;
});
await batch.execute();
}
const resultSets = [];
for (let i = 0; i < rowsPromises.length; i++) {
try {
const rows = await rowsPromises[i];
if (rows === undefined) {
throw new LibsqlBatchError(
"Statement in a transaction was not executed, " +
"probably because the transaction has been rolled back",
i,
"TRANSACTION_CLOSED",
);
}
resultSets.push(resultSetFromHrana(rows));
} catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof LibsqlError) {
throw new LibsqlBatchError(
mappedError.message,
i,
mappedError.code,
mappedError.extendedCode,
mappedError.rawCode,
mappedError.cause instanceof Error
? mappedError.cause
: undefined,
);
}
throw mappedError;
}
}
return resultSets;
} catch (e) {
throw mapHranaError(e);
}
}
async executeMultiple(sql: string): Promise<void> {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError(
"Cannot execute statements because the transaction is closed",
"TRANSACTION_CLOSED",
);
}
try {
if (this.#started === undefined) {
// If the transaction hasn't started yet, start it now
this.#started = stream
.run(transactionModeToBegin(this.#mode))
.then(() => undefined);
try {
await this.#started;
} catch (e) {
this.close();
throw e;
}
} else {
// Wait until the transaction has started
await this.#started;
}
await stream.sequence(sql);
} catch (e) {
throw mapHranaError(e);
}
}
async rollback(): Promise<void> {
try {
const stream = this._getStream();
if (stream.closed) {
return;
}
if (this.#started !== undefined) {
// We don't have to wait for the BEGIN statement to complete. If the BEGIN fails, we will
// execute a ROLLBACK outside of an active transaction, which should be harmless.
} else {
// We did nothing in the transaction, so there is nothing to rollback.
return;
}
// Pipeline the ROLLBACK statement and the stream close.
const promise = stream.run("ROLLBACK").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
} catch (e) {
throw mapHranaError(e);
} finally {
// `this.close()` may close the `hrana.Client`, which aborts all pending stream requests, so we
// must call it _after_ we receive the ROLLBACK response.
// Also note that the current stream should already be closed, but we need to call `this.close()`
// anyway, because it may need to do more cleanup.
this.close();
}
}
async commit(): Promise<void> {
// (this method is analogous to `rollback()`)
try {
const stream = this._getStream();
if (stream.closed) {
throw new LibsqlError(
"Cannot commit the transaction because it is already closed",
"TRANSACTION_CLOSED",
);
}
if (this.#started !== undefined) {
// Make sure to execute the COMMIT only if the BEGIN was successful.
await this.#started;
} else {
return;
}
const promise = stream.run("COMMIT").catch((e) => {
throw mapHranaError(e);
});
stream.closeGracefully();
await promise;
} catch (e) {
throw mapHranaError(e);
} finally {
this.close();
}
}
}
export async function executeHranaBatch(
mode: TransactionMode,
version: hrana.ProtocolVersion,
batch: hrana.Batch,
hranaStmts: Array<hrana.Stmt>,
disableForeignKeys: boolean = false,
): Promise<Array<ResultSet>> {
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=off");
}
const beginStep = batch.step();
const beginPromise = beginStep.run(transactionModeToBegin(mode));
let lastStep = beginStep;
const stmtPromises = hranaStmts.map((hranaStmt) => {
const stmtStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
stmtStep.condition(
hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)),
);
}
const stmtPromise = stmtStep.query(hranaStmt);
lastStep = stmtStep;
return stmtPromise;
});
const commitStep = batch.step().condition(hrana.BatchCond.ok(lastStep));
if (version >= 3) {
commitStep.condition(
hrana.BatchCond.not(hrana.BatchCond.isAutocommit(batch)),
);
}
const commitPromise = commitStep.run("COMMIT");
const rollbackStep = batch
.step()
.condition(hrana.BatchCond.not(hrana.BatchCond.ok(commitStep)));
rollbackStep.run("ROLLBACK").catch((_) => undefined);
if (disableForeignKeys) {
batch.step().run("PRAGMA foreign_keys=on");
}
await batch.execute();
const resultSets = [];
await beginPromise;
for (let i = 0; i < stmtPromises.length; i++) {
try {
const hranaRows = await stmtPromises[i];
if (hranaRows === undefined) {
throw new LibsqlBatchError(
"Statement in a batch was not executed, probably because the transaction has been rolled back",
i,
"TRANSACTION_CLOSED",
);
}
resultSets.push(resultSetFromHrana(hranaRows));
} catch (e) {
if (e instanceof LibsqlBatchError) {
throw e;
}
// Map hrana errors to LibsqlError first, then wrap in LibsqlBatchError
const mappedError = mapHranaError(e);
if (mappedError instanceof LibsqlError) {
throw new LibsqlBatchError(
mappedError.message,
i,
mappedError.code,
mappedError.extendedCode,
mappedError.rawCode,
mappedError.cause instanceof Error
? mappedError.cause
: undefined,
);
}
throw mappedError;
}
}
await commitPromise;
return resultSets;
}
export function stmtToHrana(stmt: InStatement | [string, InArgs?]): hrana.Stmt {
let sql: string;
let args: InArgs | undefined;
if (Array.isArray(stmt)) {
[sql, args] = stmt;
} else if (typeof stmt === "string") {
sql = stmt;
} else {
sql = stmt.sql;
args = stmt.args;
}
const hranaStmt = new hrana.Stmt(sql);
if (args) {
if (Array.isArray(args)) {
hranaStmt.bindIndexes(args);
} else {
for (const [key, value] of Object.entries(args)) {
hranaStmt.bindName(key, value);
}
}
}
return hranaStmt;
}
export function resultSetFromHrana(hranaRows: hrana.RowsResult): ResultSet {
const columns = hranaRows.columnNames.map((c) => c ?? "");
const columnTypes = hranaRows.columnDecltypes.map((c) => c ?? "");
const rows = hranaRows.rows;
const rowsAffected = hranaRows.affectedRowCount;
const lastInsertRowid =
hranaRows.lastInsertRowid !== undefined
? hranaRows.lastInsertRowid
: undefined;
return new ResultSetImpl(
columns,
columnTypes,
rows,
rowsAffected,
lastInsertRowid,
);
}
export function mapHranaError(e: unknown): unknown {
if (e instanceof hrana.ClientError) {
const code = mapHranaErrorCode(e);
// TODO: Parse extendedCode once the SQL over HTTP protocol supports it
return new LibsqlError(e.message, code, undefined, undefined, e);
}
return e;
}
function mapHranaErrorCode(e: hrana.ClientError): string {
if (e instanceof hrana.ResponseError && e.code !== undefined) {
return e.code;
} else if (e instanceof hrana.ProtoError) {
return "HRANA_PROTO_ERROR";
} else if (e instanceof hrana.ClosedError) {
return e.cause instanceof hrana.ClientError
? mapHranaErrorCode(e.cause)
: "HRANA_CLOSED_ERROR";
} else if (e instanceof hrana.WebSocketError) {
return "HRANA_WEBSOCKET_ERROR";
} else if (e instanceof hrana.HttpServerError) {
return "SERVER_ERROR";
} else if (e instanceof hrana.ProtocolVersionError) {
return "PROTOCOL_VERSION_ERROR";
} else if (e instanceof hrana.InternalError) {
return "INTERNAL_ERROR";
} else {
return "UNKNOWN";
}
}