{"id":13253,"library":"graphile-build-pg","title":"Graphile Build PostgreSQL Plugins","description":"`graphile-build-pg` is a crucial component within the Graphile ecosystem, providing a collection of plugins for `graphile-build` that enable the automatic generation of a GraphQL schema directly from a PostgreSQL database. It achieves this by introspecting the database using `pg-introspection` and constructing a `@dataplan/pg` registry. This registry then informs the creation of GraphQL types, fields, and high-performance `grafast` plan resolver functions, ensuring optimal data fetching. The current stable version is 5.0.1, part of the larger Graphile Crystal (v5) release. This package is a cornerstone of PostGraphile v5, offering significant performance advantages over traditional `DataLoader`-based GraphQL solutions by virtually eliminating the N+1 query problem through `grafast`'s advanced query planning. It is designed for modern Node.js environments, requiring `Node.js >=22`.","status":"active","version":"5.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/graphile/crystal","tags":["javascript","graphile","graphql","engine","postgraphile","pg","postgres","postgresql","graphqljs","typescript"],"install":[{"cmd":"npm install graphile-build-pg","lang":"bash","label":"npm"},{"cmd":"yarn add graphile-build-pg","lang":"bash","label":"yarn"},{"cmd":"pnpm add graphile-build-pg","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core library for data planning and PostgreSQL interaction within the Grafast ecosystem.","package":"@dataplan/pg","optional":false},{"reason":"The declarative, strongly-typed GraphQL query planning and execution engine that powers the performance optimizations.","package":"grafast","optional":false},{"reason":"The foundational plugin system for building GraphQL schemas, which `graphile-build-pg` extends.","package":"graphile-build","optional":false},{"reason":"The unified configuration system used across the Graphile v5 suite for managing plugins and presets.","package":"graphile-config","optional":false},{"reason":"The reference implementation of GraphQL.js, essential for defining the schema.","package":"graphql","optional":false},{"reason":"The official PostgreSQL client for Node.js, used for database interaction.","package":"pg","optional":false},{"reason":"A type-safe SQL query builder used for constructing optimized database queries within the plugins.","package":"pg-sql2","optional":false},{"reason":"A utility package used within the Graphile ecosystem.","package":"tamedevil","optional":false}],"imports":[{"note":"The `sql` tag from `pg-sql2` is re-exported by `graphile-build-pg` (since v5.0.1) and is crucial for writing type-safe SQL queries within custom plugins or resolvers. It's often consumed via `import { sql } from 'postgraphile/graphile-build-pg';` when using PostGraphile's unified exports.","wrong":"const { sql } = require('graphile-build-pg');","symbol":"sql","correct":"import { sql } from 'graphile-build-pg';"},{"note":"The `SQL` type from `pg-sql2` is re-exported by `graphile-build-pg` (since v5.0.1) for type-checking SQL fragments. Best practice is to import it through `graphile-build-pg` or `postgraphile/graphile-build-pg`.","wrong":"import { SQL } from 'pg-sql2'; // Direct import of underlying dependency is discouraged","symbol":"SQL","correct":"import { SQL } from 'graphile-build-pg';"},{"note":"This export provides the core array of PostgreSQL-specific Graphile Build plugins. It's used when manually assembling a `graphile-config` preset for a `graphile-build` schema, rather than relying on `postgraphile`'s integrated presets.","wrong":"import { plugins } from 'graphile-build-pg';","symbol":"defaultPlugins","correct":"import { defaultPlugins } from 'graphile-build-pg';"}],"quickstart":{"code":"import { makeSchema } from 'postgraphile';\nimport { defaultPreset } from 'postgraphile';\nimport { makePgSources } from '@dataplan/pg';\nimport { printSchema } from 'graphql';\n\n// Ensure you have a PostgreSQL database running and DATABASE_URL set.\n// Example: export DATABASE_URL=\"postgres://user:password@localhost:5432/mydb\"\nconst DATABASE_URL = process.env.DATABASE_URL ?? 'postgres://postgres:password@localhost:5432/postgres';\n\nasync function buildPostgresSchema() {\n  if (!DATABASE_URL) {\n    throw new Error('DATABASE_URL environment variable is not set.');\n  }\n\n  // makePgSources defines how to connect to your PostgreSQL database\n  // and what schemas to introspect.\n  const pgSources = [await makePgSources({\n    connection: DATABASE_URL,\n    schemas: ['public'],\n  })];\n\n  // The `defaultPreset` from `postgraphile` already includes the\n  // `graphile-build-pg` plugins. We add our database sources to it.\n  const preset = {\n    ...defaultPreset,\n    extends: [\n      ...(defaultPreset.extends || []),\n      {\n        // Add the PostgreSQL sources to the preset\n        plugins: [], // No extra plugins from this block needed\n        schema: {\n          pgSources,\n        },\n      },\n    ],\n  };\n\n  // Build the GraphQL schema using the configured preset.\n  const { schema } = await makeSchema(preset);\n\n  console.log('Successfully built GraphQL schema from PostgreSQL database:\\n');\n  console.log(printSchema(schema));\n}\n\nbuildPostgresSchema().catch(console.error);\n","lang":"typescript","description":"Demonstrates how to build a GraphQL schema from a PostgreSQL database using `graphile-build-pg`'s capabilities via a `postgraphile` preset and `makeSchema`."},"warnings":[{"fix":"Refer to the PostGraphile V5 migration guide. All custom plugins and configurations need to be rewritten to conform to the new `graphile-config` plugin object structure and `Grafast`'s plan-based resolvers. The `@behavior` system replaces many `@smartTags` from V4.","message":"Graphile V5 (Crystal) represents a complete rewrite of the PostGraphile and Graphile Build ecosystem. It replaces the V4 'lookahead' engine with 'Grafast' for query planning and introduces a new unified plugin and configuration system via `graphile-config`. This means V4 plugins, `SchemaBuilder` APIs, and configuration options are largely incompatible.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Upgrade your Node.js runtime environment to version 22 or higher to ensure compatibility and leverage modern JavaScript features.","message":"The minimum Node.js version requirement for `graphile-build-pg` and the entire Graphile V5 ecosystem has been raised to Node.js `>=22`.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"Prefer importing core Graphile modules via `postgraphile/sub-path` exports (e.g., `postgraphile/graphile-build-pg`) if your project uses PostGraphile directly. Only import from `graphile-build-pg` directly if building a custom `graphile-build` schema without the full `postgraphile` stack.","message":"Many core Graphile packages, including `graphile-build-pg`, are often re-exported directly from the `postgraphile` package itself (e.g., `import { sql } from 'postgraphile/graphile-build-pg';`). Directly importing from `graphile-build-pg` might lead to module resolution issues or unexpected behavior if not consistently applied within a PostGraphile V5 project.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Ensure all data fetching within your GraphQL schema leverages `Grafast` steps and data plans (`@dataplan/pg`) where possible. For custom logic, integrate with existing `Grafast` steps or define new ones rather than using traditional resolver patterns.","message":"While `graphile-build-pg` automatically generates an efficient schema using `Grafast`, bypassing `Grafast`'s planning capabilities with hand-written GraphQL resolvers can reintroduce N+1 query problems, negating the performance benefits.","severity":"gotcha","affected_versions":">=5.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"If using PostGraphile, try `import { /* ... */ } from 'postgraphile/graphile-build-pg';`. Ensure your project is configured for ESM (`\"type\": \"module\"` in `package.json`) for Node.js >=22. If using CJS in an older Node.js, ensure correct `require()` syntax and package compatibility.","cause":"Attempting to import `graphile-build-pg` directly when it is expected to be consumed via `postgraphile`'s re-exports, or a CJS/ESM module mismatch.","error":"Cannot find module 'graphile-build-pg' or its corresponding type declarations."},{"fix":"Set the `DATABASE_URL` environment variable, for example: `export DATABASE_URL=\"postgres://user:password@localhost:5432/mydb\"` before running your application.","cause":"The application attempts to connect to a PostgreSQL database using an environment variable that is missing or empty.","error":"Error: `DATABASE_URL` environment variable is not set."},{"fix":"Ensure `makePgSources` is called with an object containing at least `connection` and `schemas` properties, as shown in the quickstart, or a function that returns such an object. Example: `await makePgSources({ connection: process.env.DATABASE_URL, schemas: ['public'] })`.","cause":"Incorrect configuration passed to `makePgSources`, a core function for defining PostgreSQL data sources for `graphile-build-pg`.","error":"Error: `makePgSources` must be called with an object `pgConfig` or a function `getPgConfig`"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":"","cli_version":null}