Considering SQL query building
I’m thinking about using Prisma or Knex for educational clarity, as explaining SQL query building isn't overly complex. Since the user might want runnable code, I plan to include dependencies and folder structure details, like a simple domain for "Book" and "Author" or "Users" and "Posts."
For filtering, I’ll illustrate a GraphQL query type that includes filters and specify implementation details, opting for JavaScript for accessibility, while perhaps mentioning TypeScript as a beneficial option. I could use Apollo Server for the setup.Designing the query structure
I'm considering using @apollo/server with an HTTP framework for future-proofing the implementation. I need to provide code for an "index.js" file.
For the database, I might use pg (node-postgres) alongside sql-template-strings. In terms of dynamic filtering, I can build a query string while being aware of SQL injection risks and using parameterized queries.
I plan to show a function called buildBooksQuery(filter, orderBy, limit, offset) that returns an object with text and values for pg. I’ll include code for complex logical operators and define filters for strings and integers, using recursive building for whereClauses with AND/OR.Defining GraphQL types
I’m working on the GraphQL type definitions, starting with some scalar types, including DateTime. The Author type will have fields for ID, name, and country, and the Book type will include ID, title, pages, published date, and author.
The Query type will allow users to filter books and retrieve lists of authors. I’ll create a BookFilter input for complex filtering, alongside corresponding filters for authors. I need to define a sorting order with BookOrderBy and consider using graphql-scalars for the DateTime scalar or creating a custom version.Implementing resolvers with PostgreSQL
I'm planning to implement the resolvers for querying books using the pg pool. The booksResolver function will take filter criteria, order, limit, and offset as parameters, build a query with buildBooksQuery, and return the rows retrieved from the database.
For the author's data, I'll need to join the authors table based on books.author_id. To optimize this, I should consider using DataLoader to handle potential N+1 issues, but I might skip it for now. The buildBooksQuery will need to accommodate filtering by authors, either through joins or subqueries, depending on whether the filter.author is provided.Implementing query building and settings
I'm focusing on building the SQL WHERE clause from the BookFilter input, defining a helper function called buildFilter that returns the necessary clause and parameter values. It will utilize recursion for complex logical conditions like AND, OR, and NOT. I'll also ensure the proper handling of string and integer filters for building dynamic queries while managing placeholders for PostgreSQL.
In terms of the GraphQL setup, I'll provide a basic outline of package dependencies, a clear database schema for authors and books, and an implementation for a custom DateTime scalar. The goal is to give the user a comprehensive, yet concise example with clear steps to follow.Designing GraphQL type definitions
I'm creating the GraphQL typeDefs as a template string, which includes definitions for authors, books, and filters. The mappings ensure that the database columns align with GraphQL's camelCase properties.
I'll also implement the buildBookWhere function to generate the WHERE clause based on the BookFilter input. It's crucial that this function handles logical conditions properly and integrates with filters for specific properties like id, title, and authorId.
Moreover, I plan to ensure that every filter can support complex queries with AND/OR/NOT combinations. The aim is to provide robust query building for optimal performance using PostgreSQL.Implementing GraphQL with PostgreSQL
I'm defining a field mapping for GraphQL to ensure that properties like publishedAt correspond to the database columns correctly. In my orderBy implementation, I'll convert fields according to this mapping, adding safety checks for limit and offset using query parameters.
I'll set up the resolvers for both Query.books and Query.authors. The authors resolver will retrieve author details based on the author's ID. Additionally, I'll implement a custom DateTime scalar for handling date serialization and parsing seamlessly with the PostgreSQL database.
Next, I'm crafting the index.js file and the necessary package.json with dependencies for Apollo Server and PostgreSQL integration. Lastly, I’ll create an example GraphQL query to illustrate complex filtering capabilities, ensuring correctness throughout the process.Handling DateTime and Code Structuring
I want to correctly implement the DateTimeFilter in my code, ensuring start and end are both Date objects. I’ll write a concise introduction, then provide file-by-file code with comments to guide the user. Since they didn't ask for step-by-step instructions, I’ll simply start with "Below is a minimal yet complete Apollo Server..." while avoiding phrases like "Great question".
The package.json will include approximate versions, advising running npm install. The SQL schema will define the necessary tables and indexes. I'll also set up the environment variables in .env, and flesh out the index.js file with proper functions for querying and filtering books and authors, taking care to manage recursion effectively for nested filters.Clarifying Filter Functions and Resolvers
I need to ensure that I avoid double-ext referencing in filters, where the same filter object is reused. For the NOT semantics, I must remember that subclauses are combined with AND, meaning the entire group is negated.
Next, I'll focus on building my various filter functions like buildStringFilter, buildIntFilter, buildIDFilter, and buildDateTimeFilter. I’ll carefully define these functions to handle GraphQL types appropriately, especially for IDs, since they are strings in GraphQL but integers in the database.
Finally, I'll create resolvers for querying books and authors efficiently, making sure to set up the Apollo Server correctly without using emojis in the console outputs. I need to ensure everything initializes properly, including the connection pool, which must be created before running the server.Implementing DateTime Scalar and Server Structure
I'm implementing the DateTime scalar for GraphQL. It needs to correctly serialize and parse dates using ISO-8601 formatting. The serialize method must return a string, while the parseValue and parseLiteral methods handle incoming Date values.
Next, I need to ensure that the books query returns the publishedAt property correctly formatted. For the authors query, I probably won’t need to use DateTime. Now, I’ll summarize everything I need to include in an organized manner, focusing on project structure, database schema, and the application code while keeping the guidelines clear and concise. Below is a minimal but complete Apollo GraphQL server in Node.js that:
- Connects to PostgreSQL
- Exposes
Book and Author types
- Supports nested, composable filters with
AND / OR / NOT and field-level operators
- Supports ordering, pagination, and filtering by related entities (e.g., book’s author country)
You can copy-paste this into a new project and adapt it.
1. Database schema (PostgreSQL)
Example schema for authors and books:
CREATE TABLE authors (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
country TEXT
);
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
pages INT NOT NULL,
published_at TIMESTAMPTZ,
author_id INT NOT NULL REFERENCES authors(id)
);
CREATE INDEX idx_books_author_id ON books(author_id);
CREATE INDEX idx_books_published_at ON books(published_at);
CREATE INDEX idx_authors_country ON authors(country);
2. Project setup
mkdir apollo-postgres-filtering
cd apollo-postgres-filtering
npm init -y
npm install @apollo/server graphql pg dotenv
package.json (important part):
{
"name": "apollo-postgres-filtering",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"@apollo/server": "^4.11.0",
"graphql": "^16.8.1",
"pg": "^8.11.3",
"dotenv": "^16.4.5"
}
}
.env:
DATABASE_URL=postgresql://username:password@localhost:5432/mydb
PORT=4000
3. Apollo server with complex filtering (index.js)
import dotenv from 'dotenv';
dotenv.config();
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { Pool } from 'pg';
import { GraphQLScalarType, Kind } from 'graphql';
// ---------- PostgreSQL pool ----------
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
// ---------- Custom DateTime scalar ----------
const DateTime = new GraphQLScalarType({
name: 'DateTime',
description: 'ISO-8601 DateTime scalar',
serialize(value) {
if (!value) return null;
const date = value instanceof Date ? value : new Date(value);
return date.toISOString();
},
parseValue(value) {
if (!value) return null;
return new Date(value);
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new Date(ast.value);
}
return null;
},
});
// ---------- GraphQL schema ----------
const typeDefs = /* GraphQL */ `#graphql
scalar DateTime
type Author {
id: ID!
name: String!
country: String
}
type Book {
id: ID!
title: String!
pages: Int!
publishedAt: DateTime
author: Author!
}
type Query {
books(
filter: BookFilter
orderBy: [BookOrderBy!]
limit: Int = 50
offset: Int = 0
): [Book!]!
authors: [Author!]!
}
"""
Complex, composable filters for books
"""
input BookFilter {
AND: [BookFilter!]
OR: [BookFilter!]
NOT: [BookFilter!]
id: IDFilter
title: StringFilter
pages: IntFilter
publishedAt: DateTimeFilter
authorId: IDFilter
# Filter by related author fields
author: AuthorFilter
}
input AuthorFilter {
AND: [AuthorFilter!]
OR: [AuthorFilter!]
NOT: [AuthorFilter!]
id: IDFilter
name: StringFilter
country: StringFilter
}
input StringFilter {
eq: String
contains: String
in: [String!]
}
input IntFilter {
eq: Int
lt: Int
lte: Int
gt: Int
gte: Int
in: [Int!]
}
input IDFilter {
eq: ID
in: [ID!]
}
input DateTimeFilter {
eq: DateTime
before: DateTime
after: DateTime
between: DateTimeRange
}
input DateTimeRange {
start: DateTime!
end: DateTime!
}
enum SortOrder {
asc
desc
}
enum BookOrderField {
title
pages
publishedAt
}
input BookOrderBy {
field: BookOrderField!
direction: SortOrder! = asc
}
`;
// ---------- SQL query builders (filter + order) ----------
function pushValue(ctx, value) {
ctx.values.push(value);
return ctx.values.length; // 1-based index for $1, $2, ...
}
function buildStringFilter(filter, column, ctx) {
const parts = [];
if (filter.eq != null) {
const idx = pushValue(ctx, filter.eq);
parts.push(`${column} = $${idx}`);
}
if (filter.contains != null) {
const idx = pushValue(ctx, `%${filter.contains}%`);
parts.push(`${column} ILIKE $${idx}`);
}
if (Array.isArray(filter.in) && filter.in.length > 0) {
const placeholders = filter.in
.map((v) => `$${pushValue(ctx, v)}`)
.join(', ');
parts.push(`${column} IN (${placeholders})`);
}
return parts.length ? `(${parts.join(' AND ')})` : '';
}
function buildIntFilter(filter, column, ctx) {
const parts = [];
if (filter.eq != null) {
const idx = pushValue(ctx, filter.eq);
parts.push(`${column} = $${idx}`);
}
if (filter.lt != null) {
const idx = pushValue(ctx, filter.lt);
parts.push(`${column} < $${idx}`);
}
if (filter.lte != null) {
const idx = pushValue(ctx, filter.lte);
parts.push(`${column} <= $${idx}`);
}
if (filter.gt != null) {
const idx = pushValue(ctx, filter.gt);
parts.push(`${column} > $${idx}`);
}
if (filter.gte != null) {
const idx = pushValue(ctx, filter.gte);
parts.push(`${column} >= $${idx}`);
}
if (Array.isArray(filter.in) && filter.in.length > 0) {
const placeholders = filter.in
.map((v) => `$${pushValue(ctx, v)}`)
.join(', ');
parts.push(`${column} IN (${placeholders})`);
}
return parts.length ? `(${parts.join(' AND ')})` : '';
}
function buildIDFilter(filter, column, ctx) {
const parts = [];
if (filter.eq != null) {
const idx = pushValue(ctx, filter.eq);
parts.push(`${column} = $${idx}`);
}
if (Array.isArray(filter.in) && filter.in.length > 0) {
const placeholders = filter.in
.map((v) => `$${pushValue(ctx, v)}`)
.join(', ');
parts.push(`${column} IN (${placeholders})`);
}
return parts.length ? `(${parts.join(' AND ')})` : '';
}
function buildDateTimeFilter(filter, column, ctx) {
const parts = [];
if (filter.eq != null) {
const idx = pushValue(ctx, filter.eq);
parts.push(`${column} = $${idx}`);
}
if (filter.before != null) {
const idx = pushValue(ctx, filter.before);
parts.push(`${column} < $${idx}`);
}
if (filter.after != null) {
const idx = pushValue(ctx, filter.after);
parts.push(`${column} > $${idx}`);
}
if (filter.between != null) {
const startIdx = pushValue(ctx, filter.between.start);
const endIdx = pushValue(ctx, filter.between.end);
parts.push(`${column} BETWEEN $${startIdx} AND $${endIdx}`);
}
return parts.length ? `(${parts.join(' AND ')})` : '';
}
// Author filter WHERE builder (uses alias "a")
function buildAuthorWhere(filter, ctx) {
if (!filter) return '';
const alias = ctx.authorAlias;
const parts = [];
if (Array.isArray(filter.AND) && filter.AND.length) {
const sub = filter.AND.map((f) => buildAuthorWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`(${sub.join(' AND ')})`);
}
if (Array.isArray(filter.OR) && filter.OR.length) {
const sub = filter.OR.map((f) => buildAuthorWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`(${sub.join(' OR ')})`);
}
if (Array.isArray(filter.NOT) && filter.NOT.length) {
const sub = filter.NOT.map((f) => buildAuthorWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`NOT (${sub.join(' AND ')})`);
}
if (filter.id) {
const c = buildIDFilter(filter.id, `${alias}.id`, ctx);
if (c) parts.push(c);
}
if (filter.name) {
const c = buildStringFilter(filter.name, `${alias}.name`, ctx);
if (c) parts.push(c);
}
if (filter.country) {
const c = buildStringFilter(filter.country, `${alias}.country`, ctx);
if (c) parts.push(c);
}
return parts.length ? parts.join(' AND ') : '';
}
// Book filter WHERE builder (uses alias "b" and "a" for author)
function buildBookWhere(filter, ctx) {
if (!filter) return '';
const alias = ctx.bookAlias;
const parts = [];
if (Array.isArray(filter.AND) && filter.AND.length) {
const sub = filter.AND.map((f) => buildBookWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`(${sub.join(' AND ')})`);
}
if (Array.isArray(filter.OR) && filter.OR.length) {
const sub = filter.OR.map((f) => buildBookWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`(${sub.join(' OR ')})`);
}
if (Array.isArray(filter.NOT) && filter.NOT.length) {
const sub = filter.NOT.map((f) => buildBookWhere(f, ctx)).filter(Boolean);
if (sub.length) parts.push(`NOT (${sub.join(' AND ')})`);
}
if (filter.id) {
const c = buildIDFilter(filter.id, `${alias}.id`, ctx);
if (c) parts.push(c);
}
if (filter.title) {
const c = buildStringFilter(filter.title, `${alias}.title`, ctx);
if (c) parts.push(c);
}
if (filter.pages) {
const c = buildIntFilter(filter.pages, `${alias}.pages`, ctx);
if (c) parts.push(c);
}
if (filter.publishedAt) {
const c = buildDateTimeFilter(
filter.publishedAt,
`${alias}.published_at`,
ctx
);
if (c) parts.push(c);
}
if (filter.authorId) {
const c = buildIDFilter(filter.authorId, `${alias}.author_id`, ctx);
if (c) parts.push(c);
}
if (filter.author) {
const c = buildAuthorWhere(filter.author, ctx);
if (c) parts.push(c);
}
return parts.length ? parts.join(' AND ') : '';
}
function buildBooksQuery({ filter, orderBy, limit, offset }) {
const ctx = {
values: [],
bookAlias: 'b',
authorAlias: 'a',
};
let text = `
SELECT
b.id,
b.title,
b.pages,
b.published_at AS "publishedAt",
b.author_id AS "authorId"
FROM books b
LEFT JOIN authors a ON a.id = b.author_id
`;
const whereClause = filter ? buildBookWhere(filter, ctx) : '';
if (whereClause) {
text += ` WHERE ${whereClause}`;
}
// ORDER BY
const fieldMap = {
title: 'b.title',
pages: 'b.pages',
publishedAt: 'b.published_at',
};
text += ' ORDER BY ';
if (orderBy && orderBy.length) {
const orderParts = orderBy.map(({ field, direction }) => {
const column = fieldMap[field];
if (!column) {
throw new Error(`Unknown order field: ${field}`);
}
const dir =
(direction || 'asc').toLowerCase() === 'desc' ? 'DESC' : 'ASC';
return `${column} ${dir}`;
});
text += orderParts.join(', ');
} else {
text += 'b.id ASC';
}
// LIMIT / OFFSET
const limitValue = limit != null ? limit : 50;
const offsetValue = offset != null ? offset : 0;
const limitIdx = pushValue(ctx, limitValue);
const offsetIdx = pushValue(ctx, offsetValue);
text += ` LIMIT $${limitIdx} OFFSET $${offsetIdx}`;
return { text, values: ctx.values };
}
// ---------- Resolvers ----------
const resolvers = {
DateTime,
Query: {
books: async (_, args, context) => {
const { filter, orderBy, limit, offset } = args;
const { text, values } = buildBooksQuery({
filter,
orderBy,
limit,
offset,
});
const { rows } = await context.db.query(text, values);
return rows;
},
authors: async (_, __, context) => {
const { rows } = await context.db.query(
'SELECT id, name, country FROM authors ORDER BY id ASC'
);
return rows;
},
},
Book: {
// Resolve the author for a book
author: async (book, _, context) => {
const { rows } = await context.db.query(
'SELECT id, name, country FROM authors WHERE id = $1',
[book.authorId]
);
return rows[0] || null;
},
},
};
// ---------- Server bootstrap ----------
const server = new ApolloServer({
typeDefs,
resolvers,
});
const port = Number(process.env.PORT) || 4000;
const { url } = await startStandaloneServer(server, {
listen: { port },
context: async () => ({
db: pool,
}),
});
console.log(`Server running at ${url}`);
4. Example complex filter query
After npm start, open the Apollo sandbox and run:
query {
books(
filter: {
OR: [
{ title: { contains: "GraphQL" } }
{
AND: [
{ pages: { gte: 200 } }
{ author: { country: { eq: "US" } } }
]
}
]
publishedAt: {
after: "2020-01-01T00:00:00.000Z"
}
}
orderBy: [
{ field: publishedAt, direction: desc }
{ field: title, direction: asc }
]
limit: 20
offset: 0
) {
id
title
pages
publishedAt
author {
id
name
country
}
}
}
This will generate a single SQL query with nested AND / OR, joins on authors, ordering, limit, and offset.
If you want, I can adapt this to TypeScript, add DataLoader to avoid N+1 on author, or extend the filter operators further.