graphile-plugin-connection-filter 2.3.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.
Files changed (39) hide show
  1. package/ConnectionArgFilterPlugin.d.ts +3 -0
  2. package/ConnectionArgFilterPlugin.js +18 -0
  3. package/LICENSE +23 -0
  4. package/PgConnectionArgFilterBackwardRelationsPlugin.d.ts +12 -0
  5. package/PgConnectionArgFilterBackwardRelationsPlugin.js +244 -0
  6. package/PgConnectionArgFilterColumnsPlugin.d.ts +3 -0
  7. package/PgConnectionArgFilterColumnsPlugin.js +51 -0
  8. package/PgConnectionArgFilterCompositeTypeColumnsPlugin.d.ts +3 -0
  9. package/PgConnectionArgFilterCompositeTypeColumnsPlugin.js +67 -0
  10. package/PgConnectionArgFilterComputedColumnsPlugin.d.ts +3 -0
  11. package/PgConnectionArgFilterComputedColumnsPlugin.js +114 -0
  12. package/PgConnectionArgFilterForwardRelationsPlugin.d.ts +11 -0
  13. package/PgConnectionArgFilterForwardRelationsPlugin.js +130 -0
  14. package/PgConnectionArgFilterLogicalOperatorsPlugin.d.ts +3 -0
  15. package/PgConnectionArgFilterLogicalOperatorsPlugin.js +67 -0
  16. package/PgConnectionArgFilterOperatorsPlugin.d.ts +15 -0
  17. package/PgConnectionArgFilterOperatorsPlugin.js +551 -0
  18. package/PgConnectionArgFilterPlugin.d.ts +27 -0
  19. package/PgConnectionArgFilterPlugin.js +305 -0
  20. package/PgConnectionArgFilterRecordFunctionsPlugin.d.ts +3 -0
  21. package/PgConnectionArgFilterRecordFunctionsPlugin.js +75 -0
  22. package/README.md +364 -0
  23. package/esm/ConnectionArgFilterPlugin.js +16 -0
  24. package/esm/PgConnectionArgFilterBackwardRelationsPlugin.js +242 -0
  25. package/esm/PgConnectionArgFilterColumnsPlugin.js +49 -0
  26. package/esm/PgConnectionArgFilterCompositeTypeColumnsPlugin.js +65 -0
  27. package/esm/PgConnectionArgFilterComputedColumnsPlugin.js +112 -0
  28. package/esm/PgConnectionArgFilterForwardRelationsPlugin.js +128 -0
  29. package/esm/PgConnectionArgFilterLogicalOperatorsPlugin.js +65 -0
  30. package/esm/PgConnectionArgFilterOperatorsPlugin.js +549 -0
  31. package/esm/PgConnectionArgFilterPlugin.js +303 -0
  32. package/esm/PgConnectionArgFilterRecordFunctionsPlugin.js +73 -0
  33. package/esm/index.js +58 -0
  34. package/esm/types.js +1 -0
  35. package/index.d.ts +6 -0
  36. package/index.js +64 -0
  37. package/package.json +58 -0
  38. package/types.d.ts +25 -0
  39. package/types.js +2 -0
