JSPM

  • Created
  • Published
  • Downloads 65
  • Score
    100M100P100Q67113F
  • License MIT

Filtering on PostGraphile connections

Package Exports

  • graphile-plugin-connection-filter
  • graphile-plugin-connection-filter/esm/index.js
  • graphile-plugin-connection-filter/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (graphile-plugin-connection-filter) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

graphile-plugin-connection-filter

graphile-plugin-connection-filter adds a powerful suite of filtering capabilities to PostGraphile schemas.

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 section below for details.

🚀 Installation

Requires PostGraphile v4.5.0 or higher.

Install with:

pnpm add postgraphile graphile-plugin-connection-filter

✨ Features

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.

See also:

📦 Usage

CLI usage via --append-plugins:

postgraphile --append-plugins graphile-plugin-connection-filter -c postgres://localhost/my_db ...

Library usage via appendPlugins:

import ConnectionFilterPlugin from "graphile-plugin-connection-filter";
// or: const ConnectionFilterPlugin = require("graphile-plugin-connection-filter");

const middleware = postgraphile(DATABASE_URL, SCHEMAS, {
  appendPlugins: [ConnectionFilterPlugin],
});

⚠️ Performance and Security

By default, this plugin:

  • Exposes a large number of filter operators, including some that can perform expensive pattern matching.
  • Allows filtering on computed columns, which can result in expensive operations.
  • Allows filtering on functions that return setof, which can result in expensive operations.
  • Allows filtering on List fields (Postgres arrays), which can result in expensive operations.

To protect your server, you can:

  • Use the connectionFilterAllowedFieldTypes and connectionFilterAllowedOperators options to limit the filterable fields and operators exposed through GraphQL.
  • Set connectionFilterComputedColumns: false to prevent filtering on computed columns.
  • Set connectionFilterSetofFunctions: false to prevent filtering on functions that return setof.
  • Set connectionFilterArrays: false to prevent filtering on List fields (Postgres arrays).

Also see the Production Considerations page of the official PostGraphile docs, which discusses query whitelisting.

🚦 Handling null and empty objects

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.

To allow null and {} in inputs, use the connectionFilterAllowNullInput and connectionFilterAllowEmptyObjectInput options documented under 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.

🔧 Plugin Options

When using PostGraphile as a library, the following plugin options can be passed via graphileBuildOptions:

connectionFilterAllowedOperators

Restrict filtering to specific operators:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterAllowedOperators: [
      "isNull",
      "equalTo",
      "notEqualTo",
      "distinctFrom",
      "notDistinctFrom",
      "lessThan",
      "lessThanOrEqualTo",
      "greaterThan",
      "greaterThanOrEqualTo",
      "in",
      "notIn",
    ],
  },
});

connectionFilterAllowedFieldTypes

Restrict filtering to specific field types:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterAllowedFieldTypes: ["String", "Int"],
  },
});

The available field types will depend on your database schema.

connectionFilterArrays

Enable/disable filtering on PostgreSQL arrays:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterArrays: false, // default: true
  },
});

connectionFilterComputedColumns

Enable/disable filtering by computed columns:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterComputedColumns: false, // default: true
  },
});

Consider setting this to false and using @filterable smart comments to selectively enable filtering:

create function app_public.foo_computed(foo app_public.foo)
  returns ... as $$ ... $$ language sql stable;

comment on function app_public.foo_computed(foo app_public.foo) is E'@filterable';

connectionFilterOperatorNames

Use alternative names (e.g. eq, ne) for operators:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterOperatorNames: {
      equalTo: "eq",
      notEqualTo: "ne",
    },
  },
});

connectionFilterRelations

Enable/disable filtering on related fields:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterRelations: true, // default: false
  },
});

connectionFilterSetofFunctions

Enable/disable filtering on functions that return setof:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterSetofFunctions: false, // default: true
  },
});

Consider setting this to false and using @filterable smart comments to selectively enable filtering:

create function app_public.some_foos()
  returns setof ... as $$ ... $$ language sql stable;

comment on function app_public.some_foos() is E'@filterable';

connectionFilterLogicalOperators

Enable/disable filtering with logical operators (and/or/not):

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterLogicalOperators: false, // default: true
  },
});

connectionFilterAllowNullInput

Allow/forbid null literals in input:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterAllowNullInput: true, // default: false
  },
});

