forked from libredb/libredb-studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostgres-provider.test.ts
More file actions
2499 lines (2198 loc) · 96.5 KB
/
Copy pathpostgres-provider.test.ts
File metadata and controls
2499 lines (2198 loc) · 96.5 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
/**
* Integration tests for PostgresProvider
* Uses mock.module() to intercept pg before provider import.
*/
import { describe, test, expect, beforeEach, afterEach, mock, spyOn } from "bun:test";
import { EventEmitter } from "node:events";
import type { DatabaseConnection } from "@/lib/types";
import type { ReadOnlyStatementBudget } from "@/lib/db/types";
import { ConnectionError, DatabaseConfigError, ExecutionProfileError } from "@/lib/db/errors";
// ============================================================================
// Mock pg BEFORE importing the provider
// ============================================================================
let mockQueryFn: (
sql: string,
params?: unknown[],
) => Promise<{
rows: unknown[];
fields?: { name: string }[];
rowCount?: number;
}>;
const mockClient = {
query: (sql: string, params?: unknown[]) => mockQueryFn(sql, params),
// Real pg signature: release(err?) — an error argument destroys the client
// instead of returning it to the pool, which queryReadOnly relies on.
release: (_destroy?: Error) => {},
};
/**
* The pool mock is a real EventEmitter, and a fresh instance per construction, because
* that is what `pg` hands back. An `error` event with no listener is an uncaught
* exception (#298), so a plain object carrying an inert `on` could not tell a pool whose
* idle-client failure is handled from one that takes the process down with it.
*/
class MockPool extends EventEmitter {
public totalCount = 10;
public idleCount = 7;
public waitingCount = 0;
async connect() {
return mockClient;
}
async end() {}
}
/** The pool handed to the most recently constructed provider. */
let lastPool: MockPool | undefined;
mock.module("pg", () => ({
Pool: function () {
lastPool = new MockPool();
return lastPool;
},
}));
// Dynamic import AFTER mock is installed
const { PostgresProvider } = await import("@/lib/db/providers/sql/postgres");
// ============================================================================
// Helpers
// ============================================================================
function makePgConfig(overrides: Partial<DatabaseConnection> = {}): DatabaseConnection {
return {
id: "test-pg",
name: "Test Postgres",
type: "postgres",
host: "localhost",
port: 5432,
database: "testdb",
user: "postgres",
password: "secret",
createdAt: new Date(),
...overrides,
};
}
/**
* Default mock query that matches SQL patterns and returns appropriate mock data.
*/
function defaultMockQuery(sql: string): Promise<{ rows: unknown[]; fields?: { name: string }[]; rowCount?: number }> {
const normalized = sql.trim().toLowerCase();
// pg_backend_pid — PID tracking for query cancellation
if (
normalized.includes("pg_backend_pid()") &&
normalized.includes("select") &&
!normalized.includes("pg_stat_activity")
) {
return Promise.resolve({ rows: [{ pid: 12345 }], fields: [{ name: "pid" }], rowCount: 1 });
}
// pg_cancel_backend — cancel a running query
if (normalized.includes("pg_cancel_backend")) {
return Promise.resolve({ rows: [{ cancelled: true }], fields: [{ name: "cancelled" }], rowCount: 1 });
}
// pg_terminate_backend — kill session
if (normalized.includes("pg_terminate_backend")) {
return Promise.resolve({
rows: [{ pg_terminate_backend: true }],
fields: [{ name: "pg_terminate_backend" }],
rowCount: 1,
});
}
// BEGIN / COMMIT / ROLLBACK — transaction control
if (normalized === "begin" || normalized === "commit" || normalized === "rollback") {
return Promise.resolve({ rows: [], fields: [], rowCount: 0 });
}
// VACUUM ANALYZE
if (normalized.includes("vacuum analyze") || normalized === "vacuum analyze") {
return Promise.resolve({ rows: [], fields: [], rowCount: 0 });
}
// ANALYZE (without vacuum)
if (normalized.startsWith("analyze")) {
return Promise.resolve({ rows: [], fields: [], rowCount: 0 });
}
// REINDEX
if (normalized.startsWith("reindex")) {
return Promise.resolve({ rows: [], fields: [], rowCount: 0 });
}
// SELECT * FROM pg_stat_activity (exact, getPgStatActivity)
if (normalized.includes("select * from pg_stat_activity")) {
return Promise.resolve({
rows: [
{
datname: "testdb",
pid: 123,
usename: "testuser",
application_name: "testapp",
client_addr: "127.0.0.1",
backend_start: new Date().toISOString(),
state: "active",
query: "SELECT * FROM test_table",
},
],
fields: [
{ name: "datname" },
{ name: "pid" },
{ name: "usename" },
{ name: "application_name" },
{ name: "client_addr" },
{ name: "backend_start" },
{ name: "state" },
{ name: "query" },
],
rowCount: 1,
});
}
// getHealth: count(*) from pg_stat_activity
if (
normalized.includes("count(*)") &&
normalized.includes("pg_stat_activity") &&
!normalized.includes("max_connections")
) {
return Promise.resolve({ rows: [{ count: "5" }], fields: [{ name: "count" }], rowCount: 1 });
}
// getHealth: pg_size_pretty(pg_database_size(...))
if (
normalized.includes("pg_size_pretty") &&
normalized.includes("pg_database_size") &&
!normalized.includes("pg_tablespace")
) {
return Promise.resolve({
rows: [{ pg_size_pretty: "256 MB", database_size: "256 MB", database_size_bytes: "268435456" }],
fields: [{ name: "pg_size_pretty" }],
rowCount: 1,
});
}
// pg_stat_statements with total_exec_time (getHealth slow queries)
if (
normalized.includes("pg_stat_statements") &&
normalized.includes("total_exec_time desc") &&
normalized.includes("left(query, 100)")
) {
return Promise.resolve({
rows: [{ query: "SELECT * FROM users", calls: 100, avgtime: "12.5ms" }],
fields: [{ name: "query" }, { name: "calls" }, { name: "avgtime" }],
rowCount: 1,
});
}
// pg_stat_statements (getSlowQueries — detailed fields)
if (normalized.includes("pg_stat_statements") && normalized.includes("total_exec_time desc")) {
return Promise.resolve({
rows: [
{
query_id: "12345",
query: "SELECT * FROM users WHERE id = $1",
calls: "200",
total_time: "5000.00",
avg_time: "25.00",
min_time: "1.00",
max_time: "150.00",
rows: "200",
shared_blks_hit: "8000",
shared_blks_read: "50",
},
],
fields: [
{ name: "query_id" },
{ name: "query" },
{ name: "calls" },
{ name: "total_time" },
{ name: "avg_time" },
{ name: "min_time" },
{ name: "max_time" },
{ name: "rows" },
{ name: "shared_blks_hit" },
{ name: "shared_blks_read" },
],
rowCount: 1,
});
}
// pg_stat_activity fallback slow queries (state = 'active')
if (
normalized.includes("pg_stat_activity") &&
normalized.includes("state = 'active'") &&
normalized.includes("query_start asc")
) {
return Promise.resolve({
rows: [
{
query_id: "999",
query: "SELECT * FROM slow_table",
calls: "1",
total_time: "3000",
avg_time: "3000",
rows: "0",
},
],
fields: [],
rowCount: 1,
});
}
// getHealth sessions: pg_stat_activity with pid != pg_backend_pid and datname = $1
if (
normalized.includes("pg_stat_activity") &&
normalized.includes("pid != pg_backend_pid()") &&
normalized.includes("xact_start desc") &&
!normalized.includes("application_name")
) {
return Promise.resolve({
rows: [
{
pid: 101,
user: "app_user",
database: "testdb",
state: "active",
query: "SELECT 1",
duration: "2.5s",
},
],
fields: [],
rowCount: 1,
});
}
// getActiveSessions: pg_stat_activity with detailed fields
if (
normalized.includes("pg_stat_activity") &&
normalized.includes("application_name") &&
normalized.includes("wait_event_type") &&
normalized.includes("pid != pg_backend_pid()")
) {
return Promise.resolve({
rows: [
{
pid: 201,
user: "db_user",
database: "testdb",
application_name: "myapp",
client_addr: "10.0.0.1",
state: "active",
query: "SELECT * FROM orders",
query_start: new Date().toISOString(),
wait_event_type: null,
wait_event: null,
duration: "1.2s",
duration_ms: "1200",
},
],
fields: [],
rowCount: 1,
});
}
// getHealth: pg_statio_user_tables (cache ratio with heap_read + heap_hit)
if (normalized.includes("pg_statio_user_tables") && normalized.includes("heap_blks_read")) {
return Promise.resolve({
rows: [{ ratio: 99.5, heap_read: "100", heap_hit: "9900" }],
fields: [{ name: "ratio" }, { name: "heap_read" }, { name: "heap_hit" }],
rowCount: 1,
});
}
// getPerformanceMetrics: pg_statio_user_tables (cache_hit_ratio only)
if (normalized.includes("pg_statio_user_tables") && normalized.includes("cache_hit_ratio")) {
return Promise.resolve({
rows: [{ cache_hit_ratio: "98.75" }],
fields: [{ name: "cache_hit_ratio" }],
rowCount: 1,
});
}
// Schema CTE query: information_schema + table_type = 'base table'
if (normalized.includes("information_schema") && normalized.includes("table_type = 'base table'")) {
return Promise.resolve({
rows: [
{
table_schema: "public",
table_name: "users",
row_count: "1000",
total_size: "81920",
columns: [
{ name: "id", type: "integer", nullable: false, defaultValue: "nextval('users_id_seq')" },
{ name: "name", type: "character varying", nullable: true, defaultValue: null },
{ name: "email", type: "character varying", nullable: false, defaultValue: null },
],
pk_columns: ["id"],
foreign_keys: [],
indexes: [
{ name: "users_pkey", columns: ["id"], unique: true },
{ name: "idx_users_email", columns: ["email"], unique: true },
],
},
{
table_schema: "analytics",
table_name: "events",
row_count: "50000",
total_size: "4194304",
columns: [
{ name: "id", type: "integer", nullable: false, defaultValue: null },
{ name: "user_id", type: "integer", nullable: false, defaultValue: null },
{ name: "event_type", type: "character varying", nullable: false, defaultValue: null },
],
pk_columns: ["id"],
foreign_keys: [
{
columnName: "user_id",
referencedSchema: "public",
referencedTable: "users",
referencedColumn: "id",
},
],
indexes: [{ name: "events_pkey", columns: ["id"], unique: true }],
},
],
fields: [],
rowCount: 2,
});
}
// getOverview: version() + pg_postmaster_start_time()
if (normalized.includes("version()") && normalized.includes("pg_postmaster_start_time()")) {
return Promise.resolve({
rows: [
{
version: "PostgreSQL 16.2, compiled by Visual C++ build 1941, 64-bit",
start_time: new Date(Date.now() - 90061000).toISOString(),
uptime_seconds: "90061",
},
],
fields: [],
rowCount: 1,
});
}
// getOverview: connection counts (max_connections + pg_stat_activity)
if (normalized.includes("max_connections") && normalized.includes("pg_stat_activity")) {
return Promise.resolve({
rows: [{ active_connections: "12", max_connections: "200" }],
fields: [],
rowCount: 1,
});
}
// getOverview: database size (pg_database_size with pretty + bytes)
if (normalized.includes("pg_database_size") && normalized.includes("database_size_bytes")) {
return Promise.resolve({
rows: [{ database_size: "512 MB", database_size_bytes: "536870912" }],
fields: [],
rowCount: 1,
});
}
// getOverview: table + index counts
if (normalized.includes("pg_tables") && normalized.includes("pg_indexes")) {
return Promise.resolve({
rows: [{ table_count: "15", index_count: "30" }],
fields: [],
rowCount: 1,
});
}
// getPerformanceMetrics: pg_stat_database (transaction stats)
if (normalized.includes("pg_stat_database") && normalized.includes("xact_commit")) {
return Promise.resolve({
rows: [
{
xact_commit: "50000",
xact_rollback: "150",
deadlocks: "3",
blks_read: "2000",
blks_hit: "98000",
},
],
fields: [],
rowCount: 1,
});
}
// getPerformanceMetrics: pg_stat_bgwriter (checkpoint stats)
if (normalized.includes("pg_stat_bgwriter")) {
return Promise.resolve({
rows: [
{
checkpoint_write_time: "12500",
checkpoint_sync_time: "3200",
},
],
fields: [],
rowCount: 1,
});
}
// getTableStats: pg_stat_user_tables
if (normalized.includes("pg_stat_user_tables") && normalized.includes("n_live_tup")) {
return Promise.resolve({
rows: [
{
schema_name: "public",
table_name: "users",
live_row_count: "1000",
dead_row_count: "50",
row_count: "1050",
table_size: "64 kB",
table_size_bytes: "65536",
index_size: "32 kB",
index_size_bytes: "32768",
total_size: "96 kB",
total_size_bytes: "98304",
last_vacuum: null,
last_autovacuum: new Date().toISOString(),
last_analyze: null,
last_autoanalyze: new Date().toISOString(),
bloat_ratio: "4.76",
},
{
schema_name: "public",
table_name: "orders",
live_row_count: "5000",
dead_row_count: "200",
row_count: "5200",
table_size: "256 kB",
table_size_bytes: "262144",
index_size: "128 kB",
index_size_bytes: "131072",
total_size: "384 kB",
total_size_bytes: "393216",
last_vacuum: new Date().toISOString(),
last_autovacuum: null,
last_analyze: new Date().toISOString(),
last_autoanalyze: null,
bloat_ratio: "3.85",
},
],
fields: [],
rowCount: 2,
});
}
// getIndexStats: pg_stat_user_indexes
if (normalized.includes("pg_stat_user_indexes")) {
return Promise.resolve({
rows: [
{
schema_name: "public",
table_name: "users",
index_name: "users_pkey",
index_type: "btree",
index_size: "16 kB",
index_size_bytes: "16384",
scans: "5000",
tuples_read: "5000",
tuples_fetched: "5000",
is_unique: true,
is_primary: true,
columns: ["id"],
usage_ratio: "85.50",
},
{
schema_name: "public",
table_name: "users",
index_name: "idx_users_email",
index_type: "btree",
index_size: "32 kB",
index_size_bytes: "32768",
scans: "3000",
tuples_read: "3000",
tuples_fetched: "3000",
is_unique: true,
is_primary: false,
columns: ["email"],
usage_ratio: "52.17",
},
],
fields: [],
rowCount: 2,
});
}
// getStorageStats: pg_tablespace
if (normalized.includes("pg_tablespace") && normalized.includes("pg_tablespace_size")) {
return Promise.resolve({
rows: [
{
name: "pg_default",
location: "",
size: "1.2 GB",
size_bytes: "1288490188",
is_default: true,
},
],
fields: [],
rowCount: 1,
});
}
// getStorageStats: pg_wal_lsn_diff (WAL info)
if (normalized.includes("pg_wal_lsn_diff")) {
return Promise.resolve({
rows: [{ wal_size: "128 MB", wal_size_bytes: "134217728" }],
fields: [],
rowCount: 1,
});
}
// Default: generic SELECT result
return Promise.resolve({
rows: [{ id: 1, name: "test" }],
fields: [{ name: "id" }, { name: "name" }],
rowCount: 1,
});
}
// ============================================================================
// Tests
// ============================================================================
describe("PostgresProvider", () => {
let provider: InstanceType<typeof PostgresProvider>;
beforeEach(() => {
mockQueryFn = defaultMockQuery;
});
afterEach(async () => {
try {
if (provider?.isConnected()) {
await provider.disconnect();
}
} catch {
// Ignore cleanup errors
}
});
// --------------------------------------------------------------------------
// Validation
// --------------------------------------------------------------------------
describe("validate()", () => {
test("missing host throws DatabaseConfigError", () => {
expect(() => {
new PostgresProvider(makePgConfig({ host: undefined }));
}).toThrow(DatabaseConfigError);
});
test("missing database throws DatabaseConfigError", () => {
expect(() => {
new PostgresProvider(makePgConfig({ database: undefined }));
}).toThrow(DatabaseConfigError);
});
test("valid config passes validation", () => {
expect(() => {
new PostgresProvider(makePgConfig());
}).not.toThrow();
});
test("connectionString bypasses host/database requirement", () => {
expect(() => {
new PostgresProvider(
makePgConfig({
host: undefined,
database: undefined,
connectionString: "postgresql://user:pass@localhost:5432/mydb",
}),
);
}).not.toThrow();
});
});
// --------------------------------------------------------------------------
// Connection lifecycle
// --------------------------------------------------------------------------
describe("connect / disconnect", () => {
test("isConnected() is false before connect", () => {
provider = new PostgresProvider(makePgConfig());
expect(provider.isConnected()).toBe(false);
});
test("connect() sets connected to true", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
test("disconnect() sets connected to false", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.disconnect();
expect(provider.isConnected()).toBe(false);
});
test("double connect is idempotent", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
});
// --------------------------------------------------------------------------
// buildSSLConfig()
// --------------------------------------------------------------------------
describe("buildSSLConfig()", () => {
test("ssl mode disable returns false (no SSL)", async () => {
provider = new PostgresProvider(
makePgConfig({
ssl: { mode: "disable" },
}),
);
await provider.connect();
// If we get here without error, connect succeeded with ssl=false
expect(provider.isConnected()).toBe(true);
});
test("ssl mode verify-ca sets rejectUnauthorized to true", async () => {
provider = new PostgresProvider(
makePgConfig({
ssl: { mode: "verify-ca" },
}),
);
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
test("ssl mode verify-full with certs includes ca, cert, key", async () => {
provider = new PostgresProvider(
makePgConfig({
ssl: {
mode: "verify-full",
caCert: "-----BEGIN CERTIFICATE-----\nCA\n-----END CERTIFICATE-----",
clientCert: "-----BEGIN CERTIFICATE-----\nCLIENT\n-----END CERTIFICATE-----",
clientKey: "-----BEGIN RSA PRIVATE KEY-----\nKEY\n-----END RSA PRIVATE KEY-----",
},
}),
);
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
test("auto-detect cloud provider enables SSL", async () => {
provider = new PostgresProvider(
makePgConfig({
host: "my-db.supabase.co",
}),
);
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
test("options.ssl=false returns false", async () => {
provider = new PostgresProvider(makePgConfig(), { ssl: false });
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
test("no SSL config returns undefined (default)", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
expect(provider.isConnected()).toBe(true);
});
});
// --------------------------------------------------------------------------
// Query execution
// --------------------------------------------------------------------------
describe("query()", () => {
test("SELECT returns rows, fields, and executionTime", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const result = await provider.query("SELECT * FROM users");
expect(result.rows.length).toBeGreaterThan(0);
expect(Array.isArray(result.fields)).toBe(true);
expect(typeof result.executionTime).toBe("number");
expect(typeof result.rowCount).toBe("number");
});
test("PID is tracked when queryId is provided", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const result = await provider.query("SELECT 1", undefined, "test-query-id");
expect(result.rows.length).toBeGreaterThan(0);
});
test("query error is mapped to database error", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
// Override mock to throw a syntax error
mockQueryFn = async () => {
throw new Error('syntax error at or near "SELEC"');
};
await expect(provider.query("SELEC * FROM users")).rejects.toThrow();
});
});
// --------------------------------------------------------------------------
// Cancel query
// --------------------------------------------------------------------------
describe("cancelQuery()", () => {
test("cancels known PID and returns true", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
// We need a query running to have a tracked PID.
// Simulate: trigger a query with queryId, then cancel mid-flight.
// Since our mock is synchronous, we'll manually set the PID map.
// Access the private runningQueryPids map via casting.
const providerAny = provider as unknown as { runningQueryPids: Map<string, number> };
providerAny.runningQueryPids.set("cancel-test", 12345);
const cancelled = await provider.cancelQuery("cancel-test");
expect(cancelled).toBe(true);
});
test("returns false for unknown queryId", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const result = await provider.cancelQuery("nonexistent-query-id");
expect(result).toBe(false);
});
test("handles cancel error gracefully and returns false", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const providerAny = provider as unknown as { runningQueryPids: Map<string, number> };
providerAny.runningQueryPids.set("error-cancel", 99999);
// Override mock to throw on pg_cancel_backend
const originalMock = mockQueryFn;
mockQueryFn = async (sql: string, params?: unknown[]) => {
if (sql.includes("pg_cancel_backend")) {
throw new Error("Connection lost");
}
return originalMock(sql, params);
};
const result = await provider.cancelQuery("error-cancel");
expect(result).toBe(false);
});
});
// --------------------------------------------------------------------------
// Transaction lifecycle
// --------------------------------------------------------------------------
describe("Transaction lifecycle", () => {
test("beginTransaction / commitTransaction works", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
expect(provider.isInTransaction()).toBe(false);
await provider.beginTransaction();
expect(provider.isInTransaction()).toBe(true);
await provider.commitTransaction();
expect(provider.isInTransaction()).toBe(false);
});
test("beginTransaction / rollbackTransaction works", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.beginTransaction();
expect(provider.isInTransaction()).toBe(true);
await provider.rollbackTransaction();
expect(provider.isInTransaction()).toBe(false);
});
test("double beginTransaction throws", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.beginTransaction();
await expect(provider.beginTransaction()).rejects.toThrow("Transaction already active");
// Clean up
await provider.rollbackTransaction();
});
test("commitTransaction without begin throws", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await expect(provider.commitTransaction()).rejects.toThrow("No active transaction");
});
test("rollbackTransaction without begin throws", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await expect(provider.rollbackTransaction()).rejects.toThrow("No active transaction");
});
test("queryInTransaction executes within active transaction", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.beginTransaction();
const result = await provider.queryInTransaction("SELECT 1");
expect(result.rows).toBeDefined();
expect(typeof result.executionTime).toBe("number");
await provider.commitTransaction();
});
test("queryInTransaction without begin throws", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await expect(provider.queryInTransaction("SELECT 1")).rejects.toThrow("No active transaction");
});
test("expireTransaction auto-rollbacks an active transaction", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.beginTransaction();
expect(provider.isInTransaction()).toBe(true);
await provider.expireTransaction();
expect(provider.isInTransaction()).toBe(false);
});
test("expireTransaction is no-op when no active transaction", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
// Should not throw
await provider.expireTransaction();
expect(provider.isInTransaction()).toBe(false);
});
test("transaction timeout timer fires and auto-rollbacks", async () => {
// TX_TIMEOUT_MS is a private static read at beginTransaction() call time;
// shrink it so the auto-rollback timer actually fires in the test
// (same private-access-via-cast precedent as runningQueryPids above).
const providerStatics = PostgresProvider as unknown as { TX_TIMEOUT_MS: number };
const originalTimeout = providerStatics.TX_TIMEOUT_MS;
providerStatics.TX_TIMEOUT_MS = 5;
try {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
await provider.beginTransaction();
expect(provider.isInTransaction()).toBe(true);
await new Promise((resolve) => setTimeout(resolve, 50));
expect(provider.isInTransaction()).toBe(false);
} finally {
providerStatics.TX_TIMEOUT_MS = originalTimeout;
}
});
});
// --------------------------------------------------------------------------
// Schema
// --------------------------------------------------------------------------
describe("getSchema()", () => {
test("returns TableSchema array with columns, indexes, foreignKeys", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchema();
expect(schema.length).toBe(2);
for (const table of schema) {
expect(typeof table.name).toBe("string");
expect(Array.isArray(table.columns)).toBe(true);
expect(table.columns.length).toBeGreaterThan(0);
expect(Array.isArray(table.indexes)).toBe(true);
expect(Array.isArray(table.foreignKeys)).toBe(true);
}
});
test("primary key columns are detected via isPrimary flag", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchema();
const usersTable = schema.find((t) => t.name === "users");
expect(usersTable).toBeDefined();
const idCol = usersTable!.columns.find((c) => c.name === "id");
expect(idCol).toBeDefined();
expect(idCol!.isPrimary).toBe(true);
const nameCol = usersTable!.columns.find((c) => c.name === "name");
expect(nameCol).toBeDefined();
expect(nameCol!.isPrimary).toBe(false);
});
test("non-public schema tables get schema prefix in name", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchema();
const eventsTable = schema.find((t) => t.name === "analytics.events");
expect(eventsTable).toBeDefined();
expect(eventsTable!.name).toBe("analytics.events");
// Foreign key from analytics.events.user_id -> public.users.id should have no prefix
expect(eventsTable!.foreignKeys!.length).toBe(1);
expect(eventsTable!.foreignKeys![0].referencedTable).toBe("users");
});
});
// --------------------------------------------------------------------------
// getSchemaList() — fast structural path (tables + columns + PKs only)
// --------------------------------------------------------------------------
describe("getSchemaList()", () => {
// The fast path shares the tables/columns/pk CTE shape with getSchema(), so
// the default mock (information_schema + table_type = 'base table') applies.
// What it must NOT do is populate indexes/foreignKeys — those are deferred
// to getSchemaRelations() so a slow stats query can't block the table list.
test("returns tables with columns and PKs but empty indexes/foreignKeys", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchemaList();
expect(schema.length).toBe(2);
for (const table of schema) {
expect(typeof table.name).toBe("string");
expect(table.columns.length).toBeGreaterThan(0);
// The whole point of the split: relations are intentionally absent here.
expect(table.indexes).toEqual([]);
expect(table.foreignKeys).toEqual([]);
}
});
test("primary key columns are detected via isPrimary flag", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchemaList();
const usersTable = schema.find((t) => t.name === "users");
expect(usersTable).toBeDefined();
expect(usersTable!.columns.find((c) => c.name === "id")!.isPrimary).toBe(true);
expect(usersTable!.columns.find((c) => c.name === "name")!.isPrimary).toBe(false);
});
test("non-public schema tables get schema prefix in name", async () => {
provider = new PostgresProvider(makePgConfig());
await provider.connect();
const schema = await provider.getSchemaList();
expect(schema.find((t) => t.name === "analytics.events")).toBeDefined();
expect(schema.find((t) => t.name === "users")).toBeDefined();