Repository navigation
Expand file tree
/
Copy pathlibsql-provider.test.ts
More file actions
3939 lines (3458 loc) · 174 KB
/
Copy pathlibsql-provider.test.ts
File metadata and controls
3939 lines (3458 loc) · 174 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
/**
* libSQL provider, end to end (issue #424 Phase 5)
*
* Every payload below was captured on 2026-08-27 from BOTH deployments this one
* type-id reaches: a self-hosted `ghcr.io/tursodatabase/libsql-server` (sqld
* 0.24.33, SQLite 3.47.0) and a Turso Cloud database in `aws-eu-west-1`.
* `globalThis.fetch` is REPLACED per test and restored afterwards - `mock.module()`
* is refused, being process-wide in bun and able to poison sibling files - so the
* real provider, the real introspection and the real Hrana transport all execute
* here and only the server is fake.
*
* Five measured behaviours drive what is asserted:
*
* 1. A FAILED STATEMENT IS AN HTTP 200 with the failure inside `results[]`, so
* `response.ok` is never the test.
* 2. THE TWO DEPLOYMENTS WORD THE SAME REFUSAL DIFFERENTLY - "unsupported
* statement: VACUUM" against "SQL not allowed statement: VACUUM" - under one
* code, so nothing may key on the wording.
* 3. `GET /version` IS A SQLD ROUTE TURSO CLOUD DOES NOT HAVE, and a deployment
* that publishes no version is not a broken one.
* 4. AN AUTH FAILURE USES A DIFFERENT ENVELOPE (`{"error": "<string>"}`) and
* answers 401 with no token, 400 with a malformed one.
* 5. `dbstat` ANSWERS ON BOTH, so per-table bytes here are measured - which
* `bun:sqlite` cannot do at all.
*/
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { assertObjectSurface } from "../../helpers/object-surface-conformance";
import {
AuthenticationError,
ConnectionError,
DatabaseConfigError,
DatabaseError,
ExecutionProfileError,
QueryError,
} from "@/lib/db/errors";
import {
containerDepth,
isCountUnavailable,
isSourcePartUnavailable,
kindHasColumns,
sourceBoundTruncationReason,
} from "@/lib/db/object-kinds";
import { LibSQLProvider } from "@/lib/db/providers/sql/libsql";
import { SQLITE_CREATE_TABLE } from "@/lib/db/providers/sql/sqlite-create-table";
import { buildResultExport } from "@/lib/export/result-export";
import { countLibSQLObjects, type LibSQLObjectReader } from "@/lib/db/providers/sql/libsql/objects";
import type {
DatabaseConnection,
DatabaseProvider,
ObjectKindSpec,
ProviderExecutionContext,
ReadOnlyStatementBudget,
} from "@/lib/db/types";
import { readFileSync } from "node:fs";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { comparePaths } from "@/lib/db/object-path";
import { MCP_STATEMENT_READ } from "@/lib/db/compatibility";
import { acquireExecutionProfileProvider, clearProviderCache, type ExecutionProfile } from "@/lib/db/factory";
import { readQueryFormsOf } from "@/lib/db/providers/sql/read-query-forms";
import type { McpConnectionContext } from "@/lib/mcp/context";
import { MCP_ENGINE_ERROR_PREFIX, MCP_UNTRUSTED_NOTICE } from "@/lib/mcp/output";
import { runStatement, type McpStatementInput } from "@/lib/mcp/tools/run-statement";
import { mcpStatementArm, type McpStatementArm } from "@/lib/mcp/tools/statement-arms";
import type { ManagedConnection } from "@/lib/seed";
import { RUN_READ_QUERY_ENGINES, RunReadQueryInputSchema, runReadQuery } from "../../helpers/run-read-query";
// ============================================================================
// Harness
// ============================================================================
interface FetchCall {
url: string;
body: string | null;
}
const originalFetch = globalThis.fetch;
let calls: FetchCall[] = [];
/** A row set as Hrana encodes one: declared columns, positional typed values. */
type Cell = Record<string, unknown>;
function result(cols: [string, string | null][], rows: Cell[][], extra: Record<string, unknown> = {}): Cell {
return {
type: "ok",
response: {
type: "execute",
result: {
cols: cols.map(([name, decltype]) => ({ name, decltype })),
rows,
affected_row_count: 0,
last_insert_rowid: null,
replication_index: "1",
rows_read: rows.length,
rows_written: 0,
query_duration_ms: 0.107,
...extra,
},
},
};
}
function text(value: string): Cell {
return { type: "text", value };
}
function int(value: number | string): Cell {
return { type: "integer", value: String(value) };
}
function failure(message: string, code: string): Cell {
return { type: "error", error: { message, code } };
}
/**
* The fixture both deployments answered for, verbatim in shape: two tables, one
* user index, one foreign key, `dbstat` populated.
*/
function answerFor(sql: string): Cell {
if (/FROM sqlite_master\s+WHERE type = 'table'\s+AND name NOT LIKE/.test(sql) && /COUNT/.test(sql)) {
return result([["table_count", null]], [[int(2)]]);
}
if (/FROM sqlite_master\s+WHERE type = 'table'/.test(sql)) {
return result([["name", "TEXT"]], [[text("probe_customers")], [text("probe_orders")]]);
}
if (/type = 'index' AND name NOT LIKE/.test(sql)) return result([["index_count", null]], [[int(1)]]);
if (/SELECT name, tbl_name FROM sqlite_master WHERE type = 'index'/.test(sql)) {
return result(
[
["name", "TEXT"],
["tbl_name", "TEXT"],
],
[[text("idx_country"), text("probe_customers")]],
);
}
if (/FROM dbstat/.test(sql)) {
return result(
[
["name", "TEXT"],
["bytes", null],
],
[
[text("probe_customers"), int(8192)],
[text("idx_country"), int(4096)],
[text("probe_orders"), int(270336)],
],
);
}
if (/COUNT\(\*\) AS row_count FROM "probe_customers"/.test(sql)) return result([["row_count", null]], [[int(3)]]);
if (/COUNT\(\*\) AS row_count FROM "probe_orders"/.test(sql)) return result([["row_count", null]], [[int(2000)]]);
if (/pragma_table_info\('probe_customers'\)/.test(sql)) {
return result(
[
["cid", null],
["name", null],
["type", null],
["notnull", null],
["dflt_value", null],
["pk", null],
],
[
[int(0), text("id"), text("INTEGER"), int(1), { type: "null" }, int(1)],
[int(1), text("country"), text("TEXT"), int(0), { type: "null" }, int(0)],
],
);
}
if (/pragma_table_info\('probe_orders'\)/.test(sql)) {
return result(
[
["cid", null],
["name", null],
["type", null],
["notnull", null],
["dflt_value", null],
["pk", null],
],
[[int(0), text("id"), text("INTEGER"), int(0), { type: "null" }, int(1)]],
);
}
if (/pragma_index_list\('probe_customers'\)/.test(sql)) {
return result(
[
["seq", null],
["name", null],
["unique", null],
["origin", null],
],
[
[int(0), text("idx_country"), int(1), text("c")],
[int(1), text("sqlite_autoindex_probe_customers_1"), int(1), text("pk")],
],
);
}
if (/pragma_index_info\('idx_country'\)/.test(sql)) {
return result(
[
["seqno", null],
["cid", null],
["name", null],
],
[[int(0), int(1), text("country")]],
);
}
if (/pragma_foreign_key_list\('probe_orders'\)/.test(sql)) {
return result(
[
["id", null],
["seq", null],
["table", null],
["from", null],
["to", null],
],
[[int(0), int(0), text("probe_customers"), text("customer_id"), text("id")]],
);
}
if (/pragma_page_count/.test(sql)) return result([["size_bytes", null]], [[int(282624)]]);
if (/sqlite_version\(\)/.test(sql)) return result([["version", null]], [[text("3.47.0")]]);
if (/PRAGMA integrity_check/.test(sql)) return result([["integrity_check", null]], [[text("ok")]]);
if (/PRAGMA journal_mode/.test(sql)) return result([["journal_mode", null]], [[text("wal")]]);
if (/^SELECT 1$/.test(sql)) return result([["1", null]], [[int(1)]]);
return result([], []);
}
/**
* What the server does with one pipeline: an answer per statement, then a close.
*
* The bound arguments are handed over as well as the statement, because the object
* surface binds the object NAME rather than embedding it (`pragma_table_xinfo(?, ?)`
* is one statement for every object), so a server that saw only the SQL could not
* answer per object - and could not tell a name bind from a container one, which is
* the whole point of the two-level test below.
*/
type Server = (sql: string, args: unknown[]) => Cell;
let server: Server = answerFor;
let versionRoute: () => Response = () => new Response("sqld 0.24.33 (f8fb14f3 2026-08-11)", { status: 200 });
function installFetch(): void {
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const body = init?.body === undefined ? null : String(init.body);
calls.push({ url, body });
if (url.endsWith("/version")) return Promise.resolve(versionRoute());
const requests = (JSON.parse(body ?? "{}") as { requests?: { type: string; stmt?: Statement }[] }).requests;
const results = (requests ?? [])
.filter((request) => request.type === "execute")
.map((request) => server(String(request.stmt?.sql), boundArgs(request.stmt)));
return Promise.resolve(
new Response(JSON.stringify({ baton: null, base_url: null, results: [...results, { type: "ok" }] }), {
status: 200,
headers: { "content-type": "application/json" },
}),
);
}) as unknown as typeof fetch;
}
function connection(overrides: Partial<DatabaseConnection> = {}): DatabaseConnection {
return {
id: "libsql-probe",
name: "libSQL probe",
type: "libsql",
host: "127.0.0.1",
port: 18081,
createdAt: new Date("2026-08-27T00:00:00.000Z"),
...overrides,
};
}
async function connected(overrides: Partial<DatabaseConnection> = {}): Promise<LibSQLProvider> {
const provider = new LibSQLProvider(connection(overrides));
await provider.connect();
return provider;
}
/** One statement as it left this process: what was sent, and what was bound into it. */
interface Statement {
sql?: string;
args?: { value?: unknown }[];
}
/** The values bound into one statement, in order, with the wire encoding unwrapped. */
function boundArgs(statement: Statement | undefined): unknown[] {
return (statement?.args ?? []).map((arg) => arg.value);
}
/** Every statement the provider sent, with its bindings, in order. */
function sentCalls(): { sql: string; args: unknown[] }[] {
return calls
.filter((call) => call.body !== null)
.flatMap((call) => {
const requests = (JSON.parse(call.body as string) as { requests?: { stmt?: Statement }[] }).requests ?? [];
return requests
.filter((request) => request.stmt !== undefined)
.map((request) => ({ sql: String(request.stmt?.sql), args: boundArgs(request.stmt) }));
});
}
/** Every statement the provider sent, in order. */
function sentStatements(): string[] {
return sentCalls().map((call) => call.sql);
}
beforeEach(() => {
calls = [];
server = answerFor;
versionRoute = () => new Response("sqld 0.24.33 (f8fb14f3 2026-08-11)", { status: 200 });
installFetch();
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
// ============================================================================
// Configuration and connection
// ============================================================================
describe("LibSQLProvider configuration", () => {
test("refuses a connection with neither a host nor a URL", () => {
expect(() => new LibSQLProvider(connection({ host: undefined }))).toThrow(DatabaseConfigError);
});
test("resolves a libsql:// URL into host, port and token", async () => {
const provider = await connected({
host: undefined,
port: undefined,
connectionString: "libsql://libredb-probe-424-cevheri.aws-eu-west-1.turso.io?authToken=jwt-123",
});
// Port 443 is the https default, which the URL leaves out of its serialization.
expect(calls[0]?.url).toBe("https://libredb-probe-424-cevheri.aws-eu-west-1.turso.io/v2/pipeline");
await provider.disconnect();
});
test("connects with the cheapest statement there is, not a health route", async () => {
await connected();
expect(sentStatements()).toEqual(["SELECT 1"]);
});
test("connecting twice reuses the transport rather than probing again", async () => {
const provider = await connected();
await provider.connect();
expect(sentStatements()).toEqual(["SELECT 1"]);
await provider.disconnect();
});
test("reports a missing token as an authentication failure, not a connection one", async () => {
// 401, and the envelope is `{"error": "<string>"}` rather than the statement
// shape - captured from Turso Cloud with no Authorization header.
globalThis.fetch = (() =>
Promise.resolve(
new Response(
JSON.stringify({ error: "Unauthorized: `unauthorized access attempt on database: empty JWT token`" }),
{
status: 401,
},
),
)) as unknown as typeof fetch;
await expect(new LibSQLProvider(connection()).connect()).rejects.toBeInstanceOf(AuthenticationError);
});
test("reports a malformed token as an authentication failure even though the status is 400", async () => {
globalThis.fetch = (() =>
Promise.resolve(
new Response(JSON.stringify({ error: "JWT error: InvalidToken" }), { status: 400 }),
)) as unknown as typeof fetch;
await expect(new LibSQLProvider(connection({ password: "notatoken" })).connect()).rejects.toBeInstanceOf(
AuthenticationError,
);
});
test("reports an unreachable server as a connection failure naming host and port", async () => {
globalThis.fetch = (() => Promise.reject(new Error("connect ECONNREFUSED"))) as unknown as typeof fetch;
const failed = new LibSQLProvider(connection()).connect();
await expect(failed).rejects.toBeInstanceOf(ConnectionError);
await expect(failed).rejects.toThrow(/connect ECONNREFUSED/);
});
});
/**
* Which credential a connection sends, through the real provider: `connect()` builds the transport from the
* resolved connection, so this is where a `user` either reaches the header or is lost on the way.
*
* sqld's legacy HTTP Basic auth (`SQLD_HTTP_AUTH="basic:<base64(user:password)>"`) pairs a user with a password,
* so a connection that names a user sends the pair as Basic. A `libsql://` URL authenticates with the token it
* carries, so a `user` beside it is ignored and the URL path keeps sending a bearer token.
*/
describe("LibSQLProvider credentials", () => {
/**
* The Authorization header of every request from here on, in order, null where none was sent. It wraps the
* fake server `installFetch` put in place rather than replacing it, so the provider still gets real answers,
* and `afterEach` puts the real `fetch` back underneath both.
*/
function authorizationHeaders(): (string | null)[] {
const seen: (string | null)[] = [];
const answering = globalThis.fetch;
globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
seen.push(new Headers(init?.headers).get("authorization"));
return answering(input, init);
}) as unknown as typeof fetch;
return seen;
}
test("sends a user and password as HTTP Basic on the connect probe and on every query after it", async () => {
const seen = authorizationHeaders();
const provider = await connected({ user: "libsql", password: "libsql-pass" });
await provider.query("SELECT 1");
expect(seen).toEqual(["Basic bGlic3FsOmxpYnNxbC1wYXNz", "Basic bGlic3FsOmxpYnNxbC1wYXNz"]);
await provider.disconnect();
});
test("keeps the bearer token when the connection names no user", async () => {
const seen = authorizationHeaders();
const provider = await connected({ password: "tok-123" });
expect(seen).toEqual(["Bearer tok-123"]);
await provider.disconnect();
});
test("keeps a libsql:// URL's token as the bearer credential when the connection also names a user", async () => {
const seen = authorizationHeaders();
const provider = await connected({
host: undefined,
port: undefined,
user: "ignored",
connectionString: "libsql://libredb-probe-424-cevheri.aws-eu-west-1.turso.io?authToken=jwt-123",
});
expect(seen).toEqual(["Bearer jwt-123"]);
await provider.disconnect();
});
test("keeps a libsql:// URL's own password as the bearer credential, its user name ignored", async () => {
const seen = authorizationHeaders();
const provider = await connected({
host: undefined,
port: undefined,
user: "also-ignored",
connectionString: "libsql://url-user:p%40ss@db.turso.io",
});
expect(seen).toEqual(["Bearer p@ss"]);
await provider.disconnect();
});
test("drops the user of a connection whose connection string does not parse, so it sends no Basic header", async () => {
// The string is ignored and the host and port fields are used (docs/BACKLOG.md D232), but the user is dropped
// as on every connection-string path, so the password still goes out as a bearer token.
const seen = authorizationHeaders();
const provider = await connected({ user: "dropped", password: "tok-456", connectionString: "not a url" });
expect(seen).toEqual(["Bearer tok-456"]);
await provider.disconnect();
});
test("reports a Basic credential the server refused as an authentication failure", async () => {
// The body sqld's source builds for a refused Basic credential, AuthError::BasicRejected inside
// Error::AuthError, answered 401 (`libsql-server/src/error.rs` and `src/auth/errors.rs` at
// libsql-server-v0.24.32). Read from the source rather than captured live; the provider keys on the status.
globalThis.fetch = (() =>
Promise.resolve(
new Response(
JSON.stringify({ error: "Unauthorized: `The `Basic` HTTP authentication credentials were rejected`" }),
{ status: 401 },
),
)) as unknown as typeof fetch;
await expect(
new LibSQLProvider(connection({ user: "libsql", password: "wrong" })).connect(),
).rejects.toBeInstanceOf(AuthenticationError);
});
});
// ============================================================================
// Capabilities
// ============================================================================
describe("LibSQLProvider capabilities", () => {
test("offers only the two maintenance operations the server accepts", () => {
const capabilities = new LibSQLProvider(connection()).getCapabilities();
expect(capabilities.maintenanceOperations).toEqual(["reindex", "check"]);
// Measured on BOTH deployments: each of these is refused by the server's own
// statement allowlist, so a control for it could only ever fail.
expect(capabilities.maintenanceOperations).not.toContain("vacuum");
expect(capabilities.maintenanceOperations).not.toContain("analyze");
});
test("reads EXPLAIN the way SQLite does, and takes a pasted URL", () => {
const capabilities = new LibSQLProvider(connection()).getCapabilities();
expect(capabilities.explainFormat).toBe("sqlite-queryplan");
expect(capabilities.supportsConnectionString).toBe(true);
expect(capabilities.defaultPort).toBe(8080);
});
test("pages with LIMIT n OFFSET m, the grammar it shares with SQLite", () => {
// #816: declared true because `prepareQuery` really applies a positive offset.
// Measured across every type-id in tests/unit/db/result-pagination-capability.test.ts.
const provider = new LibSQLProvider(connection());
expect(provider.getCapabilities().supportsResultPagination).toBe(true);
const pageTwo = provider.prepareQuery("SELECT * FROM t", { limit: 50, offset: 50 });
expect(pageTwo.query).toBe("SELECT * FROM t LIMIT 50 OFFSET 50");
expect(pageTwo.wasLimited).toBe(true);
});
test("declares SQLite's create-table grammar, the same object, because it embeds SQLite", () => {
// #1822: shared by import, never by a type-id branch; docs/providers/sqlite.md, "Create Table form".
expect(new LibSQLProvider(connection()).getCapabilities().createTable).toBe(SQLITE_CREATE_TABLE);
});
test("declares no transaction, because the stream closes with each statement", () => {
expect(new LibSQLProvider(connection()).getCapabilities().supportsTransactions).toBe(false);
});
test("tells the reader there is no statement history to enable", () => {
expect(new LibSQLProvider(connection()).getLabels().slowQueriesEmptyState).toBe(
"libSQL keeps no statistics about finished statements, so there is nothing to enable.",
);
});
});
// ============================================================================
// Queries
// ============================================================================
describe("LibSQLProvider query", () => {
test("returns rows, declared fields and the types the engine declared", async () => {
const provider = await connected();
const answer = await provider.query("SELECT name, type FROM sqlite_master WHERE type = 'table'");
expect(answer.rows).toEqual([{ name: "probe_customers" }, { name: "probe_orders" }]);
expect(answer.fields).toEqual(["name"]);
expect(answer.columnTypes).toEqual({ name: "TEXT" });
await provider.disconnect();
});
test("a repeated or empty column name keeps its own value and type", async () => {
// The shape sqld answers for `SELECT o.id, c.id, 1 AS "" ...`: two columns declared `id`
// and one declared with an empty name. Keyed by name, the second id replaced the first.
server = () =>
result(
[
["id", "INTEGER"],
["id", "INTEGER"],
["", null],
],
[[int(100), int(1), int(7)]],
);
const provider = await connected();
const answer = await provider.query('SELECT o.id, c.id, 1 AS "" FROM probe_orders o JOIN probe_customers c');
expect(answer.fields).toEqual(["id", "id (2)", "(No column name)"]);
expect(answer.rows).toEqual([{ id: 100, "id (2)": 1, "(No column name)": 7 }]);
expect(answer.columnTypes).toEqual({ id: "INTEGER", "id (2)": "INTEGER" });
await provider.disconnect();
});
test("omits columnTypes entirely when the engine declared none", async () => {
const provider = await connected();
const answer = await provider.query("SELECT sqlite_version() AS version");
expect(answer.rows).toEqual([{ version: "3.47.0" }]);
expect(answer.columnTypes).toBeUndefined();
await provider.disconnect();
});
test("counts a write by what the engine says it changed", async () => {
server = () => result([], [], { affected_row_count: 3, last_insert_rowid: "12" });
const provider = await connected();
const answer = await provider.query("DELETE FROM probe_orders WHERE id < 4");
expect(answer.rowCount).toBe(3);
expect(answer.rows).toEqual([]);
await provider.disconnect();
});
test("binds positional parameters as the protocol requires", async () => {
const provider = await connected();
await provider.query("SELECT * FROM probe_customers WHERE country = ?", ["tr"]);
const sent = JSON.parse(calls[1]?.body ?? "{}") as { requests: { stmt?: { args?: unknown[] } }[] };
expect(sent.requests[0]?.stmt?.args).toEqual([{ type: "text", value: "tr" }]);
await provider.disconnect();
});
test("hands a past-2^53 key back as its exact digits and binds those digits back as the integer", async () => {
// The whole inline-grid round trip through the real provider: read the key out
// of a row, then send that very value back in the WHERE clause. Measured against
// sqld 0.24.33 on 2026-09-18: bound as TEXT this matched 0 rows on a column with
// no affinity (BLOB or undeclared), so the editor reported nothing changed;
// bound as an integer it matches the one row, on every column declaration.
server = () => result([["id", null]], [[int("9007199254740993")]]);
const provider = await connected();
const read = await provider.query('SELECT id FROM "probe_orders"');
const key = read.rows[0]?.id;
expect(key).toBe("9007199254740993");
server = () => result([], [], { affected_row_count: 1 });
await provider.query('UPDATE "probe_orders" SET note = ? WHERE id = ?', ["duzenlendi", key]);
const sent = JSON.parse(calls.at(-1)?.body ?? "{}") as { requests: { stmt?: { args?: unknown[] } }[] };
expect(sent.requests[0]?.stmt?.args).toEqual([
{ type: "text", value: "duzenlendi" },
{ type: "integer", value: "9007199254740993" },
]);
await provider.disconnect();
});
test("hands a BLOB to the wire as bytes, and the SQL export writes it back as X'..'", async () => {
// Measured against sqld 0.24.33 on 2026-10-04: `x'DEADBEEF00FF'` answers
// `{"type":"blob","base64":"3q2+7wD/"}` and `x''` answers base64 "". Before the
// transport decoded to a Buffer, the grid received `{"0":222,...}` and the SQL export
// wrote that object as quoted text.
server = () =>
result(
[
["bin", "BLOB"],
["empty", "BLOB"],
],
[
[
{ type: "blob", base64: "3q2+7wD/" },
{ type: "blob", base64: "" },
],
],
);
const provider = await connected();
const read = await provider.query("SELECT bin, empty FROM t_types");
const wire = JSON.parse(JSON.stringify(read.rows)) as Record<string, unknown>[];
expect(wire).toEqual([
{ bin: { type: "Buffer", data: [0xde, 0xad, 0xbe, 0xef, 0x00, 0xff] }, empty: { type: "Buffer", data: [] } },
]);
const exported = buildResultExport("sql-insert", {
rows: wire,
fields: read.fields,
tabName: "t",
dialect: "libsql",
});
expect(exported.content).toBe(`INSERT INTO t ("bin", "empty") VALUES (X'deadbeef00ff', X'');`);
await provider.disconnect();
});
test("still binds an ordinary key that happens to be all digits as text", async () => {
const provider = await connected();
await provider.query('UPDATE "probe_customers" SET country = ? WHERE code = ?', ["tr", "007"]);
const sent = JSON.parse(calls.at(-1)?.body ?? "{}") as { requests: { stmt?: { args?: unknown[] } }[] };
expect(sent.requests[0]?.stmt?.args).toEqual([
{ type: "text", value: "tr" },
{ type: "text", value: "007" },
]);
await provider.disconnect();
});
test("surfaces SQLite's own wording for a statement the engine rejected", async () => {
const provider = await connected();
server = () => failure("SQLite error: no such table: nope", "SQLITE_UNKNOWN");
const failed = provider.query("SELECT * FROM nope");
await expect(failed).rejects.toBeInstanceOf(QueryError);
await expect(failed).rejects.toThrow("SQLite error: no such table: nope");
await provider.disconnect();
});
test("surfaces a refusal the same way whichever deployment worded it", async () => {
// sqld says "unsupported statement"; Turso Cloud says "SQL not allowed
// statement". Both are SQL_PARSE_ERROR and both must reach the user verbatim.
for (const message of [
"SQL string could not be parsed: unsupported statement: VACUUM",
"SQL not allowed statement: VACUUM",
]) {
server = answerFor;
const provider = await connected();
server = () => failure(message, "SQL_PARSE_ERROR");
await expect(provider.query("VACUUM")).rejects.toThrow(message);
await provider.disconnect();
}
});
});
// ============================================================================
// Schema
// ============================================================================
// ============================================================================
// Monitoring
// ============================================================================
describe("LibSQLProvider monitoring", () => {
test("names the server version and the SQLite it embeds", async () => {
const provider = await connected();
const overview = await provider.getOverview();
expect(overview.version).toBe("sqld 0.24.33 (f8fb14f3 2026-08-11) (SQLite 3.47.0)");
expect(overview.databaseSize).toBe("276 KB");
expect(overview.tableCount).toBe(2);
expect(overview.indexCount).toBe(1);
expect(overview.maxConnections).toBe(0);
await provider.disconnect();
});
test("shows the SQLite version alone on Turso Cloud, where /version does not exist", async () => {
versionRoute = () => new Response(JSON.stringify({ error: 'route not found: ["version"]' }), { status: 404 });
const provider = await connected();
expect((await provider.getOverview()).version).toBe("SQLite 3.47.0");
await provider.disconnect();
});
test("reports the integrity check and journal mode, and no invented cache ratio", async () => {
const provider = await connected();
const health = await provider.getHealth();
expect(health.databaseSize).toBe("276 KB");
expect(health.cacheHitRatio).toBe("N/A");
expect(health.slowQueries.map((entry) => entry.query)).toEqual(["Integrity: OK", "Journal Mode: wal"]);
expect(health.activeSessions).toEqual([]);
await provider.disconnect();
});
test("counts zero deadlocks as a fact about the engine and measures nothing else", async () => {
const provider = await connected();
expect(await provider.getPerformanceMetrics()).toEqual({ deadlocks: 0 });
expect(await provider.getSlowQueries()).toEqual([]);
expect(await provider.getActiveSessions()).toEqual([]);
await provider.disconnect();
});
test("splits measured pages between tables and their indexes", async () => {
const provider = await connected();
const stats = await provider.getTableStats();
expect(stats[0]).toMatchObject({ tableName: "probe_customers", tableSizeBytes: 8192, indexSizeBytes: 4096 });
expect(stats[1]).toMatchObject({ tableName: "probe_orders", rowCount: 2000, totalSizeBytes: 270336 });
await provider.disconnect();
});
test("reports the user index with its columns and measured bytes", async () => {
const provider = await connected();
expect(await provider.getIndexStats()).toEqual([
{
schemaName: "main",
tableName: "probe_customers",
indexName: "idx_country",
columns: ["country"],
isUnique: true,
isPrimary: false,
indexSize: "4 KB",
indexSizeBytes: 4096,
scans: 0,
},
]);
await provider.disconnect();
});
test("reports the one database as storage, from its own page counters", async () => {
const provider = await connected();
expect(await provider.getStorageStats()).toEqual([{ name: "main", size: "276 KB", sizeBytes: 282624 }]);
await provider.disconnect();
});
test("a token that expires mid-session fails every monitoring read and the integrity check as authentication", async () => {
const provider = await connected();
globalThis.fetch = (() =>
Promise.resolve(
new Response(JSON.stringify({ error: "JWT error: ExpiredSignature" }), { status: 401 }),
)) as unknown as typeof fetch;
const reads: [string, () => Promise<unknown>][] = [
["getHealth", () => provider.getHealth()],
["getOverview", () => provider.getOverview()],
["getTableStats", () => provider.getTableStats()],
["getIndexStats", () => provider.getIndexStats()],
["getStorageStats", () => provider.getStorageStats()],
["runMaintenance", () => provider.runMaintenance("check")],
];
for (const [name, read] of reads) {
const refusal = await read().catch((error: unknown) => error);
expect([name, refusal instanceof AuthenticationError]).toEqual([name, true]);
expect((refusal as Error).message).toContain("ExpiredSignature");
}
});
});
// ============================================================================
// Maintenance
// ============================================================================
describe("LibSQLProvider runMaintenance", () => {
test("runs a bare REINDEX, and a targeted one against the named table", async () => {
const provider = await connected();
calls = [];
expect(await provider.runMaintenance("reindex")).toMatchObject({ success: true });
expect(await provider.runMaintenance("reindex", "probe_customers")).toMatchObject({ success: true });
// #772: a container is ignored - the connection resolves names against its one
// attached database, exactly as sqlite.ts does.
expect(await provider.runMaintenance("reindex", "probe_customers", "main")).toMatchObject({ success: true });
expect(sentStatements()).toEqual(["REINDEX", 'REINDEX "probe_customers"', 'REINDEX "probe_customers"']);
await provider.disconnect();
});
test("reads the integrity check's ANSWER rather than its status", async () => {
const provider = await connected();
expect(await provider.runMaintenance("check")).toMatchObject({ success: true, message: "ok" });
await provider.disconnect();
});
test("reports a corrupt database as a failed check, even though the statement succeeded", async () => {
server = (sql) =>
/integrity_check/.test(sql)
? result([["integrity_check", null]], [[text("*** in database main ***")]])
: answerFor(sql);
const provider = await connected();
expect(await provider.runMaintenance("check")).toMatchObject({
success: false,
message: "*** in database main ***",
});
await provider.disconnect();
});
test("refuses VACUUM here rather than relaying the server's refusal", async () => {
const provider = await connected();
calls = [];
const refused = provider.runMaintenance("vacuum");
await expect(refused).rejects.toThrow(/do not accept VACUUM/);
// Nothing was sent: the refusal is ours, so the user is not told about a
// statement they never asked for.
expect(sentStatements()).toEqual([]);
await provider.disconnect();
});
test("refuses ANALYZE and OPTIMIZE for the same measured reason", async () => {
const provider = await connected();
await expect(provider.runMaintenance("analyze")).rejects.toThrow(/do not accept ANALYZE/);
await expect(provider.runMaintenance("optimize")).rejects.toThrow(/do not accept OPTIMIZE/);
await provider.disconnect();
});
});
// ============================================================================
// Object surface (#789, task 13)
// ----------------------------------------------------------------------------
// The fixture below is a CATALOG rather than a set of canned answers, and that is
// the whole design. Every row was captured on 2026-09-11 from a live
// `ghcr.io/tursodatabase/libsql-server:v0.24.33` (sqld 0.24.33 `40a151bd`, SQLite
// 3.45.1) built by the DDL in `docs/providers/libsql.md`, in the engine's own
// order, and the fake server applies only the predicates the statement it receives
// actually spells. So dropping a predicate from the provider does not fall through
// to an unmatched regex and a canned row set: it widens the population the way it
// would against the real server, which is what makes the mutations below die for
// the right reason.
//
// The two facts that separate this engine from `sqlite.ts` are both measured and
// both drive assertions here:
//
// - sqld REFUSES `VACUUM`, `ANALYZE`, `PRAGMA query_only`, `ATTACH DATABASE` and
// `CREATE TEMP TABLE`, but ACCEPTS `CREATE VIEW temp.<name>` - so a `temp` object
// shadowing a `main` one is reachable and the schema restriction is load-bearing.
// - `CREATE FUNCTION ... LANGUAGE wasm` is refused by sqld's own parser
// ("syntax error around L1:16: `FUNCTION`"), so NO routine kind is declared.
// ============================================================================
/** One row of `PRAGMA table_list`, verbatim and in the engine's own order. */
const TABLE_LIST_ROWS: readonly { schema: string; name: string; type: string }[] = [
{ schema: "main", name: "notes_content", type: "shadow" },
{ schema: "main", name: "legacy_ref", type: "table" },
{ schema: "main", name: "legacy", type: "table" },
{ schema: "main", name: "order_summary", type: "view" },
{ schema: "main", name: "sqlite_schema", type: "table" },
{ schema: "main", name: "badges", type: "table" },
{ schema: "main", name: "orders", type: "table" },
{ schema: "main", name: "shipments", type: "table" },
{ schema: "main", name: "regions", type: "table" },
{ schema: "main", name: "notes_config", type: "shadow" },
{ schema: "main", name: "sqlite_sequence", type: "table" },
{ schema: "main", name: "archive", type: "table" },
{ schema: "main", name: "notes_idx", type: "shadow" },
{ schema: "main", name: "customers", type: "table" },
{ schema: "main", name: "sqliteXledger", type: "table" },
{ schema: "main", name: "notes_docsize", type: "shadow" },
{ schema: "main", name: "notes", type: "virtual" },
{ schema: "main", name: "notes_data", type: "shadow" },
{ schema: "temp", name: "sqlite_temp_schema", type: "table" },
];
/**
* The same catalog with a `temp` VIEW live, which sqld really does accept.
*
* `CREATE TEMP VIEW` is refused by sqld's parser and `CREATE VIEW temp.orders` is
* not, measured. The row is here so the schema restriction can be mutated: without
* `t.schema = ?` the listing answers `orders` TWICE, two objects with one path,
* which is the uniqueness the tree addresses rows by.
*/
const TABLE_LIST_WITH_TEMP: readonly { schema: string; name: string; type: string }[] = [
...TABLE_LIST_ROWS,
{ schema: "temp", name: "orders", type: "view" },
];
/**
* The same catalog plus the two names that separate the ENGINE's order from this process's.
*
* Measured on a live sqld 0.24.33: `ORDER BY t.name` answers `U+E000` before `U+1F600`,
* because SQLite's BINARY collation is the UTF-8 BYTE order (`EE 80 80` below
* `F0 9F 98 80`), while a JavaScript sort compares UTF-16 code units and puts the surrogate
* `0xD83D` first. So a bounded read's MEMBERSHIP is the server's and the ORDER of the
* answer is ours, and neither can be dropped without the other showing it.
*/
const TABLE_LIST_WITH_EXOTIC: readonly { schema: string; name: string; type: string }[] = [
...TABLE_LIST_ROWS,
{ schema: "main", name: "\uE000", type: "table" },
{ schema: "main", name: "\u{1F600}", type: "table" },
];
/**
* One row of `sqlite_schema`, verbatim and in the engine's own order.
*
* RE-CAPTURED 2026-09-13 against a self-hosted sqld 0.24.33 (40a151bd 2025-12-19) started
* from `docker/sqlite-init/02-libsql-object-fixture.sql`, which is where that DDL lives now:
* it was a fenced block in `docs/providers/libsql.md` and nowhere else, so nobody could
* re-run the measurement it stood for (D53, standing ruling 5i). The row ORDER is the
* earlier capture's and is kept; what the re-capture adds is the `badges` TRIGGER below and
* the definition text in `SQLITE_SCHEMA_SQL`.
*/
const SQLITE_SCHEMA_ROWS: readonly { type: string; name: string; tbl_name: string }[] = [
{ type: "table", name: "customers", tbl_name: "customers" },
{ type: "table", name: "sqlite_sequence", tbl_name: "sqlite_sequence" },
{ type: "table", name: "orders", tbl_name: "orders" },
{ type: "table", name: "regions", tbl_name: "regions" },
{ type: "table", name: "archive", tbl_name: "archive" },
{ type: "table", name: "sqliteXledger", tbl_name: "sqliteXledger" },
{ type: "table", name: "notes", tbl_name: "notes" },
{ type: "table", name: "notes_data", tbl_name: "notes_data" },
{ type: "table", name: "notes_idx", tbl_name: "notes_idx" },
{ type: "table", name: "notes_content", tbl_name: "notes_content" },
{ type: "table", name: "notes_docsize", tbl_name: "notes_docsize" },
{ type: "table", name: "notes_config", tbl_name: "notes_config" },
{ type: "view", name: "order_summary", tbl_name: "order_summary" },
{ type: "index", name: "idx_orders_customer", tbl_name: "orders" },
{ type: "index", name: "idx_orders_placed", tbl_name: "orders" },
{ type: "index", name: "idx_customers_name", tbl_name: "customers" },
{ type: "trigger", name: "orders_stamp", tbl_name: "orders" },
{ type: "trigger", name: "order_summary_guard", tbl_name: "order_summary" },
// A TRIGGER whose name is ALSO a TABLE's, which sqld accepts (measured, and the file
// engine accepts it too). It is here for the Source read: `SELECT sql FROM sqlite_schema
// WHERE name = 'badges'` answers TWO rows and the table's comes first, so a read taking
// its `type` from what the name matched rather than from the KIND hands a reader the
// table's DDL under a trigger's address. Every other name in this catalog resolves to one
// row whatever the type filter does.
{ type: "trigger", name: "badges", tbl_name: "badges" },
{ type: "table", name: "legacy", tbl_name: "legacy" },
{ type: "table", name: "legacy_ref", tbl_name: "legacy_ref" },
{ type: "table", name: "shipments", tbl_name: "shipments" },
{ type: "table", name: "badges", tbl_name: "badges" },
// The implicit index behind `code TEXT UNIQUE` on a ROWID table, and it IS a row of
// `sqlite_schema` rather than an invisible structure. Measured: a WITHOUT ROWID table
// (`regions`) produces an autoindex that `pragma_index_list` publishes and
// `sqlite_schema` does NOT, which is exactly the shape that hid this row from an
// earlier fixture and made the reserved-name predicate look untestable here.
{ type: "index", name: "sqlite_autoindex_badges_1", tbl_name: "badges" },
];
/**
* `sqlite_schema.sql` per row, keyed `"<type>/<name>"`, from the SAME live capture (#789).