-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathplugin.ts
More file actions
857 lines (766 loc) · 34.1 KB
/
plugin.ts
File metadata and controls
857 lines (766 loc) · 34.1 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
/**
* Unified Search Plugin
*
* A single Graphile plugin that iterates over all registered SearchAdapters
* and wires their column detection, filter fields, score fields, and orderBy
* enums into the Graphile v5 hook system.
*
* This replaces the need for separate plugins per algorithm — one plugin,
* multiple adapters.
*
* ARCHITECTURE:
* - init hook: calls adapter.registerTypes() for each adapter
* - GraphQLObjectType_fields hook: adds score fields for each adapter's columns
* - GraphQLEnumType_values hook: adds orderBy enums for each adapter's columns
* - GraphQLInputObjectType_fields hook: adds filter fields for each adapter's columns
*
* Uses the same Grafast meta system (setMeta/getMeta) as the individual plugins.
*/
import 'graphile-build';
import 'graphile-build-pg';
import 'graphile-connection-filter';
import { TYPES } from '@dataplan/pg';
import type { PgCodecWithAttributes } from '@dataplan/pg';
import type { GraphileConfig } from 'graphile-config';
import { getQueryBuilder } from 'graphile-connection-filter';
import type { SearchAdapter, SearchableColumn, UnifiedSearchOptions } from './types';
// ─── TypeScript Namespace Augmentations ──────────────────────────────────────
declare global {
namespace GraphileBuild {
interface Inflection {
/** Name for a unified search score field: {column}{Algorithm}{Metric} */
pgSearchScore(this: Inflection, fieldName: string, algorithmName: string, metricName: string): string;
/** Name for a unified search orderBy enum: {COLUMN}_{ALGORITHM}_{METRIC}_ASC/DESC */
pgSearchOrderByEnum(
this: Inflection,
codec: PgCodecWithAttributes,
attributeName: string,
algorithmName: string,
metricName: string,
ascending: boolean,
): string;
}
interface ScopeObjectFieldsField {
isUnifiedSearchScoreField?: boolean;
}
interface BehaviorStrings {
'unifiedSearch:select': true;
'unifiedSearch:orderBy': true;
}
}
namespace GraphileConfig {
interface Plugins {
UnifiedSearchPlugin: true;
}
}
}
/**
* Interface for the meta value stored by the filter apply via setMeta
* and read by the output field plan via getMeta.
*/
interface SearchScoreDetails {
selectIndex: number;
}
/**
* Cache key for discovered columns per adapter per codec.
* Built during the first hook invocation and reused across hooks.
*/
interface AdapterColumnCache {
adapter: SearchAdapter;
columns: SearchableColumn[];
}
/**
* Creates the unified search plugin with the given options.
*/
export function createUnifiedSearchPlugin(
options: UnifiedSearchOptions
): GraphileConfig.Plugin {
const { adapters, enableSearchScore = true, enableFullTextSearch = true } = options;
// Per-codec cache of discovered columns, keyed by codec name
const codecCache = new Map<string, AdapterColumnCache[]>();
/**
* Get (or compute) the adapter columns for a given codec.
*
* Runs non-supplementary adapters first (e.g. tsvector, BM25, pgvector).
* Supplementary adapters (e.g. trgm with requireIntentionalSearch) are only
* run if at least one adapter with `isIntentionalSearch: true` found columns.
*
* This distinction matters because pgvector (embeddings) is NOT intentional
* text search — its presence alone should not trigger trgm similarity fields.
* Only tsvector and BM25, which represent explicit search infrastructure,
* count as intentional search.
*/
function getAdapterColumns(codec: PgCodecWithAttributes, build: any): AdapterColumnCache[] {
const cacheKey = codec.name;
if (codecCache.has(cacheKey)) {
return codecCache.get(cacheKey)!;
}
const primaryAdapters = adapters.filter((a) => !a.isSupplementary);
const supplementaryAdapters = adapters.filter((a) => a.isSupplementary);
// Phase 1: Run non-supplementary adapters (tsvector, BM25, pgvector, etc.)
const results: AdapterColumnCache[] = [];
let hasIntentionalSearch = false;
for (const adapter of primaryAdapters) {
const columns = adapter.detectColumns(codec, build);
if (columns.length > 0) {
results.push({ adapter, columns });
// Track whether any "intentional search" adapter found columns.
// isIntentionalSearch defaults to true when not explicitly set.
if (adapter.isIntentionalSearch !== false) {
hasIntentionalSearch = true;
}
}
}
// Phase 2: Run supplementary adapters if intentional search exists
// OR if the table/column has a @trgmSearch smart tag.
// pgvector (isIntentionalSearch: false) alone won't trigger trgm.
const hasTrgmSearchTag =
// Table-level tag
(codec.extensions as any)?.tags?.trgmSearch ||
// Column-level tag
(codec.attributes && Object.values(codec.attributes as Record<string, any>).some(
(attr: any) => attr?.extensions?.tags?.trgmSearch
));
if (hasIntentionalSearch || hasTrgmSearchTag) {
for (const adapter of supplementaryAdapters) {
const columns = adapter.detectColumns(codec, build);
if (columns.length > 0) {
results.push({ adapter, columns });
}
}
}
codecCache.set(cacheKey, results);
return results;
}
return {
name: 'UnifiedSearchPlugin',
version: '1.0.0',
description:
'Unified search plugin — abstracts tsvector, BM25, pg_trgm, and pgvector behind a single adapter-based architecture',
after: [
'PgAttributesPlugin',
'PgConnectionArgFilterPlugin',
'PgConnectionArgFilterAttributesPlugin',
'PgConnectionArgFilterOperatorsPlugin',
'AddConnectionFilterOperatorPlugin',
'ConnectionFilterTypesPlugin',
'ConnectionFilterCustomOperatorsPlugin',
// Allow individual codec plugins to load first (e.g. Bm25CodecPlugin)
'Bm25CodecPlugin',
'VectorCodecPlugin',
],
// ─── Custom Inflection Methods ─────────────────────────────────────
inflection: {
add: {
pgSearchScore(_preset, fieldName, algorithmName, metricName) {
// Dedup: if fieldName already ends with the algorithm name, skip it
const algoLower = algorithmName.toLowerCase();
const fieldLower = fieldName.toLowerCase();
const algoSuffix = fieldLower.endsWith(algoLower) ? '' : `-${algorithmName}`;
return this.camelCase(`${fieldName}${algoSuffix}-${metricName}`);
},
pgSearchOrderByEnum(_preset, codec, attributeName, algorithmName, metricName, ascending) {
const columnName = this._attributeName({
codec,
attributeName,
skipRowId: true,
});
// Dedup: if columnName already ends with the algorithm, skip it
const algoLower = algorithmName.toLowerCase();
const colLower = columnName.toLowerCase();
const algoSuffix = colLower.endsWith(`_${algoLower}`) || colLower.endsWith(algoLower)
? '' : `_${algorithmName}`;
return this.constantCase(
`${columnName}${algoSuffix}_${metricName}_${ascending ? 'asc' : 'desc'}`,
);
},
},
},
schema: {
// ─── Behavior Registry ─────────────────────────────────────────────
behaviorRegistry: {
add: {
'unifiedSearch:select': {
description: 'Should unified search score fields be exposed for this attribute',
entities: ['pgCodecAttribute'],
},
'unifiedSearch:orderBy': {
description: 'Should unified search orderBy enums be exposed for this attribute',
entities: ['pgCodecAttribute'],
},
},
},
entityBehavior: {
pgCodecAttribute: {
inferred: {
provides: ['default'],
before: ['inferred', 'override', 'PgAttributesPlugin'],
callback(behavior, [codec, attributeName], build) {
// Use getAdapterColumns which respects isSupplementary logic,
// so trgm columns only appear when intentional search exists
if (!codec?.attributes) return behavior;
const adapterColumns = getAdapterColumns(codec as PgCodecWithAttributes, build);
for (const { columns } of adapterColumns) {
if (columns.some((c) => c.attributeName === attributeName)) {
return [
'unifiedSearch:orderBy',
'unifiedSearch:select',
behavior,
];
}
}
return behavior;
},
},
},
},
hooks: {
/**
* Register all adapter-specific GraphQL types during init.
*/
init(_, build) {
for (const adapter of adapters) {
adapter.registerTypes(build);
}
// Register StringTrgmFilter — a variant of StringFilter that includes
// trgm operators (similarTo, wordSimilarTo). Only string columns on
// tables that qualify for trgm will use this type instead of StringFilter.
const hasTrgmAdapter = adapters.some((a) => a.name === 'trgm');
if (hasTrgmAdapter) {
const DPTYPES = (build as any).dataplanPg?.TYPES;
const textCodec = DPTYPES?.text ?? TYPES.text;
build.registerInputObjectType(
'StringTrgmFilter',
{
pgConnectionFilterOperators: {
isList: false,
pgCodecs: [textCodec],
inputTypeName: 'String',
rangeElementInputTypeName: null,
domainBaseTypeName: null,
},
},
() => ({
description:
'A filter to be used against String fields with pg_trgm support. ' +
'All fields are combined with a logical \u2018and.\u2019',
}),
'UnifiedSearchPlugin (StringTrgmFilter)'
);
}
return _;
},
/**
* Add score/rank/similarity/distance fields for each adapter's columns
* on the appropriate output types.
*/
GraphQLObjectType_fields(fields, build, context) {
const {
inflection,
graphql: { GraphQLFloat },
grafast: { lambda },
} = build;
const {
scope: { isPgClassType, pgCodec: rawPgCodec },
fieldWithHooks,
} = context;
if (!isPgClassType || !rawPgCodec?.attributes) {
return fields;
}
const codec = rawPgCodec as PgCodecWithAttributes;
const adapterColumns = getAdapterColumns(codec, build);
if (adapterColumns.length === 0) {
return fields;
}
let newFields = fields;
for (const { adapter, columns } of adapterColumns) {
for (const column of columns) {
const baseFieldName = inflection.attribute({
codec: codec as any,
attributeName: column.attributeName,
});
const fieldName = inflection.pgSearchScore(
baseFieldName,
adapter.name,
adapter.scoreSemantics.metric,
);
const metaKey = `__unified_search_${adapter.name}_${baseFieldName}`;
newFields = build.extend(
newFields,
{
[fieldName]: fieldWithHooks(
{
fieldName,
isUnifiedSearchScoreField: true,
} as any,
() => ({
description: `${adapter.name.toUpperCase()} ${adapter.scoreSemantics.metric} when searching \`${baseFieldName}\`. Returns null when no ${adapter.name} search filter is active.`,
type: GraphQLFloat,
plan($step: any) {
const $row = $step;
const $select = typeof $row.getClassStep === 'function'
? $row.getClassStep()
: null;
if (!$select) return build.grafast.constant(null);
if (typeof $select.setInliningForbidden === 'function') {
$select.setInliningForbidden();
}
const $details = $select.getMeta(metaKey);
return lambda(
[$details, $row],
([details, row]: readonly [any, any]) => {
const d = details as SearchScoreDetails | null;
if (d == null || row == null || d.selectIndex == null) {
return null;
}
const rawValue = row[d.selectIndex];
return rawValue == null
? null
: TYPES.float.fromPg(rawValue as string);
}
);
},
})
),
},
`UnifiedSearchPlugin adding ${adapter.name} ${adapter.scoreSemantics.metric} field '${fieldName}' for '${column.attributeName}' on '${codec.name}'`
);
}
}
// ── Composite searchScore field ──
if (enableSearchScore && adapterColumns.length > 0) {
// Collect all meta keys for all adapters/columns so the
// composite field can read them at execution time
const allMetaKeys: Array<{
adapterName: string;
metaKey: string;
lowerIsBetter: boolean;
range: [number, number] | null;
}> = [];
for (const { adapter, columns } of adapterColumns) {
for (const column of columns) {
const baseFieldName = inflection.attribute({
codec: codec as any,
attributeName: column.attributeName,
});
allMetaKeys.push({
adapterName: adapter.name,
metaKey: `__unified_search_${adapter.name}_${baseFieldName}`,
lowerIsBetter: adapter.scoreSemantics.lowerIsBetter,
range: adapter.scoreSemantics.range,
});
}
}
newFields = build.extend(
newFields,
{
searchScore: fieldWithHooks(
{
fieldName: 'searchScore',
isUnifiedSearchScoreField: true,
} as any,
() => ({
description:
'Composite search relevance score (0..1, higher = more relevant). ' +
'Computed by normalizing and averaging all active search signals. ' +
'Returns null when no search filters are active.',
type: GraphQLFloat,
plan($step: any) {
const $row = $step;
const $select = typeof $row.getClassStep === 'function'
? $row.getClassStep()
: null;
if (!$select) return build.grafast.constant(null);
if (typeof $select.setInliningForbidden === 'function') {
$select.setInliningForbidden();
}
// Collect all meta steps for all adapters
const $metaSteps = allMetaKeys.map((mk) => $select.getMeta(mk.metaKey));
return lambda(
[...$metaSteps, $row],
(args: readonly any[]) => {
const row = args[args.length - 1];
if (row == null) return null;
let sum = 0;
let count = 0;
for (let i = 0; i < allMetaKeys.length; i++) {
const details = args[i] as SearchScoreDetails | null;
if (details == null || details.selectIndex == null) continue;
const rawValue = row[details.selectIndex];
if (rawValue == null) continue;
const score = TYPES.float.fromPg(rawValue as string);
if (typeof score !== 'number' || isNaN(score)) continue;
const mk = allMetaKeys[i];
// Normalize to 0..1 (higher = better)
let normalized: number;
if (mk.range) {
// Known range: linear normalization
const [min, max] = mk.range;
normalized = mk.lowerIsBetter
? 1 - (score - min) / (max - min)
: (score - min) / (max - min);
} else {
// Unbounded: sigmoid normalization
if (mk.lowerIsBetter) {
// BM25: negative scores, more negative = better
// Map via 1 / (1 + abs(score))
normalized = 1 / (1 + Math.abs(score));
} else {
// Hypothetical unbounded higher-is-better
normalized = score / (1 + score);
}
}
// Clamp to [0, 1]
normalized = Math.max(0, Math.min(1, normalized));
sum += normalized;
count++;
}
if (count === 0) return null;
// Apply optional weights
if (options.searchScoreWeights) {
let weightedSum = 0;
let totalWeight = 0;
let weightIdx = 0;
for (let i = 0; i < allMetaKeys.length; i++) {
const details = args[i] as SearchScoreDetails | null;
if (details == null || details.selectIndex == null) continue;
const rawValue = row[details.selectIndex];
if (rawValue == null) continue;
const mk = allMetaKeys[i];
const weight = options.searchScoreWeights[mk.adapterName] ?? 1;
const score = TYPES.float.fromPg(rawValue as string);
if (typeof score !== 'number' || isNaN(score)) continue;
let normalized: number;
if (mk.range) {
const [min, max] = mk.range;
normalized = mk.lowerIsBetter
? 1 - (score - min) / (max - min)
: (score - min) / (max - min);
} else {
if (mk.lowerIsBetter) {
normalized = 1 / (1 + Math.abs(score));
} else {
normalized = score / (1 + score);
}
}
normalized = Math.max(0, Math.min(1, normalized));
weightedSum += normalized * weight;
totalWeight += weight;
weightIdx++;
}
return totalWeight > 0 ? weightedSum / totalWeight : null;
}
return sum / count;
}
);
},
})
),
},
`UnifiedSearchPlugin adding composite searchScore field on '${codec.name}'`
);
}
return newFields;
},
/**
* Add orderBy enum values for each adapter's score metrics.
*/
GraphQLEnumType_values(values, build, context) {
const { inflection } = build;
const {
scope: { isPgRowSortEnum, pgCodec: rawPgCodec },
} = context;
if (!isPgRowSortEnum || !rawPgCodec?.attributes) {
return values;
}
const codec = rawPgCodec as PgCodecWithAttributes;
const adapterColumns = getAdapterColumns(codec, build);
if (adapterColumns.length === 0) {
return values;
}
let newValues = values;
for (const { adapter, columns } of adapterColumns) {
for (const column of columns) {
const baseFieldName = inflection.attribute({
codec: codec as any,
attributeName: column.attributeName,
});
const metaKey = `unified_order_${adapter.name}_${baseFieldName}`;
const makePlan =
(direction: 'ASC' | 'DESC') => (step: any) => {
if (typeof step.setMeta === 'function') {
step.setMeta(metaKey, direction);
}
};
const ascName = inflection.pgSearchOrderByEnum(
codec, column.attributeName, adapter.name, adapter.scoreSemantics.metric, true,
);
const descName = inflection.pgSearchOrderByEnum(
codec, column.attributeName, adapter.name, adapter.scoreSemantics.metric, false,
);
newValues = build.extend(
newValues,
{
[ascName]: {
extensions: {
grafast: {
apply: makePlan('ASC'),
},
},
},
[descName]: {
extensions: {
grafast: {
apply: makePlan('DESC'),
},
},
},
},
`UnifiedSearchPlugin adding ${adapter.name} orderBy for '${column.attributeName}' on '${codec.name}'`
);
}
}
// ── Composite SEARCH_SCORE orderBy ──
if (enableSearchScore && adapterColumns.length > 0) {
const searchScoreAscName = inflection.constantCase('search_score_asc');
const searchScoreDescName = inflection.constantCase('search_score_desc');
const makeSearchScorePlan =
(direction: 'ASC' | 'DESC') => (step: any) => {
if (typeof step.setMeta === 'function') {
step.setMeta('unified_order_search_score', direction);
}
};
newValues = build.extend(
newValues,
{
[searchScoreAscName]: {
extensions: {
grafast: {
apply: makeSearchScorePlan('ASC'),
},
},
},
[searchScoreDescName]: {
extensions: {
grafast: {
apply: makeSearchScorePlan('DESC'),
},
},
},
},
`UnifiedSearchPlugin adding composite SEARCH_SCORE orderBy on '${codec.name}'`
);
}
return newValues;
},
/**
* Add filter fields for each adapter's columns on connection filter
* input types.
*/
GraphQLInputObjectType_fields(fields, build, context) {
const { inflection, sql } = build;
const {
scope: { isPgConnectionFilter, pgCodec } = {},
fieldWithHooks,
} = context;
if (
!isPgConnectionFilter ||
!pgCodec ||
!pgCodec.attributes ||
pgCodec.isAnonymous
) {
return fields;
}
const codec = pgCodec as PgCodecWithAttributes;
const adapterColumns = getAdapterColumns(codec, build);
if (adapterColumns.length === 0) {
return fields;
}
let newFields = fields;
// ── StringFilter → StringTrgmFilter type swapping ──
// For tables that qualify for trgm, swap the type of string attribute
// filter fields so they get similarTo/wordSimilarTo operators.
const hasTrgm = adapterColumns.some((ac) => ac.adapter.name === 'trgm');
if (hasTrgm) {
const StringTrgmFilterType = build.getTypeByName('StringTrgmFilter');
const StringFilterType = build.getTypeByName('StringFilter');
if (StringTrgmFilterType && StringFilterType) {
const swapped: Record<string, any> = {};
for (const [key, field] of Object.entries(newFields)) {
if (field && typeof field === 'object' && (field as any).type === StringFilterType) {
swapped[key] = Object.assign({}, field, { type: StringTrgmFilterType });
} else {
swapped[key] = field;
}
}
newFields = swapped;
}
}
for (const { adapter, columns } of adapterColumns) {
for (const column of columns) {
const fieldName = inflection.camelCase(
`${adapter.filterPrefix}_${column.attributeName}`
);
const baseFieldName = inflection.attribute({
codec: pgCodec as any,
attributeName: column.attributeName,
});
const scoreMetaKey = `__unified_search_${adapter.name}_${baseFieldName}`;
newFields = build.extend(
newFields,
{
[fieldName]: fieldWithHooks(
{
fieldName,
isPgConnectionFilterField: true,
} as any,
{
description: build.wrapDescription(
`${adapter.name.toUpperCase()} search on the \`${column.attributeName}\` column.`,
'field'
),
type: build.getTypeByName(adapter.getFilterTypeName(build)) as any,
apply: function plan($condition: any, val: any) {
if (val == null) return;
const result = adapter.buildFilterApply(
sql,
$condition.alias,
column,
val,
build,
);
if (!result) return;
// Apply WHERE clause
if (result.whereClause) {
$condition.where(result.whereClause);
}
// Get the query builder for SELECT/ORDER BY injection
const qb = getQueryBuilder(build, $condition);
if (qb && qb.mode === 'normal') {
// Add score to the SELECT list
const wrappedScoreSql = sql`${sql.parens(result.scoreExpression)}::text`;
const scoreIndex = qb.selectAndReturnIndex(wrappedScoreSql);
// Store the select index in meta for the output field plan
qb.setMeta(scoreMetaKey, {
selectIndex: scoreIndex,
} as SearchScoreDetails);
}
// ORDER BY: only add when explicitly requested
if (qb && typeof qb.getMetaRaw === 'function') {
const orderMetaKey = `unified_order_${adapter.name}_${baseFieldName}`;
const explicitDir = qb.getMetaRaw(orderMetaKey);
if (explicitDir) {
qb.orderBy({
fragment: result.scoreExpression,
codec: TYPES.float,
direction: explicitDir,
});
}
}
},
}
),
},
`UnifiedSearchPlugin adding ${adapter.name} filter field '${fieldName}' for '${column.attributeName}' on '${codec.name}'`
);
}
}
// ── fullTextSearch composite filter ──
// Adds a single `fullTextSearch: String` field that fans out the same
// text query to all adapters where supportsTextSearch is true.
// WHERE clauses are combined with OR (match ANY algorithm).
if (enableFullTextSearch) {
// Collect text-compatible adapters and their columns for this codec
const textAdapterColumns = adapterColumns.filter(
(ac) => ac.adapter.supportsTextSearch && ac.adapter.buildTextSearchInput
);
if (textAdapterColumns.length > 0) {
const fieldName = 'fullTextSearch';
newFields = build.extend(
newFields,
{
[fieldName]: fieldWithHooks(
{
fieldName,
isPgConnectionFilterField: true,
} as any,
{
description: build.wrapDescription(
'Composite full-text search. Provide a search string and it will be dispatched ' +
'to all text-compatible search algorithms (tsvector, BM25, pg_trgm) simultaneously. ' +
'Rows matching ANY algorithm are returned. All matching score fields are populated.',
'field'
),
type: build.graphql.GraphQLString as any,
apply: function plan($condition: any, val: any) {
if (val == null || (typeof val === 'string' && val.trim().length === 0)) return;
const text = typeof val === 'string' ? val : String(val);
const qb = getQueryBuilder(build, $condition);
// Collect all WHERE clauses (combined with OR)
const whereClauses: any[] = [];
for (const { adapter, columns } of textAdapterColumns) {
for (const column of columns) {
// Convert text to adapter-specific filter input
const filterInput = adapter.buildTextSearchInput!(text);
const result = adapter.buildFilterApply(
sql,
$condition.alias,
column,
filterInput,
build,
);
if (!result) continue;
// Collect WHERE clause for OR combination
if (result.whereClause) {
whereClauses.push(result.whereClause);
}
// Still inject score into SELECT so score fields are populated
if (qb && qb.mode === 'normal') {
const baseFieldName = inflection.attribute({
codec: pgCodec as any,
attributeName: column.attributeName,
});
const scoreMetaKey = `__unified_search_${adapter.name}_${baseFieldName}`;
const wrappedScoreSql = sql`${sql.parens(result.scoreExpression)}::text`;
const scoreIndex = qb.selectAndReturnIndex(wrappedScoreSql);
qb.setMeta(scoreMetaKey, {
selectIndex: scoreIndex,
} as SearchScoreDetails);
// ORDER BY: only add when explicitly requested via orderBy enum
if (typeof qb.getMetaRaw === 'function') {
const orderMetaKey = `unified_order_${adapter.name}_${baseFieldName}`;
const explicitDir = qb.getMetaRaw(orderMetaKey);
if (explicitDir) {
qb.orderBy({
fragment: result.scoreExpression,
codec: TYPES.float,
direction: explicitDir,
});
}
}
}
}
}
// Apply combined WHERE with OR
if (whereClauses.length > 0) {
if (whereClauses.length === 1) {
$condition.where(whereClauses[0]);
} else {
const combined = sql.fragment`(${sql.join(whereClauses, ' OR ')})`;
$condition.where(combined);
}
}
},
}
),
},
`UnifiedSearchPlugin adding fullTextSearch composite filter on '${codec.name}'`
);
}
}
return newFields;
},
},
},
};
}