package/README.md ADDED
@@ -0,0 +1,364 @@
1
+ # graphile-plugin-connection-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
+ <a href="https://www.npmjs.com/package/graphile-plugin-connection-filter"><img height="20" src="https://img.shields.io/github/package-json/v/launchql/launchql?filename=graphile%2Fgraphile-plugin-connection-filter%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ Adds a powerful suite of filtering capabilities to a PostGraphile schema.
16
+
17
+ > **Warning:** Use of this plugin with the default options may make it **astoundingly trivial** for a malicious actor (or a well-intentioned application that generates complex GraphQL queries) to overwhelm your database with expensive queries. See the [Performance and Security](https://github.com/graphile-contrib/graphile-plugin-connection-filter#performance-and-security) section below for details.
18
+
19
+ ## Usage
20
+
21
+ Requires PostGraphile v4.5.0 or higher.
22
+
23
+ Install with:
24
+
25
+ ```
26
+ yarn add postgraphile graphile-plugin-connection-filter
27
+ ```
28
+
29
+ CLI usage via `--append-plugins`:
30
+
31
+ ```
32
+ postgraphile --append-plugins graphile-plugin-connection-filter -c postgres://localhost/my_db ...
33
+ ```
34
+
35
+ Library usage via `appendPlugins`:
36
+
37
+ ```ts
38
+ import ConnectionFilterPlugin from "graphile-plugin-connection-filter";
39
+ // or: const ConnectionFilterPlugin = require("graphile-plugin-connection-filter");
40
+
41
+ const middleware = postgraphile(DATABASE_URL, SCHEMAS, {
42
+ appendPlugins: [ConnectionFilterPlugin],
43
+ });
44
+ ```
45
+
46
+ ## Performance and Security
47
+
48
+ By default, this plugin:
49
+
50
+ - Exposes a large number of filter operators, including some that can perform expensive pattern matching.
51
+ - Allows filtering on [computed columns](https://www.graphile.org/postgraphile/computed-columns/), which can result in expensive operations.
52
+ - Allows filtering on functions that return `setof`, which can result in expensive operations.
53
+ - Allows filtering on List fields (Postgres arrays), which can result in expensive operations.
54
+
55
+ To protect your server, you can:
56
+
57
+ - Use the `connectionFilterAllowedFieldTypes` and `connectionFilterAllowedOperators` options to limit the filterable fields and operators exposed through GraphQL.
58
+ - Set `connectionFilterComputedColumns: false` to prevent filtering on [computed columns](https://www.graphile.org/postgraphile/computed-columns/).
59
+ - Set `connectionFilterSetofFunctions: false` to prevent filtering on functions that return `setof`.
60
+ - Set `connectionFilterArrays: false` to prevent filtering on List fields (Postgres arrays).
61
+
62
+ Also see the [Production Considerations](https://www.graphile.org/postgraphile/production) page of the official PostGraphile docs, which discusses query whitelisting.
63
+
64
+ ## Features
65
+
66
+ This plugin supports filtering on almost all PostgreSQL types, including complex types such as domains, ranges, arrays, and composite types. For details on the specific operators supported for each type, see [docs/operators.md](https://github.com/graphile-contrib/graphile-plugin-connection-filter/blob/master/docs/operators.md).
67
+
68
+ See also:
69
+
70
+ - [@graphile/pg-aggregates](https://github.com/graphile/pg-aggregates) - integrates with this plugin to enable powerful aggregate filtering
71
+ - [postgraphile-plugin-connection-filter-postgis](https://github.com/graphile-contrib/postgraphile-plugin-connection-filter-postgis) - adds PostGIS functions and operators for filtering on `geography`/`geometry` columns
72
+ - [postgraphile-plugin-fulltext-filter](https://github.com/mlipscombe/postgraphile-plugin-fulltext-filter) - adds a full text search operator for filtering on `tsvector` columns
73
+ - [postgraphile-plugin-unaccented-text-search-filter](https://github.com/spacefill/postgraphile-plugin-unaccented-text-search-filter) - adds unaccent text search operators
74
+
75
+ ## Handling `null` and empty objects
76
+
77
+ By default, this plugin will throw an error when `null` literals or empty objects (`{}`) are included in `filter` input objects. This prevents queries with ambiguous semantics such as `filter: { field: null }` and `filter: { field: { equalTo: null } }` from returning unexpected results. For background on this decision, see https://github.com/graphile-contrib/graphile-plugin-connection-filter/issues/58.
78
+
79
+ To allow `null` and `{}` in inputs, use the `connectionFilterAllowNullInput` and `connectionFilterAllowEmptyObjectInput` options documented under [Plugin Options](https://github.com/graphile-contrib/graphile-plugin-connection-filter#plugin-options). Please note that even with `connectionFilterAllowNullInput` enabled, `null` is never interpreted as a SQL `NULL`; fields with `null` values are simply ignored when resolving the query.
80
+
81
+ ## Plugin Options
82
+
83
+ When using PostGraphile as a library, the following plugin options can be passed via `graphileBuildOptions`:
84
+
85
+ #### connectionFilterAllowedOperators
86
+
87
+ Restrict filtering to specific operators:
88
+
89
+ ```js
90
+ postgraphile(pgConfig, schema, {
91
+ graphileBuildOptions: {
92
+ connectionFilterAllowedOperators: [
93
+ "isNull",
94
+ "equalTo",
95
+ "notEqualTo",
96
+ "distinctFrom",
97
+ "notDistinctFrom",
98
+ "lessThan",
99
+ "lessThanOrEqualTo",
100
+ "greaterThan",
101
+ "greaterThanOrEqualTo",
102
+ "in",
103
+ "notIn",
104
+ ],
105
+ },
106
+ });
107
+ ```
108
+
109
+ #### connectionFilterAllowedFieldTypes
110
+
111
+ Restrict filtering to specific field types:
112
+
113
+ ```js
114
+ postgraphile(pgConfig, schema, {
115
+ graphileBuildOptions: {
116
+ connectionFilterAllowedFieldTypes: ["String", "Int"],
117
+ },
118
+ });
119
+ ```
120
+
121
+ The available field types will depend on your database schema.
122
+
123
+ #### connectionFilterArrays
124
+
125
+ Enable/disable filtering on PostgreSQL arrays:
126
+
127
+ ```js
128
+ postgraphile(pgConfig, schema, {
129
+ graphileBuildOptions: {
130
+ connectionFilterArrays: false, // default: true
131
+ },
132
+ });
133
+ ```
134
+
135
+ #### connectionFilterComputedColumns
136
+
137
+ Enable/disable filtering by computed columns:
138
+
139
+ ```js
140
+ postgraphile(pgConfig, schema, {
141
+ graphileBuildOptions: {
142
+ connectionFilterComputedColumns: false, // default: true
143
+ },
144
+ });
145
+ ```
146
+
147
+ Consider setting this to `false` and using `@filterable` [smart comments](https://www.graphile.org/postgraphile/smart-comments/) to selectively enable filtering:
148
+
149
+ ```sql
150
+ create function app_public.foo_computed(foo app_public.foo)
151
+ returns ... as $$ ... $$ language sql stable;
152
+
153
+ comment on function app_public.foo_computed(foo app_public.foo) is E'@filterable';
154
+ ```
155
+
156
+ #### connectionFilterOperatorNames
157
+
158
+ Use alternative names (e.g. `eq`, `ne`) for operators:
159
+
160
+ ```js
161
+ postgraphile(pgConfig, schema, {
162
+ graphileBuildOptions: {
163
+ connectionFilterOperatorNames: {
164
+ equalTo: "eq",
165
+ notEqualTo: "ne",
166
+ },
167
+ },
168
+ });
169
+ ```
170
+
171
+ #### connectionFilterRelations
172
+
173
+ Enable/disable filtering on related fields:
174
+
175
+ ```js
176
+ postgraphile(pgConfig, schema, {
177
+ graphileBuildOptions: {
178
+ connectionFilterRelations: true, // default: false
179
+ },
180
+ });
181
+ ```
182
+
183
+ #### connectionFilterSetofFunctions
184
+
185
+ Enable/disable filtering on functions that return `setof`:
186
+
187
+ ```js
188
+ postgraphile(pgConfig, schema, {
189
+ graphileBuildOptions: {
190
+ connectionFilterSetofFunctions: false, // default: true
191
+ },
192
+ });
193
+ ```
194
+
195
+ Consider setting this to `false` and using `@filterable` [smart comments](https://www.graphile.org/postgraphile/smart-comments/) to selectively enable filtering:
196
+
197
+ ```sql
198
+ create function app_public.some_foos()
199
+ returns setof ... as $$ ... $$ language sql stable;
200
+
201
+ comment on function app_public.some_foos() is E'@filterable';
202
+ ```
203
+
204
+ #### connectionFilterLogicalOperators
205
+
206
+ Enable/disable filtering with logical operators (`and`/`or`/`not`):
207
+
208
+ ```js
209
+ postgraphile(pgConfig, schema, {
210
+ graphileBuildOptions: {
211
+ connectionFilterLogicalOperators: false, // default: true
212
+ },
213
+ });
214
+ ```
215
+
216
+ #### connectionFilterAllowNullInput
217
+
218
+ Allow/forbid `null` literals in input:
219
+
220
+ ```js
221
+ postgraphile(pgConfig, schema, {
222
+ graphileBuildOptions: {
223
+ connectionFilterAllowNullInput: true, // default: false
224
+ },
225
+ });
226
+ ```
227
+
228
+ When `false`, passing `null` as a field value will throw an error.
229
+ When `true`, passing `null` as a field value is equivalent to omitting the field.
230
+
231
+ #### connectionFilterAllowEmptyObjectInput
232
+
233
+ Allow/forbid empty objects (`{}`) in input:
234
+
235
+ ```js
236
+ postgraphile(pgConfig, schema, {
237
+ graphileBuildOptions: {
238
+ connectionFilterAllowEmptyObjectInput: true, // default: false
239
+ },
240
+ });
241
+ ```
242
+
243
+ When `false`, passing `{}` as a field value will throw an error.
244
+ When `true`, passing `{}` as a field value is equivalent to omitting the field.
245
+
246
+ #### connectionFilterUseListInflectors
247
+
248
+ When building the "many" relationship filters, if this option is set `true`
249
+ then we will use the "list" field names rather than the "connection" field
250
+ names when naming the fields in the filter input. This would be desired if you
251
+ have `simpleCollection` set to `"only"` or `"both"` and you've simplified your
252
+ inflection to omit the `-list` suffix, e.g. using
253
+ `@graphile-contrib/pg-simplify-inflector`'s `pgOmitListSuffix` option. Use this
254
+ if you see `Connection` added to your filter field names.
255
+
256
+ ```js
257
+ postgraphile(pgConfig, schema, {
258
+ graphileBuildOptions: {
259
+ connectionFilterUseListInflectors: true, // default: false
260
+ },
261
+ });
262
+ ```
263
+
264
+ ## Examples
265
+
266
+ ```graphql
267
+ query {
268
+ allPosts(filter: {
269
+ createdAt: { greaterThan: "2021-01-01" }
270
+ }) {
271
+ ...
272
+ }
273
+ }
274
+ ```
275
+
276
+ For an extensive set of examples, see [docs/examples.md](https://github.com/graphile-contrib/graphile-plugin-connection-filter/blob/master/docs/examples.md).
277
+
278
+ ## Development
279
+
280
+ To establish a test environment, create an empty PostgreSQL database with C collation (required for consistent ordering of strings) and set a `TEST_DATABASE_URL` environment variable with your database connection string.
281
+
282
+ ```bash
283
+ createdb graphile_test_c --template template0 --lc-collate C
284
+ export TEST_DATABASE_URL=postgres://localhost:5432/graphile_test_c
285
+ yarn
286
+ yarn test
287
+ ```
288
+
289
+ ---
290
+
291
+ ## Education and Tutorials
292
+
293
+ 1. 🚀 [Quickstart: Getting Up and Running](https://launchql.com/learn/quickstart)
294
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
295
+
296
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://launchql.com/learn/modular-postgres)
297
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
298
+
299
+ 3. ✏️ [Authoring Database Changes](https://launchql.com/learn/authoring-database-changes)
300
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
301
+
302
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://launchql.com/learn/e2e-postgres-testing)
303
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
304
+
305
+ 5. ⚡ [Supabase Testing](https://launchql.com/learn/supabase)
306
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
307
+
308
+ 6. 💧 [Drizzle ORM Testing](https://launchql.com/learn/drizzle-testing)
309
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
310
+
311
+ 7. 🔧 [Troubleshooting](https://launchql.com/learn/troubleshooting)
312
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
313
+
314
+ ## Related LaunchQL Tooling
315
+
316
+ ### 🧪 Testing
317
+
318
+ * [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.
319
+ * [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.
320
+ * [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.
321
+ * [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.
322
+
323
+ ### 🧠 Parsing & AST
324
+
325
+ * [launchql/pgsql-parser](https://github.com/launchql/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
326
+ * [launchql/libpg-query-node](https://github.com/launchql/libpg-query-node): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
327
+ * [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.
328
+ * [@pgsql/enums](https://github.com/launchql/pgsql-parser/tree/main/packages/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
329
+ * [@pgsql/types](https://github.com/launchql/pgsql-parser/tree/main/packages/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
330
+ * [@pgsql/utils](https://github.com/launchql/pgsql-parser/tree/main/packages/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
331
+ * [launchql/pg-ast](https://github.com/launchql/launchql/tree/main/packages/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
332
+
333
+ ### 🚀 API & Dev Tools
334
+
335
+ * [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.
336
+ * [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.
337
+
338
+ ### 🔁 Streaming & Uploads
339
+
340
+ * [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.
341
+ * [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.
342
+ * [launchql/etag-stream](https://github.com/launchql/launchql/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
343
+ * [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.
344
+ * [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.
345
+ * [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.
346
+
347
+ ### 🧰 CLI & Codegen
348
+
349
+ * [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.
350
+ * [@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.
351
+ * [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.
352
+ * [@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.
353
+ * [@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.
354
+
355
+ ## Credits
356
+
357
+ 🛠 Built by LaunchQL — if you like our tools, please checkout and contribute to [our github ⚛️](https://github.com/launchql)
358
+
359
+
360
+ ## Disclaimer
361
+
362
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
363
+
364
+ 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.
@@ -0,0 +1,16 @@
1
+ const ConnectionArgFilterPlugin = (builder) => {
2
+ builder.hook('inflection', (inflection) => {
3
+ return Object.assign(inflection, {
4
+ filterType(typeName) {
5
+ return `${typeName}Filter`;
6
+ },
7
+ filterFieldType(typeName) {
8
+ return `${typeName}Filter`;
9
+ },
10
+ filterFieldListType(typeName) {
11
+ return `${typeName}ListFilter`;
12
+ },
13
+ });
14
+ });
15
+ };
16
+ export default ConnectionArgFilterPlugin;
@@ -0,0 +1,242 @@
1
+ const PgConnectionArgFilterBackwardRelationsPlugin = (builder, rawOptions) => {
2
+ const { pgSimpleCollections, pgOmitListSuffix, connectionFilterUseListInflectors, } = rawOptions;
3
+ const hasConnections = pgSimpleCollections !== 'only';
4
+ const simpleInflectorsAreShorter = pgOmitListSuffix === true;
5
+ if (simpleInflectorsAreShorter &&
6
+ connectionFilterUseListInflectors === undefined) {
7
+ // TODO: in V3 consider doing this for the user automatically (doing it in V2 would be a breaking change)
8
+ console.warn(`We recommend you set the 'connectionFilterUseListInflectors' option to 'true' since you've set the 'pgOmitListSuffix' option`);
9
+ }
10
+ const useConnectionInflectors = connectionFilterUseListInflectors === undefined
11
+ ? hasConnections
12
+ : !connectionFilterUseListInflectors;
13
+ builder.hook('inflection', (inflection) => {
14
+ return Object.assign(inflection, {
15
+ filterManyType(table, foreignTable) {
16
+ return this.upperCamelCase(`${this.tableType(table)}-to-many-${this.tableType(foreignTable)}-filter`);
17
+ },
18
+ filterBackwardSingleRelationExistsFieldName(relationFieldName) {
19
+ return `${relationFieldName}Exists`;
20
+ },
21
+ filterBackwardManyRelationExistsFieldName(relationFieldName) {
22
+ return `${relationFieldName}Exist`;
23
+ },
24
+ filterSingleRelationByKeysBackwardsFieldName(fieldName) {
25
+ return fieldName;
26
+ },
27
+ filterManyRelationByKeysFieldName(fieldName) {
28
+ return fieldName;
29
+ },
30
+ });
31
+ });
32
+ builder.hook('GraphQLInputObjectType:fields', (fields, build, context) => {
33
+ const { describePgEntity, extend, newWithHooks, inflection, pgOmit: omit, pgSql: sql, pgIntrospectionResultsByKind: introspectionResultsByKind, graphql: { GraphQLInputObjectType, GraphQLBoolean }, connectionFilterResolve, connectionFilterRegisterResolver, connectionFilterTypesByTypeName, connectionFilterType, } = build;
34
+ const { fieldWithHooks, scope: { pgIntrospection: table, isPgConnectionFilter }, Self, } = context;
35
+ if (!isPgConnectionFilter || table.kind !== 'class')
36
+ return fields;
37
+ connectionFilterTypesByTypeName[Self.name] = Self;
38
+ const backwardRelationSpecs = introspectionResultsByKind.constraint
39
+ .filter((con) => con.type === 'f')
40
+ .filter((con) => con.foreignClassId === table.id)
41
+ .reduce((memo, foreignConstraint) => {
42
+ if (omit(foreignConstraint, 'read') ||
43
+ omit(foreignConstraint, 'filter')) {
44
+ return memo;
45
+ }
46
+ const foreignTable = introspectionResultsByKind.classById[foreignConstraint.classId];
47
+ if (!foreignTable) {
48
+ throw new Error(`Could not find the foreign table (constraint: ${foreignConstraint.name})`);
49
+ }
50
+ if (omit(foreignTable, 'read') || omit(foreignTable, 'filter')) {
51
+ return memo;
52
+ }
53
+ const attributes = introspectionResultsByKind.attribute
54
+ .filter((attr) => attr.classId === table.id)
55
+ .sort((a, b) => a.num - b.num);
56
+ const foreignAttributes = introspectionResultsByKind.attribute
57
+ .filter((attr) => attr.classId === foreignTable.id)
58
+ .sort((a, b) => a.num - b.num);
59
+ const keyAttributes = foreignConstraint.foreignKeyAttributeNums.map((num) => attributes.filter((attr) => attr.num === num)[0]);
60
+ const foreignKeyAttributes = foreignConstraint.keyAttributeNums.map((num) => foreignAttributes.filter((attr) => attr.num === num)[0]);
61
+ if (keyAttributes.some((attr) => omit(attr, 'read'))) {
62
+ return memo;
63
+ }
64
+ if (foreignKeyAttributes.some((attr) => omit(attr, 'read'))) {
65
+ return memo;
66
+ }
67
+ const isForeignKeyUnique = !!introspectionResultsByKind.constraint.find((c) => c.classId === foreignTable.id &&
68
+ (c.type === 'p' || c.type === 'u') &&
69
+ c.keyAttributeNums.length === foreignKeyAttributes.length &&
70
+ c.keyAttributeNums.every((n, i) => foreignKeyAttributes[i].num === n));
71
+ memo.push({
72
+ table,
73
+ keyAttributes,
74
+ foreignTable,
75
+ foreignKeyAttributes,
76
+ foreignConstraint,
77
+ isOneToMany: !isForeignKeyUnique,
78
+ });
79
+ return memo;
80
+ }, []);
81
+ let backwardRelationSpecByFieldName = {};
82
+ const addField = (fieldName, description, type, resolve, spec, hint) => {
83
+ // Field
84
+ fields = extend(fields, {
85
+ [fieldName]: fieldWithHooks(fieldName, {
86
+ description,
87
+ type,
88
+ }, {
89
+ isPgConnectionFilterField: true,
90
+ }),
91
+ }, hint);
92
+ // Relation spec for use in resolver
93
+ backwardRelationSpecByFieldName = extend(backwardRelationSpecByFieldName, {
94
+ [fieldName]: spec,
95
+ });
96
+ // Resolver
97
+ connectionFilterRegisterResolver(Self.name, fieldName, resolve);
98
+ };
99
+ const resolveSingle = ({ sourceAlias, fieldName, fieldValue, queryBuilder, }) => {
100
+ if (fieldValue == null)
101
+ return null;
102
+ const { foreignTable, foreignKeyAttributes, keyAttributes } = backwardRelationSpecByFieldName[fieldName];
103
+ const foreignTableTypeName = inflection.tableType(foreignTable);
104
+ const foreignTableAlias = sql.identifier(Symbol());
105
+ const foreignTableFilterTypeName = inflection.filterType(foreignTableTypeName);
106
+ const sqlIdentifier = sql.identifier(foreignTable.namespace.name, foreignTable.name);
107
+ const sqlKeysMatch = sql.query `(${sql.join(foreignKeyAttributes.map((attr, i) => {
108
+ return sql.fragment `${foreignTableAlias}.${sql.identifier(attr.name)} = ${sourceAlias}.${sql.identifier(keyAttributes[i].name)}`;
109
+ }), ') and (')})`;
110
+ const sqlSelectWhereKeysMatch = sql.query `select 1 from ${sqlIdentifier} as ${foreignTableAlias} where ${sqlKeysMatch}`;
111
+ const sqlFragment = connectionFilterResolve(fieldValue, foreignTableAlias, foreignTableFilterTypeName, queryBuilder);
112
+ return sqlFragment == null
113
+ ? null
114
+ : sql.query `exists(${sqlSelectWhereKeysMatch} and (${sqlFragment}))`;
115
+ };
116
+ const resolveExists = ({ sourceAlias, fieldName, fieldValue, }) => {
117
+ if (fieldValue == null)
118
+ return null;
119
+ const { foreignTable, foreignKeyAttributes, keyAttributes } = backwardRelationSpecByFieldName[fieldName];
120
+ const foreignTableAlias = sql.identifier(Symbol());
121
+ const sqlIdentifier = sql.identifier(foreignTable.namespace.name, foreignTable.name);
122
+ const sqlKeysMatch = sql.query `(${sql.join(foreignKeyAttributes.map((attr, i) => {
123
+ return sql.fragment `${foreignTableAlias}.${sql.identifier(attr.name)} = ${sourceAlias}.${sql.identifier(keyAttributes[i].name)}`;
124
+ }), ') and (')})`;
125
+ const sqlSelectWhereKeysMatch = sql.query `select 1 from ${sqlIdentifier} as ${foreignTableAlias} where ${sqlKeysMatch}`;
126
+ return fieldValue === true
127
+ ? sql.query `exists(${sqlSelectWhereKeysMatch})`
128
+ : sql.query `not exists(${sqlSelectWhereKeysMatch})`;
129
+ };
130
+ const makeResolveMany = (backwardRelationSpec) => {
131
+ const resolveMany = ({ sourceAlias, fieldName, fieldValue, queryBuilder, }) => {
132
+ if (fieldValue == null)
133
+ return null;
134
+ const { foreignTable } = backwardRelationSpecByFieldName[fieldName];
135
+ const foreignTableFilterManyTypeName = inflection.filterManyType(table, foreignTable);
136
+ const sqlFragment = connectionFilterResolve(fieldValue, sourceAlias, foreignTableFilterManyTypeName, queryBuilder, null, null, null, { backwardRelationSpec });
137
+ return sqlFragment == null ? null : sqlFragment;
138
+ };
139
+ return resolveMany;
140
+ };
141
+ for (const spec of backwardRelationSpecs) {
142
+ const { foreignTable, foreignKeyAttributes, foreignConstraint, isOneToMany, } = spec;
143
+ const foreignTableTypeName = inflection.tableType(foreignTable);
144
+ const foreignTableFilterTypeName = inflection.filterType(foreignTableTypeName);
145
+ const ForeignTableFilterType = connectionFilterType(newWithHooks, foreignTableFilterTypeName, foreignTable, foreignTableTypeName);
146
+ if (!ForeignTableFilterType)
147
+ continue;
148
+ if (isOneToMany) {
149
+ if (!omit(foreignTable, 'many')) {
150
+ const filterManyTypeName = inflection.filterManyType(table, foreignTable);
151
+ if (!connectionFilterTypesByTypeName[filterManyTypeName]) {
152
+ connectionFilterTypesByTypeName[filterManyTypeName] = newWithHooks(GraphQLInputObjectType, {
153
+ name: filterManyTypeName,
154
+ description: `A filter to be used against many \`${foreignTableTypeName}\` object types. All fields are combined with a logical ‘and.’`,
155
+ }, {
156
+ foreignTable,
157
+ isPgConnectionFilterMany: true,
158
+ });
159
+ }
160
+ const FilterManyType = connectionFilterTypesByTypeName[filterManyTypeName];
161
+ const fieldName = useConnectionInflectors
162
+ ? inflection.manyRelationByKeys(foreignKeyAttributes, foreignTable, table, foreignConstraint)
163
+ : inflection.manyRelationByKeysSimple(foreignKeyAttributes, foreignTable, table, foreignConstraint);
164
+ const filterFieldName = inflection.filterManyRelationByKeysFieldName(fieldName);
165
+ addField(filterFieldName, `Filter by the object’s \`${fieldName}\` relation.`, FilterManyType, makeResolveMany(spec), spec, `Adding connection filter backward relation field from ${describePgEntity(table)} to ${describePgEntity(foreignTable)}`);
166
+ const existsFieldName = inflection.filterBackwardManyRelationExistsFieldName(fieldName);
167
+ addField(existsFieldName, `Some related \`${fieldName}\` exist.`, GraphQLBoolean, resolveExists, spec, `Adding connection filter backward relation exists field from ${describePgEntity(table)} to ${describePgEntity(foreignTable)}`);
168
+ }
169
+ }
170
+ else {
171
+ const fieldName = inflection.singleRelationByKeysBackwards(foreignKeyAttributes, foreignTable, table, foreignConstraint);
172
+ const filterFieldName = inflection.filterSingleRelationByKeysBackwardsFieldName(fieldName);
173
+ addField(filterFieldName, `Filter by the object’s \`${fieldName}\` relation.`, ForeignTableFilterType, resolveSingle, spec, `Adding connection filter backward relation field from ${describePgEntity(table)} to ${describePgEntity(foreignTable)}`);
174
+ const existsFieldName = inflection.filterBackwardSingleRelationExistsFieldName(fieldName);
175
+ addField(existsFieldName, `A related \`${fieldName}\` exists.`, GraphQLBoolean, resolveExists, spec, `Adding connection filter backward relation exists field from ${describePgEntity(table)} to ${describePgEntity(foreignTable)}`);
176
+ }
177
+ }
178
+ return fields;
179
+ });
180
+ builder.hook('GraphQLInputObjectType:fields', (fields, build, context) => {
181
+ const { extend, newWithHooks, inflection, pgSql: sql, connectionFilterResolve, connectionFilterRegisterResolver, connectionFilterTypesByTypeName, connectionFilterType, } = build;
182
+ const { fieldWithHooks, scope: { foreignTable, isPgConnectionFilterMany }, Self, } = context;
183
+ if (!isPgConnectionFilterMany || !foreignTable)
184
+ return fields;
185
+ connectionFilterTypesByTypeName[Self.name] = Self;
186
+ const foreignTableTypeName = inflection.tableType(foreignTable);
187
+ const foreignTableFilterTypeName = inflection.filterType(foreignTableTypeName);
188
+ const FilterType = connectionFilterType(newWithHooks, foreignTableFilterTypeName, foreignTable, foreignTableTypeName);
189
+ const manyFields = {
190
+ every: fieldWithHooks('every', {
191
+ description: `Every related \`${foreignTableTypeName}\` matches the filter criteria. All fields are combined with a logical ‘and.’`,
192
+ type: FilterType,
193
+ }, {
194
+ isPgConnectionFilterManyField: true,
195
+ }),
196
+ some: fieldWithHooks('some', {
197
+ description: `Some related \`${foreignTableTypeName}\` matches the filter criteria. All fields are combined with a logical ‘and.’`,
198
+ type: FilterType,
199
+ }, {
200
+ isPgConnectionFilterManyField: true,
201
+ }),
202
+ none: fieldWithHooks('none', {
203
+ description: `No related \`${foreignTableTypeName}\` matches the filter criteria. All fields are combined with a logical ‘and.’`,
204
+ type: FilterType,
205
+ }, {
206
+ isPgConnectionFilterManyField: true,
207
+ }),
208
+ };
209
+ const resolve = ({ sourceAlias, fieldName, fieldValue, queryBuilder, parentFieldInfo, }) => {
210
+ if (fieldValue == null)
211
+ return null;
212
+ if (!parentFieldInfo || !parentFieldInfo.backwardRelationSpec)
213
+ throw new Error('Did not receive backward relation spec');
214
+ const { keyAttributes, foreignKeyAttributes } = parentFieldInfo.backwardRelationSpec;
215
+ const foreignTableAlias = sql.identifier(Symbol());
216
+ const sqlIdentifier = sql.identifier(foreignTable.namespace.name, foreignTable.name);
217
+ const sqlKeysMatch = sql.query `(${sql.join(foreignKeyAttributes.map((attr, i) => {
218
+ return sql.fragment `${foreignTableAlias}.${sql.identifier(attr.name)} = ${sourceAlias}.${sql.identifier(keyAttributes[i].name)}`;
219
+ }), ') and (')})`;
220
+ const sqlSelectWhereKeysMatch = sql.query `select 1 from ${sqlIdentifier} as ${foreignTableAlias} where ${sqlKeysMatch}`;
221
+ const sqlFragment = connectionFilterResolve(fieldValue, foreignTableAlias, foreignTableFilterTypeName, queryBuilder);
222
+ if (sqlFragment == null) {
223
+ return null;
224
+ }
225
+ else if (fieldName === 'every') {
226
+ return sql.query `not exists(${sqlSelectWhereKeysMatch} and not (${sqlFragment}))`;
227
+ }
228
+ else if (fieldName === 'some') {
229
+ return sql.query `exists(${sqlSelectWhereKeysMatch} and (${sqlFragment}))`;
230
+ }
231
+ else if (fieldName === 'none') {
232
+ return sql.query `not exists(${sqlSelectWhereKeysMatch} and (${sqlFragment}))`;
233
+ }
234
+ throw new Error(`Unknown field name: ${fieldName}`);
235
+ };
236
+ for (const fieldName of Object.keys(manyFields)) {
237
+ connectionFilterRegisterResolver(Self.name, fieldName, resolve);
238
+ }
239
+ return extend(fields, manyFields);
240
+ });
241
+ };
242
+ export default PgConnectionArgFilterBackwardRelationsPlugin;