@stonyx/orm 0.2.1-beta.81 → 0.2.1-beta.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,531 @@
1
+ import { getPool, closePool } from './connection.js';
2
+ import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
3
+ import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
4
+ import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
5
+ import { buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
6
+ import { createRecord, store } from '@stonyx/orm';
7
+ import { confirm } from '@stonyx/utils/prompt';
8
+ import { readFile } from '@stonyx/utils/file';
9
+ import { getPluralName } from '../plural-registry.js';
10
+ import config from 'stonyx/config';
11
+ import log from 'stonyx/log';
12
+ import path from 'path';
13
+
14
+ const defaultDeps = {
15
+ getPool, closePool, ensureMigrationsTable, getAppliedMigrations,
16
+ getMigrationFiles, applyMigration, parseMigrationFile,
17
+ introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
18
+ loadLatestSnapshot, detectSchemaDrift,
19
+ buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch,
20
+ createRecord, store, confirm, readFile, getPluralName, config, log, path
21
+ };
22
+
23
+ export default class PostgresDB {
24
+ /** @type {string[]} PostgreSQL extensions to enable on pool init. Subclasses can override. */
25
+ static extensions = ['vector'];
26
+
27
+ /** @type {string} Config key under config.orm for this adapter. Subclasses can override. */
28
+ static configKey = 'postgres';
29
+
30
+ constructor(deps = {}) {
31
+ const Ctor = this.constructor;
32
+ if (Ctor.instance) return Ctor.instance;
33
+ Ctor.instance = this;
34
+
35
+ this.deps = { ...defaultDeps, ...deps };
36
+ this.pool = null;
37
+ this.pgConfig = this.deps.config.orm[Ctor.configKey];
38
+ }
39
+
40
+ async init() {
41
+ this.pool = await this.deps.getPool(this.pgConfig, this.constructor.extensions);
42
+ await this.deps.ensureMigrationsTable(this.pool, this.pgConfig.migrationsTable);
43
+ await this.loadMemoryRecords();
44
+ }
45
+
46
+ async startup() {
47
+ const migrationsPath = this.deps.path.resolve(this.deps.config.rootPath, this.pgConfig.migrationsDir);
48
+
49
+ // Check for pending migrations
50
+ const applied = await this.deps.getAppliedMigrations(this.pool, this.pgConfig.migrationsTable);
51
+ const files = await this.deps.getMigrationFiles(migrationsPath);
52
+ const pending = files.filter(f => !applied.includes(f));
53
+
54
+ if (pending.length > 0) {
55
+ this.deps.log.db(`${pending.length} pending migration(s) found.`);
56
+
57
+ const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
58
+
59
+ if (shouldApply) {
60
+ for (const filename of pending) {
61
+ const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename));
62
+ const { up } = this.deps.parseMigrationFile(content);
63
+
64
+ await this.deps.applyMigration(this.pool, filename, up, this.pgConfig.migrationsTable);
65
+ this.deps.log.db(`Applied migration: ${filename}`);
66
+ }
67
+
68
+ // Reload records after applying migrations
69
+ await this.loadMemoryRecords();
70
+ } else {
71
+ this.deps.log.warn('Skipping pending migrations. Schema may be outdated.');
72
+ }
73
+ } else if (files.length === 0) {
74
+ const schemas = this.deps.introspectModels();
75
+ const modelCount = Object.keys(schemas).length;
76
+
77
+ if (modelCount > 0) {
78
+ const shouldGenerate = await this.deps.confirm(
79
+ `No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
80
+ );
81
+
82
+ if (shouldGenerate) {
83
+ const { generateMigration } = await import('./migration-generator.js');
84
+ const result = await generateMigration('initial_setup');
85
+
86
+ if (result) {
87
+ const { up } = this.deps.parseMigrationFile(result.content);
88
+ await this.deps.applyMigration(this.pool, result.filename, up, this.pgConfig.migrationsTable);
89
+ this.deps.log.db(`Applied migration: ${result.filename}`);
90
+ await this.loadMemoryRecords();
91
+ }
92
+ } else {
93
+ this.deps.log.warn('Skipping initial migration. Tables may not exist.');
94
+ }
95
+ }
96
+ }
97
+
98
+ // Check for schema drift
99
+ const schemas = this.deps.introspectModels();
100
+ const snapshot = await this.deps.loadLatestSnapshot(this.deps.path.resolve(this.deps.config.rootPath, this.pgConfig.migrationsDir));
101
+
102
+ if (Object.keys(snapshot).length > 0) {
103
+ const drift = this.deps.detectSchemaDrift(schemas, snapshot);
104
+
105
+ if (drift.hasChanges) {
106
+ this.deps.log.warn('Schema drift detected: models have changed since the last migration.');
107
+ this.deps.log.warn('Run `stonyx db:generate-migration` to create a new migration.');
108
+ }
109
+ }
110
+ }
111
+
112
+ async shutdown() {
113
+ await this.deps.closePool();
114
+ this.pool = null;
115
+ }
116
+
117
+ async save() {
118
+ // No-op: PostgreSQL persists data immediately via persist()
119
+ }
120
+
121
+ /**
122
+ * Loads only models with memory: true into the in-memory store on startup.
123
+ * Models with memory: false are skipped — accessed on-demand via find()/findAll().
124
+ */
125
+ async loadMemoryRecords() {
126
+ const schemas = this.deps.introspectModels();
127
+ const order = this.deps.getTopologicalOrder(schemas);
128
+ const Orm = (await import('@stonyx/orm')).default;
129
+
130
+ for (const modelName of order) {
131
+ const { modelClass } = Orm.instance.getRecordClasses(modelName);
132
+ if (modelClass?.memory === false) {
133
+ this.deps.log.db(`Skipping memory load for '${modelName}' (memory: false)`);
134
+ continue;
135
+ }
136
+
137
+ const schema = schemas[modelName];
138
+ const { sql, values } = this.deps.buildSelect(schema.table);
139
+
140
+ try {
141
+ const result = await this.pool.query(sql, values);
142
+
143
+ for (const row of result.rows) {
144
+ const rawData = this._rowToRawData(row, schema);
145
+ this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
146
+ }
147
+ } catch (error) {
148
+ // 42P01 = undefined_table (PG equivalent of ER_NO_SUCH_TABLE)
149
+ if (error.code === '42P01') {
150
+ this.deps.log.db(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
151
+ continue;
152
+ }
153
+
154
+ throw error;
155
+ }
156
+ }
157
+
158
+ // Load views with memory: true
159
+ const viewSchemas = this.deps.introspectViews();
160
+
161
+ for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
162
+ const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName);
163
+ if (viewClass?.memory !== true) {
164
+ this.deps.log.db(`Skipping memory load for view '${viewName}' (memory: false)`);
165
+ continue;
166
+ }
167
+
168
+ const schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
169
+ const { sql, values } = this.deps.buildSelect(schema.table);
170
+
171
+ try {
172
+ const result = await this.pool.query(sql, values);
173
+
174
+ for (const row of result.rows) {
175
+ const rawData = this._rowToRawData(row, schema);
176
+ this.deps.createRecord(viewName, rawData, { isDbRecord: true, serialize: false, transform: false });
177
+ }
178
+ } catch (error) {
179
+ if (error.code === '42P01') {
180
+ this.deps.log.db(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
181
+ continue;
182
+ }
183
+ throw error;
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
190
+ */
191
+ async loadAllRecords() {
192
+ return this.loadMemoryRecords();
193
+ }
194
+
195
+ /**
196
+ * Find a single record by ID from PostgreSQL.
197
+ * Does NOT cache the result in the store for memory: false models.
198
+ * @param {string} modelName
199
+ * @param {string|number} id
200
+ * @returns {Promise<Record|undefined>}
201
+ */
202
+ async findRecord(modelName, id) {
203
+ const schemas = this.deps.introspectModels();
204
+ let schema = schemas[modelName];
205
+
206
+ // Check views if not found in models
207
+ if (!schema) {
208
+ const viewSchemas = this.deps.introspectViews();
209
+ const viewSchema = viewSchemas[modelName];
210
+ if (viewSchema) {
211
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
212
+ }
213
+ }
214
+
215
+ if (!schema) return undefined;
216
+
217
+ const { sql, values } = this.deps.buildSelect(schema.table, { id });
218
+
219
+ try {
220
+ const result = await this.pool.query(sql, values);
221
+
222
+ if (result.rows.length === 0) return undefined;
223
+
224
+ const rawData = this._rowToRawData(result.rows[0], schema);
225
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
226
+
227
+ this._evictIfNotMemory(modelName, record);
228
+
229
+ return record;
230
+ } catch (error) {
231
+ if (error.code === '42P01') return undefined;
232
+ throw error;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Find all records of a model from PostgreSQL, with optional conditions.
238
+ * @param {string} modelName
239
+ * @param {Object} [conditions] - Optional WHERE conditions (key-value pairs)
240
+ * @returns {Promise<Record[]>}
241
+ */
242
+ async findAll(modelName, conditions) {
243
+ const schemas = this.deps.introspectModels();
244
+ let schema = schemas[modelName];
245
+
246
+ // Check views if not found in models
247
+ if (!schema) {
248
+ const viewSchemas = this.deps.introspectViews();
249
+ const viewSchema = viewSchemas[modelName];
250
+ if (viewSchema) {
251
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
252
+ }
253
+ }
254
+
255
+ if (!schema) return [];
256
+
257
+ const { sql, values } = this.deps.buildSelect(schema.table, conditions);
258
+
259
+ try {
260
+ const result = await this.pool.query(sql, values);
261
+
262
+ const records = result.rows.map(row => {
263
+ const rawData = this._rowToRawData(row, schema);
264
+ return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
265
+ });
266
+
267
+ for (const record of records) {
268
+ this._evictIfNotMemory(modelName, record);
269
+ }
270
+
271
+ return records;
272
+ } catch (error) {
273
+ if (error.code === '42P01') return [];
274
+ throw error;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Perform a vector similarity search using cosine distance.
280
+ * @param {string} modelName
281
+ * @param {string} vectorColumn - Name of the vector column
282
+ * @param {number[]} queryVector - The query vector
283
+ * @param {Object} [options]
284
+ * @param {number} [options.limit=10]
285
+ * @param {Object} [options.where] - Additional conditions
286
+ * @returns {Promise<{ record: Record, distance: number }[]>}
287
+ */
288
+ async vectorSearch(modelName, vectorColumn, queryVector, options = {}) {
289
+ const schemas = this.deps.introspectModels();
290
+ const schema = schemas[modelName];
291
+ if (!schema) return [];
292
+
293
+ const { sql, values } = this.deps.buildVectorSearch(schema.table, vectorColumn, queryVector, options);
294
+
295
+ try {
296
+ const result = await this.pool.query(sql, values);
297
+
298
+ return result.rows.map(row => {
299
+ const distance = row.distance;
300
+ delete row.distance;
301
+ const rawData = this._rowToRawData(row, schema);
302
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
303
+ this._evictIfNotMemory(modelName, record);
304
+ return { record, distance };
305
+ });
306
+ } catch (error) {
307
+ if (error.code === '42P01') return [];
308
+ throw error;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Perform a hybrid search combining vector similarity with text filtering.
314
+ * @param {string} modelName
315
+ * @param {string} vectorColumn
316
+ * @param {number[]} queryVector
317
+ * @param {string} textColumn
318
+ * @param {string} textQuery
319
+ * @param {Object} [options]
320
+ * @returns {Promise<{ record: Record, distance: number }[]>}
321
+ */
322
+ async hybridSearch(modelName, vectorColumn, queryVector, textColumn, textQuery, options = {}) {
323
+ const schemas = this.deps.introspectModels();
324
+ const schema = schemas[modelName];
325
+ if (!schema) return [];
326
+
327
+ const { sql, values } = this.deps.buildHybridSearch(schema.table, vectorColumn, queryVector, textColumn, textQuery, options);
328
+
329
+ try {
330
+ const result = await this.pool.query(sql, values);
331
+
332
+ return result.rows.map(row => {
333
+ const distance = row.distance;
334
+ delete row.distance;
335
+ const rawData = this._rowToRawData(row, schema);
336
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
337
+ this._evictIfNotMemory(modelName, record);
338
+ return { record, distance };
339
+ });
340
+ } catch (error) {
341
+ if (error.code === '42P01') return [];
342
+ throw error;
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Remove a record from the in-memory store if its model has memory: false.
348
+ * The record object itself survives — the caller retains the reference.
349
+ * @private
350
+ */
351
+ _evictIfNotMemory(modelName, record) {
352
+ const store = this.deps.store;
353
+
354
+ if (store._memoryResolver && !store._memoryResolver(modelName)) {
355
+ const modelStore = store.get?.(modelName) ?? store.data?.get(modelName);
356
+ if (modelStore) modelStore.delete(record.id);
357
+ }
358
+ }
359
+
360
+ _rowToRawData(row, schema) {
361
+ const rawData = { ...row };
362
+
363
+ // PostgreSQL returns native booleans and parsed JSONB — no manual conversion needed.
364
+ // Only FK remapping and timestamp stripping required.
365
+
366
+ // Map FK columns back to relationship keys
367
+ for (const [fkCol] of Object.entries(schema.foreignKeys)) {
368
+ const relName = fkCol.replace(/_id$/, '');
369
+
370
+ if (rawData[fkCol] !== undefined) {
371
+ rawData[relName] = rawData[fkCol];
372
+ delete rawData[fkCol];
373
+ }
374
+ }
375
+
376
+ // Remove timestamp columns — managed by PostgreSQL
377
+ delete rawData.created_at;
378
+ delete rawData.updated_at;
379
+
380
+ return rawData;
381
+ }
382
+
383
+ async persist(operation, modelName, context, response) {
384
+ // Views are read-only — no-op for all write operations
385
+ const Orm = (await import('@stonyx/orm')).default;
386
+ if (Orm.instance?.isView?.(modelName)) return;
387
+
388
+ switch (operation) {
389
+ case 'create':
390
+ return this._persistCreate(modelName, context, response);
391
+ case 'update':
392
+ return this._persistUpdate(modelName, context, response);
393
+ case 'delete':
394
+ return this._persistDelete(modelName, context);
395
+ }
396
+ }
397
+
398
+ async _persistCreate(modelName, context, response) {
399
+ const schemas = this.deps.introspectModels();
400
+ const schema = schemas[modelName];
401
+
402
+ if (!schema) return;
403
+
404
+ const recordId = response?.data?.id;
405
+ const record = recordId != null ? this.deps.store.get(modelName, isNaN(recordId) ? recordId : parseInt(recordId)) : null;
406
+
407
+ if (!record) return;
408
+
409
+ const insertData = this._recordToRow(record, schema);
410
+
411
+ // For auto-increment models, remove the pending ID
412
+ const isPendingId = record.__data.__pendingSqlId;
413
+
414
+ if (isPendingId) {
415
+ delete insertData.id;
416
+ }
417
+
418
+ const { sql, values } = this.deps.buildInsert(schema.table, insertData);
419
+
420
+ const result = await this.pool.query(sql, values);
421
+
422
+ // Re-key the record in the store if PostgreSQL generated the ID (via RETURNING)
423
+ if (isPendingId && result.rows.length > 0) {
424
+ const pendingId = record.id;
425
+ const realId = result.rows[0].id;
426
+ const modelStore = this.deps.store.get(modelName);
427
+
428
+ modelStore.delete(pendingId);
429
+ record.__data.id = realId;
430
+ record.id = realId;
431
+ modelStore.set(realId, record);
432
+
433
+ // Update the response data with the real ID
434
+ if (response?.data) {
435
+ response.data.id = realId;
436
+ }
437
+
438
+ delete record.__data.__pendingSqlId;
439
+ }
440
+ }
441
+
442
+ async _persistUpdate(modelName, context, response) {
443
+ const schemas = this.deps.introspectModels();
444
+ const schema = schemas[modelName];
445
+
446
+ if (!schema) return;
447
+
448
+ const record = context.record;
449
+ if (!record) return;
450
+
451
+ const id = record.id;
452
+ const oldState = context.oldState || {};
453
+ const currentData = record.__data;
454
+
455
+ // Build a diff of changed columns
456
+ const changedData = {};
457
+
458
+ for (const [col] of Object.entries(schema.columns)) {
459
+ if (currentData[col] !== oldState[col]) {
460
+ changedData[col] = currentData[col] ?? null;
461
+ }
462
+ }
463
+
464
+ // Check FK changes too
465
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
466
+ const relName = fkCol.replace(/_id$/, '');
467
+ const currentFkValue = record.__relationships[relName]?.id ?? null;
468
+ const oldFkValue = oldState[relName] ?? null;
469
+
470
+ if (currentFkValue !== oldFkValue) {
471
+ changedData[fkCol] = currentFkValue;
472
+ }
473
+ }
474
+
475
+ if (Object.keys(changedData).length === 0) return;
476
+
477
+ // PostgreSQL doesn't have ON UPDATE CURRENT_TIMESTAMP — set updated_at manually
478
+ changedData.updated_at = new Date();
479
+
480
+ const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
481
+ await this.pool.query(sql, values);
482
+ }
483
+
484
+ async _persistDelete(modelName, context) {
485
+ const schemas = this.deps.introspectModels();
486
+ const schema = schemas[modelName];
487
+
488
+ if (!schema) return;
489
+
490
+ const id = context.recordId;
491
+ if (id == null) return;
492
+
493
+ const { sql, values } = this.deps.buildDelete(schema.table, id);
494
+ await this.pool.query(sql, values);
495
+ }
496
+
497
+ _recordToRow(record, schema) {
498
+ const row = {};
499
+ const data = record.__data;
500
+
501
+ // ID
502
+ if (data.id !== undefined) {
503
+ row.id = data.id;
504
+ }
505
+
506
+ // Attribute columns
507
+ for (const [col, pgType] of Object.entries(schema.columns)) {
508
+ if (data[col] !== undefined) {
509
+ // JSONB columns: stringify non-string values for PostgreSQL JSONB storage
510
+ row[col] = pgType === 'JSONB' && typeof data[col] !== 'string'
511
+ ? JSON.stringify(data[col])
512
+ : data[col];
513
+ }
514
+ }
515
+
516
+ // FK columns from relationships
517
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
518
+ const relName = fkCol.replace(/_id$/, '');
519
+ const related = record.__relationships[relName];
520
+
521
+ if (related) {
522
+ row[fkCol] = related.id;
523
+ } else if (data[relName] !== undefined) {
524
+ // Raw FK value (e.g., from create payload)
525
+ row[fkCol] = data[relName];
526
+ }
527
+ }
528
+
529
+ return row;
530
+ }
531
+ }
@@ -0,0 +1,149 @@
1
+ const SAFE_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;
2
+
3
+ export function validateIdentifier(name, context = 'identifier') {
4
+ if (!name || typeof name !== 'string' || !SAFE_IDENTIFIER.test(name)) {
5
+ throw new Error(`Invalid SQL ${context}: "${name}". Identifiers must match ${SAFE_IDENTIFIER}`);
6
+ }
7
+
8
+ return name;
9
+ }
10
+
11
+ export function buildInsert(table, data) {
12
+ validateIdentifier(table, 'table name');
13
+
14
+ const keys = Object.keys(data);
15
+ keys.forEach(k => validateIdentifier(k, 'column name'));
16
+
17
+ const placeholders = keys.map((_, i) => `$${i + 1}`);
18
+ const values = keys.map(k => data[k]);
19
+
20
+ const sql = `INSERT INTO "${table}" (${keys.map(k => `"${k}"`).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING "id"`;
21
+
22
+ return { sql, values };
23
+ }
24
+
25
+ export function buildUpdate(table, id, data) {
26
+ validateIdentifier(table, 'table name');
27
+
28
+ const keys = Object.keys(data);
29
+ keys.forEach(k => validateIdentifier(k, 'column name'));
30
+
31
+ const setClauses = keys.map((k, i) => `"${k}" = $${i + 1}`);
32
+ const values = [...keys.map(k => data[k]), id];
33
+
34
+ const sql = `UPDATE "${table}" SET ${setClauses.join(', ')} WHERE "id" = $${keys.length + 1}`;
35
+
36
+ return { sql, values };
37
+ }
38
+
39
+ export function buildDelete(table, id) {
40
+ validateIdentifier(table, 'table name');
41
+
42
+ return {
43
+ sql: `DELETE FROM "${table}" WHERE "id" = $1`,
44
+ values: [id],
45
+ };
46
+ }
47
+
48
+ export function buildSelect(table, conditions) {
49
+ validateIdentifier(table, 'table name');
50
+
51
+ if (!conditions || Object.keys(conditions).length === 0) {
52
+ return { sql: `SELECT * FROM "${table}"`, values: [] };
53
+ }
54
+
55
+ const keys = Object.keys(conditions);
56
+ keys.forEach(k => validateIdentifier(k, 'column name'));
57
+
58
+ const whereClauses = keys.map((k, i) => `"${k}" = $${i + 1}`);
59
+ const values = keys.map(k => conditions[k]);
60
+
61
+ const sql = `SELECT * FROM "${table}" WHERE ${whereClauses.join(' AND ')}`;
62
+
63
+ return { sql, values };
64
+ }
65
+
66
+ /**
67
+ * Build a vector similarity search query using cosine distance (<=>).
68
+ * @param {string} table - Table name
69
+ * @param {string} vectorColumn - Name of the vector column
70
+ * @param {number[]} queryVector - The query vector
71
+ * @param {Object} [options]
72
+ * @param {number} [options.limit=10] - Number of results to return
73
+ * @param {Object} [options.where] - Additional WHERE conditions
74
+ * @returns {{ sql: string, values: any[] }}
75
+ */
76
+ export function buildVectorSearch(table, vectorColumn, queryVector, options = {}) {
77
+ validateIdentifier(table, 'table name');
78
+ validateIdentifier(vectorColumn, 'column name');
79
+
80
+ const { limit = 10, where } = options;
81
+ const values = [];
82
+ let paramIndex = 1;
83
+
84
+ // Vector parameter as a formatted string for pgvector
85
+ const vectorStr = `[${queryVector.join(',')}]`;
86
+ values.push(vectorStr);
87
+ const vectorParam = `$${paramIndex++}`;
88
+
89
+ let whereClauses = [];
90
+ if (where) {
91
+ for (const [k, v] of Object.entries(where)) {
92
+ validateIdentifier(k, 'column name');
93
+ whereClauses.push(`"${k}" = $${paramIndex++}`);
94
+ values.push(v);
95
+ }
96
+ }
97
+
98
+ const whereStr = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
99
+ values.push(limit);
100
+
101
+ const sql = `SELECT *, ("${vectorColumn}" <=> ${vectorParam}::vector) AS distance FROM "${table}"${whereStr} ORDER BY "${vectorColumn}" <=> ${vectorParam}::vector LIMIT $${paramIndex}`;
102
+
103
+ return { sql, values };
104
+ }
105
+
106
+ /**
107
+ * Build a hybrid search query combining vector similarity with text filtering.
108
+ * Uses cosine distance for vector ranking and ILIKE for text matching.
109
+ * @param {string} table - Table name
110
+ * @param {string} vectorColumn - Vector column name
111
+ * @param {number[]} queryVector - The query vector
112
+ * @param {string} textColumn - Column to search text in
113
+ * @param {string} textQuery - Text to search for
114
+ * @param {Object} [options]
115
+ * @param {number} [options.limit=10]
116
+ * @param {Object} [options.where] - Additional WHERE conditions
117
+ * @returns {{ sql: string, values: any[] }}
118
+ */
119
+ export function buildHybridSearch(table, vectorColumn, queryVector, textColumn, textQuery, options = {}) {
120
+ validateIdentifier(table, 'table name');
121
+ validateIdentifier(vectorColumn, 'column name');
122
+ validateIdentifier(textColumn, 'column name');
123
+
124
+ const { limit = 10, where } = options;
125
+ const values = [];
126
+ let paramIndex = 1;
127
+
128
+ const vectorStr = `[${queryVector.join(',')}]`;
129
+ values.push(vectorStr);
130
+ const vectorParam = `$${paramIndex++}`;
131
+
132
+ values.push(`%${textQuery}%`);
133
+ const textParam = `$${paramIndex++}`;
134
+
135
+ let whereClauses = [`"${textColumn}" ILIKE ${textParam}`];
136
+ if (where) {
137
+ for (const [k, v] of Object.entries(where)) {
138
+ validateIdentifier(k, 'column name');
139
+ whereClauses.push(`"${k}" = $${paramIndex++}`);
140
+ values.push(v);
141
+ }
142
+ }
143
+
144
+ values.push(limit);
145
+
146
+ const sql = `SELECT *, ("${vectorColumn}" <=> ${vectorParam}::vector) AS distance FROM "${table}" WHERE ${whereClauses.join(' AND ')} ORDER BY "${vectorColumn}" <=> ${vectorParam}::vector LIMIT $${paramIndex}`;
147
+
148
+ return { sql, values };
149
+ }