constructive-graphql
Constructive GraphQL
The complete GraphQL layer for Constructive: design your database → run codegen → query via typed SDK. Covers code generation, runtime query building, search across all algorithms, pagination, and documentation generation.
When to Apply
Use this skill when:
- Code generation: Generating React Query hooks, ORM client, CLI, or documentation from a GraphQL schema
- Querying: Using the generated ORM or hooks to fetch, mutate, paginate, or search data
- Search: Adding or querying any search strategy (tsvector, BM25, trgm, pgvector, PostGIS) or the unified
unifiedSearch/searchScoresystem - Runtime queries: Building GraphQL queries dynamically at runtime (browser-safe
graphql-querypackage) - Schema export: Exporting GraphQL SDL from a database or endpoint
The Flow
1. Design DB → Use @constructive-io/sdk to create tables, fields, indexes, search columns
2. Codegen → cnc codegen --orm --react-query (generates typed TS client)
3. Query → Use generated ORM/hooks to fetch, mutate, search, paginate
Quick Start: Codegen
import { generate } from '@constructive-io/graphql-codegen';
await generate({
schemaFile: './schemas/public.graphql', // or: endpoint, db, pgpm module
output: './src/generated',
reactQuery: true,
orm: true,
});
See codegen.md for full setup, schema sources, and options.
Quick Start: ORM Queries
import { createClient } from '@/generated/orm';
const db = createClient({
endpoint: process.env.GRAPHQL_URL!,
headers: { Authorization: `Bearer ${token}` },
});
// Find many with filters
const users = await db.user.findMany({
select: { id: true, name: true, email: true },
where: { role: { equalTo: 'ADMIN' } },
first: 10,
}).execute().unwrap();
// Find one
const user = await db.user.findOne({ id: '123' }).execute().unwrap();
// Create
const newUser = await db.user.create({
input: { name: 'John', email: 'john@example.com' },
}).execute().unwrap();
Error handling:
.execute()returns a discriminated union — it does NOT throw. Chain.execute().unwrap()to get throw-on-error behavior. See codegen-error-handling.md for full patterns.
Quick Start: Search
The simplest way to search — unifiedSearch fans a single string to all text-compatible algorithms automatically:
const results = await db.article.findMany({
where: { unifiedSearch: 'machine learning' },
orderBy: 'SEARCH_SCORE_DESC',
select: { title: true, searchScore: true },
}).execute();
searchScore is computed server-side — no need to select individual score fields. See search.md for all strategies and combined patterns.
Quick Start: Pagination
// Cursor-based (recommended)
const page1 = await db.user.findMany({
first: 20,
select: {
id: true, name: true,
__pageInfo: { hasNextPage: true, endCursor: true },
},
}).execute().unwrap();
// Next page
const page2 = await db.user.findMany({
first: 20,
after: page1.__pageInfo.endCursor,
select: { id: true, name: true },
}).execute().unwrap();
See pagination.md for the full pagination reference — offset vs cursor, forward vs backward, nested relation paging, and usage across ORM, hooks, and runtime query builder.
Quick Start: React Query Hooks
import { configure, useUsersQuery, useCreateUserMutation } from '@/generated/hooks';
// Configure once at app startup
configure({
endpoint: process.env.NEXT_PUBLIC_GRAPHQL_URL!,
headers: { Authorization: `Bearer ${getToken()}` },
});
// Query
function UserList() {
const { data, isLoading } = useUsersQuery({ first: 10 });
return <ul>{data?.users?.nodes.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
// Mutate
function CreateUser() {
const create = useCreateUserMutation();
return <button onClick={() => create.mutate({ input: { name: 'John' } })}>Create</button>;
}
See codegen-hooks-patterns.md for advanced patterns.
Search Strategy Overview
| Strategy | Best For | Score Direction |
|---|---|---|
| TSVector | Keyword search with stemming | Higher = better |
| BM25 | Best relevance ranking for documents | More negative = better (sort ASC) |
| Trigram | Fuzzy matching, typo tolerance | 0..1, higher = more similar |
| pgvector | Semantic/embedding similarity, RAG | Lower distance = closer (sort ASC) |
| PostGIS | Location queries, geofencing, proximity | Depends on operator |
| Unified | Multi-signal ranking via unifiedSearch + searchScore |
Higher = more relevant (0..1) |
See search.md for the decision matrix and combined query patterns.
Reference Guide
Code Generation
| Reference | Topic | Consult When |
|---|---|---|
| codegen.md | Full codegen setup, schema sources, API | Setting up code generation, choosing schema source |
| codegen-config-reference.md | defineConfig file reference |
Using config files instead of programmatic API |
| codegen-cli-reference.md | CLI flags and options | Running codegen from command line |
| codegen-generate-schemas.md | Schema export workflow | Exporting .graphql SDL files |
| codegen-generate-sdk.md | SDK generation workflow | Generating React Query hooks and/or ORM |
| codegen-generate-cli.md | CLI generation workflow | Generating inquirerer-based CLI |
| codegen-generate-node.md | Node.js adapter generation | *.localhost subdomain routing |
Using Generated Code
| Reference | Topic | Consult When |
|---|---|---|
| codegen-orm-patterns.md | ORM query patterns | Using findMany, findOne, create, update, delete |
| pagination.md | Pagination reference | Offset vs cursor, forward/backward paging, infinite scroll, nested relation pagination |
| codegen-orm-output.md | ORM generated output structure | Understanding what codegen produces |
| codegen-hooks-patterns.md | React Query hook patterns | Using generated hooks in React components |
| codegen-hooks-output.md | Hooks generated output structure | Understanding hook file structure |
| codegen-error-handling.md | Error handling patterns (read first!) | .unwrap() vs .execute(), silent error trap, QueryResult<T> discriminated union |
| codegen-relations.md | Relation queries and M:N mutations | Nested selects, belongsTo, hasMany, manyToMany, composite PKs, expose_in_api, add/remove methods |
| codegen-query-keys.md | Query key factory | Cache invalidation, invalidate.*, remove.* |
| codegen-node-http-adapter.md | Node.js HTTP adapter | Subdomain routing in Node.js |
Search
| Reference | Topic | Consult When |
|---|---|---|
| search.md | Search overview, decision matrix, combined patterns | Choosing a strategy, combining algorithms, score fields |
| search-tsvector.md | TSVector full-text search | Creating tsvector columns, GIN indexes, querying |
| search-bm25.md | BM25 ranked search | Creating BM25 indexes, querying with negative scores |
| search-trigram.md | Trigram fuzzy matching | similarTo, wordSimilarTo, @trgmSearch smart tag |
| search-pgvector.md | pgvector similarity | Creating vector columns, HNSW indexes, distance metrics |
| search-postgis.md | PostGIS spatial queries | Geometry columns, spatial filters, proximity |
| search-composite.md | Unified composite system | unifiedSearch, searchScore, combined multi-algorithm patterns |
| search-rag.md | RAG patterns with ORM | Vector search for RAG, multi-table retrieval, hybrid search, embedding ingestion |
Runtime Query Generation
| Reference | Topic | Consult When |
|---|---|---|
| query-runtime.md | @constructive-io/graphql-query package |
Runtime/browser-safe query generation, _meta introspection |
| query-generators-api.md | Generator API reference | buildSelect, buildFindOne, buildCount, mutations |
| query-meta-introspection.md | _meta endpoint reference |
PostGraphile metadata introspection, cleanTable() adapter |
Cross-References
constructive-ai— agentic-kit.md: Multi-provider LLM abstraction for RAG generation stepconstructive-ai— rag-pipeline.md: End-to-end RAG pipeline architecturegraphile-search— Plugin architecture and adapter internals (team-level, not SDK consumers)constructive— Platform core: server config, deployment, CNC CLIpgpm— Database migrations and module management
More from constructive-io/constructive-skills
drizzle-orm
Drizzle ORM patterns for PostgreSQL schema design and queries. Use when asked to "design Drizzle schema", "write Drizzle queries", "set up Drizzle ORM", or when building type-safe database layers.
21planning-blueprinting
In-repo planning and specification system for software projects. Use when asked to "create a plan", "write a spec", "document a proposal", "blueprint a feature", or when doing architectural planning work.
20pgsql-parser-testing
Test the pgsql-parser repository (SQL parser/deparser). Use when working in the pgsql-parser repo, fixing deparser issues, running parser tests, or validating SQL round-trips. Scoped specifically to the constructive-io/pgsql-parser repository.
18constructive-graphql-codegen
Generate type-safe React Query hooks, Prisma-like ORM client, or inquirerer-based CLI from GraphQL endpoints, schema files/directories, databases, or PGPM modules using @constructive-io/graphql-codegen. Also generates documentation (README, AGENTS.md, skills/, mcp.json). Use when asked to "generate GraphQL hooks", "generate ORM", "generate CLI", "set up codegen", "generate docs", "generate skills", "export schema", or when implementing data fetching for a PostGraphile backend.
17constructive-server-config
Configure and run the Constructive GraphQL server (cnc server), GraphiQL explorer (cnc explorer), and code generation (cnc codegen). Use when asked to "start the server", "run cnc server", "start GraphQL API", "run GraphiQL", "configure API routing", "generate types", or when working with the Constructive CLI and PostGraphile.
17constructive-boilerplate-nextjs-app
Set up and develop with the Constructive App frontend boilerplate — a Next.js application with authentication, organization management, invites, members, and a GraphQL SDK. Use when scaffolding a new Constructive frontend application from the boilerplate.
17