When false, passing null as a field value will throw an error. When true, passing null as a field value is equivalent to omitting the field.

connectionFilterAllowEmptyObjectInput

Allow/forbid empty objects ({}) in input:

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterAllowEmptyObjectInput: true, // default: false
  },
});

When false, passing {} as a field value will throw an error. When true, passing {} as a field value is equivalent to omitting the field.

connectionFilterUseListInflectors

When building the "many" relationship filters, if this option is set true then we will use the "list" field names rather than the "connection" field names when naming the fields in the filter input. This would be desired if you have simpleCollection set to "only" or "both" and you've simplified your inflection to omit the -list suffix, e.g. using @graphile-contrib/pg-simplify-inflector's pgOmitListSuffix option. Use this if you see Connection added to your filter field names.

postgraphile(pgConfig, schema, {
  graphileBuildOptions: {
    connectionFilterUseListInflectors: true, // default: false
  },
});

🧪 Examples

query {
  allPosts(filter: {
    createdAt: { greaterThan: "2021-01-01" }
  }) {
    ...
  }
}

For an extensive set of examples, see docs/examples.md.

🧪 Testing

# requires a local Postgres available (defaults to postgres/password@localhost:5432)
pnpm --filter graphile-plugin-connection-filter test

Education and Tutorials

  1. 🚀 Quickstart: Getting Up and Running Get started with modular databases in minutes. Install prerequisites and deploy your first module.

  2. 📦 Modular PostgreSQL Development with Database Packages Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.

  3. ✏️ Authoring Database Changes Master the workflow for adding, organizing, and managing database changes with pgpm.

  4. 🧪 End-to-End PostgreSQL Testing with TypeScript Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.

  5. Supabase Testing Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.

  6. 💧 Drizzle ORM Testing Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.

  7. 🔧 Troubleshooting Common issues and solutions for pgpm, PostgreSQL, and testing.

🧪 Testing

  • pgsql-test: 📊 Isolated testing environments with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
  • supabase-test: 🧪 Supabase-native test harness preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
  • graphile-test: 🔐 Authentication mocking for Graphile-focused test helpers and emulating row-level security contexts.
  • 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.

🧠 Parsing & AST

  • pgsql-parser: 🔄 SQL conversion engine that interprets and converts PostgreSQL syntax.
  • libpg-query-node: 🌉 Node.js bindings for libpg_query, converting SQL into parse trees.
  • pg-proto-parser: 📦 Protobuf parser for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
  • @pgsql/enums: 🏷️ TypeScript enums for PostgreSQL AST for safe and ergonomic parsing logic.
  • @pgsql/types: 📝 Type definitions for PostgreSQL AST nodes in TypeScript.
  • @pgsql/utils: 🛠️ AST utilities for constructing and transforming PostgreSQL syntax trees.
  • pg-ast: 🔍 Low-level AST tools and transformations for Postgres query structures.

🚀 API & Dev Tools

  • @constructive-io/graphql-server: ⚡ Express-based API server powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
  • @constructive-io/graphql-explorer: 🔎 Visual API explorer with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.

🔁 Streaming & Uploads

  • etag-hash: 🏷️ S3-compatible ETags created by streaming and hashing file uploads in chunks.
  • etag-stream: 🔄 ETag computation via Node stream transformer during upload or transfer.
  • uuid-hash: 🆔 Deterministic UUIDs generated from hashed content, great for deduplication and asset referencing.
  • uuid-stream: 🌊 Streaming UUID generation based on piped file content—ideal for upload pipelines.
  • @constructive-io/s3-streamer: 📤 Direct S3 streaming for large files with support for metadata injection and content validation.
  • @constructive-io/upload-names: 📂 Collision-resistant filenames utility for structured and unique file names for uploads.

🧰 CLI & Codegen

  • pgpm: 🖥️ PostgreSQL Package Manager for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
  • @constructive-io/cli: 🖥️ Command-line toolkit for managing Constructive projects—supports database scaffolding, migrations, seeding, code generation, and automation.
  • @constructive-io/graphql-codegen: ✨ GraphQL code generation (types, operations, SDK) from schema/endpoint introspection.
  • @constructive-io/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.
  • @constructive-io/graphql-query: 🧩 Fluent GraphQL builder for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.

Credits

🛠 Built by the Constructive team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on GitHub.

Disclaimer

AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.

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.