-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathPostgraphileFullTextFilterPlugin.js
More file actions
293 lines (255 loc) · 9.23 KB
/
PostgraphileFullTextFilterPlugin.js
File metadata and controls
293 lines (255 loc) · 9.23 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
const tsquery = require('pg-tsquery');
const { omit } = require('graphile-build-pg');
module.exports = function PostGraphileFulltextFilterPlugin(builder) {
builder.hook('inflection', (inflection, build) => build.extend(inflection, {
fullTextScalarTypeName() {
return 'FullText';
},
pgTsvRank(fieldName) {
return this.camelCase(`${fieldName}-rank`);
},
pgTsvOrderByColumnRankEnum(table, attr, ascending) {
const columnName = attr.kind === 'procedure'
? attr.name.substr(table.name.length + 1)
: this._columnName(attr, { skipRowId: true }); // eslint-disable-line no-underscore-dangle
return this.constantCase(`${columnName}_rank_${ascending ? 'asc' : 'desc'}`);
},
}));
builder.hook('build', (build) => {
const {
pgIntrospectionResultsByKind: introspectionResultsByKind,
pgRegisterGqlTypeByTypeId: registerGqlTypeByTypeId,
pgRegisterGqlInputTypeByTypeId: registerGqlInputTypeByTypeId,
graphql: {
GraphQLScalarType,
},
inflection,
} = build;
const tsvectorType = introspectionResultsByKind.type.find(
t => t.name === 'tsvector',
);
if (!tsvectorType) {
throw new Error('Unable to find tsvector type through introspection.');
}
const scalarName = inflection.fullTextScalarTypeName();
const GraphQLFullTextType = new GraphQLScalarType({
name: scalarName,
serialize(value) {
return value;
},
parseValue(value) {
return value;
},
parseLiteral(lit) {
return lit;
},
});
registerGqlTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
registerGqlInputTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
return build.extend(build, {
pgTsvType: tsvectorType,
});
});
builder.hook('init', (_, build) => {
const {
addConnectionFilterOperator,
pgSql: sql,
pgGetGqlInputTypeByTypeIdAndModifier: getGqlInputTypeByTypeIdAndModifier,
graphql: {
GraphQLString,
},
pgTsvType,
} = build;
if (!pgTsvType) {
return build;
}
if (!(addConnectionFilterOperator instanceof Function)) {
throw new Error('PostGraphileFulltextFilterPlugin requires PostGraphileConnectionFilterPlugin to be loaded before it.');
}
const InputType = getGqlInputTypeByTypeIdAndModifier(pgTsvType.id, null);
addConnectionFilterOperator(
[InputType.name],
'matches',
'Performs a full text search on the field.',
() => GraphQLString,
(identifier, val, input, fieldName, queryBuilder) => {
const tsQueryString = tsquery(input);
queryBuilder.__fts_ranks = queryBuilder.__fts_ranks || {};
queryBuilder.__fts_ranks[fieldName] = [identifier, tsQueryString];
return sql.query`${identifier} @@ to_tsquery(${sql.value(tsQueryString)})`;
},
);
return (_, build);
});
builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
const {
pgIntrospectionResultsByKind: introspectionResultsByKind,
graphql: { GraphQLFloat },
pgColumnFilter,
pg2gql,
pgSql: sql,
inflection,
pgTsvType,
} = build;
const {
scope: { isPgRowType, isPgCompoundType, pgIntrospection: table },
fieldWithHooks,
} = context;
if (
!(isPgRowType || isPgCompoundType)
|| !table
|| table.kind !== 'class'
|| !pgTsvType
) {
return fields;
}
const tableType = introspectionResultsByKind.type
.filter(type => type.type === 'c'
&& type.namespaceId === table.namespaceId
&& type.classId === table.id)[0];
if (!tableType) {
throw new Error('Could not determine the type of this table.');
}
const tsvColumns = table.attributes
.filter(attr => attr.typeId === pgTsvType.id)
.filter(attr => pgColumnFilter(attr, build, context))
.filter(attr => !omit(attr, 'filter'));
const tsvProcs = introspectionResultsByKind.procedure
.filter(proc => proc.isStable)
.filter(proc => proc.namespaceId === table.namespaceId)
.filter(proc => proc.name.startsWith(`${table.name}_`))
.filter(proc => proc.argTypeIds.length > 0)
.filter(proc => proc.argTypeIds[0] === tableType.id)
.filter(proc => proc.returnTypeId === pgTsvType.id)
.filter(proc => !omit(proc, 'filter'));
if (tsvColumns.length === 0 && tsvProcs.length === 0) {
return fields;
}
const newRankField = (baseFieldName, rankFieldName) => fieldWithHooks(
rankFieldName,
({ addDataGenerator }) => {
addDataGenerator(({ alias }) => ({
pgQuery: (queryBuilder) => {
const { parentQueryBuilder } = queryBuilder;
if (
!parentQueryBuilder
|| !parentQueryBuilder.__fts_ranks
|| !parentQueryBuilder.__fts_ranks[baseFieldName]) {
return;
}
const [
identifier,
tsQueryString,
] = parentQueryBuilder.__fts_ranks[baseFieldName];
queryBuilder.select(
sql.fragment`ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`,
alias,
);
},
}));
return {
description: `Full-text search ranking when filtered by \`${baseFieldName}\`.`,
type: GraphQLFloat,
resolve: data => pg2gql(data[rankFieldName], GraphQLFloat),
};
},
{
isPgTSVRankField: true,
},
);
const tsvFields = tsvColumns
.reduce((memo, attr) => {
const fieldName = inflection.column(attr);
const rankFieldName = inflection.pgTsvRank(fieldName);
memo[rankFieldName] = newRankField(fieldName, rankFieldName); // eslint-disable-line no-param-reassign
return memo;
}, {});
const tsvProcFields = tsvProcs
.reduce((memo, proc) => {
const psuedoColumnName = proc.name.substr(table.name.length + 1);
const fieldName = inflection.computedColumn(psuedoColumnName, proc, table);
const rankFieldName = inflection.pgTsvRank(fieldName);
memo[rankFieldName] = newRankField(fieldName, rankFieldName); // eslint-disable-line no-param-reassign
return memo;
}, {});
return Object.assign({}, fields, tsvFields, tsvProcFields);
});
builder.hook('GraphQLEnumType:values', (values, build, context) => {
const {
extend,
pgSql: sql,
pgColumnFilter,
pgIntrospectionResultsByKind: introspectionResultsByKind,
inflection,
pgTsvType,
} = build;
const {
scope: {
isPgRowSortEnum,
pgIntrospection: table,
},
} = context;
if (!isPgRowSortEnum || !table || table.kind !== 'class' || !pgTsvType) {
return values;
}
const tableType = introspectionResultsByKind.type
.filter(type => type.type === 'c'
&& type.namespaceId === table.namespaceId
&& type.classId === table.id)[0];
if (!tableType) {
throw new Error('Could not determine the type of this table.');
}
const tsvColumns = introspectionResultsByKind.attribute
.filter(attr => attr.classId === table.id)
.filter(attr => attr.typeId === pgTsvType.id);
const tsvProcs = introspectionResultsByKind.procedure
.filter(proc => proc.isStable)
.filter(proc => proc.namespaceId === table.namespaceId)
.filter(proc => proc.name.startsWith(`${table.name}_`))
.filter(proc => proc.argTypeIds.length === 1)
.filter(proc => proc.argTypeIds[0] === tableType.id)
.filter(proc => proc.returnTypeId === pgTsvType.id)
.filter(proc => !omit(proc, 'order'));
if (tsvColumns.length === 0 && tsvProcs.length === 0) {
return values;
}
return extend(
values,
tsvColumns
.concat(tsvProcs)
.filter(attr => pgColumnFilter(attr, build, context))
.filter(attr => !omit(attr, 'order'))
.reduce((memo, attr) => {
const fieldName = attr.kind === 'procedure'
? inflection.computedColumn(attr.name.substr(table.name.length + 1), attr, table)
: inflection.column(attr);
const ascFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, true);
const descFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, false);
const findExpr = ({ queryBuilder }) => {
if (!queryBuilder.__fts_ranks || !queryBuilder.__fts_ranks[fieldName]) {
return sql.fragment`1`;
}
const [
identifier,
tsQueryString,
] = queryBuilder.__fts_ranks[fieldName];
return sql.fragment`ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`;
};
memo[ascFieldName] = { // eslint-disable-line no-param-reassign
value: {
alias: `${ascFieldName.toLowerCase()}`,
specs: [[findExpr, true]],
},
};
memo[descFieldName] = { // eslint-disable-line no-param-reassign
value: {
alias: `${descFieldName.toLowerCase()}`,
specs: [[findExpr, false]],
},
};
return memo;
}, {}),
`Adding TSV rank columns for sorting on table '${table.name}'`,
);
});
};