Repository navigation
Expand file tree
/
Copy pathpg.js
More file actions
1398 lines (1256 loc) · 48.8 KB
/
Copy pathpg.js
File metadata and controls
1398 lines (1256 loc) · 48.8 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
/**
* @module @krusch/toolkit/pg
* Standardized PostgreSQL connection pool, transactional helper, idempotent SQL migration runner,
* and SQL-injection-guarded pgvector cosine similarity search brick.
*/
import os from 'node:os';
import path from 'node:path';
import pg from 'pg';
import { setupLogging } from './log.js';
import { validateVectorDimension } from './embeddings.js';
const IDENT_RE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
/**
* Validate a PostgreSQL table or column identifier against SQL injection.
*
* @param {string} name
* @param {string} [label='identifier']
* @returns {string}
*/
export function assertSafePgIdentifier(name, label = 'identifier') {
if (typeof name !== 'string' || !IDENT_RE.test(name)) {
throw new Error(`[pg] Unsafe SQL ${label}: "${String(name)}". Must match ${IDENT_RE}.`);
}
return name;
}
/**
* Resolve a PostgreSQL connection string from explicit URL, `DATABASE_URL`, or URI-encoded components.
*
* @param {object | string} [dbConfig={}]
* @returns {string}
*/
export function buildPgConnectionString(dbConfig = {}) {
if (typeof dbConfig === 'string' && dbConfig.trim().length > 0) {
return dbConfig.trim();
}
const cfg = dbConfig && typeof dbConfig === 'object' ? dbConfig : {};
const directUrl = cfg.url || cfg.connectionString;
if (typeof directUrl === 'string' && directUrl.trim().length > 0) {
return directUrl.trim();
}
const hasExplicitComponents =
cfg.host !== undefined ||
cfg.port !== undefined ||
cfg.user !== undefined ||
cfg.password !== undefined ||
cfg.database !== undefined;
if (
!hasExplicitComponents &&
typeof process.env.DATABASE_URL === 'string' &&
process.env.DATABASE_URL.trim().length > 0
) {
return process.env.DATABASE_URL.trim();
}
const rawHost = String(cfg.host ?? '127.0.0.1').trim() || '127.0.0.1';
const host = rawHost.includes(':') && !rawHost.startsWith('[') ? `[${rawHost}]` : rawHost;
const parsedPort = Number(cfg.port ?? 5432);
const port = Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535 ? parsedPort : 5432;
const user = String(cfg.user ?? 'postgres');
const password = String(cfg.password ?? '');
const database = String(cfg.database ?? 'postgres');
return `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${host}:${port}/${encodeURIComponent(database)}`;
}
function resolvePgLogger(serviceName, logger, logDir) {
if (logger) return logger;
try {
return setupLogging(serviceName, {
logDir: logDir || path.join(os.tmpdir(), 'krusch-logs'),
console: false,
});
} catch {
return {
info() {},
debug() {},
warn() {},
error(msg, err) {
console.error(`[${serviceName}] ${msg}`, err?.message || err || '');
},
};
}
}
/**
* Create a standardized `pg.Pool` wrapper with idle error guarding, timed query logging,
* safe transactions, health checks, and idempotent shutdown.
*
* @param {object | string} [dbConfig={}]
* @param {object} [options={}]
* @returns {{ pool: object, query: Function, queryOne: Function, withTransaction: Function, healthCheck: Function, close: Function }}
*/
export function createPgPool(
dbConfig = {},
{
serviceName = 'krusch-pg',
max = 15,
idleTimeoutMillis = 30000,
connectionTimeoutMillis = 3000,
PoolClass = null,
logger = null,
logDir = null,
ssl = undefined,
} = {}
) {
const connectionString = buildPgConnectionString(dbConfig);
const PoolImpl = PoolClass || pg.Pool;
const log = resolvePgLogger(serviceName, logger, logDir);
const effectiveSsl = ssl !== undefined ? ssl : dbConfig?.ssl;
const pool = new PoolImpl({
connectionString,
max,
idleTimeoutMillis,
connectionTimeoutMillis,
...(effectiveSsl !== undefined ? { ssl: effectiveSsl } : {}),
});
pool.on?.('error', (err) => {
log.error?.('Unexpected error on idle PostgreSQL client', err);
});
async function query(sql, params = []) {
const start = Date.now();
try {
const res = await pool.query(sql, params);
const durationMs = Date.now() - start;
log.debug?.('Executed PostgreSQL query', {
durationMs,
rowCount: res?.rowCount ?? res?.rows?.length ?? 0,
});
return res;
} catch (err) {
const durationMs = Date.now() - start;
const snippet = String(sql || '').replace(/\s+/g, ' ').trim().slice(0, 160);
log.error?.('PostgreSQL query failed', {
error: err,
durationMs,
sql: snippet,
});
const wrapped = new Error(
`[${serviceName}] PostgreSQL query failed (${durationMs}ms): ${err?.message || String(err)} [sql="${snippet}"]`,
{ cause: err }
);
if (err?.code) wrapped.code = err.code;
if (err?.detail) wrapped.detail = err.detail;
throw wrapped;
}
}
async function queryOne(sql, params = []) {
const res = await query(sql, params);
return res?.rows?.[0] ?? null;
}
async function withTransaction(fn) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await fn(client);
await client.query('COMMIT');
return result;
} catch (err) {
try {
await client.query('ROLLBACK');
} catch (rollbackErr) {
log.error?.('PostgreSQL transaction rollback failed', rollbackErr);
}
throw err;
} finally {
client.release?.();
}
}
async function healthCheck() {
const start = Date.now();
await pool.query('SELECT 1 AS ok');
const latencyMs = Date.now() - start;
return { ok: true, latencyMs };
}
let closed = false;
async function close() {
if (closed) return;
closed = true;
if (typeof pool.end === 'function') {
await pool.end();
}
}
return {
pool,
query,
queryOne,
withTransaction,
healthCheck,
close,
};
}
function isSinglePgClient(pgWrapper) {
if (!pgWrapper || typeof pgWrapper !== 'object') return false;
if (typeof pg.Pool === 'function' && pgWrapper instanceof pg.Pool) return false;
if (typeof pg.Client === 'function' && pgWrapper instanceof pg.Client) return true;
if (typeof pgWrapper.release === 'function') return true;
if (pgWrapper._connected === true || pgWrapper._connecting === true) return true;
return false;
}
async function runInClientTransaction(pgWrapper, fn) {
if (typeof pgWrapper?.withTransaction === 'function') {
return await pgWrapper.withTransaction(fn);
}
if (!isSinglePgClient(pgWrapper) && typeof pgWrapper?.connect === 'function') {
const client = await pgWrapper.connect();
try {
await client.query('BEGIN');
const res = await fn(client);
await client.query('COMMIT');
return res;
} catch (err) {
try {
await client.query('ROLLBACK');
} catch {
// Preserve primary error
}
throw err;
} finally {
client.release?.();
}
}
await pgWrapper.query('BEGIN');
try {
const res = await fn(pgWrapper);
await pgWrapper.query('COMMIT');
return res;
} catch (err) {
try {
await pgWrapper.query('ROLLBACK');
} catch {
// Preserve primary error
}
throw err;
}
}
/**
* Run idempotent `{ id, sql }` schema migrations inside transactions and return an INV-LEGO-01 envelope.
*
* @param {{ query: Function, withTransaction?: Function, connect?: Function }} pgWrapper
* @param {Array<{ id: string, sql: string }>} [migrations=[]]
* @param {{ tableName?: string }} [options={}]
* @returns {Promise<{ ok: true, tool: 'pg.migrate', summary: string, data: { applied: string[], skipped: string[] } }>}
*/
export async function runSqlMigrations(
pgWrapper,
migrations = [],
{ tableName = 'schema_migrations' } = {}
) {
assertSafePgIdentifier(tableName, 'tableName');
if (!pgWrapper || typeof pgWrapper.query !== 'function') {
throw new Error('[pg.migrate] Valid pgWrapper with .query() is required.');
}
await pgWrapper.query(
`CREATE TABLE IF NOT EXISTS ${tableName} (id TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`
);
const existingRes = await pgWrapper.query(`SELECT id FROM ${tableName}`);
const appliedSet = new Set((existingRes?.rows || []).map((row) => String(row.id)));
const applied = [];
const skipped = [];
for (const migration of migrations) {
const migId = typeof migration?.id === 'string' ? migration.id.trim() : '';
if (!migId) {
throw new Error('[pg.migrate] Each migration must define a non-empty string "id".');
}
if (typeof migration?.sql !== 'string' || migration.sql.trim().length === 0) {
throw new Error(`[pg.migrate] Migration "${migId}" must define a non-empty "sql" string.`);
}
if (appliedSet.has(migId)) {
skipped.push(migId);
continue;
}
await runInClientTransaction(pgWrapper, async (tx) => {
await tx.query(migration.sql);
await tx.query(`INSERT INTO ${tableName} (id) VALUES ($1)`, [migId]);
});
appliedSet.add(migId);
applied.push(migId);
}
return {
ok: true,
tool: 'pg.migrate',
summary: `Applied ${applied.length} migration(s), skipped ${skipped.length}`,
data: { applied, skipped },
};
}
/**
* Validate a SQL WHERE predicate fragment against stacked queries, SQL comments, UNION/INTO,
* dollar-quoting, and unbalanced-parenthesis breakout (`INV-LEGO-04` / SQLi defense).
*
* @param {string} whereSql
* @returns {string}
*/
const DISALLOWED_WHERE_KEYWORDS_RE =
/(?<![a-zA-Z0-9_$\u0080-\uffff])(?:SELECT|TABLE|VALUES|WITH(?!\s+TIME\s+ZONE(?![a-zA-Z0-9_$\u0080-\uffff]))|UNION|INTERSECT|EXCEPT|INTO|COPY|INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|TRUNCATE|GRANT|REVOKE|EXECUTE|PREPARE|DEALLOCATE|CALL|DO|SET|SHOW|RESET|DISCARD|FETCH|MOVE|DECLARE|CLOSE|LOCK|LISTEN|UNLISTEN|NOTIFY|LOAD|VACUUM|ANALYZE|EXPLAIN|CLUSTER|REINDEX|REFRESH|CHECKPOINT|COMMENT|SECURITY|PG_NOTIFY|SET_CONFIG|CURRENT_SETTING|CURRENT_USER|SESSION_USER|SYSTEM_USER|USER|CURRENT_ROLE|CURRENT_DATABASE|CURRENT_SCHEMA|CURRENT_CATALOG|REGCLASS|REGPROC|REGPROCEDURE|REGOPER|REGOPERATOR|REGTYPE|REGROLE|REGNAMESPACE|REGCONFIG|REGDICTIONARY|PG_SLEEP|PG_READ_FILE|PG_READ_BINARY_FILE|PG_LS_DIR|PG_STAT_FILE|PG_TERMINATE_BACKEND|PG_CANCEL_BACKEND|PG_RELOAD_CONF|PG_ROTATE_LOGFILE|PG_ADVISORY_LOCK|PG_ADVISORY_XACT_LOCK|LO_IMPORT|LO_EXPORT|DBLINK|QUERY_TO_XML|QUERY_TO_XMLSCHEMA|QUERY_TO_XML_AND_XMLSCHEMA|TABLE_TO_XML|TABLE_TO_XMLSCHEMA|TABLE_TO_XML_AND_XMLSCHEMA|CURSOR_TO_XML|CURSOR_TO_XMLSCHEMA|SCHEMA_TO_XML|SCHEMA_TO_XMLSCHEMA|SCHEMA_TO_XML_AND_XMLSCHEMA|DATABASE_TO_XML|DATABASE_TO_XMLSCHEMA|DATABASE_TO_XML_AND_XMLSCHEMA|XMLTABLE|JSON_TABLE|XPATH|XPATH_EXISTS|XMLPARSE)(?![a-zA-Z0-9_$\u0080-\uffff])/i;
const SAFE_WHERE_CALLABLES = new Set([
'AND', 'OR', 'NOT', 'IN', 'ANY', 'SOME', 'ALL', 'SIMILAR', 'SYMMETRIC', 'ASYMMETRIC',
'BETWEEN', 'IS', 'DISTINCT', 'CASE', 'WHEN', 'THEN', 'ELSE',
'COALESCE', 'NULLIF', 'GREATEST', 'LEAST', 'CAST', 'ROW',
'LOWER', 'UPPER', 'TRIM', 'BTRIM', 'LTRIM', 'RTRIM',
'LENGTH', 'CHAR_LENGTH', 'CHARACTER_LENGTH', 'OCTET_LENGTH',
'SUBSTRING', 'SUBSTR', 'LEFT', 'RIGHT', 'LPAD', 'RPAD', 'REPLACE', 'SPLIT_PART', 'STARTS_WITH',
'POSITION', 'STRPOS', 'CONCAT', 'CONCAT_WS',
'ABS', 'MOD', 'ROUND', 'TRUNC', 'CEIL', 'CEILING', 'FLOOR', 'SIGN', 'SQRT', 'POWER',
'NOW', 'DATE_TRUNC', 'DATE_PART', 'EXTRACT', 'AGE', 'TO_CHAR', 'TO_DATE', 'TO_TIMESTAMP', 'TO_NUMBER',
'ARRAY_LENGTH', 'ARRAY_POSITION', 'CARDINALITY',
'JSONB_EXTRACT_PATH_TEXT', 'JSON_EXTRACT_PATH_TEXT', 'JSONB_TYPEOF', 'JSON_TYPEOF',
'JSONB_ARRAY_LENGTH', 'JSON_ARRAY_LENGTH',
'VARCHAR', 'CHAR', 'CHARACTER', 'VARYING', 'NUMERIC', 'DECIMAL', 'BIT', 'VARBIT',
'TIMESTAMP', 'TIMESTAMPTZ', 'TIME', 'TIMETZ', 'INTERVAL', 'VECTOR', 'SPARSEVEC'
]);
export function assertSafeWhereClause(whereSql, { maxParamIndex = null } = {}) {
if (typeof whereSql !== 'string') {
throw new Error('[pg.vectorSearch] "whereSql" must be a string.');
}
if (whereSql.includes('\x00')) {
throw new Error('[pg.vectorSearch] Null byte disallowed in whereSql.');
}
const trimmed = whereSql.trim().replace(/^WHERE\s+/i, '');
if (!trimmed) return '';
let inSingleQuote = false;
let inDoubleQuote = false;
let parenDepth = 0;
let stripped = '';
for (let i = 0; i < trimmed.length; i += 1) {
const ch = trimmed[i];
const next = trimmed[i + 1] || '';
if (inSingleQuote) {
if (ch === '\\') {
throw new Error(`[pg.vectorSearch] Backslash escapes inside string literals are disallowed in whereSql (use $N parameters): "${trimmed}".`);
}
if (ch === "'" && next === "'") {
i += 1;
continue;
}
if (ch === "'") {
inSingleQuote = false;
}
continue;
}
if (inDoubleQuote) {
if (ch === '"' && next === '"') {
i += 1;
continue;
}
if (ch === '"') {
inDoubleQuote = false;
let look = i + 1;
while (look < trimmed.length && /\s/.test(trimmed[look])) {
look += 1;
}
if (trimmed[look] === '(') {
throw new Error(`[pg.vectorSearch] Disallowed double-quoted function call in whereSql: "${trimmed}".`);
}
}
continue;
}
if (ch === '$') {
const prev = i > 0 ? trimmed[i - 1] : '';
if (prev && /[a-zA-Z0-9_$\u0080-\uffff]/.test(prev)) {
throw new Error(`[pg.vectorSearch] Disallowed dollar-quoted or dollar-identifier token in whereSql: "${trimmed}".`);
}
const paramMatch = trimmed.slice(i).match(/^\$(\d+)(?![a-zA-Z0-9_$\u0080-\uffff])/);
if (!paramMatch) {
throw new Error(`[pg.vectorSearch] Invalid SQL parameter or dollar-quoting in whereSql: "${trimmed}".`);
}
const digits = paramMatch[1];
const idx = Number(digits);
if (!Number.isSafeInteger(idx) || idx < 1 || digits.startsWith('0')) {
throw new Error(`[pg.vectorSearch] Invalid SQL parameter index $${digits} in whereSql (must be >= $1).`);
}
if (maxParamIndex !== null && idx > maxParamIndex) {
throw new Error(
`[pg.vectorSearch] Out-of-range SQL parameter $${idx} in whereSql (only ${maxParamIndex} param(s) supplied).`
);
}
stripped += ` $${idx} `;
i += digits.length;
continue;
}
if (ch === "'") {
const prev = i > 0 ? trimmed[i - 1] : '';
if (prev && /[a-zA-Z0-9_&\u0080-\uffff]/.test(prev)) {
throw new Error(`[pg.vectorSearch] Prefixed PostgreSQL string literals are disallowed in whereSql (use $N parameters): "${trimmed}".`);
}
inSingleQuote = true;
stripped += ' ';
continue;
}
if (ch === '"') {
const prev = i > 0 ? trimmed[i - 1] : '';
if (prev && /[a-zA-Z0-9_&\u0080-\uffff]/.test(prev)) {
throw new Error(`[pg.vectorSearch] Prefixed or Unicode-escaped identifiers are disallowed in whereSql: "${trimmed}".`);
}
inDoubleQuote = true;
stripped += ' _ident_ ';
continue;
}
if (ch === ';' || ch === '\\' || (ch === '-' && next === '-') || (ch === '/' && next === '*') || (ch === '*' && next === '/')) {
throw new Error(`[pg.vectorSearch] Unsafe SQL token in whereSql: "${trimmed}".`);
}
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth < 0) {
throw new Error(`[pg.vectorSearch] Unbalanced parentheses in whereSql: "${trimmed}".`);
}
}
stripped += ch;
}
if (inSingleQuote || inDoubleQuote || parenDepth !== 0) {
throw new Error(`[pg.vectorSearch] Unclosed quote or parentheses in whereSql: "${trimmed}".`);
}
if (DISALLOWED_WHERE_KEYWORDS_RE.test(stripped)) {
throw new Error(`[pg.vectorSearch] Disallowed SQL keyword in whereSql: "${trimmed}".`);
}
if (/(?<![a-zA-Z0-9_$\u0080-\uffff])[a-zA-Z_\u0080-\uffff][a-zA-Z0-9_$\u0080-\uffff]*\s*\.\s*(?:[a-zA-Z_\u0080-\uffff][a-zA-Z0-9_$\u0080-\uffff]*|_ident_)\s*\(/.test(stripped)) {
throw new Error(`[pg.vectorSearch] Disallowed schema-qualified function call in whereSql: "${trimmed}".`);
}
for (const callMatch of stripped.matchAll(/(?<![a-zA-Z0-9_$\u0080-\uffff])([a-zA-Z_\u0080-\uffff][a-zA-Z0-9_$\u0080-\uffff]*)\s*\(/g)) {
const fnName = callMatch[1].toUpperCase();
if (fnName === '_IDENT_') {
throw new Error(`[pg.vectorSearch] Disallowed double-quoted function call in whereSql: "${trimmed}".`);
}
if (!SAFE_WHERE_CALLABLES.has(fnName)) {
throw new Error(`[pg.vectorSearch] Disallowed SQL function "${callMatch[1]}" in whereSql: "${trimmed}".`);
}
}
return trimmed;
}
/**
* Execute a parameterized pgvector cosine similarity search (`<=>`) with strict SQL identifier
* and vector dimensionality validation.
*
* @param {{ query: Function }} pgWrapper
* @param {object} options
* @returns {Promise<{ ok: true, tool: 'pg.vectorSearch', summary: string, data: { rows: object[] } }>}
*/
export async function pgVectorSearch(
pgWrapper,
{
table,
embeddingColumn = 'embedding',
vector,
selectColumns = ['id'],
whereSql = '',
params = [],
limit = 10,
expectedDims = 1024,
} = {}
) {
if (!pgWrapper || typeof pgWrapper.query !== 'function') {
throw new Error('[pg.vectorSearch] Valid pgWrapper with .query() is required.');
}
assertSafePgIdentifier(table, 'table');
assertSafePgIdentifier(embeddingColumn, 'embeddingColumn');
if (!Array.isArray(selectColumns) || selectColumns.length === 0) {
throw new Error('[pg.vectorSearch] "selectColumns" must be a non-empty array of column identifiers.');
}
const safeColumns = selectColumns.map((col) => assertSafePgIdentifier(col, 'selectColumn'));
const vecArray =
ArrayBuffer.isView(vector) && !(vector instanceof DataView) ? Array.from(vector) : vector;
const validatedVec = validateVectorDimension(vecArray, expectedDims, 'pgVectorSearch');
if (!validatedVec || !validatedVec.every((n) => typeof n === 'number' && Number.isFinite(n))) {
throw new Error(
`[pg.vectorSearch] "vector" must be a finite numeric array of length ${expectedDims}.`
);
}
const parsedLimit = Number(limit);
if (!Number.isInteger(parsedLimit) || parsedLimit <= 0) {
throw new Error(`[pg.vectorSearch] "limit" must be a positive integer, received: ${String(limit)}`);
}
const vectorLiteral = `[${validatedVec.map(Number).join(',')}]`;
const baseParams = Array.isArray(params) ? [...params] : [];
const vecIdx = baseParams.length + 1;
const limitIdx = baseParams.length + 2;
const cleanedWhere =
whereSql === undefined || whereSql === null
? ''
: assertSafeWhereClause(whereSql, { maxParamIndex: baseParams.length });
const whereClause = cleanedWhere
? `WHERE ${embeddingColumn} IS NOT NULL AND (${cleanedWhere})`
: `WHERE ${embeddingColumn} IS NOT NULL`;
const sql = `SELECT ${safeColumns.join(', ')}, 1 - (${embeddingColumn} <=> $${vecIdx}::vector) AS similarity FROM ${table} ${whereClause} ORDER BY ${embeddingColumn} <=> $${vecIdx}::vector ASC LIMIT $${limitIdx}`;
const boundParams = [...baseParams, vectorLiteral, parsedLimit];
const res = await pgWrapper.query(sql, boundParams);
const rows = Array.isArray(res?.rows) ? res.rows : [];
return {
ok: true,
tool: 'pg.vectorSearch',
summary: `Found ${rows.length} vector match(es)`,
data: { rows },
};
}
/**
* Default PostgreSQL `pg_*` introspection functions permitted inside read-only SQL queries.
* All other `pg_*` functions (advisory locks, backend signaling, server file I/O, etc.)
* bypass `SET TRANSACTION READ ONLY` and are blocked by `assertSafeReadOnlySql`.
*/
export const DEFAULT_ALLOWED_PG_FUNCTIONS = Object.freeze([
'pg_typeof',
'pg_column_size',
'pg_size_pretty',
]);
const FORBIDDEN_READONLY_SQL_KEYWORDS_RE =
/(?<![a-zA-Z0-9_$\u0080-\uffff])(?:INSERT|UPDATE|DELETE|MERGE|CREATE|DROP|ALTER|TRUNCATE|GRANT|REVOKE|COPY|INTO|CALL|DO|EXEC|EXECUTE|PREPARE|DEALLOCATE|SET|RESET|LOCK|VACUUM|REINDEX|CHECKPOINT|DISCARD|LISTEN|UNLISTEN|NOTIFY|PRAGMA|ATTACH|DETACH|TABLE|ANALYZE|BEGIN|START|COMMIT|ROLLBACK|ABORT|SAVEPOINT|RELEASE|DECLARE|MOVE|CLOSE|REASSIGN)(?![a-zA-Z0-9_$\u0080-\uffff])/i;
const FORBIDDEN_READONLY_ADMIN_CLAUSE_RE =
/(?<![a-zA-Z0-9_$\u0080-\uffff])(?:COMMENT\s+ON|REFRESH\s+MATERIALIZED|SECURITY\s+(?:LABEL|DEFINER|INVOKER)|CLUSTER\s+(?:VERBOSE\s+)?[a-zA-Z_"\u0080-\uffff]|LOAD\s+')/i;
const FORBIDDEN_READONLY_LOCK_CLAUSE_RE =
/(?<![a-zA-Z0-9_$\u0080-\uffff])FOR\s+(?:(?:NO\s+KEY\s+)?UPDATE|(?:KEY\s+)?SHARE)(?![a-zA-Z0-9_$\u0080-\uffff])/i;
const FORBIDDEN_READONLY_FUNCTIONS = new Set([
'currval',
'lastval',
'nextval',
'setval',
'set_config',
'ts_stat',
'brin_summarize_new_values',
'brin_summarize_range',
'brin_desummarize_range',
'gin_clean_pending_list',
'xmltable',
'xpath',
'xpath_exists',
'query_to_xml',
'query_to_xmlschema',
'query_to_xml_and_xmlschema',
'cursor_to_xml',
'cursor_to_xmlschema',
'table_to_xml',
'table_to_xmlschema',
'table_to_xml_and_xmlschema',
'schema_to_xml',
'schema_to_xmlschema',
'schema_to_xml_and_xmlschema',
'database_to_xml',
'database_to_xmlschema',
'database_to_xml_and_xmlschema',
]);
const FORBIDDEN_READONLY_FUNCTION_PREFIXES = Object.freeze(['pg_', 'dblink', 'lo_']);
const READONLY_LEAD_KEYWORDS = new Set(['SELECT', 'WITH', 'VALUES']);
const SQL_CLAUSE_STOP_WORDS = new Set([
'WHERE', 'GROUP', 'ORDER', 'HAVING', 'LIMIT', 'OFFSET', 'FETCH',
'JOIN', 'INNER', 'LEFT', 'RIGHT', 'FULL', 'CROSS', 'NATURAL', 'OUTER',
'ON', 'USING', 'UNION', 'INTERSECT', 'EXCEPT', 'WINDOW', 'FOR', 'AS', 'LATERAL', 'ONLY', 'TABLESAMPLE',
]);
const NON_TABLE_FROM_CALLERS = new Set(['EXTRACT', 'SUBSTRING', 'TRIM', 'OVERLAY', 'POSITION']);
const PG_PARAM_STICKY_RE = /\$([1-9]\d*)(?![a-zA-Z0-9_$\u0080-\uffff])/y;
function isIdentChar(ch) {
return Boolean(ch) && /[a-zA-Z0-9_$\u0080-\uffff]/.test(ch);
}
/**
* Lex read-only SQL into sanitized text (literals replaced with spaces, comments/dollar-quoting
* rejected) and a complete token stream preserving operators and numbers for exact callable,
* lexical CTE, table, and top-level LIMIT checks.
*/
function lexReadOnlySql(trimmed, { maxParamIndex = null } = {}) {
let inSingleQuote = false;
let inDoubleQuote = false;
let doubleQuoteBuf = '';
let parenDepth = 0;
let stripped = '';
const tokens = [];
let i = 0;
while (i < trimmed.length) {
const ch = trimmed[i];
const next = trimmed[i + 1] || '';
if (inSingleQuote) {
if (ch === '\\') {
throw new Error('[pg.readOnlySql] Backslash escapes inside string literals are disallowed.');
}
if (ch === "'" && next === "'") {
i += 2;
continue;
}
if (ch === "'") {
inSingleQuote = false;
}
i += 1;
continue;
}
if (inDoubleQuote) {
if (ch === '"' && next === '"') {
doubleQuoteBuf += '"';
i += 2;
continue;
}
if (ch === '"') {
inDoubleQuote = false;
tokens.push({ type: 'ident', value: doubleQuoteBuf, quoted: true, depth: parenDepth });
doubleQuoteBuf = '';
stripped += ' _qident_ ';
i += 1;
continue;
}
doubleQuoteBuf += ch;
i += 1;
continue;
}
if (ch === ';' || ch === '\\' || (ch === '-' && next === '-') || (ch === '/' && next === '*') || (ch === '*' && next === '/')) {
throw new Error('[pg.readOnlySql] Multi-statement semicolons, backslashes, and SQL comments are disallowed.');
}
if (ch === '$') {
const prev = i > 0 ? trimmed[i - 1] : '';
if (isIdentChar(prev)) {
throw new Error('[pg.readOnlySql] Dollar-quoted strings and dollar-identifiers are disallowed.');
}
PG_PARAM_STICKY_RE.lastIndex = i;
const paramMatch = PG_PARAM_STICKY_RE.exec(trimmed);
if (!paramMatch) {
throw new Error('[pg.readOnlySql] Dollar-quoting or invalid $N parameter is disallowed.');
}
const digits = paramMatch[1];
const idx = Number(digits);
if (!Number.isSafeInteger(idx) || idx < 1 || idx > 65535) {
throw new Error(`[pg.readOnlySql] SQL parameter index $${digits} out of valid range ($1..$65535).`);
}
if (maxParamIndex !== null && idx > maxParamIndex) {
throw new Error(
`[pg.readOnlySql] Out-of-range SQL parameter $${idx} (only ${maxParamIndex} param(s) supplied).`
);
}
tokens.push({ type: 'param', value: `$${digits}`, depth: parenDepth });
stripped += ` $${digits} `;
i += digits.length + 1;
continue;
}
if (ch === "'") {
const prev = i > 0 ? trimmed[i - 1] : '';
if (prev && /[a-zA-Z0-9_&\u0080-\uffff]/.test(prev)) {
throw new Error('[pg.readOnlySql] Prefixed string literals (e.g. E\'...\') are disallowed.');
}
inSingleQuote = true;
tokens.push({ type: 'string', value: '', depth: parenDepth });
stripped += ' ';
i += 1;
continue;
}
if (ch === '"') {
const prev = i > 0 ? trimmed[i - 1] : '';
if (prev && /[a-zA-Z0-9_&\u0080-\uffff]/.test(prev)) {
throw new Error('[pg.readOnlySql] Prefixed or Unicode-escaped identifiers are disallowed.');
}
inDoubleQuote = true;
doubleQuoteBuf = '';
i += 1;
continue;
}
if (ch === '(') {
tokens.push({ type: 'punct', value: '(', depth: parenDepth });
parenDepth += 1;
stripped += ch;
i += 1;
continue;
}
if (ch === ')') {
parenDepth -= 1;
if (parenDepth < 0) {
throw new Error('[pg.readOnlySql] Unbalanced parentheses in SQL.');
}
tokens.push({ type: 'punct', value: ')', depth: parenDepth });
stripped += ch;
i += 1;
continue;
}
if (ch === ',' || ch === '.') {
tokens.push({ type: 'punct', value: ch, depth: parenDepth });
stripped += ch;
i += 1;
continue;
}
if (/[0-9]/.test(ch)) {
let end = i + 1;
while (end < trimmed.length && /[0-9._]/.test(trimmed[end])) {
end += 1;
}
const numText = trimmed.slice(i, end);
tokens.push({ type: 'number', value: numText, depth: parenDepth });
stripped += numText;
i = end;
continue;
}
if (/[a-zA-Z_\u0080-\uffff]/.test(ch)) {
let end = i + 1;
while (end < trimmed.length && /[a-zA-Z0-9_\u0080-\uffff]/.test(trimmed[end])) {
end += 1;
}
const word = trimmed.slice(i, end);
tokens.push({ type: 'word', value: word, quoted: false, depth: parenDepth });
stripped += word;
i = end;
continue;
}
if (!/\s/.test(ch)) {
tokens.push({ type: 'op', value: ch, depth: parenDepth });
}
stripped += ch;
i += 1;
}
if (inSingleQuote || inDoubleQuote || parenDepth !== 0) {
throw new Error('[pg.readOnlySql] Unclosed quote or unbalanced parentheses in SQL.');
}
return { stripped, tokens };
}
function skipBalancedParens(tokens, openIdx) {
if (tokens[openIdx]?.type !== 'punct' || tokens[openIdx].value !== '(') return openIdx;
const openDepth = tokens[openIdx].depth;
let cursor = openIdx + 1;
while (
cursor < tokens.length &&
!(tokens[cursor].type === 'punct' && tokens[cursor].value === ')' && tokens[cursor].depth === openDepth)
) {
cursor += 1;
}
return cursor < tokens.length ? cursor + 1 : cursor;
}
function foldPgIdentifier(tok) {
return tok.quoted ? tok.value : tok.value.toLowerCase();
}
function readQualifiedTableAt(tokens, startIdx) {
let idx = startIdx;
let unwrappedOnly = false;
if (tokens[idx]?.type === 'word' && tokens[idx].value.toUpperCase() === 'ONLY') {
idx += 1;
if (tokens[idx]?.type === 'punct' && tokens[idx].value === '(') {
unwrappedOnly = true;
idx += 1;
}
}
const first = tokens[idx];
if (!first || (first.type !== 'word' && first.type !== 'ident')) return null;
if (!first.quoted && SQL_CLAUSE_STOP_WORDS.has(first.value.toUpperCase())) return null;
const foldedParts = [foldPgIdentifier(first)];
const lowerParts = [first.value.toLowerCase()];
idx += 1;
while (
tokens[idx]?.type === 'punct' &&
tokens[idx].value === '.' &&
(tokens[idx + 1]?.type === 'word' || tokens[idx + 1]?.type === 'ident')
) {
foldedParts.push(foldPgIdentifier(tokens[idx + 1]));
lowerParts.push(tokens[idx + 1].value.toLowerCase());
idx += 2;
}
// Table-valued function call (e.g. FROM generate_series(...) or FROM unnest(...)):
// return a function-item marker so the FROM loop skips past its balanced parens & continues comma-joins.
if (!unwrappedOnly && tokens[idx]?.type === 'punct' && tokens[idx].value === '(') {
let nextIdx = skipBalancedParens(tokens, idx);
if (
tokens[nextIdx]?.type === 'word' &&
tokens[nextIdx].value.toUpperCase() === 'WITH' &&
tokens[nextIdx + 1]?.type === 'word' &&
tokens[nextIdx + 1].value.toUpperCase() === 'ORDINALITY'
) {
nextIdx += 2;
}
return { isFunction: true, nextIdx };
}
if (unwrappedOnly) {
if (tokens[idx]?.type === 'punct' && tokens[idx].value === ')') {
idx += 1;
}
}
// PostgreSQL inheritance wildcard: `FROM table_name *`
if (tokens[idx]?.type === 'op' && tokens[idx].value === '*') {
idx += 1;
}
return {
isFunction: false,
fullName: lowerParts.join('.'),
tableName: lowerParts[lowerParts.length - 1],
foldedTableName: foldedParts[foldedParts.length - 1],
schemaName: lowerParts.length >= 2 ? lowerParts[lowerParts.length - 2] : null,
nextIdx: idx,
};
}
/**
* Extract physical table references while maintaining lexical per-depth CTE scopes
* (non-recursive CTEs only enter scope *after* their `AS (...)` body closes, CTE names follow
* exact PostgreSQL case-folding for quoted vs unquoted identifiers, and parenthesized joins
* like `FROM (t1 JOIN t2)` are unpacked cleanly).
*/
function extractReferencedTables(tokens) {
const refs = [];
const enclosingCallStack = [];
const cteScopesByDepth = new Map();
const pendingCteActivation = new Map();
function addCteToDepth(depth, foldedName) {
if (!cteScopesByDepth.has(depth)) cteScopesByDepth.set(depth, new Set());
cteScopesByDepth.get(depth).add(foldedName);
}
function isCteVisible(foldedName, currentDepth) {
for (const [d, set] of cteScopesByDepth.entries()) {
if (d <= currentDepth && set.has(foldedName)) return true;
}
return false;
}
function clearScopesDeeperThan(depth) {
for (const d of [...cteScopesByDepth.keys()]) {
if (d > depth) cteScopesByDepth.delete(d);
}
}
// Pre-register WITH CTE declaration boundaries with exact lexical activation indices
for (let i = 0; i < tokens.length; i += 1) {
const tok = tokens[i];
if (tok.type !== 'word' || tok.value.toUpperCase() !== 'WITH') continue;
const nextUpper = tokens[i + 1]?.type === 'word' ? tokens[i + 1].value.toUpperCase() : '';
if (nextUpper === 'TIME' || nextUpper === 'ORDINALITY' || nextUpper === 'TIES') continue;
const withDepth = tok.depth;
let cursor = i + 1;
let isRecursive = false;
if (tokens[cursor]?.type === 'word' && tokens[cursor].value.toUpperCase() === 'RECURSIVE') {
isRecursive = true;
cursor += 1;
}
while (cursor < tokens.length && tokens[cursor].depth >= withDepth) {
const nameTok = tokens[cursor];
if (!nameTok || (nameTok.type !== 'word' && nameTok.type !== 'ident')) break;
const cteName = foldPgIdentifier(nameTok);
cursor += 1;
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
cursor = skipBalancedParens(tokens, cursor);
}
if (tokens[cursor]?.type !== 'word' || tokens[cursor].value.toUpperCase() !== 'AS') break;
cursor += 1;
if (tokens[cursor]?.type === 'word' && tokens[cursor].value.toUpperCase() === 'NOT') cursor += 1;
if (tokens[cursor]?.type === 'word' && tokens[cursor].value.toUpperCase() === 'MATERIALIZED') cursor += 1;
if (tokens[cursor]?.type !== 'punct' || tokens[cursor].value !== '(') break;
const bodyOpenIdx = cursor;
const afterBodyIdx = skipBalancedParens(tokens, bodyOpenIdx);
const bodyCloseIdx = afterBodyIdx - 1;
const activationIdx = isRecursive ? bodyOpenIdx : bodyCloseIdx;
if (!pendingCteActivation.has(activationIdx)) pendingCteActivation.set(activationIdx, []);
pendingCteActivation.get(activationIdx).push({ depth: withDepth, cteName });
cursor = afterBodyIdx;
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === ',') {
cursor += 1;
continue;
}
break;
}
}
function scanFromOrJoinItem(startIdx, baseDepth) {
let cursor = startIdx;
if (tokens[cursor]?.type === 'word' && tokens[cursor].value.toUpperCase() === 'LATERAL') {
cursor += 1;
}
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
const innerIdx = cursor + 1;
const innerLead =
tokens[innerIdx]?.type === 'word' ? tokens[innerIdx].value.toUpperCase() : '';
// Parenthesized join expression like `FROM (t1 CROSS JOIN t2)` or `FROM ((t1 JOIN t2))`:
// extract the leading table/join item inside the parens (inner JOINs are also scanned by main loop).
if (innerLead !== 'SELECT' && innerLead !== 'WITH' && innerLead !== 'VALUES') {
scanFromOrJoinItem(innerIdx, tokens[cursor].depth + 1);
}
cursor = skipBalancedParens(tokens, cursor);
} else {
const parsed = readQualifiedTableAt(tokens, cursor);
if (!parsed) return null;
if (!parsed.isFunction) {
if (!(parsed.schemaName === null && isCteVisible(parsed.foldedTableName, baseDepth))) {
refs.push({
fullName: parsed.fullName,
tableName: parsed.tableName,
schemaName: parsed.schemaName,
});
}
}
cursor = parsed.nextIdx;
}
// Consume trailing alias / TABLESAMPLE modifiers in either order (PG allows alias before TABLESAMPLE)
for (let step = 0; step < 3; step += 1) {
const curTok = tokens[cursor];
if (!curTok || curTok.depth !== baseDepth) break;
if (curTok.type === 'word' && curTok.value.toUpperCase() === 'TABLESAMPLE') {
cursor += 2; // TABLESAMPLE <method>
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
cursor = skipBalancedParens(tokens, cursor);
}
if (tokens[cursor]?.type === 'word' && tokens[cursor].value.toUpperCase() === 'REPEATABLE') {
cursor += 1;
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
cursor = skipBalancedParens(tokens, cursor);
}
}
continue;
}
if (curTok.type === 'word' && curTok.value.toUpperCase() === 'AS') {
cursor += 1;
// Function column definition list without alias name: `func() AS (a int, b text)`
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
cursor = skipBalancedParens(tokens, cursor);
} else if (tokens[cursor] && (tokens[cursor].type === 'word' || tokens[cursor].type === 'ident')) {
cursor += 1;
if (tokens[cursor]?.type === 'punct' && tokens[cursor].value === '(') {
cursor = skipBalancedParens(tokens, cursor);
}
}
continue;
}
if (
(curTok.type === 'word' || curTok.type === 'ident') &&
!(curTok.type === 'word' && SQL_CLAUSE_STOP_WORDS.has(curTok.value.toUpperCase()))