graphile-plugin-fulltext-filter 2.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Hyperweb <developers@hyperweb.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # graphile-plugin-fulltext-filter
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/launchql/launchql/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/launchql/launchql/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/launchql/launchql/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ </p>
13
+
14
+ Full text searching on `tsvector` fields for use with `postgraphile-plugin-connection-filter`. This plugin implements a full text search operator for `tsvector` columns in PostGraphile v4.
15
+
16
+ ## Install
17
+
18
+ ```sh
19
+ pnpm add graphile-plugin-fulltext-filter
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### CLI
25
+
26
+ ```bash
27
+ postgraphile --append-plugins postgraphile-plugin-connection-filter,graphile-plugin-fulltext-filter
28
+ ```
29
+
30
+ See [here](https://www.graphile.org/postgraphile/extending/#loading-additional-plugins) for more information about loading plugins with PostGraphile.
31
+
32
+ ### Library
33
+
34
+ ```js
35
+ const express = require('express');
36
+ const { postgraphile } = require('postgraphile');
37
+ const PostGraphileConnectionFilterPlugin = require('postgraphile-plugin-connection-filter');
38
+ const FulltextFilterPlugin = require('graphile-plugin-fulltext-filter');
39
+
40
+ const app = express();
41
+
42
+ app.use(
43
+ postgraphile(pgConfig, schema, {
44
+ appendPlugins: [
45
+ PostGraphileConnectionFilterPlugin,
46
+ FulltextFilterPlugin,
47
+ ],
48
+ })
49
+ );
50
+
51
+ app.listen(5000);
52
+ ```
53
+
54
+ ## Performance
55
+
56
+ All `tsvector` columns that aren't `@omit`'d should have indexes on them:
57
+
58
+ ```sql
59
+ ALTER TABLE posts ADD COLUMN full_text tsvector;
60
+ CREATE INDEX full_text_idx ON posts USING gin(full_text);
61
+ ```
62
+
63
+ ## Operators
64
+
65
+ This plugin adds the `matches` filter operator to the filter plugin, accepting a GraphQL String input and using the `@@` operator to perform full-text searches on `tsvector` columns.
66
+
67
+ This plugin uses [pg-tsquery](https://github.com/caub/pg-tsquery) to parse the user input to prevent Postgres throwing on bad user input unnecessarily.
68
+
69
+ ## Fields
70
+
71
+ For each `tsvector` column, a rank column will be automatically added to the GraphQL type for the table by appending `Rank` to the end of the column's name. For example, a column `full_text` will appear as `fullText` in the GraphQL type, and a second column, `fullTextRank` will be added to the type as a `Float`.
72
+
73
+ This rank field can be used for ordering and is automatically added to the orderBy enum for the table.
74
+
75
+ ## Examples
76
+
77
+ ```graphql
78
+ query {
79
+ allPosts(
80
+ filter: {
81
+ fullText: { matches: 'foo -bar' }
82
+ }
83
+ orderBy: FULL_TEXT_RANK_DESC
84
+ ) {
85
+ ...
86
+ fullTextRank
87
+ }
88
+ }
89
+ ```
90
+
91
+ ## Testing
92
+
93
+ ```sh
94
+ pnpm test
95
+ ```
96
+
97
+ Tests expect a running PostgreSQL instance. See test configuration for database connection details.
98
+
99
+ ---
100
+
101
+ ## Education and Tutorials
102
+
103
+ 1. 🚀 [Quickstart: Getting Up and Running](https://launchql.com/learn/quickstart)
104
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
105
+
106
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://launchql.com/learn/modular-postgres)
107
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
108
+
109
+ 3. ✏️ [Authoring Database Changes](https://launchql.com/learn/authoring-database-changes)
110
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
111
+
112
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://launchql.com/learn/e2e-postgres-testing)
113
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
114
+
115
+ 5. ⚡ [Supabase Testing](https://launchql.com/learn/supabase)
116
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
117
+
118
+ 6. 💧 [Drizzle ORM Testing](https://launchql.com/learn/drizzle-testing)
119
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
120
+
121
+ 7. 🔧 [Troubleshooting](https://launchql.com/learn/troubleshooting)
122
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
123
+
124
+ ## Related LaunchQL Tooling
125
+
126
+ ### 🧪 Testing
127
+
128
+ * [launchql/pgsql-test](https://github.com/launchql/launchql/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
129
+ * [launchql/supabase-test](https://github.com/launchql/launchql/tree/main/packages/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
130
+ * [launchql/graphile-test](https://github.com/launchql/launchql/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
131
+ * [launchql/pg-query-context](https://github.com/launchql/launchql/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
132
+
133
+ ### 🧠 Parsing & AST
134
+
135
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
136
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
137
+ * [launchql/pg-proto-parser](https://github.com/launchql/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
138
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
139
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
140
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
141
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
142
+
143
+ ### 🚀 API & Dev Tools
144
+
145
+ * [launchql/server](https://github.com/launchql/launchql/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
146
+ * [launchql/explorer](https://github.com/launchql/launchql/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
147
+
148
+ ### 🔁 Streaming & Uploads
149
+
150
+ * [launchql/s3-streamer](https://github.com/launchql/launchql/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
151
+ * [launchql/etag-hash](https://github.com/launchql/launchql/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
152
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
153
+ * [launchql/uuid-hash](https://github.com/launchql/launchql/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
154
+ * [launchql/uuid-stream](https://github.com/launchql/launchql/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
155
+ * [launchql/upload-names](https://github.com/launchql/launchql/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
156
+
157
+ ### 🧰 CLI & Codegen
158
+
159
+ * [pgpm](https://github.com/launchql/launchql/tree/main/packages/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
160
+ * [@launchql/cli](https://github.com/launchql/launchql/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
161
+ * [launchql/launchql-gen](https://github.com/launchql/launchql/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
162
+ * [@launchql/query-builder](https://github.com/launchql/launchql/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
163
+ * [@launchql/query](https://github.com/launchql/launchql/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
164
+
165
+ ## Credits
166
+
167
+ 🛠 Built by LaunchQL — if you like our tools, please checkout and contribute to [our github ⚛️](https://github.com/launchql)
168
+
169
+
170
+ ## Disclaimer
171
+
172
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
173
+
174
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,189 @@
1
+ import { Tsquery } from 'pg-tsquery';
2
+ import { omit } from 'graphile-build-pg';
3
+ const tsquery = new Tsquery();
4
+ const PostGraphileFulltextFilterPlugin = (builder) => {
5
+ builder.hook('inflection', (inflection, build) => build.extend(inflection, {
6
+ fullTextScalarTypeName() {
7
+ return 'FullText';
8
+ },
9
+ pgTsvRank(fieldName) {
10
+ return this.camelCase(`${fieldName}-rank`);
11
+ },
12
+ pgTsvOrderByColumnRankEnum(table, attr, ascending) {
13
+ const columnName = attr.kind === 'procedure'
14
+ ? attr.name.substring(table.name.length + 1)
15
+ : this._columnName(attr, { skipRowId: true }); // eslint-disable-line no-underscore-dangle
16
+ return this.constantCase(`${columnName}_rank_${ascending ? 'asc' : 'desc'}`);
17
+ },
18
+ }));
19
+ builder.hook('build', (build) => {
20
+ const { pgIntrospectionResultsByKind: introspectionResultsByKind, pgRegisterGqlTypeByTypeId: registerGqlTypeByTypeId, pgRegisterGqlInputTypeByTypeId: registerGqlInputTypeByTypeId, graphql: { GraphQLScalarType }, inflection, } = build;
21
+ const tsvectorType = introspectionResultsByKind.type.find((t) => t.name === 'tsvector');
22
+ if (!tsvectorType) {
23
+ throw new Error('Unable to find tsvector type through introspection.');
24
+ }
25
+ const scalarName = inflection.fullTextScalarTypeName();
26
+ const GraphQLFullTextType = new GraphQLScalarType({
27
+ name: scalarName,
28
+ serialize(value) {
29
+ return value;
30
+ },
31
+ parseValue(value) {
32
+ return value;
33
+ },
34
+ parseLiteral(lit) {
35
+ return lit;
36
+ },
37
+ });
38
+ registerGqlTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
39
+ registerGqlInputTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
40
+ return build.extend(build, {
41
+ pgTsvType: tsvectorType,
42
+ });
43
+ });
44
+ builder.hook('init', (_, build) => {
45
+ const { addConnectionFilterOperator, pgSql: sql, pgGetGqlInputTypeByTypeIdAndModifier: getGqlInputTypeByTypeIdAndModifier, graphql: { GraphQLString }, pgTsvType, } = build;
46
+ if (!pgTsvType) {
47
+ return build;
48
+ }
49
+ if (!(addConnectionFilterOperator instanceof Function)) {
50
+ throw new Error('PostGraphileFulltextFilterPlugin requires PostGraphileConnectionFilterPlugin to be loaded before it.');
51
+ }
52
+ const InputType = getGqlInputTypeByTypeIdAndModifier(pgTsvType.id, null);
53
+ addConnectionFilterOperator(InputType.name, 'matches', 'Performs a full text search on the field.', () => GraphQLString, (identifier, val, input, fieldName, queryBuilder) => {
54
+ const tsQueryString = `${tsquery.parse(input) || ''}`;
55
+ queryBuilder.__fts_ranks = queryBuilder.__fts_ranks || {};
56
+ queryBuilder.__fts_ranks[fieldName] = [identifier, tsQueryString];
57
+ return sql.query `${identifier} @@ to_tsquery(${sql.value(tsQueryString)})`;
58
+ }, {
59
+ allowedFieldTypes: [InputType.name],
60
+ });
61
+ return build;
62
+ });
63
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
64
+ const { pgIntrospectionResultsByKind: introspectionResultsByKind, graphql: { GraphQLFloat }, pgColumnFilter, pg2gql, pgSql: sql, inflection, pgTsvType, } = build;
65
+ const { scope: { isPgRowType, isPgCompoundType, pgIntrospection: table }, fieldWithHooks, } = context;
66
+ if (!(isPgRowType || isPgCompoundType) ||
67
+ !table ||
68
+ table.kind !== 'class' ||
69
+ !pgTsvType) {
70
+ return fields;
71
+ }
72
+ const tableType = introspectionResultsByKind.type.find((type) => type.type === 'c' &&
73
+ type.namespaceId === table.namespaceId &&
74
+ type.classId === table.id);
75
+ if (!tableType) {
76
+ throw new Error('Could not determine the type of this table.');
77
+ }
78
+ const tsvColumns = table.attributes
79
+ .filter((attr) => attr.typeId === pgTsvType.id)
80
+ .filter((attr) => pgColumnFilter(attr, build, context))
81
+ .filter((attr) => !omit(attr, 'filter'));
82
+ const tsvProcs = introspectionResultsByKind.procedure
83
+ .filter((proc) => proc.isStable)
84
+ .filter((proc) => proc.namespaceId === table.namespaceId)
85
+ .filter((proc) => proc.name.startsWith(`${table.name}_`))
86
+ .filter((proc) => proc.argTypeIds.length > 0)
87
+ .filter((proc) => proc.argTypeIds[0] === tableType.id)
88
+ .filter((proc) => proc.returnTypeId === pgTsvType.id)
89
+ .filter((proc) => !omit(proc, 'filter'));
90
+ if (tsvColumns.length === 0 && tsvProcs.length === 0) {
91
+ return fields;
92
+ }
93
+ const newRankField = (baseFieldName, rankFieldName) => fieldWithHooks(rankFieldName, ({ addDataGenerator }) => {
94
+ addDataGenerator(({ alias }) => ({
95
+ pgQuery: (queryBuilder) => {
96
+ const { parentQueryBuilder } = queryBuilder;
97
+ if (!parentQueryBuilder ||
98
+ !parentQueryBuilder.__fts_ranks ||
99
+ !parentQueryBuilder.__fts_ranks[baseFieldName]) {
100
+ return;
101
+ }
102
+ const [identifier, tsQueryString] = parentQueryBuilder.__fts_ranks[baseFieldName];
103
+ queryBuilder.select?.(sql.fragment `ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`, alias);
104
+ },
105
+ }));
106
+ return {
107
+ description: `Full-text search ranking when filtered by \`${baseFieldName}\`.`,
108
+ type: GraphQLFloat,
109
+ resolve: (data) => pg2gql(data[rankFieldName], GraphQLFloat),
110
+ };
111
+ }, {
112
+ isPgTSVRankField: true,
113
+ });
114
+ const tsvFields = tsvColumns.reduce((memo, attr) => {
115
+ const fieldName = inflection.column(attr);
116
+ const rankFieldName = inflection.pgTsvRank(fieldName);
117
+ memo[rankFieldName] = newRankField(fieldName, rankFieldName);
118
+ return memo;
119
+ }, {});
120
+ const tsvProcFields = tsvProcs.reduce((memo, proc) => {
121
+ const psuedoColumnName = proc.name.substring(table.name.length + 1);
122
+ const fieldName = inflection.computedColumn(psuedoColumnName, proc, table);
123
+ const rankFieldName = inflection.pgTsvRank(fieldName);
124
+ memo[rankFieldName] = newRankField(fieldName, rankFieldName);
125
+ return memo;
126
+ }, {});
127
+ return Object.assign({}, fields, tsvFields, tsvProcFields);
128
+ });
129
+ builder.hook('GraphQLEnumType:values', (values, build, context) => {
130
+ const { extend, pgSql: sql, pgColumnFilter, pgIntrospectionResultsByKind: introspectionResultsByKind, inflection, pgTsvType, } = build;
131
+ const { scope: { isPgRowSortEnum, pgIntrospection: table }, } = context;
132
+ if (!isPgRowSortEnum || !table || table.kind !== 'class' || !pgTsvType) {
133
+ return values;
134
+ }
135
+ const tableType = introspectionResultsByKind.type.find((type) => type.type === 'c' &&
136
+ type.namespaceId === table.namespaceId &&
137
+ type.classId === table.id);
138
+ if (!tableType) {
139
+ throw new Error('Could not determine the type of this table.');
140
+ }
141
+ const tsvColumns = introspectionResultsByKind.attribute
142
+ .filter((attr) => attr.classId === table.id)
143
+ .filter((attr) => attr.typeId === pgTsvType.id);
144
+ const tsvProcs = introspectionResultsByKind.procedure
145
+ .filter((proc) => proc.isStable)
146
+ .filter((proc) => proc.namespaceId === table.namespaceId)
147
+ .filter((proc) => proc.name.startsWith(`${table.name}_`))
148
+ .filter((proc) => proc.argTypeIds.length === 1)
149
+ .filter((proc) => proc.argTypeIds[0] === tableType.id)
150
+ .filter((proc) => proc.returnTypeId === pgTsvType.id)
151
+ .filter((proc) => !omit(proc, 'order'));
152
+ if (tsvColumns.length === 0 && tsvProcs.length === 0) {
153
+ return values;
154
+ }
155
+ return extend(values, tsvColumns
156
+ .concat(tsvProcs)
157
+ .filter((attr) => pgColumnFilter(attr, build, context))
158
+ .filter((attr) => !omit(attr, 'order'))
159
+ .reduce((memo, attr) => {
160
+ const fieldName = attr.kind === 'procedure'
161
+ ? inflection.computedColumn(attr.name.substring(table.name.length + 1), attr, table)
162
+ : inflection.column(attr);
163
+ const ascFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, true);
164
+ const descFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, false);
165
+ const findExpr = ({ queryBuilder }) => {
166
+ if (!queryBuilder.__fts_ranks || !queryBuilder.__fts_ranks[fieldName]) {
167
+ return sql.fragment `1`;
168
+ }
169
+ const [identifier, tsQueryString] = queryBuilder.__fts_ranks[fieldName];
170
+ return sql.fragment `ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`;
171
+ };
172
+ memo[ascFieldName] = {
173
+ value: {
174
+ alias: `${ascFieldName.toLowerCase()}`,
175
+ specs: [[findExpr, true]],
176
+ },
177
+ };
178
+ memo[descFieldName] = {
179
+ value: {
180
+ alias: `${descFieldName.toLowerCase()}`,
181
+ specs: [[findExpr, false]],
182
+ },
183
+ };
184
+ return memo;
185
+ }, {}), `Adding TSV rank columns for sorting on table '${table.name}'`);
186
+ });
187
+ };
188
+ export { PostGraphileFulltextFilterPlugin };
189
+ export default PostGraphileFulltextFilterPlugin;
package/index.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from 'graphile-build';
2
+ declare const PostGraphileFulltextFilterPlugin: Plugin;
3
+ export { PostGraphileFulltextFilterPlugin };
4
+ export default PostGraphileFulltextFilterPlugin;
package/index.js ADDED
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PostGraphileFulltextFilterPlugin = void 0;
4
+ const pg_tsquery_1 = require("pg-tsquery");
5
+ const graphile_build_pg_1 = require("graphile-build-pg");
6
+ const tsquery = new pg_tsquery_1.Tsquery();
7
+ const PostGraphileFulltextFilterPlugin = (builder) => {
8
+ builder.hook('inflection', (inflection, build) => build.extend(inflection, {
9
+ fullTextScalarTypeName() {
10
+ return 'FullText';
11
+ },
12
+ pgTsvRank(fieldName) {
13
+ return this.camelCase(`${fieldName}-rank`);
14
+ },
15
+ pgTsvOrderByColumnRankEnum(table, attr, ascending) {
16
+ const columnName = attr.kind === 'procedure'
17
+ ? attr.name.substring(table.name.length + 1)
18
+ : this._columnName(attr, { skipRowId: true }); // eslint-disable-line no-underscore-dangle
19
+ return this.constantCase(`${columnName}_rank_${ascending ? 'asc' : 'desc'}`);
20
+ },
21
+ }));
22
+ builder.hook('build', (build) => {
23
+ const { pgIntrospectionResultsByKind: introspectionResultsByKind, pgRegisterGqlTypeByTypeId: registerGqlTypeByTypeId, pgRegisterGqlInputTypeByTypeId: registerGqlInputTypeByTypeId, graphql: { GraphQLScalarType }, inflection, } = build;
24
+ const tsvectorType = introspectionResultsByKind.type.find((t) => t.name === 'tsvector');
25
+ if (!tsvectorType) {
26
+ throw new Error('Unable to find tsvector type through introspection.');
27
+ }
28
+ const scalarName = inflection.fullTextScalarTypeName();
29
+ const GraphQLFullTextType = new GraphQLScalarType({
30
+ name: scalarName,
31
+ serialize(value) {
32
+ return value;
33
+ },
34
+ parseValue(value) {
35
+ return value;
36
+ },
37
+ parseLiteral(lit) {
38
+ return lit;
39
+ },
40
+ });
41
+ registerGqlTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
42
+ registerGqlInputTypeByTypeId(tsvectorType.id, () => GraphQLFullTextType);
43
+ return build.extend(build, {
44
+ pgTsvType: tsvectorType,
45
+ });
46
+ });
47
+ builder.hook('init', (_, build) => {
48
+ const { addConnectionFilterOperator, pgSql: sql, pgGetGqlInputTypeByTypeIdAndModifier: getGqlInputTypeByTypeIdAndModifier, graphql: { GraphQLString }, pgTsvType, } = build;
49
+ if (!pgTsvType) {
50
+ return build;
51
+ }
52
+ if (!(addConnectionFilterOperator instanceof Function)) {
53
+ throw new Error('PostGraphileFulltextFilterPlugin requires PostGraphileConnectionFilterPlugin to be loaded before it.');
54
+ }
55
+ const InputType = getGqlInputTypeByTypeIdAndModifier(pgTsvType.id, null);
56
+ addConnectionFilterOperator(InputType.name, 'matches', 'Performs a full text search on the field.', () => GraphQLString, (identifier, val, input, fieldName, queryBuilder) => {
57
+ const tsQueryString = `${tsquery.parse(input) || ''}`;
58
+ queryBuilder.__fts_ranks = queryBuilder.__fts_ranks || {};
59
+ queryBuilder.__fts_ranks[fieldName] = [identifier, tsQueryString];
60
+ return sql.query `${identifier} @@ to_tsquery(${sql.value(tsQueryString)})`;
61
+ }, {
62
+ allowedFieldTypes: [InputType.name],
63
+ });
64
+ return build;
65
+ });
66
+ builder.hook('GraphQLObjectType:fields', (fields, build, context) => {
67
+ const { pgIntrospectionResultsByKind: introspectionResultsByKind, graphql: { GraphQLFloat }, pgColumnFilter, pg2gql, pgSql: sql, inflection, pgTsvType, } = build;
68
+ const { scope: { isPgRowType, isPgCompoundType, pgIntrospection: table }, fieldWithHooks, } = context;
69
+ if (!(isPgRowType || isPgCompoundType) ||
70
+ !table ||
71
+ table.kind !== 'class' ||
72
+ !pgTsvType) {
73
+ return fields;
74
+ }
75
+ const tableType = introspectionResultsByKind.type.find((type) => type.type === 'c' &&
76
+ type.namespaceId === table.namespaceId &&
77
+ type.classId === table.id);
78
+ if (!tableType) {
79
+ throw new Error('Could not determine the type of this table.');
80
+ }
81
+ const tsvColumns = table.attributes
82
+ .filter((attr) => attr.typeId === pgTsvType.id)
83
+ .filter((attr) => pgColumnFilter(attr, build, context))
84
+ .filter((attr) => !(0, graphile_build_pg_1.omit)(attr, 'filter'));
85
+ const tsvProcs = introspectionResultsByKind.procedure
86
+ .filter((proc) => proc.isStable)
87
+ .filter((proc) => proc.namespaceId === table.namespaceId)
88
+ .filter((proc) => proc.name.startsWith(`${table.name}_`))
89
+ .filter((proc) => proc.argTypeIds.length > 0)
90
+ .filter((proc) => proc.argTypeIds[0] === tableType.id)
91
+ .filter((proc) => proc.returnTypeId === pgTsvType.id)
92
+ .filter((proc) => !(0, graphile_build_pg_1.omit)(proc, 'filter'));
93
+ if (tsvColumns.length === 0 && tsvProcs.length === 0) {
94
+ return fields;
95
+ }
96
+ const newRankField = (baseFieldName, rankFieldName) => fieldWithHooks(rankFieldName, ({ addDataGenerator }) => {
97
+ addDataGenerator(({ alias }) => ({
98
+ pgQuery: (queryBuilder) => {
99
+ const { parentQueryBuilder } = queryBuilder;
100
+ if (!parentQueryBuilder ||
101
+ !parentQueryBuilder.__fts_ranks ||
102
+ !parentQueryBuilder.__fts_ranks[baseFieldName]) {
103
+ return;
104
+ }
105
+ const [identifier, tsQueryString] = parentQueryBuilder.__fts_ranks[baseFieldName];
106
+ queryBuilder.select?.(sql.fragment `ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`, alias);
107
+ },
108
+ }));
109
+ return {
110
+ description: `Full-text search ranking when filtered by \`${baseFieldName}\`.`,
111
+ type: GraphQLFloat,
112
+ resolve: (data) => pg2gql(data[rankFieldName], GraphQLFloat),
113
+ };
114
+ }, {
115
+ isPgTSVRankField: true,
116
+ });
117
+ const tsvFields = tsvColumns.reduce((memo, attr) => {
118
+ const fieldName = inflection.column(attr);
119
+ const rankFieldName = inflection.pgTsvRank(fieldName);
120
+ memo[rankFieldName] = newRankField(fieldName, rankFieldName);
121
+ return memo;
122
+ }, {});
123
+ const tsvProcFields = tsvProcs.reduce((memo, proc) => {
124
+ const psuedoColumnName = proc.name.substring(table.name.length + 1);
125
+ const fieldName = inflection.computedColumn(psuedoColumnName, proc, table);
126
+ const rankFieldName = inflection.pgTsvRank(fieldName);
127
+ memo[rankFieldName] = newRankField(fieldName, rankFieldName);
128
+ return memo;
129
+ }, {});
130
+ return Object.assign({}, fields, tsvFields, tsvProcFields);
131
+ });
132
+ builder.hook('GraphQLEnumType:values', (values, build, context) => {
133
+ const { extend, pgSql: sql, pgColumnFilter, pgIntrospectionResultsByKind: introspectionResultsByKind, inflection, pgTsvType, } = build;
134
+ const { scope: { isPgRowSortEnum, pgIntrospection: table }, } = context;
135
+ if (!isPgRowSortEnum || !table || table.kind !== 'class' || !pgTsvType) {
136
+ return values;
137
+ }
138
+ const tableType = introspectionResultsByKind.type.find((type) => type.type === 'c' &&
139
+ type.namespaceId === table.namespaceId &&
140
+ type.classId === table.id);
141
+ if (!tableType) {
142
+ throw new Error('Could not determine the type of this table.');
143
+ }
144
+ const tsvColumns = introspectionResultsByKind.attribute
145
+ .filter((attr) => attr.classId === table.id)
146
+ .filter((attr) => attr.typeId === pgTsvType.id);
147
+ const tsvProcs = introspectionResultsByKind.procedure
148
+ .filter((proc) => proc.isStable)
149
+ .filter((proc) => proc.namespaceId === table.namespaceId)
150
+ .filter((proc) => proc.name.startsWith(`${table.name}_`))
151
+ .filter((proc) => proc.argTypeIds.length === 1)
152
+ .filter((proc) => proc.argTypeIds[0] === tableType.id)
153
+ .filter((proc) => proc.returnTypeId === pgTsvType.id)
154
+ .filter((proc) => !(0, graphile_build_pg_1.omit)(proc, 'order'));
155
+ if (tsvColumns.length === 0 && tsvProcs.length === 0) {
156
+ return values;
157
+ }
158
+ return extend(values, tsvColumns
159
+ .concat(tsvProcs)
160
+ .filter((attr) => pgColumnFilter(attr, build, context))
161
+ .filter((attr) => !(0, graphile_build_pg_1.omit)(attr, 'order'))
162
+ .reduce((memo, attr) => {
163
+ const fieldName = attr.kind === 'procedure'
164
+ ? inflection.computedColumn(attr.name.substring(table.name.length + 1), attr, table)
165
+ : inflection.column(attr);
166
+ const ascFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, true);
167
+ const descFieldName = inflection.pgTsvOrderByColumnRankEnum(table, attr, false);
168
+ const findExpr = ({ queryBuilder }) => {
169
+ if (!queryBuilder.__fts_ranks || !queryBuilder.__fts_ranks[fieldName]) {
170
+ return sql.fragment `1`;
171
+ }
172
+ const [identifier, tsQueryString] = queryBuilder.__fts_ranks[fieldName];
173
+ return sql.fragment `ts_rank(${identifier}, to_tsquery(${sql.value(tsQueryString)}))`;
174
+ };
175
+ memo[ascFieldName] = {
176
+ value: {
177
+ alias: `${ascFieldName.toLowerCase()}`,
178
+ specs: [[findExpr, true]],
179
+ },
180
+ };
181
+ memo[descFieldName] = {
182
+ value: {
183
+ alias: `${descFieldName.toLowerCase()}`,
184
+ specs: [[findExpr, false]],
185
+ },
186
+ };
187
+ return memo;
188
+ }, {}), `Adding TSV rank columns for sorting on table '${table.name}'`);
189
+ });
190
+ };
191
+ exports.PostGraphileFulltextFilterPlugin = PostGraphileFulltextFilterPlugin;
192
+ exports.default = PostGraphileFulltextFilterPlugin;
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "graphile-plugin-fulltext-filter",
3
+ "version": "2.0.1",
4
+ "description": "Full text searching on tsvector fields for use with postgraphile-plugin-connection-filter",
5
+ "main": "index.js",
6
+ "module": "esm/index.js",
7
+ "types": "index.d.ts",
8
+ "author": "Mark Lipscombe",
9
+ "homepage": "https://github.com/launchql/launchql",
10
+ "license": "MIT",
11
+ "scripts": {
12
+ "clean": "makage clean",
13
+ "copy": "makage assets",
14
+ "prepack": "pnpm run build",
15
+ "build": "makage build",
16
+ "build:dev": "makage build --dev",
17
+ "lint": "eslint . --fix",
18
+ "test": "jest",
19
+ "test:watch": "jest --watch"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "directory": "dist"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/launchql/launchql"
28
+ },
29
+ "keywords": [
30
+ "postgraphile",
31
+ "graphile",
32
+ "launchql",
33
+ "plugin",
34
+ "postgres",
35
+ "graphql",
36
+ "fulltext",
37
+ "tsvector"
38
+ ],
39
+ "bugs": {
40
+ "url": "https://github.com/launchql/launchql/issues"
41
+ },
42
+ "dependencies": {
43
+ "graphile-build": "^4.14.1",
44
+ "graphile-build-pg": "^4.14.1",
45
+ "pg-tsquery": "^8.1.0",
46
+ "postgraphile-plugin-connection-filter": "^2.0.0"
47
+ },
48
+ "peerDependencies": {
49
+ "postgraphile-core": "^4.2.0",
50
+ "postgraphile-plugin-connection-filter": "^2.0.0"
51
+ },
52
+ "devDependencies": {
53
+ "graphile-test": "^2.8.8",
54
+ "graphql": "15.10.1",
55
+ "makage": "^0.1.6",
56
+ "pgsql-test": "^2.14.11",
57
+ "postgraphile-plugin-connection-filter": "^2.0.0"
58
+ },
59
+ "gitHead": "ff477433074d91c28be6017e858b601fa99aa568"
60
+ }