pg_graphql is a powerful PostgreSQL extension that provides a complete GraphQL service engine within the database. With this extension, you can automatically convert existing SQL tables, views, and their relationships into a fully functional GraphQL schema, enabling serverless GraphQL queries.
It builds a seamless bridge between PostgreSQL and GraphQL, allowing any client or programming language that can connect to the database to leverage GraphQL's declarative, strongly typed query advantages without deploying and maintaining additional intermediate services.
- Rapid prototyping: provide a fully functional GraphQL API for your database within minutes, accelerating frontend and mobile app development.
- Simplify backend architecture: for data-centric applications, pg_graphql can replace traditional REST APIs or customized GraphQL servers, reducing architectural complexity.
- Data as a Service (DaaS): expose structured data query capabilities securely to internal teams or external partners by treating the database as a service.
- Integrate with serverless frameworks: combine with function computing on platforms like Vercel, Netlify, or Supabase to build high-performance and scalable applications.
Primary key requirements: all tables that need to be exposed in the GraphQL Schema must define a primary key. Tables without primary keys will be ignored by the extension and cannot be queried through the GraphQL API.
Create and delete extension
Execute the following SQL command to enable the pg_graphql extension.
If no longer needed, execute the following command to uninstall it.
The following is a complete getting-started example:
- First, create two tables: accounts and posts, and use foreign keys to establish a one-to-many relationship between them.
- Insert some data into the tables for subsequent queries.
- Use the core function graphql.resolve to execute GraphQL queries. Pass the query statement as a text parameter.
- The graphql.resolve function returns a JSONB object containing two fields: data and errors.
Core function: graphql.resolve
graphql.resolve is the core function that executes all GraphQL actions.
- query (text): required, a string containing a GraphQL query, mutation, or subscription action.
- variables (jsonb): optional, a JSONB object providing values for variables defined in the query. Defaults to an empty object ({}).
- "operationName" (text): optional, specifies which named action to execute when the query string contains multiple named actions.
- extensions (jsonb): optional, used to pass data for the GraphQL extensions protocol, typically for advanced toolchain integration.
- The simplest call method is to pass the GraphQL query string directly.
- To improve query reuse and security, using variables is recommended.
- If a request contains multiple actions, specify which one to execute using the "operationName" parameter.