Skip to content

Commit b15d555

Browse files
committed
updates
0 parents  commit b15d555

84 files changed

Lines changed: 28733 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
---
2+
name: constructive-graphql
3+
description: "Unified GraphQL skill for Constructive — code generation (React Query hooks, Prisma-like ORM, CLI), runtime query generation, search (tsvector, BM25, trgm, pgvector, PostGIS, unified composite), pagination, and documentation generation. Use when asked to generate hooks, ORM, CLI, query data, add search, paginate results, or work with @constructive-io/graphql-codegen or @constructive-io/graphql-query."
4+
compatibility: Node.js 22+, PostgreSQL 14+, PostGraphile v5+
5+
metadata:
6+
author: constructive-io
7+
version: "5.0.0"
8+
---
9+
10+
# Constructive GraphQL
11+
12+
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.
13+
14+
## When to Apply
15+
16+
Use this skill when:
17+
- **Code generation**: Generating React Query hooks, ORM client, CLI, or documentation from a GraphQL schema
18+
- **Querying**: Using the generated ORM or hooks to fetch, mutate, paginate, or search data
19+
- **Search**: Adding or querying any search strategy (tsvector, BM25, trgm, pgvector, PostGIS) or the unified `unifiedSearch`/`searchScore` system
20+
- **Runtime queries**: Building GraphQL queries dynamically at runtime (browser-safe `graphql-query` package)
21+
- **Schema export**: Exporting GraphQL SDL from a database or endpoint
22+
23+
## The Flow
24+
25+
```
26+
1. Design DB → Use @constructive-io/sdk to create tables, fields, indexes, search columns
27+
2. Codegen → cnc codegen --orm --react-query (generates typed TS client)
28+
3. Query → Use generated ORM/hooks to fetch, mutate, search, paginate
29+
```
30+
31+
## Quick Start: Codegen
32+
33+
```typescript
34+
import { generate } from '@constructive-io/graphql-codegen';
35+
36+
await generate({
37+
schemaFile: './schemas/public.graphql', // or: endpoint, db, pgpm module
38+
output: './src/generated',
39+
reactQuery: true,
40+
orm: true,
41+
});
42+
```
43+
44+
See [codegen.md](./references/codegen.md) for full setup, schema sources, and options.
45+
46+
## Quick Start: ORM Queries
47+
48+
```typescript
49+
import { createClient } from '@/generated/orm';
50+
51+
const db = createClient({
52+
endpoint: process.env.GRAPHQL_URL!,
53+
headers: { Authorization: `Bearer ${token}` },
54+
});
55+
56+
// Find many with filters
57+
const users = await db.user.findMany({
58+
select: { id: true, name: true, email: true },
59+
where: { role: { equalTo: 'ADMIN' } },
60+
first: 10,
61+
}).execute().unwrap();
62+
63+
// Find one
64+
const user = await db.user.findOne({ id: '123' }).execute().unwrap();
65+
66+
// Create
67+
const newUser = await db.user.create({
68+
input: { name: 'John', email: 'john@example.com' },
69+
}).execute().unwrap();
70+
```
71+
72+
> **Error handling:** `.execute()` returns a discriminated union — it does NOT throw.
73+
> Chain `.execute().unwrap()` to get throw-on-error behavior. See [codegen-error-handling.md](./references/codegen-error-handling.md) for full patterns.
74+
75+
## Quick Start: Search
76+
77+
The simplest way to search — `unifiedSearch` fans a single string to all text-compatible algorithms automatically:
78+
79+
```typescript
80+
const results = await db.article.findMany({
81+
where: { unifiedSearch: 'machine learning' },
82+
orderBy: 'SEARCH_SCORE_DESC',
83+
select: { title: true, searchScore: true },
84+
}).execute();
85+
```
86+
87+
`searchScore` is computed server-side — no need to select individual score fields. See [search.md](./references/search.md) for all strategies and combined patterns.
88+
89+
## Quick Start: Pagination
90+
91+
```typescript
92+
// Cursor-based (recommended)
93+
const page1 = await db.user.findMany({
94+
first: 20,
95+
select: {
96+
id: true, name: true,
97+
__pageInfo: { hasNextPage: true, endCursor: true },
98+
},
99+
}).execute().unwrap();
100+
101+
// Next page
102+
const page2 = await db.user.findMany({
103+
first: 20,
104+
after: page1.__pageInfo.endCursor,
105+
select: { id: true, name: true },
106+
}).execute().unwrap();
107+
```
108+
109+
See [pagination.md](./references/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.
110+
111+
## Quick Start: React Query Hooks
112+
113+
```typescript
114+
import { configure, useUsersQuery, useCreateUserMutation } from '@/generated/hooks';
115+
116+
// Configure once at app startup
117+
configure({
118+
endpoint: process.env.NEXT_PUBLIC_GRAPHQL_URL!,
119+
headers: { Authorization: `Bearer ${getToken()}` },
120+
});
121+
122+
// Query
123+
function UserList() {
124+
const { data, isLoading } = useUsersQuery({ first: 10 });
125+
return <ul>{data?.users?.nodes.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
126+
}
127+
128+
// Mutate
129+
function CreateUser() {
130+
const create = useCreateUserMutation();
131+
return <button onClick={() => create.mutate({ input: { name: 'John' } })}>Create</button>;
132+
}
133+
```
134+
135+
See [codegen-hooks-patterns.md](./references/codegen-hooks-patterns.md) for advanced patterns.
136+
137+
## Search Strategy Overview
138+
139+
| Strategy | Best For | Score Direction |
140+
|----------|----------|-----------------|
141+
| **TSVector** | Keyword search with stemming | Higher = better |
142+
| **BM25** | Best relevance ranking for documents | More negative = better (sort ASC) |
143+
| **Trigram** | Fuzzy matching, typo tolerance | 0..1, higher = more similar |
144+
| **pgvector** | Semantic/embedding similarity, RAG | Lower distance = closer (sort ASC) |
145+
| **PostGIS** | Location queries, geofencing, proximity | Depends on operator |
146+
| **Unified** | Multi-signal ranking via `unifiedSearch` + `searchScore` | Higher = more relevant (0..1) |
147+
148+
See [search.md](./references/search.md) for the decision matrix and combined query patterns.
149+
150+
## Reference Guide
151+
152+
### Code Generation
153+
154+
| Reference | Topic | Consult When |
155+
|-----------|-------|--------------|
156+
| [codegen.md](./references/codegen.md) | Full codegen setup, schema sources, API | Setting up code generation, choosing schema source |
157+
| [codegen-config-reference.md](./references/codegen-config-reference.md) | `defineConfig` file reference | Using config files instead of programmatic API |
158+
| [codegen-cli-reference.md](./references/codegen-cli-reference.md) | CLI flags and options | Running codegen from command line |
159+
| [codegen-generate-schemas.md](./references/codegen-generate-schemas.md) | Schema export workflow | Exporting `.graphql` SDL files |
160+
| [codegen-generate-sdk.md](./references/codegen-generate-sdk.md) | SDK generation workflow | Generating React Query hooks and/or ORM |
161+
| [codegen-generate-cli.md](./references/codegen-generate-cli.md) | CLI generation workflow | Generating inquirerer-based CLI |
162+
| [codegen-generate-node.md](./references/codegen-generate-node.md) | Node.js adapter generation | `*.localhost` subdomain routing |
163+
164+
### Using Generated Code
165+
166+
| Reference | Topic | Consult When |
167+
|-----------|-------|--------------|
168+
| [codegen-orm-patterns.md](./references/codegen-orm-patterns.md) | ORM query patterns | Using `findMany`, `findOne`, `create`, `update`, `delete` |
169+
| [pagination.md](./references/pagination.md) | Pagination reference | Offset vs cursor, forward/backward paging, infinite scroll, nested relation pagination |
170+
| [codegen-orm-output.md](./references/codegen-orm-output.md) | ORM generated output structure | Understanding what codegen produces |
171+
| [codegen-hooks-patterns.md](./references/codegen-hooks-patterns.md) | React Query hook patterns | Using generated hooks in React components |
172+
| [codegen-hooks-output.md](./references/codegen-hooks-output.md) | Hooks generated output structure | Understanding hook file structure |
173+
| [codegen-error-handling.md](./references/codegen-error-handling.md) | **Error handling patterns (read first!)** | `.unwrap()` vs `.execute()`, silent error trap, `QueryResult<T>` discriminated union |
174+
| [codegen-relations.md](./references/codegen-relations.md) | Relation queries and M:N mutations | Nested selects, belongsTo, hasMany, manyToMany, composite PKs, `expose_in_api`, add/remove methods |
175+
| [codegen-query-keys.md](./references/codegen-query-keys.md) | Query key factory | Cache invalidation, `invalidate.*`, `remove.*` |
176+
| [codegen-node-http-adapter.md](./references/codegen-node-http-adapter.md) | Node.js HTTP adapter | Subdomain routing in Node.js |
177+
178+
### Search
179+
180+
| Reference | Topic | Consult When |
181+
|-----------|-------|--------------|
182+
| [search.md](./references/search.md) | Search overview, decision matrix, combined patterns | Choosing a strategy, combining algorithms, score fields |
183+
| [search-tsvector.md](./references/search-tsvector.md) | TSVector full-text search | Creating tsvector columns, GIN indexes, querying |
184+
| [search-bm25.md](./references/search-bm25.md) | BM25 ranked search | Creating BM25 indexes, querying with negative scores |
185+
| [search-trigram.md](./references/search-trigram.md) | Trigram fuzzy matching | `similarTo`, `wordSimilarTo`, `@trgmSearch` smart tag |
186+
| [search-pgvector.md](./references/search-pgvector.md) | pgvector similarity | Creating vector columns, HNSW indexes, distance metrics |
187+
| [search-postgis.md](./references/search-postgis.md) | PostGIS spatial queries | Geometry columns, spatial filters, proximity |
188+
| [search-composite.md](./references/search-composite.md) | Unified composite system | `unifiedSearch`, `searchScore`, combined multi-algorithm patterns |
189+
| [search-rag.md](./references/search-rag.md) | RAG patterns with ORM | Vector search for RAG, multi-table retrieval, hybrid search, embedding ingestion |
190+
191+
### Runtime Query Generation
192+
193+
| Reference | Topic | Consult When |
194+
|-----------|-------|--------------|
195+
| [query-runtime.md](./references/query-runtime.md) | `@constructive-io/graphql-query` package | Runtime/browser-safe query generation, `_meta` introspection |
196+
| [query-generators-api.md](./references/query-generators-api.md) | Generator API reference | `buildSelect`, `buildFindOne`, `buildCount`, mutations |
197+
| [query-meta-introspection.md](./references/query-meta-introspection.md) | `_meta` endpoint reference | PostGraphile metadata introspection, `cleanTable()` adapter |
198+
199+
## Cross-References
200+
201+
- `constructive-ai`[agentic-kit.md](../constructive-ai/references/agentic-kit.md): Multi-provider LLM abstraction for RAG generation step
202+
- `constructive-ai`[rag-pipeline.md](../constructive-ai/references/rag-pipeline.md): End-to-end RAG pipeline architecture
203+
- `graphile-search` — Plugin architecture and adapter internals (team-level, not SDK consumers)
204+
- `constructive` — Platform core: server config, deployment, CNC CLI
205+
- `pgpm` — Database migrations and module management
Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
# CLI Reference
2+
3+
Complete reference for `@constructive-io/graphql-codegen` CLI commands.
4+
5+
## @constructive-io/graphql-codegen generate
6+
7+
Generate type-safe React Query hooks and/or ORM client from GraphQL schema.
8+
9+
```bash
10+
npx @constructive-io/graphql-codegen generate [options]
11+
```
12+
13+
### Source Options (choose one)
14+
15+
| Option | Alias | Description | Default |
16+
|--------|-------|-------------|---------|
17+
| `--endpoint <url>` | `-e` | GraphQL endpoint URL | - |
18+
| `--schema-file <path>` | `-s` | Path to GraphQL schema file (.graphql) | - |
19+
| `--schemas <list>` | - | PostgreSQL schemas (comma-separated) | - |
20+
| `--api-names <list>` | - | API names for auto schema discovery | - |
21+
| `--config <path>` | `-c` | Path to config file | `graphql-codegen.config.ts` |
22+
23+
### Generator Options
24+
25+
| Option | Description | Default |
26+
|--------|-------------|---------|
27+
| `--react-query` | Generate React Query hooks | `false` |
28+
| `--orm` | Generate ORM client | `false` |
29+
30+
### Output Options
31+
32+
| Option | Alias | Description | Default |
33+
|--------|-------|-------------|---------|
34+
| `--output <dir>` | `-o` | Output directory | `./generated/graphql` |
35+
| `--target <name>` | `-t` | Target name (for multi-target configs) | - |
36+
37+
### Schema Export Options
38+
39+
| Option | Description | Default |
40+
|--------|-------------|---------|
41+
| `--schema-enabled` | Export GraphQL SDL schema file | `false` |
42+
| `--schema-output <dir>` | Output directory for exported schema | Same as `--output` |
43+
| `--schema-filename <name>` | Filename for exported schema | `schema.graphql` |
44+
45+
### Other Options
46+
47+
| Option | Alias | Description | Default |
48+
|--------|-------|-------------|---------|
49+
| `--authorization <token>` | `-a` | Authorization header value | - |
50+
| `--verbose` | `-v` | Show detailed output | `false` |
51+
| `--dry-run` | - | Preview without writing files | `false` |
52+
| `--help` | `-h` | Show help message | - |
53+
54+
## Examples
55+
56+
### From GraphQL Endpoint
57+
58+
```bash
59+
# Generate React Query hooks
60+
npx @constructive-io/graphql-codegen generate --react-query --endpoint https://api.example.com/graphql
61+
62+
# Generate ORM client
63+
npx @constructive-io/graphql-codegen generate --orm --endpoint https://api.example.com/graphql
64+
65+
# Generate both
66+
npx @constructive-io/graphql-codegen generate --react-query --orm --endpoint https://api.example.com/graphql
67+
68+
# With custom output
69+
npx @constructive-io/graphql-codegen generate --react-query --endpoint https://api.example.com/graphql --output ./generated
70+
71+
# With authorization
72+
npx @constructive-io/graphql-codegen generate --orm --endpoint https://api.example.com/graphql --authorization "Bearer token123"
73+
```
74+
75+
### From Schema File
76+
77+
```bash
78+
# Generate from .graphql file
79+
npx @constructive-io/graphql-codegen generate --react-query --schema-file ./schema.graphql --output ./generated
80+
81+
# With both generators
82+
npx @constructive-io/graphql-codegen generate --react-query --orm --schema-file ./schema.graphql
83+
```
84+
85+
### From Database
86+
87+
```bash
88+
# Explicit schemas
89+
npx @constructive-io/graphql-codegen generate --react-query --schemas public,app_public
90+
91+
# Auto-discover from API names
92+
npx @constructive-io/graphql-codegen generate --orm --api-names my_api
93+
94+
# With custom output
95+
npx @constructive-io/graphql-codegen generate --react-query --schemas public --output ./generated
96+
```
97+
98+
### Using Config File
99+
100+
```bash
101+
# Use default config file (graphql-codegen.config.ts)
102+
npx @constructive-io/graphql-codegen generate
103+
104+
# Use specific config file
105+
npx @constructive-io/graphql-codegen generate --config ./config/codegen.config.ts
106+
107+
# Override config with CLI options
108+
npx @constructive-io/graphql-codegen generate --config ./config.ts --react-query --orm
109+
110+
# Multi-target: generate specific target
111+
npx @constructive-io/graphql-codegen generate --target production
112+
113+
# Multi-target: generate all targets
114+
npx @constructive-io/graphql-codegen generate
115+
```
116+
117+
### Development Workflow
118+
119+
```bash
120+
# Dry run to preview changes
121+
npx @constructive-io/graphql-codegen generate --react-query --endpoint https://api.example.com/graphql --dry-run
122+
123+
# Verbose output for debugging
124+
npx @constructive-io/graphql-codegen generate --orm --endpoint https://api.example.com/graphql --verbose
125+
126+
# Keep ephemeral database for debugging (when using PGPM modules)
127+
npx @constructive-io/graphql-codegen generate --schemas public --keep-db
128+
```
129+
130+
## Environment Variables
131+
132+
The CLI respects these environment variables:
133+
134+
| Variable | Description |
135+
|----------|-------------|
136+
| `PGHOST` | PostgreSQL host (for database introspection) |
137+
| `PGPORT` | PostgreSQL port |
138+
| `PGDATABASE` | PostgreSQL database name |
139+
| `PGUSER` | PostgreSQL user |
140+
| `PGPASSWORD` | PostgreSQL password |
141+
142+
## Exit Codes
143+
144+
| Code | Meaning |
145+
|------|---------|
146+
| `0` | Success |
147+
| `1` | General error |
148+
| `2` | Configuration error |
149+
| `3` | Network/schema error |
150+
151+
## Troubleshooting
152+
153+
| Issue | Solution |
154+
|-------|----------|
155+
| No code generated | Add `--react-query` or `--orm` flag |
156+
| "Cannot use both endpoint and schemas" | Choose one schema source |
157+
| "schemas and apiNames are mutually exclusive" | Use either `--schemas` or `--api-names`, not both |
158+
| Database connection errors | Check `PG*` environment variables |

0 commit comments

Comments
 (0)