@graphql-mesh/transport-sql 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/cjs/adapter.js +60 -0
  3. package/dist/cjs/batch.js +113 -0
  4. package/dist/cjs/client.js +205 -0
  5. package/dist/cjs/client.js.map +7 -0
  6. package/dist/cjs/dialect.js +60 -0
  7. package/dist/cjs/dialect.js.map +7 -0
  8. package/dist/cjs/entity.js +186 -0
  9. package/dist/cjs/execution.js +307 -0
  10. package/dist/cjs/execution.js.map +7 -0
  11. package/dist/cjs/index.js +23 -0
  12. package/dist/cjs/index.js.map +7 -0
  13. package/dist/cjs/mapping.js +260 -0
  14. package/dist/cjs/mapping.js.map +7 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/pg-executor.js +53 -0
  17. package/dist/cjs/pg-plans.js +103 -0
  18. package/dist/cjs/pg-registry.js +239 -0
  19. package/dist/cjs/plan.js +359 -0
  20. package/dist/cjs/sql-builder.js +653 -0
  21. package/dist/cjs/sql-builder.js.map +7 -0
  22. package/dist/cjs/types.js +0 -0
  23. package/dist/cjs/types.js.map +7 -0
  24. package/dist/cjs/uri.js +267 -0
  25. package/dist/esm/adapter.js +54 -0
  26. package/dist/esm/batch.js +107 -0
  27. package/dist/esm/client.js +197 -0
  28. package/dist/esm/client.js.map +7 -0
  29. package/dist/esm/dialect.js +54 -0
  30. package/dist/esm/dialect.js.map +7 -0
  31. package/dist/esm/entity.js +180 -0
  32. package/dist/esm/execution.js +303 -0
  33. package/dist/esm/execution.js.map +7 -0
  34. package/dist/esm/index.js +20 -0
  35. package/dist/esm/index.js.map +7 -0
  36. package/dist/esm/mapping.js +255 -0
  37. package/dist/esm/mapping.js.map +7 -0
  38. package/dist/esm/pg-executor.js +49 -0
  39. package/dist/esm/pg-plans.js +100 -0
  40. package/dist/esm/pg-registry.js +236 -0
  41. package/dist/esm/plan.js +351 -0
  42. package/dist/esm/sql-builder.js +636 -0
  43. package/dist/esm/sql-builder.js.map +7 -0
  44. package/dist/esm/types.js +0 -0
  45. package/dist/esm/types.js.map +7 -0
  46. package/dist/esm/uri.js +261 -0
  47. package/dist/package.json +57 -0
  48. package/dist/typings/adapter.d.cts +9 -0
  49. package/dist/typings/adapter.d.ts +9 -0
  50. package/dist/typings/batch.d.cts +21 -0
  51. package/dist/typings/batch.d.ts +21 -0
  52. package/dist/typings/client.d.cts +36 -0
  53. package/dist/typings/client.d.ts +36 -0
  54. package/dist/typings/dialect.d.cts +9 -0
  55. package/dist/typings/dialect.d.ts +9 -0
  56. package/dist/typings/entity.d.cts +24 -0
  57. package/dist/typings/entity.d.ts +24 -0
  58. package/dist/typings/execution.d.cts +9 -0
  59. package/dist/typings/execution.d.ts +9 -0
  60. package/dist/typings/index.d.cts +15 -0
  61. package/dist/typings/index.d.ts +15 -0
  62. package/dist/typings/mapping.d.cts +13 -0
  63. package/dist/typings/mapping.d.ts +13 -0
  64. package/dist/typings/pg-executor.d.cts +19 -0
  65. package/dist/typings/pg-executor.d.ts +19 -0
  66. package/dist/typings/pg-plans.d.cts +12 -0
  67. package/dist/typings/pg-plans.d.ts +12 -0
  68. package/dist/typings/pg-registry.d.cts +16 -0
  69. package/dist/typings/pg-registry.d.ts +16 -0
  70. package/dist/typings/plan.d.cts +47 -0
  71. package/dist/typings/plan.d.ts +47 -0
  72. package/dist/typings/sql-builder.d.cts +75 -0
  73. package/dist/typings/sql-builder.d.ts +75 -0
  74. package/dist/typings/types.d.cts +50 -0
  75. package/dist/typings/types.d.ts +50 -0
  76. package/dist/typings/uri.d.cts +42 -0
  77. package/dist/typings/uri.d.ts +42 -0
  78. package/package.json +67 -4
  79. package/src/adapter.ts +56 -0
  80. package/src/batch.ts +150 -0
  81. package/src/client.ts +233 -0
  82. package/src/entity.ts +235 -0
  83. package/src/execution.ts +411 -0
  84. package/src/index.ts +25 -0
  85. package/src/mapping.ts +291 -0
  86. package/src/pg-executor.ts +68 -0
  87. package/src/pg-plans.ts +118 -0
  88. package/src/pg-registry.ts +290 -0
  89. package/src/plan.ts +466 -0
  90. package/src/sql-builder.ts +809 -0
  91. package/src/types.ts +63 -0
  92. package/src/uri.ts +301 -0
  93. package/test/client-bun.test.ts +8 -0
  94. package/test/client.bun.test.ts +46 -0
  95. package/test/execution.test.ts +277 -0
  96. package/test/mapping.test.ts +79 -0
  97. package/test/pg-registry.test.ts +103 -0
  98. package/test/sql-builder.test.ts +131 -0
  99. package/test/uri.test.ts +123 -0
  100. package/README.md +0 -3
