Repository navigation
Expand file tree
/
Copy pathquery.test.ts
More file actions
2241 lines (1953 loc) · 91.7 KB
/
Copy pathquery.test.ts
File metadata and controls
2241 lines (1953 loc) · 91.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 { describe, test, expect, mock, beforeEach, afterEach, spyOn } from "bun:test";
import { installStandInVocabulary, STAND_IN_TYPE } from "../../helpers/stand-in-vocabulary";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { createMockRequest, parseResponseJSON } from "../../helpers/mock-next";
import { createMockProvider } from "../../helpers/mock-provider";
import { discoverRoutes } from "../../security/helpers/discover-routes";
import { clearRateLimitState } from "@/lib/api/rate-limit";
import { agentReadSqlInput } from "@/lib/db/operations/statement-guard";
import { OXIA_MAX_TEXT_BYTES } from "@/lib/db/providers/keyvalue/oxia/constants";
import {
SNOWFLAKE_ERROR_SENTENCES,
SnowflakeError,
toDatabaseError as toSnowflakeDatabaseError,
} from "@/lib/db/providers/sql/snowflake/errors";
import {
QueryError,
TimeoutError,
DatabaseError,
DatabaseConfigError,
ConnectionError,
AuthenticationError,
PoolExhaustedError,
QueryCancelledError,
isDatabaseError,
isConnectionError,
isQueryError,
isTimeoutError,
isAuthenticationError,
isRetryableError,
mapDatabaseError,
} from "@/lib/db/errors";
import type { DatabaseConnection } from "@/lib/types";
import type { QueryEventRow } from "@/lib/query-events/types";
import type { QueryEventBatchWrite, QueryEventWriteFailure } from "@/lib/query-events/postgres-sink";
// ─── Mock provider ──────────────────────────────────────────────────────────
const mockProvider = createMockProvider();
const mockGetOrCreateProvider = mock(async () => mockProvider);
/** The unconnected provider a route reads a declaration from, `provider-meta`'s way (#457). */
const mockCreateDatabaseProvider = mock(async (_connection: unknown) => mockProvider);
const mockGetSession = mock(
async (): Promise<{ role: string; username: string } | null> => ({ role: "admin", username: "admin" }),
);
// ─── Mock auth + seed resolution BEFORE importing the route ─────────────────
mock.module("@/lib/auth", () => ({
getSession: mockGetSession,
signJWT: mock(async () => "mock-token"),
verifyJWT: mock(async () => null),
login: mock(async () => {}),
logout: mock(async () => {}),
}));
/** What `resolveConnection` answers instead of the default below, for the governance tests at the end of this file. */
let resolveConnectionOverride: ((body: Record<string, unknown>) => Promise<unknown>) | undefined;
mock.module("@/lib/seed/resolve-connection", () => {
class SeedConnectionError extends Error {
constructor(
message: string,
public statusCode: number,
public code?: string,
) {
super(message);
this.name = "SeedConnectionError";
}
}
return {
resolveConnection: mock(async (body: Record<string, unknown>) => {
if (resolveConnectionOverride !== undefined) return resolveConnectionOverride(body);
if (!body.connection && !body.connectionId) {
throw new SeedConnectionError("Either connection or connectionId is required", 400);
}
// A managed id resolves from the OPERATOR's config and everything the caller attached to the
// request is discarded — which the real `resolveConnection` does for the same reason (a `seed:`
// id is the operator's namespace, GHSA-3wh2-8x78). This is exactly the path the top-level
// `database` field has to survive: nothing the caller sent on a connection reaches this object.
if (typeof body.connectionId === "string" && body.connectionId.startsWith("seed:")) {
return {
id: body.connectionId,
name: "Seed Redis",
type: "redis",
host: "seed-host",
port: 6379,
database: "0",
};
}
return body.connection;
}),
SeedConnectionError,
};
});
// ─── Mock @/lib/db BEFORE importing the route ───────────────────────────────
mock.module("@/lib/db", () => ({
getOrCreateProvider: mockGetOrCreateProvider,
createDatabaseProvider: mockCreateDatabaseProvider,
removeProvider: mock(),
clearProviderCache: mock(),
getProviderCacheStats: mock(),
QueryError,
TimeoutError,
DatabaseError,
DatabaseConfigError,
ConnectionError,
AuthenticationError,
PoolExhaustedError,
QueryCancelledError,
isDatabaseError,
isConnectionError,
isQueryError,
isTimeoutError,
isAuthenticationError,
isRetryableError,
mapDatabaseError,
BaseDatabaseProvider: class {},
}));
// ─── The query event insert, faked: the sink, the builder and the admission gate stay real ──────
const realPostgresSink = await import("@/lib/query-events/postgres-sink");
/** Every row the sink handed to an insert that took it. */
const insertedEvents: QueryEventRow[] = [];
/** When set, every insert fails this way and keeps its batch queued, so the sink backs off. */
let insertFailure: QueryEventWriteFailure | null = null;
mock.module("@/lib/query-events/postgres-sink", () => ({
...realPostgresSink,
writeQueryEventBatch: mock(async (rows: readonly QueryEventRow[]): Promise<QueryEventBatchWrite> => {
if (insertFailure !== null) return { settled: 0, rejections: [], failure: insertFailure };
insertedEvents.push(...rows);
return { settled: rows.length, rejections: [], failure: null };
}),
}));
// ─── Import route handler AFTER mocking ─────────────────────────────────────
const { POST } = await import("@/app/api/db/query/route");
// The real check the factory runs first (#1089). This file replaces `@/lib/db`, the route's own import,
// and not `@/lib/db/factory`, so the test below can run the real refusal inside the replaced factory.
const { assertReadOnlyHonoured } = await import("@/lib/db/factory");
// ─── Fixtures ───────────────────────────────────────────────────────────────
const validConnection = {
id: "test-1",
name: "Test DB",
type: "postgres",
host: "localhost",
port: 5432,
database: "testdb",
};
// ─── Tests ──────────────────────────────────────────────────────────────────
describe("POST /api/db/query", () => {
beforeEach(() => {
clearRateLimitState();
mockGetOrCreateProvider.mockClear();
(mockProvider.query as ReturnType<typeof mock>).mockClear();
(mockProvider.prepareQuery as ReturnType<typeof mock>).mockClear();
mockGetSession.mockClear();
mockGetSession.mockImplementation(
async (): Promise<{ role: string; username: string } | null> => ({ role: "admin", username: "admin" }),
);
});
// `count` is what the engine answered to the statement that ran, which asks for one row past the
// 50-row page (#1440): 50 is a page that ended exactly full, 51 is a page with a next one.
for (const [count, providerLimited, expectedMore, expectedReturned, expectedLimited] of [
[2, false, false, 2, false],
[50, false, false, 50, false],
[51, false, true, 50, true],
[2, true, false, 2, true],
] as const) {
test(`reports a ${count}-row answer with provider cut=${providerLimited} accurately`, async () => {
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: Array.from({ length: count }, (_, i) => ({ id: i + 1 })),
fields: ["id"],
rowCount: count,
executionTime: 1,
pagination: { limit: 50, offset: 0, hasMore: false, totalReturned: count, wasLimited: providerLimited },
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ pagination: unknown }>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({
limit: 50,
offset: 0,
hasMore: expectedMore,
totalReturned: expectedReturned,
wasLimited: expectedLimited,
});
});
}
// `JSON.stringify` writes NaN and both infinities as `null`, so a stored NaN reached the
// grid as SQL NULL (PostgreSQL 18.6 `'NaN'::float8`, 2026-10-04). They travel as words.
test("answers NaN and the infinities as words, not as null", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [
{
f: Number.NaN,
r: Number.POSITIVE_INFINITY,
n: Number.NEGATIVE_INFINITY,
arr: [Number.NaN, 2],
ok: 1.5,
z: null,
},
],
fields: ["f", "r", "n", "arr", "ok", "z"],
rowCount: 1,
executionTime: 1,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM floats" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ rows: unknown[] }>(res);
expect(res.status).toBe(200);
expect(data.rows).toEqual([{ f: "NaN", r: "Infinity", n: "-Infinity", arr: ["NaN", 2], ok: 1.5, z: null }]);
});
test("returns 401 when no session exists", async () => {
mockGetSession.mockResolvedValueOnce(null);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(401);
expect(data.error).toContain("Authentication required");
});
test("a queryId that is not a string returns 400 (#1364)", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT 1", queryId: 42 },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toBe("queryId must be a string");
});
test("passes queryId to provider when cancellation is supported", async () => {
const providerWithCancel = {
...createMockProvider(),
cancelQuery: mock(async () => true),
};
mockGetOrCreateProvider.mockResolvedValueOnce(providerWithCancel as never);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users", queryId: "query-42" },
});
const res = await POST(req as never);
expect(res.status).toBe(200);
expect(providerWithCancel.query).toHaveBeenCalledWith(
"SELECT * FROM users LIMIT 50",
undefined,
"query-42",
expect.any(String),
);
});
test("answers a multi-result text with its first set and sends no copy of the others (#1312)", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [{ a: 1 }],
fields: ["a"],
rowCount: 1,
executionTime: 1,
resultSets: [
{ rows: [{ a: 1 }], fields: ["a"] },
{ rows: [{ b: 2 }], fields: ["b"] },
],
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "EXEC sp_help" },
});
const data = await parseResponseJSON<Record<string, unknown>>(await POST(req as never));
expect(data.rows).toEqual([{ a: 1 }]);
expect(Object.hasOwn(data, "resultSets")).toBe(false);
});
// ── Bound parameters (#290) ───────────────────────────────────────────────
//
// A generated statement (the inline row editor) sends its values here instead of
// writing them into the SQL, so a value cannot close a string literal and have
// the rest read as statement text. The route is the last hop before the driver's
// bind path, so it is also where an unbindable value is refused.
test("binds the request's parameters instead of running the statement unbound", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: {
connection: validConnection,
sql: `UPDATE users SET "name" = $1 WHERE "id" = $2`,
params: ["\\' WHERE 1=1 -- ", 7],
},
});
const res = await POST(req as never);
expect(res.status).toBe(200);
expect(mockProvider.query).toHaveBeenCalledWith(
`UPDATE users SET "name" = $1 WHERE "id" = $2 LIMIT 50`,
["\\' WHERE 1=1 -- ", 7],
undefined,
expect.any(String),
);
});
test("binds parameters alongside a queryId when cancellation is supported", async () => {
const providerWithCancel = {
...createMockProvider(),
cancelQuery: mock(async () => true),
};
mockGetOrCreateProvider.mockResolvedValueOnce(providerWithCancel as never);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: {
connection: validConnection,
sql: `UPDATE users SET "name" = $1 WHERE "id" = $2`,
params: ["Alice", 7],
queryId: "query-42",
},
});
const res = await POST(req as never);
expect(res.status).toBe(200);
expect(providerWithCancel.query).toHaveBeenCalledWith(
`UPDATE users SET "name" = $1 WHERE "id" = $2 LIMIT 50`,
["Alice", 7],
"query-42",
expect.any(String),
);
});
test("returns 400 for a parameter the driver cannot bind as a scalar", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users WHERE id = $1", params: [{ nested: true }] },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toContain("params");
expect(mockProvider.query).not.toHaveBeenCalled();
});
test("returns 200 with rows and pagination for valid query", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
rows: unknown[];
fields: string[];
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.rows).toBeDefined();
expect(data.fields).toBeDefined();
expect(data.pagination).toBeDefined();
expect(data.pagination.limit).toBe(50);
expect(data.pagination.offset).toBe(0);
expect(data.pagination.wasLimited).toBe(false);
});
test("carries the engine's notices beside the result (#1401)", async () => {
// Apache Cloudberry 2.1.0's own WARNING for a foreign key it accepts and will not enforce.
const warning = {
message:
"referential integrity (FOREIGN KEY) constraints are not supported in Apache Cloudberry, will not be enforced",
code: "01000",
severity: "WARNING",
};
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [],
fields: [],
rowCount: 0,
executionTime: 1,
warnings: [warning],
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: {
connection: validConnection,
sql: "ALTER TABLE orders ADD CONSTRAINT orders_cust_fk FOREIGN KEY (customer_id) REFERENCES customers(id)",
},
});
const data = await parseResponseJSON<{ warnings?: unknown[] }>(await POST(req as never));
expect(data.warnings).toEqual([warning]);
});
test("returns 400 when connection is missing", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { sql: "SELECT 1" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toContain("required");
});
// A `sql` that is present but not a string reached the provider and answered 500 with the TypeError's own text.
// It is refused in words before any provider resolves, a falsy one (0, false) included.
for (const [label, sql] of [
["a number", 123],
["an object", { text: "SELECT 1" }],
["an array", ["SELECT 1"]],
["true", true],
["zero", 0],
["false", false],
] as const) {
test(`answers 400 when sql is ${label}, before any provider resolves`, async () => {
mockGetOrCreateProvider.mockClear();
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toBe("sql must be a string");
expect(mockGetOrCreateProvider).not.toHaveBeenCalled();
});
}
test("an empty sql keeps the answer of a missing one", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toBe("Connection and query are required");
});
test("a null sql keeps the answer of a missing one", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: null },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toBe("Connection and query are required");
});
test("returns 400 when sql is missing", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toContain("required");
});
// #1089. The factory refuses a readOnly the engine cannot keep before it builds anything, and this
// route answers that refusal as the configuration error it is. The replaced factory runs the real
// check on the connection the route resolved, so a route that dropped or rewrote the field on the way
// would fail here too.
test("an inline read-only connection on an engine that does not enforce the mode answers 400 and runs nothing", async () => {
mockCreateDatabaseProvider.mockClear();
mockGetOrCreateProvider.mockImplementationOnce(async (...args: unknown[]) => {
assertReadOnlyHonoured(args[0] as DatabaseConnection);
return mockProvider;
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: { ...validConnection, readOnly: true }, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(400);
expect(data.code).toBe("CONFIG_ERROR");
expect(data.error).toBe(
"readOnly: true is refused for postgres: its provider does not enforce a read-only mode, so the connection would open able to write. Remove readOnly from the connection, or connect with a database role that cannot write.",
);
expect(mockGetOrCreateProvider).toHaveBeenCalledTimes(1);
expect(mockCreateDatabaseProvider).not.toHaveBeenCalled();
expect(mockProvider.query).not.toHaveBeenCalled();
});
test("returns 400 for QueryError", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
new QueryError('syntax error at or near "FORM"'),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FORM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(400);
expect(data.error).toContain("syntax error");
expect(data.code).toBe("QUERY_ERROR");
});
test("a syntax error that names the bound Studio added says so; one that does not is left alone (SF-022)", async () => {
const send = async (message: string) => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(new QueryError(message));
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM D_PARENT WHERE" },
});
const res = await POST(req as never);
return { status: res.status, data: await parseResponseJSON<{ error: string; code: string }>(res) };
};
const named = await send("SQL compilation error: syntax error line 1 at position 29 unexpected 'LIMIT'.");
expect(named.status).toBe(400);
expect(named.data.code).toBe("QUERY_ERROR");
expect(named.data.error).toEndWith(
"unexpected 'LIMIT'. Studio added the clause LIMIT 50 to this statement to bound its rows, so a position or token this error names may be in that clause rather than in your text.",
);
expect((await send("Object 'D_PARENT' does not exist or not authorized.")).data.error).toBe(
"Object 'D_PARENT' does not exist or not authorized.",
);
});
test("returns 504 for TimeoutError", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
new TimeoutError("Query timed out after 30000ms"),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT pg_sleep(60)" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(504);
expect(data.error).toContain("timed out");
});
test("a Snowflake statement past its deadline answers 400 QUERY_ERROR, not a retryable timeout, so the person is not invited to run it again", async () => {
// A TimeoutError is retryable, and a second run would start the statement on the warehouse a second time; the Snowflake
// provider cancels the statement at its deadline and throws a QueryError naming the timeout instead.
const sql = "SELECT SYSTEM$WAIT(700000)";
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
toSnowflakeDatabaseError(new SnowflakeError("query", SNOWFLAKE_ERROR_SENTENCES.deadline(604_800)), sql),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(400);
expect(res.status).not.toBe(504);
expect(data.code).toBe("QUERY_ERROR");
expect(data.error).toBe(SNOWFLAKE_ERROR_SENTENCES.deadline(604_800));
});
test("returns 500 for DatabaseError", async () => {
const dbError = new DatabaseError("Internal database failure", "postgres", "INTERNAL_ERROR");
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(dbError);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT 1" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(500);
expect(data.error).toBe("Internal database failure");
expect(data.code).toBe("INTERNAL_ERROR");
});
test("returns 499 for cancelled query", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
new QueryCancelledError("Query was cancelled"),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM large_table" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(499);
expect(data.code).toBe("QUERY_CANCELLED");
expect(data.error).toContain("cancelled");
});
test("a PostgreSQL statement timeout answers 504 TIMEOUT_ERROR, not 499 (#1145)", async () => {
// The end-to-end shape of the bug: the provider throws the mapped error a real
// `statement_timeout` produces, and the route must answer a retryable 504 timeout
// rather than the 499 QUERY_CANCELLED that kept the previous rows on screen and
// never told the user the statement timed out.
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
mapDatabaseError(new Error("canceling statement due to statement timeout"), "postgres"),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT pg_sleep(5)" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string; retryable?: boolean }>(res);
expect(res.status).toBe(504);
expect(data.code).toBe("TIMEOUT_ERROR");
expect(res.status).not.toBe(499);
});
test("returns 500 for generic error", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(new Error("Something unexpected happened"));
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT 1" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string }>(res);
expect(res.status).toBe(500);
expect(data.error).toBe("Something unexpected happened");
});
// The probe adds one to the limit, so a limit that is not a number would be concatenated, not added.
for (const options of [{ limit: "500" }, { limit: -1 }, { limit: 1.5 }, { offset: "0" }, { offset: -5 }, null]) {
test(`refuses options ${JSON.stringify(options)} before any provider is reached`, async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users", options },
});
const res = await POST(req as never);
expect(res.status).toBe(400);
expect(mockProvider.prepareQuery).not.toHaveBeenCalled();
expect(mockProvider.query).not.toHaveBeenCalled();
});
}
test("calls prepareQuery with sql and options", async () => {
const req = createMockRequest("/api/db/query", {
method: "POST",
body: {
connection: validConnection,
sql: "SELECT * FROM users",
options: { limit: 100 },
},
});
await POST(req as never);
// The first call is the page the caller asked for; the second, made only because the limiter
// bounded it, asks for one row more so the route can tell a full last page from a full page (#1440).
expect(mockProvider.prepareQuery).toHaveBeenCalledTimes(2);
expect(mockProvider.prepareQuery).toHaveBeenNthCalledWith(1, "SELECT * FROM users", { limit: 100 });
expect(mockProvider.prepareQuery).toHaveBeenNthCalledWith(2, "SELECT * FROM users", {
limit: 51,
unlimited: false,
});
});
test("the statement that runs is the one that asks for a row past the page, and the extra row is not answered", async () => {
(mockProvider.prepareQuery as ReturnType<typeof mock>)
.mockImplementationOnce(() => ({ query: "page", wasLimited: true, limit: 3, offset: 0 }))
.mockImplementationOnce(() => ({ query: "page+1", wasLimited: true, limit: 4, offset: 0 }));
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
fields: ["id"],
rowCount: 4,
executionTime: 10,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
rows: unknown[];
rowCount: number;
pagination: { hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect((mockProvider.query as ReturnType<typeof mock>).mock.calls.at(-1)?.[0]).toBe("page+1");
expect(data.rows).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }]);
expect(data.rowCount).toBe(3);
expect(data.pagination).toMatchObject({ hasMore: true, totalReturned: 3, wasLimited: true });
});
test("a page that ends exactly full offers no further page (#1440)", async () => {
const fiftyRows = Array.from({ length: 50 }, (_, i) => ({ id: i + 1 }));
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: fiftyRows,
fields: ["id"],
rowCount: 50,
executionTime: 10,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { hasMore: boolean; totalReturned: number };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination.hasMore).toBe(false);
expect(data.pagination.totalReturned).toBe(50);
});
/**
* `hasMore` requires that the bound is OURS (#816).
*
* A statement the limiter DECLINED to rewrite comes back `wasLimited: false` with the
* user's own bound still in the text — a ClickHouse query ending in `SETTINGS`, or a
* hand-written `LIMIT 50`. Without this conjunct such a statement, returning exactly
* `prepared.limit` rows, offered a Load More whose click re-ran it unchanged and
* appended the rows already on screen. The two neighbouring tests both run with the
* mock's default `wasLimited: true`, so neither can see this arm.
*/
test("pagination hasMore is false at exactly limit rows when the bound is not ours", async () => {
const declinedProvider = createMockProvider({
prepareQueryResult: { query: "SELECT * FROM users LIMIT 50", wasLimited: false, limit: 50, offset: 0 },
});
mockGetOrCreateProvider.mockResolvedValueOnce(declinedProvider as never);
(declinedProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: Array.from({ length: 50 }, (_, i) => ({ id: i + 1 })),
fields: ["id"],
rowCount: 50,
executionTime: 10,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users LIMIT 50" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination.wasLimited).toBe(false);
expect(data.pagination.totalReturned).toBe(50);
expect(data.pagination.hasMore).toBe(false);
});
test("pagination hasMore is false when rows.length less than limit", async () => {
const threeRows = [{ id: 1 }, { id: 2 }, { id: 3 }];
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: threeRows,
fields: ["id"],
rowCount: 3,
executionTime: 5,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { hasMore: boolean; totalReturned: number };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination.hasMore).toBe(false);
expect(data.pagination.totalReturned).toBe(3);
});
/**
* A bound the PROVIDER applied reaches the response too (#1085, section 5.4).
*
* The route rebuilt `pagination` from `prepareQuery` alone, so a provider that cut its own
* result said so into a field the response then overwrote. The fixture is that provider's
* shape: its `prepareQuery` rewrites nothing, and its result carries its own `pagination`.
* The rows fill `prepared.limit` exactly and the provider's own `hasMore` says true, so a
* route that took `hasMore` from the provider, or from the joined `wasLimited`, would offer
* a Load More that re-runs the same statement; and the provider's other four fields differ
* from the route's, so only `wasLimited` may cross.
*/
test("keeps a provider-reported wasLimited, and hasMore stays on the limiter's own bound", async () => {
const selfBounded = createMockProvider({
prepareQueryResult: { query: "up", wasLimited: false, limit: 3, offset: 0 },
});
mockGetOrCreateProvider.mockResolvedValueOnce(selfBounded as never);
(selfBounded.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [{ value: 1 }, { value: 2 }, { value: 3 }],
fields: ["value"],
rowCount: 3,
executionTime: 4,
pagination: { limit: 500, offset: 7, hasMore: true, totalReturned: 500, wasLimited: true },
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "up" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({ limit: 3, offset: 0, hasMore: false, totalReturned: 3, wasLimited: true });
});
test("the control: the same provider with no pagination of its own reports the limiter's false", async () => {
const unbounded = createMockProvider({
prepareQueryResult: { query: "up", wasLimited: false, limit: 3, offset: 0 },
});
mockGetOrCreateProvider.mockResolvedValueOnce(unbounded as never);
(unbounded.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [{ value: 1 }, { value: 2 }, { value: 3 }],
fields: ["value"],
rowCount: 3,
executionTime: 4,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "up" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({ limit: 3, offset: 0, hasMore: false, totalReturned: 3, wasLimited: false });
});
test("a SQL result with no pagination of its own answers exactly what the route answered before", async () => {
// Every shipped provider's shape: the mock's default `prepareQuery` rewrote the statement
// (`wasLimited: true`, limit 50, `tests/helpers/mock-provider.ts:157-165`) and the result
// carries no `pagination`. The whole object is pinned, so no field of it moved.
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: Array.from({ length: 51 }, (_, i) => ({ id: i + 1 })),
fields: ["id"],
rowCount: 51,
executionTime: 10,
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({ limit: 50, offset: 0, hasMore: true, totalReturned: 50, wasLimited: true });
});
test("a provider's own false cannot clear a bound the limiter applied", async () => {
// The same limiter-bounded statement, and a result that says `wasLimited: false`. No shipped
// provider sets `pagination`, so this is the arm that keeps an external implementer's
// `false` from hiding the badge, and `hasMore` still answers from the limiter's bound.
(mockProvider.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: Array.from({ length: 51 }, (_, i) => ({ id: i + 1 })),
fields: ["id"],
rowCount: 51,
executionTime: 10,
pagination: { limit: 50, offset: 0, hasMore: false, totalReturned: 51, wasLimited: false },
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({ limit: 50, offset: 0, hasMore: true, totalReturned: 50, wasLimited: true });
});
test("a provider's own false leaves an untouched statement unlimited", async () => {
// The mirror of the test above: nothing bounded this statement, and the provider's result
// carries a `pagination` that says `wasLimited: false`. Only a `true` crosses, so a
// `pagination` that is present is not by itself a bound, and the badge stays off.
const untouched = createMockProvider({
prepareQueryResult: { query: "up", wasLimited: false, limit: 3, offset: 0 },
});
mockGetOrCreateProvider.mockResolvedValueOnce(untouched as never);
(untouched.query as ReturnType<typeof mock>).mockResolvedValueOnce({
rows: [{ value: 1 }, { value: 2 }, { value: 3 }],
fields: ["value"],
rowCount: 3,
executionTime: 4,
pagination: { limit: 3, offset: 0, hasMore: false, totalReturned: 3, wasLimited: false },
});
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "up" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{
pagination: { limit: number; offset: number; hasMore: boolean; totalReturned: number; wasLimited: boolean };
}>(res);
expect(res.status).toBe(200);
expect(data.pagination).toEqual({ limit: 3, offset: 0, hasMore: false, totalReturned: 3, wasLimited: false });
});
test("returns 499 for interrupted query execution", async () => {
(mockProvider.query as ReturnType<typeof mock>).mockRejectedValueOnce(
new QueryCancelledError("Query execution was interrupted"),
);
const req = createMockRequest("/api/db/query", {
method: "POST",
body: { connection: validConnection, sql: "SELECT * FROM users" },
});
const res = await POST(req as never);
const data = await parseResponseJSON<{ error: string; code: string }>(res);
expect(res.status).toBe(499);
expect(data.code).toBe("QUERY_CANCELLED");
});
});
/**
* Regression for #328: the agent enforcement layer must not have followed the
* operator into the editor. Everything #328 built — the read-only execution
* profiles, the statement guard, the policy pipeline, the audited execution
* glue — applies to the AGENT path only; a human running a write in the editor
* is the product's primary use, and gating it would be a silent regression
* that no test in the operations layer could see.
*/