-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdatabase.ts
More file actions
1025 lines (933 loc) · 28.7 KB
/
database.ts
File metadata and controls
1025 lines (933 loc) · 28.7 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ffi from "./ffi.ts";
import { fromFileUrl } from "../deps.ts";
import {
SQLITE3_OPEN_CREATE,
SQLITE3_OPEN_MEMORY,
SQLITE3_OPEN_READONLY,
SQLITE3_OPEN_READWRITE,
SQLITE_BLOB,
SQLITE_FLOAT,
SQLITE_INTEGER,
SQLITE_NULL,
SQLITE_SERIALIZE_NOCOPY,
SQLITE_TEXT,
} from "./constants.ts";
import { readCstr, toCString, unwrap } from "./util.ts";
import {
type RestBindParameters,
Statement,
STATEMENTS_TO_DB,
} from "./statement.ts";
import { type BlobOpenOptions, SQLBlob } from "./blob.ts";
/** Various options that can be configured when opening Database connection. */
export interface DatabaseOpenOptions {
/** Whether to open database only in read-only mode. By default, this is false. */
readonly?: boolean;
/** Whether to create a new database file at specified path if one does not exist already. By default this is true. */
create?: boolean;
/** Raw SQLite C API flags. Specifying this ignores all other options. */
flags?: number;
/** Opens an in-memory database. */
memory?: boolean;
/** Whether to support BigInt columns. False by default, integers larger than 32 bit will be inaccurate. */
int64?: boolean;
/** Apply agressive optimizations that are not possible with concurrent clients. */
unsafeConcurrency?: boolean;
/** Enable or disable extension loading */
enableLoadExtension?: boolean;
/** Whether to parse JSON columns as JS objects. True by default. */
parseJson?: boolean;
}
/** Transaction function created using `Database#transaction`. */
export type Transaction<T extends (...args: any[]) => void> =
& ((...args: Parameters<T>) => ReturnType<T>)
& {
/** BEGIN */
default: Transaction<T>;
/** BEGIN DEFERRED */
deferred: Transaction<T>;
/** BEGIN IMMEDIATE */
immediate: Transaction<T>;
/** BEGIN EXCLUSIVE */
exclusive: Transaction<T>;
database: Database;
};
/**
* Options for user-defined functions.
*
* @link https://www.sqlite.org/c3ref/c_deterministic.html
*/
export interface FunctionOptions {
varargs?: boolean;
deterministic?: boolean;
directOnly?: boolean;
innocuous?: boolean;
subtype?: boolean;
}
/**
* Options for user-defined aggregate functions.
*/
export interface AggregateFunctionOptions extends FunctionOptions {
start: any | (() => any);
step: (aggregate: any, ...args: any[]) => void;
final?: (aggregate: any) => any;
}
const {
sqlite3_open_v2,
sqlite3_close_v2,
sqlite3_changes,
sqlite3_total_changes,
sqlite3_last_insert_rowid,
sqlite3_get_autocommit,
sqlite3_exec,
sqlite3_free,
sqlite3_libversion,
sqlite3_sourceid,
sqlite3_serialize,
sqlite3_complete,
sqlite3_finalize,
sqlite3_result_blob,
sqlite3_result_double,
sqlite3_result_error,
sqlite3_result_int64,
sqlite3_result_null,
sqlite3_result_text,
sqlite3_value_blob,
sqlite3_value_bytes,
sqlite3_value_double,
sqlite3_value_int64,
sqlite3_value_text,
sqlite3_value_type,
sqlite3_create_function,
sqlite3_result_int,
sqlite3_aggregate_context,
sqlite3_enable_load_extension,
sqlite3_load_extension,
sqlite3_backup_init,
sqlite3_backup_step,
sqlite3_backup_finish,
sqlite3_errcode,
sqlite3_update_hook,
} = ffi;
/** SQLite version string */
export const SQLITE_VERSION: string = readCstr(sqlite3_libversion()!);
/** SQLite source ID string */
export const SQLITE_SOURCEID: string = readCstr(sqlite3_sourceid()!);
/**
* Whether the given SQL statement is complete.
*
* @param statement SQL statement string
*/
export function isComplete(statement: string): boolean {
return Boolean(sqlite3_complete(toCString(statement)));
}
export enum SqliteUpdateType {
SQLITE_INSERT = 18,
SQLITE_DELETE = 9,
SQLITE_UPDATE = 23,
}
const BIG_MAX = BigInt(Number.MAX_SAFE_INTEGER);
/**
* Represents a SQLite3 database connection.
*
* Example:
* ```ts
* // Open a database from file, creates if doesn't exist.
* const db = new Database("myfile.db");
*
* // Open an in-memory database.
* const db = new Database(":memory:");
*
* // Open a read-only database.
* const db = new Database("myfile.db", { readonly: true });
*
* // Or open using File URL
* const db = new Database(new URL("./myfile.db", import.meta.url));
* ```
*/
export class Database {
#path: string;
#handle: Deno.PointerValue;
#open = true;
#enableLoadExtension = false;
/** Whether to support BigInt columns. False by default, integers larger than 32 bit will be inaccurate. */
int64: boolean;
/** Whether to parse JSON columns as JS objects. True by default. */
parseJson: boolean;
unsafeConcurrency: boolean;
/** Whether DB connection is open */
get open(): boolean {
return this.#open;
}
/** Unsafe Raw (pointer) to the sqlite object */
get unsafeHandle(): Deno.PointerValue {
return this.#handle;
}
/** Path of the database file. */
get path(): string {
return this.#path;
}
/** Number of rows changed by the last executed statement. */
get changes(): number {
return sqlite3_changes(this.#handle);
}
/** Number of rows changed since the database connection was opened. */
get totalChanges(): number {
return sqlite3_total_changes(this.#handle);
}
/** Gets last inserted Row ID */
get lastInsertRowId(): number {
return Number(sqlite3_last_insert_rowid(this.#handle));
}
/** Whether autocommit is enabled. Enabled by default, can be disabled using BEGIN statement. */
get autocommit(): boolean {
return sqlite3_get_autocommit(this.#handle) === 1;
}
/** Whether DB is in mid of a transaction */
get inTransaction(): boolean {
return this.#open && !this.autocommit;
}
get enableLoadExtension(): boolean {
return this.#enableLoadExtension;
}
set enableLoadExtension(enabled: boolean) {
if (sqlite3_enable_load_extension === null) {
throw new Error(
"Extension loading is not supported by the shared library that was used.",
);
}
const result = sqlite3_enable_load_extension(this.#handle, Number(enabled));
unwrap(result, this.#handle);
this.#enableLoadExtension = enabled;
}
constructor(path: string | URL, options: DatabaseOpenOptions = {}) {
this.#path = path instanceof URL ? fromFileUrl(path) : path;
let flags = 0;
this.int64 = options.int64 ?? false;
this.parseJson = options.parseJson ?? true;
this.unsafeConcurrency = options.unsafeConcurrency ?? false;
if (options.flags !== undefined) {
flags = options.flags;
} else {
if (options.memory) {
flags |= SQLITE3_OPEN_MEMORY;
}
if (options.readonly ?? false) {
flags |= SQLITE3_OPEN_READONLY;
} else {
flags |= SQLITE3_OPEN_READWRITE;
}
if ((options.create ?? true) && !options.readonly) {
flags |= SQLITE3_OPEN_CREATE;
}
}
const pHandle = new BigUint64Array(1);
const result = sqlite3_open_v2(toCString(this.#path), pHandle, flags, null);
this.#handle = Deno.UnsafePointer.create(pHandle[0]);
if (result !== 0) sqlite3_close_v2(this.#handle);
unwrap(result);
if (options.enableLoadExtension) {
this.enableLoadExtension = options.enableLoadExtension;
}
}
/**
* Creates a new Prepared Statement from the given SQL statement.
*
* Example:
* ```ts
* const stmt = db.prepare("SELECT * FROM mytable WHERE id = ?");
*
* for (const row of stmt.all(1)) {
* console.log(row);
* }
* ```
*
* Bind parameters can be either provided as an array of values, or as an object
* mapping the parameter name to the value.
*
* Example:
* ```ts
* const stmt = db.prepare("SELECT * FROM mytable WHERE id = ?");
* const row = stmt.get(1);
*
* // or
*
* const stmt = db.prepare("SELECT * FROM mytable WHERE id = :id");
* const row = stmt.get({ id: 1 });
* ```
*
* Statements are automatically freed once GC catches them, however
* you can also manually free using `finalize` method.
*
* @param sql SQL statement string
* @returns Statement object
*/
prepare<T extends object = Record<string, any>>(sql: string): Statement<T> {
return new Statement<T>(this, sql);
}
/**
* Open a Blob for incremental I/O.
*
* Make sure to close the blob after you are done with it,
* otherwise you will have memory leaks.
*/
openBlob(options: BlobOpenOptions): SQLBlob {
return new SQLBlob(this, options);
}
/**
* Simply executes the SQL statement (supports multiple statements separated by semicolon).
* Returns the number of changes made by last statement.
*
* Example:
* ```ts
* // Create table
* db.exec("create table users (id integer not null, username varchar(20) not null)");
*
* // Inserts
* db.exec("insert into users (id, username) values(?, ?)", id, username);
*
* // Insert with named parameters
* db.exec("insert into users (id, username) values(:id, :username)", { id, username });
*
* // Pragma statements
* db.exec("pragma journal_mode = WAL");
* db.exec("pragma synchronous = normal");
* db.exec("pragma temp_store = memory");
* ```
*
* Under the hood, it uses `sqlite3_exec` if no parameters are given to bind
* with the SQL statement, a prepared statement otherwise.
*/
exec(sql: string, ...params: RestBindParameters): number {
if (params.length === 0) {
const pErr = new BigUint64Array(1);
sqlite3_exec(
this.#handle,
toCString(sql),
null,
null,
new Uint8Array(pErr.buffer),
);
const errPtr = Deno.UnsafePointer.create(pErr[0]);
if (errPtr !== null) {
const err = readCstr(errPtr);
sqlite3_free(errPtr);
throw new Error(err);
}
return sqlite3_changes(this.#handle);
}
const stmt = this.prepare(sql);
stmt.run(...params);
return sqlite3_changes(this.#handle);
}
/** Alias for `exec`. */
run(sql: string, ...params: RestBindParameters): number {
return this.exec(sql, ...params);
}
/** Safely execute SQL with parameters using a tagged template */
sql<T extends Record<string, any> = Record<string, any>>(
strings: TemplateStringsArray,
...parameters: RestBindParameters
): T[] {
const sql = strings.join("?");
const stmt = this.prepare(sql);
return stmt.all(...parameters);
}
/**
* Wraps a callback function in a transaction.
*
* - When function is called, the transaction is started.
* - When function returns, the transaction is committed.
* - When function throws an error, the transaction is rolled back.
*
* Example:
* ```ts
* const stmt = db.prepare("insert into users (id, username) values(?, ?)");
*
* interface User {
* id: number;
* username: string;
* }
*
* const insertUsers = db.transaction((data: User[]) => {
* for (const user of data) {
* stmt.run(user);
* }
* });
*
* insertUsers([
* { id: 1, username: "alice" },
* { id: 2, username: "bob" },
* ]);
*
* // May also use `insertUsers.deferred`, `immediate`, or `exclusive`.
* // They corresspond to using `BEGIN DEFERRED`, `BEGIN IMMEDIATE`, and `BEGIN EXCLUSIVE`.
* // For eg.
*
* insertUsers.deferred([
* { id: 1, username: "alice" },
* { id: 2, username: "bob" },
* ]);
* ```
*/
transaction<T extends (this: Transaction<T>, ...args: any[]) => void>(
fn: T,
): Transaction<T> {
// Based on https://github.com/WiseLibs/better-sqlite3/blob/master/lib/methods/transaction.js
const controller = getController(this);
// Each version of the transaction function has these same properties
const properties = {
default: { value: wrapTransaction(fn, this, controller.default) },
deferred: { value: wrapTransaction(fn, this, controller.deferred) },
immediate: { value: wrapTransaction(fn, this, controller.immediate) },
exclusive: { value: wrapTransaction(fn, this, controller.exclusive) },
database: { value: this, enumerable: true },
};
Object.defineProperties(properties.default.value, properties);
Object.defineProperties(properties.deferred.value, properties);
Object.defineProperties(properties.immediate.value, properties);
Object.defineProperties(properties.exclusive.value, properties);
// Return the default version of the transaction function
return properties.default.value as Transaction<T>;
}
#callbacks = new Set<Deno.UnsafeCallback>();
/**
* Creates a new user-defined function.
*
* Example:
* ```ts
* db.function("add", (a: number, b: number) => a + b);
* db.prepare("select add(1, 2)").value<[number]>()!; // [3]
* ```
*/
function(
name: string,
fn: CallableFunction,
options?: FunctionOptions,
): void {
if (sqlite3_create_function === null) {
throw new Error(
"User-defined functions are not supported by the shared library that was used.",
);
}
const cb = new Deno.UnsafeCallback(
{
parameters: ["pointer", "i32", "pointer"],
result: "void",
} as const,
(ctx, nArgs, pArgs) => {
const argptr = new Deno.UnsafePointerView(pArgs!);
const args: any[] = [];
for (let i = 0; i < nArgs; i++) {
const arg = Deno.UnsafePointer.create(
argptr.getBigUint64(i * 8),
);
const type = sqlite3_value_type(arg);
switch (type) {
case SQLITE_INTEGER: {
const value = sqlite3_value_int64(arg);
if (value < -BIG_MAX || value > BIG_MAX) {
args.push(value);
} else {
args.push(Number(value));
}
break;
}
case SQLITE_FLOAT:
args.push(sqlite3_value_double(arg));
break;
case SQLITE_TEXT:
args.push(
new TextDecoder().decode(
new Uint8Array(
Deno.UnsafePointerView.getArrayBuffer(
sqlite3_value_text(arg)!,
sqlite3_value_bytes(arg),
),
),
),
);
break;
case SQLITE_BLOB:
args.push(
new Uint8Array(
Deno.UnsafePointerView.getArrayBuffer(
sqlite3_value_blob(arg)!,
sqlite3_value_bytes(arg),
),
),
);
break;
case SQLITE_NULL:
args.push(null);
break;
default:
throw new Error(`Unknown type: ${type}`);
}
}
let result: any;
try {
result = fn(...args);
} catch (err) {
const buf = new TextEncoder().encode(
err instanceof Error ? err.message : String(err),
);
sqlite3_result_error(ctx, buf, buf.byteLength);
return;
}
if (result === undefined || result === null) {
sqlite3_result_null(ctx);
} else if (typeof result === "boolean") {
sqlite3_result_int(ctx, result ? 1 : 0);
} else if (typeof result === "number") {
if (Number.isSafeInteger(result)) {
sqlite3_result_int64(ctx, BigInt(result));
} else sqlite3_result_double(ctx, result);
} else if (typeof result === "bigint") {
sqlite3_result_int64(ctx, result);
} else if (typeof result === "string") {
const buffer = new TextEncoder().encode(result);
sqlite3_result_text(ctx, buffer, buffer.byteLength, 0n);
} else if (result instanceof Uint8Array) {
sqlite3_result_blob(ctx, result as BufferSource, result.length, -1n);
} else {
const buffer = new TextEncoder().encode(
`Invalid return value: ${Deno.inspect(result)}`,
);
sqlite3_result_error(ctx, buffer, buffer.byteLength);
}
},
);
let flags = 1;
if (options?.deterministic) {
flags |= 0x000000800;
}
if (options?.directOnly) {
flags |= 0x000080000;
}
if (options?.subtype) {
flags |= 0x000100000;
}
if (options?.directOnly) {
flags |= 0x000200000;
}
const err = sqlite3_create_function(
this.#handle,
toCString(name),
options?.varargs ? -1 : fn.length,
flags,
null,
cb.pointer,
null,
null,
);
unwrap(err, this.#handle);
this.#callbacks.add(cb as Deno.UnsafeCallback);
}
/**
* Creates a new user-defined aggregate function.
*/
aggregate(name: string, options: AggregateFunctionOptions): void {
if (
sqlite3_aggregate_context === null || sqlite3_create_function === null
) {
throw new Error(
"User-defined functions are not supported by the shared library that was used.",
);
}
const contexts = new Map<number | bigint, any>();
const cb = new Deno.UnsafeCallback(
{
parameters: ["pointer", "i32", "pointer"],
result: "void",
} as const,
(ctx, nArgs, pArgs) => {
const aggrCtx = sqlite3_aggregate_context(ctx, 8);
const aggrPtr = Deno.UnsafePointer.value(aggrCtx);
let aggregate;
if (contexts.has(aggrPtr)) {
aggregate = contexts.get(aggrPtr);
} else {
aggregate = typeof options.start === "function"
? options.start()
: options.start;
contexts.set(aggrPtr, aggregate);
}
const argptr = new Deno.UnsafePointerView(pArgs!);
const args: any[] = [];
for (let i = 0; i < nArgs; i++) {
const arg = Deno.UnsafePointer.create(
argptr.getBigUint64(i * 8),
);
const type = sqlite3_value_type(arg);
switch (type) {
case SQLITE_INTEGER: {
const value = sqlite3_value_int64(arg);
if (value < -BIG_MAX || value > BIG_MAX) {
args.push(value);
} else {
args.push(Number(value));
}
break;
}
case SQLITE_FLOAT:
args.push(sqlite3_value_double(arg));
break;
case SQLITE_TEXT:
args.push(
new TextDecoder().decode(
new Uint8Array(
Deno.UnsafePointerView.getArrayBuffer(
sqlite3_value_text(arg)!,
sqlite3_value_bytes(arg),
),
),
),
);
break;
case SQLITE_BLOB:
args.push(
new Uint8Array(
Deno.UnsafePointerView.getArrayBuffer(
sqlite3_value_blob(arg)!,
sqlite3_value_bytes(arg),
),
),
);
break;
case SQLITE_NULL:
args.push(null);
break;
default:
throw new Error(`Unknown type: ${type}`);
}
}
let result: any;
try {
result = options.step(aggregate, ...args);
} catch (err) {
const buf = new TextEncoder().encode(
err instanceof Error ? err.message : String(err),
);
sqlite3_result_error(ctx, buf, buf.byteLength);
return;
}
contexts.set(aggrPtr, result);
},
);
const cbFinal = new Deno.UnsafeCallback(
{
parameters: ["pointer"],
result: "void",
} as const,
(ctx) => {
const aggrCtx = sqlite3_aggregate_context(ctx, 0);
const aggrPtr = Deno.UnsafePointer.value(aggrCtx);
const aggregate = contexts.get(aggrPtr);
contexts.delete(aggrPtr);
let result: any;
try {
result = options.final ? options.final(aggregate) : aggregate;
} catch (err) {
const buf = new TextEncoder().encode(
err instanceof Error ? err.message : String(err),
);
sqlite3_result_error(ctx, buf, buf.byteLength);
return;
}
if (result === undefined || result === null) {
sqlite3_result_null(ctx);
} else if (typeof result === "boolean") {
sqlite3_result_int(ctx, result ? 1 : 0);
} else if (typeof result === "number") {
if (Number.isSafeInteger(result)) {
sqlite3_result_int64(ctx, BigInt(result));
} else sqlite3_result_double(ctx, result);
} else if (typeof result === "bigint") {
sqlite3_result_int64(ctx, result);
} else if (typeof result === "string") {
const buffer = new TextEncoder().encode(result);
sqlite3_result_text(ctx, buffer, buffer.byteLength, 0n);
} else if (result instanceof Uint8Array) {
sqlite3_result_blob(ctx, result as BufferSource, result.length, -1n);
} else {
const buffer = new TextEncoder().encode(
`Invalid return value: ${Deno.inspect(result)}`,
);
sqlite3_result_error(ctx, buffer, buffer.byteLength);
}
},
);
let flags = 1;
if (options?.deterministic) {
flags |= 0x000000800;
}
if (options?.directOnly) {
flags |= 0x000080000;
}
if (options?.subtype) {
flags |= 0x000100000;
}
if (options?.directOnly) {
flags |= 0x000200000;
}
const err = sqlite3_create_function(
this.#handle,
toCString(name),
options?.varargs ? -1 : options.step.length - 1,
flags,
null,
null,
cb.pointer,
cbFinal.pointer,
);
unwrap(err, this.#handle);
this.#callbacks.add(cb as Deno.UnsafeCallback);
this.#callbacks.add(cbFinal as Deno.UnsafeCallback);
}
/**
* Loads an SQLite extension library from the named file.
*/
loadExtension(file: string, entryPoint?: string): void {
if (sqlite3_load_extension === null) {
throw new Error(
"Extension loading is not supported by the shared library that was used.",
);
}
if (!this.enableLoadExtension) {
throw new Error("Extension loading is not enabled");
}
const pzErrMsg = new BigUint64Array(1);
const result = sqlite3_load_extension(
this.#handle,
toCString(file),
entryPoint ? toCString(entryPoint) : null,
pzErrMsg,
);
const pzErrPtr = Deno.UnsafePointer.create(
pzErrMsg[0],
);
if (pzErrPtr !== null) {
const pzErr = readCstr(pzErrPtr);
sqlite3_free(pzErrPtr);
throw new Error(pzErr);
}
unwrap(result, this.#handle);
}
#updateHook?: Deno.UnsafeCallback<{
readonly parameters: readonly [
"pointer",
"i32",
"pointer",
"pointer",
"i64",
];
readonly result: "void";
}>;
/**
* Sets a callback function that is invoked whenever a row is updated, inserted or deleted.
*
* The callback function receives the type of update (insert, update, or delete), the database name, the table name, and the row ID of the row being modified.
*
* Example:
* ```ts
* db.setUpdateHook((type, dbName, tableName, rowId) => {
* console.log(`Row with ID ${rowId} in table ${tableName} was modified in database ${dbName}. Update type: ${type}`);
* });
* ```
*/
setUpdateHook(
hook:
| ((
type: SqliteUpdateType,
dbName: string,
tableName: string,
rowId: bigint,
) => void)
| null,
): void {
if (hook === null) {
sqlite3_update_hook(this.#handle, null, null);
if (this.#updateHook) {
this.#updateHook.close();
this.#updateHook = undefined;
}
return;
}
const updateHook = new Deno.UnsafeCallback(
{
parameters: ["pointer", "i32", "pointer", "pointer", "i64"],
result: "void",
} as const,
(_, type, pDbName, pTableName, rowId) => {
const dbName = readCstr(pDbName!);
const tableName = readCstr(pTableName!);
hook(type, dbName, tableName, rowId);
},
);
sqlite3_update_hook(this.#handle, updateHook.pointer, null);
if (this.#updateHook) {
this.#updateHook.close();
}
this.#updateHook = updateHook;
}
/**
* Closes the database connection.
*
* Calling this method more than once is no-op.
*/
close(): void {
if (!this.#open) return;
for (const [stmt, db] of STATEMENTS_TO_DB) {
if (db === this.#handle) {
sqlite3_finalize(stmt);
STATEMENTS_TO_DB.delete(stmt);
}
}
for (const cb of this.#callbacks) {
cb.close();
}
if (this.#updateHook) {
this.#updateHook.close();
}
unwrap(sqlite3_close_v2(this.#handle));
this.#open = false;
}
/**
* @param dest The destination database connection.
* @param name Destination database name. "main" for main database, "temp" for temporary database, or the name specified after the AS keyword in an ATTACH statement for an attached database.
* @param pages The number of pages to copy. If it is negative, all remaining pages are copied (default).
*/
backup(dest: Database, name = "main", pages = -1): void {
const backup = sqlite3_backup_init(
dest.#handle,
toCString(name),
this.#handle,
toCString("main"),
);
if (backup) {
unwrap(sqlite3_backup_step(backup, pages));
unwrap(sqlite3_backup_finish(backup));
} else {
unwrap(sqlite3_errcode(dest.#handle), dest.#handle);
}
}
#serialize(name: string, flags: number): [Deno.PointerValue, number] {
if (sqlite3_serialize === null) {
throw new Error(
"Database serialization is not supported by the shared library that was used.",
);
}
const size = new BigInt64Array(1);
const ptr = sqlite3_serialize(this.#handle, toCString(name), size, flags);
const bytes = size[0];
if (bytes < 0) {
throw new Error("Failed to serialize database");
}
if (bytes > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new RangeError("Database is too large to represent in JavaScript");
}
return [ptr, Number(bytes)];
}
/**
* Export a database schema as serialized bytes.
*
* For on-disk databases this is equivalent to the database file contents.
* For in-memory databases this is the same byte sequence that would be
* written if the database were backed up to disk.
*
* @param name Schema name to export. Defaults to "main".
*/
export(name = "main"): Uint8Array {
const [ptr, size] = this.#serialize(name, 0);
if (ptr === null) {
throw new Error("Failed to serialize database");
}
try {
return new Uint8Array(
Deno.UnsafePointerView.getArrayBuffer(ptr, size).slice(0),
);
} finally {
sqlite3_free(ptr);
}
}
/**
* Get the serialized size of a database schema in bytes.
*
* @param name Schema name to measure. Defaults to "main".
*/
size(name = "main"): number {
return this.#serialize(name, SQLITE_SERIALIZE_NOCOPY)[1];
}
[Symbol.for("Deno.customInspect")](): string {
return `SQLite3.Database { path: ${this.path} }`;
}
}
const controllers = new WeakMap();
// Return the database's cached transaction controller, or create a new one
const getController = (db: Database) => {
let controller = controllers.get(db);
if (!controller) {
const shared = {
commit: db.prepare("COMMIT"),
rollback: db.prepare("ROLLBACK"),
savepoint: db.prepare("SAVEPOINT `\t_bs3.\t`"),
release: db.prepare("RELEASE `\t_bs3.\t`"),
rollbackTo: db.prepare("ROLLBACK TO `\t_bs3.\t`"),
};
controllers.set(
db,
controller = {
default: Object.assign(
{ begin: db.prepare("BEGIN") },
shared,
),
deferred: Object.assign(
{ begin: db.prepare("BEGIN DEFERRED") },
shared,
),
immediate: Object.assign(
{ begin: db.prepare("BEGIN IMMEDIATE") },
shared,
),
exclusive: Object.assign(
{ begin: db.prepare("BEGIN EXCLUSIVE") },
shared,
),
},
);
}
return controller;
};
// Return a new transaction function by wrapping the given function
const wrapTransaction = <T extends (...args: any[]) => void>(
fn: T,
db: Database,
{ begin, commit, rollback, savepoint, release, rollbackTo }: any,
) =>
function sqliteTransaction(...args: Parameters<T>): ReturnType<T> {