package/src/mapping.ts ADDED
@@ -0,0 +1,291 @@
1
+ import type { ParsedSqlMapping, SqlMappingEntry, SqlMappingValue } from './types.js';
2
+
3
+ /**
4
+ * Parse `@sql` `where` / `set` / `selection` block strings.
5
+ * Skips `# ...` comments to EOL. Supports nested `{ ... }` blocks and `$args` / `$this` / `$pseudo`.
6
+ */
7
+ export function parseSqlMapping(source: string | null | undefined): ParsedSqlMapping {
8
+ if (source == null || !String(source).trim()) {
9
+ return { entries: [] };
10
+ }
11
+ const text = stripComments(String(source));
12
+ const { entries, next } = parseBlock(text, 0, false);
13
+ if (next < text.length && text.slice(next).trim()) {
14
+ throw new Error(`Unexpected trailing content in SQL mapping: ${text.slice(next, next + 40)}`);
15
+ }
16
+ return { entries };
17
+ }
18
+
19
+ function stripComments(source: string): string {
20
+ return source
21
+ .split('\n')
22
+ .map(line => {
23
+ const idx = line.indexOf('#');
24
+ if (idx === -1) return line;
25
+ // Keep `#` inside quotes
26
+ let inQuote: '"' | "'" | null = null;
27
+ for (let i = 0; i < line.length; i++) {
28
+ const c = line[i];
29
+ if (inQuote) {
30
+ if (c === '\\') {
31
+ i++;
32
+ continue;
33
+ }
34
+ if (c === inQuote) inQuote = null;
35
+ continue;
36
+ }
37
+ if (c === '"' || c === "'") {
38
+ inQuote = c;
39
+ continue;
40
+ }
41
+ if (c === '#') {
42
+ return line.slice(0, i);
43
+ }
44
+ }
45
+ return line;
46
+ })
47
+ .join('\n');
48
+ }
49
+
50
+ function parseBlock(
51
+ text: string,
52
+ start: number,
53
+ expectClosing: boolean,
54
+ ): { entries: SqlMappingEntry[]; next: number } {
55
+ const entries: SqlMappingEntry[] = [];
56
+ let i = skipWs(text, start);
57
+ while (i < text.length) {
58
+ if (text[i] === '}') {
59
+ if (!expectClosing) {
60
+ throw new Error(`Unexpected "}" in SQL mapping at ${i}`);
61
+ }
62
+ return { entries, next: i + 1 };
63
+ }
64
+ if (expectClosing === false && text[i] === '{') {
65
+ throw new Error(`Unexpected "{" in SQL mapping at ${i}`);
66
+ }
67
+
68
+ // Connectors-style spread: `...$args.where` / `...$this.filters`
69
+ if (text.startsWith('...', i)) {
70
+ const afterDots = skipWs(text, i + 3);
71
+ if (afterDots >= text.length || text[afterDots] !== '$') {
72
+ throw new Error(`Expected "$" after "..." in SQL mapping at ${i}`);
73
+ }
74
+ const rhs = readPseudoOrPath(text, afterDots);
75
+ if (rhs.value.kind !== 'args' && rhs.value.kind !== 'this') {
76
+ throw new Error(`Spread target must be $args / $this path, got ${rhs.raw}`);
77
+ }
78
+ entries.push({
79
+ key: `...${rhs.raw}`,
80
+ value: rhs.value,
81
+ spread: true,
82
+ });
83
+ i = skipWs(text, rhs.next);
84
+ continue;
85
+ }
86
+
87
+ // Bare pseudo `$` (COUNT selection) or `$token`
88
+ if (text[i] === '$' && !isIdentStart(text[i + 1] ?? '')) {
89
+ // look ahead for ident after $
90
+ }
91
+ if (text[i] === '$') {
92
+ const pseudo = readPseudoOrPath(text, i);
93
+ entries.push({
94
+ key: pseudo.raw,
95
+ value: pseudo.value,
96
+ });
97
+ i = skipWs(text, pseudo.next);
98
+ continue;
99
+ }
100
+
101
+ const key = readIdent(text, i);
102
+ i = skipWs(text, key.next);
103
+ if (i < text.length && text[i] === '{') {
104
+ const nested = parseBlock(text, i + 1, true);
105
+ entries.push({ key: key.value, children: nested.entries });
106
+ i = skipWs(text, nested.next);
107
+ continue;
108
+ }
109
+ if (i >= text.length || text[i] !== ':') {
110
+ // bare field pick (rare) — treat as identity column
111
+ entries.push({
112
+ key: key.value,
113
+ value: { kind: 'column', value: key.value },
114
+ });
115
+ continue;
116
+ }
117
+ i = skipWs(text, i + 1);
118
+ if (i < text.length && text[i] === '{') {
119
+ const nested = parseBlock(text, i + 1, true);
120
+ entries.push({ key: key.value, children: nested.entries });
121
+ i = skipWs(text, nested.next);
122
+ continue;
123
+ }
124
+ if (i < text.length && text[i] === '$') {
125
+ const rhs = readPseudoOrPath(text, i);
126
+ entries.push({ key: key.value, value: rhs.value });
127
+ i = skipWs(text, rhs.next);
128
+ continue;
129
+ }
130
+ if (i < text.length && (text[i] === '"' || text[i] === "'")) {
131
+ const lit = readQuoted(text, i);
132
+ entries.push({
133
+ key: key.value,
134
+ value: { kind: 'literal', value: lit.value },
135
+ });
136
+ i = skipWs(text, lit.next);
137
+ continue;
138
+ }
139
+ const col = readIdent(text, i);
140
+ entries.push({
141
+ key: key.value,
142
+ value: { kind: 'column', value: col.value },
143
+ });
144
+ i = skipWs(text, col.next);
145
+ }
146
+ if (expectClosing) {
147
+ throw new Error('Unclosed "{" in SQL mapping');
148
+ }
149
+ return { entries, next: i };
150
+ }
151
+
152
+ function readPseudoOrPath(
153
+ text: string,
154
+ start: number,
155
+ ): { raw: string; value: SqlMappingValue; next: number } {
156
+ if (text[start] !== '$') {
157
+ throw new Error(`Expected "$" at ${start}`);
158
+ }
159
+ // `$` alone
160
+ if (start + 1 >= text.length || !isIdentStart(text[start + 1])) {
161
+ return {
162
+ raw: '$',
163
+ value: { kind: 'pseudo', value: '$' },
164
+ next: start + 1,
165
+ };
166
+ }
167
+ let i = start + 1;
168
+ const head = readIdent(text, i);
169
+ i = head.next;
170
+ if (head.value === 'args' || head.value === 'this') {
171
+ const path: string[] = [];
172
+ while (i < text.length && text[i] === '.') {
173
+ i++;
174
+ const seg = readIdent(text, i);
175
+ path.push(seg.value);
176
+ i = seg.next;
177
+ }
178
+ return {
179
+ raw: `$${head.value}${path.length ? '.' + path.join('.') : ''}`,
180
+ value: {
181
+ kind: head.value === 'args' ? 'args' : 'this',
182
+ value: path[0] ?? '',
183
+ path,
184
+ },
185
+ next: i,
186
+ };
187
+ }
188
+ // $cursor, $totalCount, ...
189
+ return {
190
+ raw: `$${head.value}`,
191
+ value: { kind: 'pseudo', value: head.value },
192
+ next: i,
193
+ };
194
+ }
195
+
196
+ function readIdent(text: string, start: number): { value: string; next: number } {
197
+ let i = skipWs(text, start);
198
+ if (i >= text.length || !isIdentStart(text[i])) {
199
+ throw new Error(`Expected identifier at ${i} near "${text.slice(i, i + 20)}"`);
200
+ }
201
+ const from = i;
202
+ i++;
203
+ while (i < text.length && isIdentCont(text[i])) i++;
204
+ return { value: text.slice(from, i), next: i };
205
+ }
206
+
207
+ function readQuoted(text: string, start: number): { value: string; next: number } {
208
+ const q = text[start];
209
+ let i = start + 1;
210
+ let out = '';
211
+ while (i < text.length) {
212
+ const c = text[i];
213
+ if (c === '\\' && i + 1 < text.length) {
214
+ out += text[i + 1];
215
+ i += 2;
216
+ continue;
217
+ }
218
+ if (c === q) {
219
+ return { value: out, next: i + 1 };
220
+ }
221
+ out += c;
222
+ i++;
223
+ }
224
+ throw new Error('Unclosed string in SQL mapping');
225
+ }
226
+
227
+ function skipWs(text: string, start: number): number {
228
+ let i = start;
229
+ while (i < text.length && /\s/.test(text[i])) i++;
230
+ return i;
231
+ }
232
+
233
+ function isIdentStart(c: string): boolean {
234
+ return /[A-Za-z_]/.test(c);
235
+ }
236
+
237
+ function isIdentCont(c: string): boolean {
238
+ return /[A-Za-z0-9_]/.test(c);
239
+ }
240
+
241
+ /** Flatten selection entries that map GraphQL field -> SQL column (ignore nested/pseudo). */
242
+ export function columnMapFromSelection(selection: ParsedSqlMapping): Map<string, string> {
243
+ const map = new Map<string, string>();
244
+ const walk = (entries: SqlMappingEntry[]) => {
245
+ for (const entry of entries) {
246
+ if (entry.children) {
247
+ walk(entry.children);
248
+ continue;
249
+ }
250
+ if (entry.value?.kind === 'column') {
251
+ map.set(entry.key, entry.value.value);
252
+ }
253
+ }
254
+ };
255
+ walk(selection.entries);
256
+ return map;
257
+ }
258
+
259
+ /** Resolve `$args.path` / `$this.path` / literal against runtime. */
260
+ export function resolveMappingValue(
261
+ value: SqlMappingValue | undefined,
262
+ ctx: { args?: Record<string, any>; parent?: Record<string, any> },
263
+ ): unknown {
264
+ if (!value) return undefined;
265
+ switch (value.kind) {
266
+ case 'literal':
267
+ return value.value;
268
+ case 'args': {
269
+ let cur: any = ctx.args;
270
+ for (const seg of value.path || []) {
271
+ if (cur == null) return undefined;
272
+ cur = cur[seg];
273
+ }
274
+ return cur;
275
+ }
276
+ case 'this': {
277
+ let cur: any = ctx.parent;
278
+ for (const seg of value.path || []) {
279
+ if (cur == null) return undefined;
280
+ cur = cur[seg];
281
+ }
282
+ return cur;
283
+ }
284
+ case 'column':
285
+ return value.value;
286
+ case 'pseudo':
287
+ return undefined;
288
+ default:
289
+ return undefined;
290
+ }
291
+ }
@@ -0,0 +1,68 @@
1
+ import { execute as grafastExecute } from 'grafast';
2
+ import type { GraphQLSchema } from 'graphql';
3
+ import type { Pool } from 'pg';
4
+ import { makePgAdaptorWithPgClient } from '@dataplan/pg/adaptors/pg';
5
+ import type { DisposableExecutor } from '@graphql-mesh/transport-common';
6
+ import { DisposableSymbols } from '@whatwg-node/disposablestack';
7
+ import { wirePostgresSqlPlans } from './pg-plans.js';
8
+ import { buildPgRegistryFromSqlSchema } from './pg-registry.js';
9
+ import type { SqlClient } from './types.js';
10
+
11
+ export interface CreatePostgresGrafastExecutorOpts {
12
+ subgraph: GraphQLSchema;
13
+ sqlClient: SqlClient;
14
+ /** Called on dispose in addition to releasing withPgClient */
15
+ disposeClient: () => void | Promise<void>;
16
+ }
17
+
18
+ /**
19
+ * Postgres fast path: Grafast + `@dataplan/pg` plans for `@sql` fields.
20
+ * Requires a Node `pg.Pool` on `sqlClient.pgPool` (Bun.SQL falls back to the
21
+ * generic GraphQL.js planner).
22
+ */
23
+ export function createPostgresGrafastExecutor(
24
+ opts: CreatePostgresGrafastExecutorOpts,
25
+ ): DisposableExecutor | null {
26
+ const pool = opts.sqlClient.pgPool;
27
+ if (!pool) return null;
28
+
29
+ const { registry, relationNames } = buildPgRegistryFromSqlSchema(opts.subgraph);
30
+ const schema = wirePostgresSqlPlans(opts.subgraph, registry, { relationNames });
31
+ const withPgClient = makePgAdaptorWithPgClient(pool);
32
+
33
+ const executor: DisposableExecutor = async function postgresGrafastExecutor(executionRequest) {
34
+ const baseContext =
35
+ executionRequest.context && typeof executionRequest.context === 'object'
36
+ ? executionRequest.context
37
+ : {};
38
+ const contextValue = {
39
+ ...baseContext,
40
+ pgSettings: (baseContext as any).pgSettings ?? {},
41
+ withPgClient,
42
+ pgSubscriber: (baseContext as any).pgSubscriber ?? null,
43
+ };
44
+
45
+ return grafastExecute({
46
+ schema,
47
+ document: executionRequest.document,
48
+ variableValues: executionRequest.variables,
49
+ rootValue: executionRequest.rootValue,
50
+ contextValue,
51
+ operationName: executionRequest.operationName,
52
+ } as any);
53
+ };
54
+
55
+ executor[DisposableSymbols.dispose] = () => {
56
+ void withPgClient.release?.();
57
+ void opts.disposeClient();
58
+ };
59
+ executor[DisposableSymbols.asyncDispose] = async () => {
60
+ await withPgClient.release?.();
61
+ await opts.disposeClient();
62
+ };
63
+ return executor;
64
+ }
65
+
66
+ export function hasPgPool(client: SqlClient): client is SqlClient & { pgPool: Pool } {
67
+ return Boolean(client.pgPool);
68
+ }
@@ -0,0 +1,118 @@
1
+ import { connection } from 'grafast';
2
+ import type { GraphQLFieldConfig, GraphQLSchema } from 'graphql';
3
+ import { getDefDirectives } from '@graphql-mesh/utils';
4
+ import { MapperKind, mapSchema } from '@graphql-tools/utils';
5
+ import { batchableEqualityColumn } from './batch.js';
6
+ import { parseSqlMapping } from './mapping.js';
7
+ import type { MeshPgRegistry } from './pg-registry.js';
8
+ import type { SqlKind } from './types.js';
9
+
10
+ /**
11
+ * Attach Grafast / `@dataplan/pg` plan resolvers for `@sql` query fields.
12
+ * Mutations keep traditional resolvers for this slice.
13
+ */
14
+ export function wirePostgresSqlPlans(
15
+ schema: GraphQLSchema,
16
+ registry: MeshPgRegistry,
17
+ meta: {
18
+ relationNames: Map<string, Map<string, { remoteTable: string; kind: 'ROW' | 'ROWS' }>>;
19
+ },
20
+ ): GraphQLSchema {
21
+ return mapSchema(schema, {
22
+ [MapperKind.OBJECT_FIELD](fieldConfig, fieldName, typeName) {
23
+ const sqlDir = getDefDirectives(schema, fieldConfig).find(d => d.name === 'sql');
24
+ if (!sqlDir) return fieldConfig;
25
+
26
+ const table = String(sqlDir.args.table || '');
27
+ const kind = (sqlDir.args.kind || 'ROWS') as SqlKind;
28
+ const resource = (registry.pgResources as any)[table];
29
+ if (!resource) return fieldConfig;
30
+
31
+ if (kind === 'INSERT' || kind === 'UPDATE' || kind === 'DELETE') {
32
+ return fieldConfig;
33
+ }
34
+
35
+ const where = parseSqlMapping(sqlDir.args.where as string | undefined);
36
+ const extensions = (fieldConfig.extensions ??= {}) as Record<string, any>;
37
+ const grafast = (extensions.grafast ??= {});
38
+
39
+ const isRoot = typeName === 'Query' || typeName === 'Mutation';
40
+ const relMeta = meta.relationNames.get(typeName)?.get(fieldName);
41
+
42
+ if (!isRoot && relMeta && (kind === 'ROW' || kind === 'ROWS')) {
43
+ grafast.plan = makeRelationPlan(kind, fieldName);
44
+ } else {
45
+ grafast.plan = makeRootPlan(resource, kind, where);
46
+ }
47
+
48
+ delete (fieldConfig as GraphQLFieldConfig<any, any>).resolve;
49
+ return fieldConfig;
50
+ },
51
+ });
52
+ }
53
+
54
+ function makeRelationPlan(kind: 'ROW' | 'ROWS', relationName: string) {
55
+ return function sqlRelationPlan($parent: any) {
56
+ if (kind === 'ROW' && typeof $parent?.singleRelation === 'function') {
57
+ return $parent.singleRelation(relationName);
58
+ }
59
+ if (kind === 'ROWS' && typeof $parent?.manyRelation === 'function') {
60
+ const $rows = $parent.manyRelation(relationName);
61
+ return $rows;
62
+ }
63
+ return null;
64
+ };
65
+ }
66
+
67
+ function makeRootPlan(resource: any, kind: SqlKind, where: ReturnType<typeof parseSqlMapping>) {
68
+ return function sqlRootPlan(_$parent: any, fieldArgs: any) {
69
+ if (kind === 'ROW') {
70
+ const eqCol = batchableEqualityColumn(where);
71
+ const binder = eqCol ? where.entries.find(e => e.key === eqCol) : undefined;
72
+ if (binder?.value?.kind === 'args') {
73
+ const argName = binder.value.path?.[0] || binder.value.value;
74
+ const $arg = fieldArgs.get(argName);
75
+ const attr = pkAttribute(resource);
76
+ return resource.get({ [attr]: $arg });
77
+ }
78
+ const $rows = resource.find();
79
+ return typeof $rows.single === 'function' ? $rows.single() : $rows;
80
+ }
81
+
82
+ if (kind === 'CONNECTION') {
83
+ const $rows = resource.find();
84
+ if (typeof $rows.setFirst === 'function') {
85
+ const $first = fieldArgs.getRaw('first');
86
+ $rows.setFirst($first);
87
+ }
88
+ const $connection = connection($rows);
89
+ if (typeof $connection.setFirst === 'function') {
90
+ $connection.setFirst(fieldArgs.getRaw('first'));
91
+ }
92
+ return $connection;
93
+ }
94
+
95
+ if (kind === 'COUNT') {
96
+ const $rows = resource.find();
97
+ // Dataplan aggregate COUNT can be layered later; approximate via find for now.
98
+ return $rows;
99
+ }
100
+
101
+ // ROWS
102
+ const $rows = resource.find();
103
+ if (typeof $rows.setFirst === 'function') {
104
+ $rows.setFirst(fieldArgs.getRaw('limit'));
105
+ }
106
+ if (typeof $rows.setOffset === 'function') {
107
+ $rows.setOffset(fieldArgs.getRaw('offset'));
108
+ }
109
+ return $rows;
110
+ };
111
+ }
112
+
113
+ function pkAttribute(resource: any): string {
114
+ const attrs = resource?.codec?.attributes;
115
+ if (attrs && typeof attrs === 'object' && 'id' in attrs) return 'id';
116
+ const keys = attrs ? Object.keys(attrs) : [];
117
+ return String(keys[0] ?? 'id');
118
+ }