@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.
- package/CHANGELOG.md +9 -0
- package/dist/cjs/adapter.js +60 -0
- package/dist/cjs/batch.js +113 -0
- package/dist/cjs/client.js +205 -0
- package/dist/cjs/client.js.map +7 -0
- package/dist/cjs/dialect.js +60 -0
- package/dist/cjs/dialect.js.map +7 -0
- package/dist/cjs/entity.js +186 -0
- package/dist/cjs/execution.js +307 -0
- package/dist/cjs/execution.js.map +7 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/mapping.js +260 -0
- package/dist/cjs/mapping.js.map +7 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pg-executor.js +53 -0
- package/dist/cjs/pg-plans.js +103 -0
- package/dist/cjs/pg-registry.js +239 -0
- package/dist/cjs/plan.js +359 -0
- package/dist/cjs/sql-builder.js +653 -0
- package/dist/cjs/sql-builder.js.map +7 -0
- package/dist/cjs/types.js +0 -0
- package/dist/cjs/types.js.map +7 -0
- package/dist/cjs/uri.js +267 -0
- package/dist/esm/adapter.js +54 -0
- package/dist/esm/batch.js +107 -0
- package/dist/esm/client.js +197 -0
- package/dist/esm/client.js.map +7 -0
- package/dist/esm/dialect.js +54 -0
- package/dist/esm/dialect.js.map +7 -0
- package/dist/esm/entity.js +180 -0
- package/dist/esm/execution.js +303 -0
- package/dist/esm/execution.js.map +7 -0
- package/dist/esm/index.js +20 -0
- package/dist/esm/index.js.map +7 -0
- package/dist/esm/mapping.js +255 -0
- package/dist/esm/mapping.js.map +7 -0
- package/dist/esm/pg-executor.js +49 -0
- package/dist/esm/pg-plans.js +100 -0
- package/dist/esm/pg-registry.js +236 -0
- package/dist/esm/plan.js +351 -0
- package/dist/esm/sql-builder.js +636 -0
- package/dist/esm/sql-builder.js.map +7 -0
- package/dist/esm/types.js +0 -0
- package/dist/esm/types.js.map +7 -0
- package/dist/esm/uri.js +261 -0
- package/dist/package.json +57 -0
- package/dist/typings/adapter.d.cts +9 -0
- package/dist/typings/adapter.d.ts +9 -0
- package/dist/typings/batch.d.cts +21 -0
- package/dist/typings/batch.d.ts +21 -0
- package/dist/typings/client.d.cts +36 -0
- package/dist/typings/client.d.ts +36 -0
- package/dist/typings/dialect.d.cts +9 -0
- package/dist/typings/dialect.d.ts +9 -0
- package/dist/typings/entity.d.cts +24 -0
- package/dist/typings/entity.d.ts +24 -0
- package/dist/typings/execution.d.cts +9 -0
- package/dist/typings/execution.d.ts +9 -0
- package/dist/typings/index.d.cts +15 -0
- package/dist/typings/index.d.ts +15 -0
- package/dist/typings/mapping.d.cts +13 -0
- package/dist/typings/mapping.d.ts +13 -0
- package/dist/typings/pg-executor.d.cts +19 -0
- package/dist/typings/pg-executor.d.ts +19 -0
- package/dist/typings/pg-plans.d.cts +12 -0
- package/dist/typings/pg-plans.d.ts +12 -0
- package/dist/typings/pg-registry.d.cts +16 -0
- package/dist/typings/pg-registry.d.ts +16 -0
- package/dist/typings/plan.d.cts +47 -0
- package/dist/typings/plan.d.ts +47 -0
- package/dist/typings/sql-builder.d.cts +75 -0
- package/dist/typings/sql-builder.d.ts +75 -0
- package/dist/typings/types.d.cts +50 -0
- package/dist/typings/types.d.ts +50 -0
- package/dist/typings/uri.d.cts +42 -0
- package/dist/typings/uri.d.ts +42 -0
- package/package.json +67 -4
- package/src/adapter.ts +56 -0
- package/src/batch.ts +150 -0
- package/src/client.ts +233 -0
- package/src/entity.ts +235 -0
- package/src/execution.ts +411 -0
- package/src/index.ts +25 -0
- package/src/mapping.ts +291 -0
- package/src/pg-executor.ts +68 -0
- package/src/pg-plans.ts +118 -0
- package/src/pg-registry.ts +290 -0
- package/src/plan.ts +466 -0
- package/src/sql-builder.ts +809 -0
- package/src/types.ts +63 -0
- package/src/uri.ts +301 -0
- package/test/client-bun.test.ts +8 -0
- package/test/client.bun.test.ts +46 -0
- package/test/execution.test.ts +277 -0
- package/test/mapping.test.ts +79 -0
- package/test/pg-registry.test.ts +103 -0
- package/test/sql-builder.test.ts +131 -0
- package/test/uri.test.ts +123 -0
- package/README.md +0 -3
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getSqlExecutor = getSqlExecutor;
|
|
4
|
+
const tslib_1 = require("tslib");
|
|
5
|
+
const transport_common_1 = require("@graphql-mesh/transport-common");
|
|
6
|
+
const utils_1 = require("@graphql-mesh/utils");
|
|
7
|
+
const utils_2 = require("@graphql-tools/utils");
|
|
8
|
+
const disposablestack_1 = require("@whatwg-node/disposablestack");
|
|
9
|
+
const adapter_js_1 = require("./adapter.js");
|
|
10
|
+
const batch_js_1 = require("./batch.js");
|
|
11
|
+
const client_js_1 = require("./client.js");
|
|
12
|
+
const entity_js_1 = require("./entity.js");
|
|
13
|
+
const mapping_js_1 = require("./mapping.js");
|
|
14
|
+
const plan_js_1 = require("./plan.js");
|
|
15
|
+
const sql_builder_js_1 = require("./sql-builder.js");
|
|
16
|
+
const uri_js_1 = require("./uri.js");
|
|
17
|
+
const MUTATION_KINDS = new Set(['INSERT', 'UPDATE', 'DELETE']);
|
|
18
|
+
function connectionNodeSelection(selection) {
|
|
19
|
+
const nodes = (0, sql_builder_js_1.nestedSelection)(selection, 'nodes');
|
|
20
|
+
if (nodes.entries.length)
|
|
21
|
+
return nodes;
|
|
22
|
+
const edgeNode = (0, sql_builder_js_1.nestedSelection)((0, sql_builder_js_1.nestedSelection)(selection, 'edges'), 'node');
|
|
23
|
+
if (edgeNode.entries.length)
|
|
24
|
+
return edgeNode;
|
|
25
|
+
return selection;
|
|
26
|
+
}
|
|
27
|
+
function mapSelectRow(row, selection, joins, hasMany = []) {
|
|
28
|
+
return joins.length || hasMany.length
|
|
29
|
+
? (0, sql_builder_js_1.mapRowToGraphqlWithJoins)(row, selection, joins, hasMany)
|
|
30
|
+
: (0, sql_builder_js_1.mapRowToGraphql)(row, selection);
|
|
31
|
+
}
|
|
32
|
+
function rowWhereFullyUnresolved(whereMapping, graphqlArgs, parent) {
|
|
33
|
+
let required = 0;
|
|
34
|
+
let resolved = 0;
|
|
35
|
+
for (const entry of whereMapping.entries) {
|
|
36
|
+
if (entry.children)
|
|
37
|
+
continue;
|
|
38
|
+
if (entry.key === 'filter' ||
|
|
39
|
+
entry.key === 'orderBy' ||
|
|
40
|
+
entry.key === 'limit' ||
|
|
41
|
+
entry.key === 'offset' ||
|
|
42
|
+
entry.key === 'first' ||
|
|
43
|
+
entry.key === 'after' ||
|
|
44
|
+
entry.key === 'last' ||
|
|
45
|
+
entry.key === 'before') {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
required++;
|
|
49
|
+
const val = (0, mapping_js_1.resolveMappingValue)(entry.value, { args: graphqlArgs, parent });
|
|
50
|
+
if (val !== undefined)
|
|
51
|
+
resolved++;
|
|
52
|
+
}
|
|
53
|
+
return required > 0 && resolved === 0;
|
|
54
|
+
}
|
|
55
|
+
async function runSqlSelect(sqlClient, opts) {
|
|
56
|
+
const { table, kind, selection, whereMapping, planners, graphqlArgs, parent, context } = opts;
|
|
57
|
+
const fullSelection = kind === 'CONNECTION' ? connectionNodeSelection(selection) : selection;
|
|
58
|
+
// Never run a ROW with unresolved equality binders (would pick an arbitrary row).
|
|
59
|
+
if (kind === 'ROW' && rowWhereFullyUnresolved(whereMapping, graphqlArgs, parent)) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
const planned = opts.schema && opts.info && kind !== 'COUNT'
|
|
63
|
+
? (0, plan_js_1.planSelection)(opts.schema, opts.info, fullSelection)
|
|
64
|
+
: { selection: fullSelection, joins: [], hasMany: [] };
|
|
65
|
+
const selectSelection = planned.selection.entries.length ? planned.selection : fullSelection;
|
|
66
|
+
const { joins, hasMany } = planned;
|
|
67
|
+
// Batch ROW / simple ROWS when there is exactly one equality binder (FK / PK)
|
|
68
|
+
// and we are not folding joins / has-many into this query.
|
|
69
|
+
if (!joins.length && !hasMany.length && (kind === 'ROW' || kind === 'ROWS')) {
|
|
70
|
+
const column = (0, batch_js_1.batchableEqualityColumn)(whereMapping);
|
|
71
|
+
if (column) {
|
|
72
|
+
const key = (0, batch_js_1.resolveEqualityKey)(whereMapping, column, graphqlArgs, parent);
|
|
73
|
+
if (key !== undefined) {
|
|
74
|
+
return (0, batch_js_1.loadBatchedByColumn)(context, {
|
|
75
|
+
client: sqlClient,
|
|
76
|
+
table,
|
|
77
|
+
kind,
|
|
78
|
+
selection: selectSelection,
|
|
79
|
+
whereMapping,
|
|
80
|
+
planners,
|
|
81
|
+
column,
|
|
82
|
+
graphqlArgs,
|
|
83
|
+
}, key);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const query = (0, sql_builder_js_1.buildSelect)(sqlClient.adapter, {
|
|
88
|
+
table,
|
|
89
|
+
kind,
|
|
90
|
+
selection: selectSelection,
|
|
91
|
+
whereMapping,
|
|
92
|
+
planners,
|
|
93
|
+
graphqlArgs,
|
|
94
|
+
parent,
|
|
95
|
+
joins,
|
|
96
|
+
hasMany,
|
|
97
|
+
});
|
|
98
|
+
const result = await sqlClient.query(query.sql, query.params);
|
|
99
|
+
if (kind === 'COUNT') {
|
|
100
|
+
const row = result.rows[0];
|
|
101
|
+
const count = row?.count ?? row?.COUNT ?? Object.values(row || {})[0] ?? 0;
|
|
102
|
+
return Number(count);
|
|
103
|
+
}
|
|
104
|
+
if (kind === 'ROW') {
|
|
105
|
+
const row = result.rows[0];
|
|
106
|
+
return row ? mapSelectRow(row, selectSelection, joins, hasMany) : null;
|
|
107
|
+
}
|
|
108
|
+
if (kind === 'CONNECTION') {
|
|
109
|
+
const first = Number(graphqlArgs.first ?? 10);
|
|
110
|
+
const after = typeof graphqlArgs.after === 'string' ? graphqlArgs.after : '';
|
|
111
|
+
const offset = after ? (0, sql_builder_js_1.decodeCursor)(after) : 0;
|
|
112
|
+
const rows = result.rows;
|
|
113
|
+
const hasNextPage = rows.length > first;
|
|
114
|
+
const pageRows = hasNextPage ? rows.slice(0, first) : rows;
|
|
115
|
+
const nodes = pageRows.map(r => mapSelectRow(r, selectSelection, joins, hasMany));
|
|
116
|
+
const edges = nodes.map((node, i) => ({
|
|
117
|
+
cursor: (0, sql_builder_js_1.encodeCursor)(offset + i),
|
|
118
|
+
node,
|
|
119
|
+
}));
|
|
120
|
+
const endCursor = edges.length ? edges[edges.length - 1].cursor : null;
|
|
121
|
+
const startCursor = edges.length ? edges[0].cursor : null;
|
|
122
|
+
let totalCount = offset + pageRows.length + (hasNextPage ? 1 : 0);
|
|
123
|
+
if (selection.entries.some(e => e.key === 'totalCount')) {
|
|
124
|
+
const countQ = (0, sql_builder_js_1.buildSelect)(sqlClient.adapter, {
|
|
125
|
+
table,
|
|
126
|
+
kind: 'COUNT',
|
|
127
|
+
selection: selectSelection,
|
|
128
|
+
whereMapping,
|
|
129
|
+
planners,
|
|
130
|
+
graphqlArgs,
|
|
131
|
+
parent,
|
|
132
|
+
});
|
|
133
|
+
const countRes = await sqlClient.query(countQ.sql, countQ.params);
|
|
134
|
+
const crow = countRes.rows[0];
|
|
135
|
+
totalCount = Number(crow?.count ?? crow?.COUNT ?? Object.values(crow || {})[0] ?? 0);
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
nodes,
|
|
139
|
+
edges,
|
|
140
|
+
pageInfo: {
|
|
141
|
+
hasNextPage,
|
|
142
|
+
hasPreviousPage: offset > 0,
|
|
143
|
+
startCursor,
|
|
144
|
+
endCursor,
|
|
145
|
+
},
|
|
146
|
+
totalCount,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
return result.rows.map(r => mapSelectRow(r, selectSelection, joins, hasMany));
|
|
150
|
+
}
|
|
151
|
+
async function getSqlExecutor({ subgraph, cwd, client, }) {
|
|
152
|
+
const transportDirectives = (0, utils_2.getDirective)(subgraph, subgraph, 'transport');
|
|
153
|
+
if (!transportDirectives?.length) {
|
|
154
|
+
throw new Error('No @transport directive found on SQL subgraph schema');
|
|
155
|
+
}
|
|
156
|
+
const transport = transportDirectives[0];
|
|
157
|
+
const location = transport.location ||
|
|
158
|
+
(0, uri_js_1.resolveConnectionStringFromEnv)(undefined, { adapter: transport.options?.adapter });
|
|
159
|
+
const adapter = transport.options?.adapter || (0, adapter_js_1.inferAdapterFromLocation)(location) || 'sqlite';
|
|
160
|
+
if (!location) {
|
|
161
|
+
throw new Error('@transport(kind: "sql") requires location (connection URI / file path) or a Bun-compatible env URL (DATABASE_URL, POSTGRES_URL, MYSQL_URL, SQLITE_URL, …)');
|
|
162
|
+
}
|
|
163
|
+
const sqlClient = client ||
|
|
164
|
+
(0, client_js_1.createSqlClient)({
|
|
165
|
+
adapter,
|
|
166
|
+
location,
|
|
167
|
+
cwd,
|
|
168
|
+
max: transport.options?.max,
|
|
169
|
+
idleTimeout: transport.options?.idleTimeout,
|
|
170
|
+
connectionTimeout: transport.options?.connectionTimeout,
|
|
171
|
+
tls: transport.options?.tls,
|
|
172
|
+
});
|
|
173
|
+
subgraph = (0, utils_2.mapSchema)(subgraph, {
|
|
174
|
+
[utils_2.MapperKind.OBJECT_FIELD](fieldConfig) {
|
|
175
|
+
const directives = (0, utils_1.getDefDirectives)(subgraph, fieldConfig);
|
|
176
|
+
for (const directive of directives) {
|
|
177
|
+
switch (directive.name) {
|
|
178
|
+
case 'sql': {
|
|
179
|
+
const table = directive.args.table;
|
|
180
|
+
const kind = (directive.args.kind || 'ROWS');
|
|
181
|
+
const { whereMapping, setMapping, selection, planners } = (0, sql_builder_js_1.parseSqlDirectiveMappings)({
|
|
182
|
+
where: directive.args.where,
|
|
183
|
+
set: directive.args.set,
|
|
184
|
+
selection: directive.args.selection,
|
|
185
|
+
filter: directive.args.filter,
|
|
186
|
+
orderBy: directive.args.orderBy,
|
|
187
|
+
limit: directive.args.limit,
|
|
188
|
+
offset: directive.args.offset,
|
|
189
|
+
first: directive.args.first,
|
|
190
|
+
after: directive.args.after,
|
|
191
|
+
});
|
|
192
|
+
if (MUTATION_KINDS.has(kind)) {
|
|
193
|
+
const mutationKind = kind;
|
|
194
|
+
fieldConfig.resolve = async function sqlMutationResolver(_root, args) {
|
|
195
|
+
if (mutationKind === 'DELETE') {
|
|
196
|
+
const query = (0, sql_builder_js_1.buildDelete)(sqlClient.adapter, table, whereMapping, args);
|
|
197
|
+
const result = await sqlClient.query(query.sql, query.params);
|
|
198
|
+
const affected = result.rowCount;
|
|
199
|
+
return {
|
|
200
|
+
ok: affected > 0,
|
|
201
|
+
affectedRows: affected,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
const returningCols = (0, sql_builder_js_1.collectReturningColumns)(selection);
|
|
205
|
+
const query = mutationKind === 'INSERT'
|
|
206
|
+
? (0, sql_builder_js_1.buildInsert)(sqlClient.adapter, table, setMapping, args, returningCols)
|
|
207
|
+
: (0, sql_builder_js_1.buildUpdate)(sqlClient.adapter, table, setMapping, whereMapping, args, returningCols);
|
|
208
|
+
let row;
|
|
209
|
+
if (returningCols.length && (adapter === 'sqlite' || adapter === 'postgres')) {
|
|
210
|
+
const result = await sqlClient.query(query.sql, query.params);
|
|
211
|
+
row = result.rows[0];
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
await sqlClient.query(query.sql, query.params);
|
|
215
|
+
}
|
|
216
|
+
const payloadKey = selection.entries.find(e => e.children)?.key;
|
|
217
|
+
if (payloadKey) {
|
|
218
|
+
const nested = (0, sql_builder_js_1.nestedSelection)(selection, payloadKey);
|
|
219
|
+
return {
|
|
220
|
+
[payloadKey]: row ? (0, sql_builder_js_1.mapRowToGraphql)(row, nested) : null,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
return row ? (0, sql_builder_js_1.mapRowToGraphql)(row, selection) : null;
|
|
224
|
+
};
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
const queryKind = kind;
|
|
228
|
+
fieldConfig.resolve = async function sqlQueryResolver(root, args, context, info) {
|
|
229
|
+
// Parent already folded this belongs-to via JOIN lookahead.
|
|
230
|
+
if ((0, plan_js_1.hasJoinedField)(root, info.fieldName)) {
|
|
231
|
+
return root[info.fieldName];
|
|
232
|
+
}
|
|
233
|
+
return runSqlSelect(sqlClient, {
|
|
234
|
+
schema: subgraph,
|
|
235
|
+
info,
|
|
236
|
+
table,
|
|
237
|
+
kind: queryKind,
|
|
238
|
+
selection,
|
|
239
|
+
whereMapping,
|
|
240
|
+
planners,
|
|
241
|
+
graphqlArgs: args,
|
|
242
|
+
parent: root,
|
|
243
|
+
context,
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return fieldConfig;
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
// Type-level `@sql` → resolveReference + Query._entities (Connectors-style).
|
|
254
|
+
subgraph = (0, entity_js_1.wireSqlEntityResolvers)(subgraph, {
|
|
255
|
+
executeTypeLevelRow(sqlArgs, reference, context) {
|
|
256
|
+
const table = sqlArgs.table;
|
|
257
|
+
const { whereMapping, selection, planners } = (0, sql_builder_js_1.parseSqlDirectiveMappings)({
|
|
258
|
+
where: sqlArgs.where,
|
|
259
|
+
selection: sqlArgs.selection,
|
|
260
|
+
filter: sqlArgs.filter,
|
|
261
|
+
orderBy: sqlArgs.orderBy,
|
|
262
|
+
limit: sqlArgs.limit,
|
|
263
|
+
offset: sqlArgs.offset,
|
|
264
|
+
first: sqlArgs.first,
|
|
265
|
+
after: sqlArgs.after,
|
|
266
|
+
});
|
|
267
|
+
return runSqlSelect(sqlClient, {
|
|
268
|
+
table,
|
|
269
|
+
kind: 'ROW',
|
|
270
|
+
selection,
|
|
271
|
+
whereMapping,
|
|
272
|
+
planners,
|
|
273
|
+
graphqlArgs: {},
|
|
274
|
+
parent: reference,
|
|
275
|
+
context,
|
|
276
|
+
});
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
// Postgres + Node pg.Pool → Grafast / `@dataplan/pg` fast path.
|
|
280
|
+
// MySQL / SQLite / Bun.SQL keep the GraphQL.js + JOIN planner path.
|
|
281
|
+
// Dynamic import keeps grafast off the static graph (Jest --detectLeaks).
|
|
282
|
+
if (adapter === 'postgres' && sqlClient.pgPool) {
|
|
283
|
+
const { createPostgresGrafastExecutor } = await Promise.resolve().then(() => tslib_1.__importStar(require('./pg-executor.js')));
|
|
284
|
+
const grafastExecutor = createPostgresGrafastExecutor({
|
|
285
|
+
subgraph,
|
|
286
|
+
sqlClient,
|
|
287
|
+
disposeClient: () => sqlClient.dispose(),
|
|
288
|
+
});
|
|
289
|
+
if (grafastExecutor) {
|
|
290
|
+
return grafastExecutor;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const defaultExecutor = (0, transport_common_1.createDefaultExecutor)(subgraph);
|
|
294
|
+
const executor = async function sqlExecutor(executionRequest) {
|
|
295
|
+
// Ensure a shared mutable context so DataLoaders coalesce within one operation.
|
|
296
|
+
const context = executionRequest.context && typeof executionRequest.context === 'object'
|
|
297
|
+
? executionRequest.context
|
|
298
|
+
: {};
|
|
299
|
+
return defaultExecutor({
|
|
300
|
+
...executionRequest,
|
|
301
|
+
context,
|
|
302
|
+
});
|
|
303
|
+
};
|
|
304
|
+
executor[disposablestack_1.DisposableSymbols.dispose] = () => sqlClient.dispose();
|
|
305
|
+
executor[disposablestack_1.DisposableSymbols.asyncDispose] = async () => sqlClient.dispose();
|
|
306
|
+
return executor;
|
|
307
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/execution.ts"],
|
|
4
|
+
"sourcesContent": ["import type { GraphQLSchema } from 'graphql';\nimport { createDefaultExecutor, type DisposableExecutor } from '@graphql-mesh/transport-common';\nimport { getDefDirectives } from '@graphql-mesh/utils';\nimport { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils';\nimport { DisposableSymbols } from '@whatwg-node/disposablestack';\nimport { createSqlClient } from './client.js';\nimport { inferDialectFromLocation } from './dialect.js';\nimport {\n buildDelete,\n buildInsert,\n buildSelect,\n buildUpdate,\n collectReturningColumns,\n decodeCursor,\n encodeCursor,\n mapRowToGraphql,\n nestedSelection,\n parseArgsAndSelection,\n} from './sql-builder.js';\nimport type {\n ParsedSqlMapping,\n SqlClient,\n SqlDialect,\n SqlMutationKind,\n SqlQueryKind,\n} from './types.js';\n\nexport interface GetSqlExecutorOpts {\n subgraph: GraphQLSchema;\n cwd?: string;\n client?: SqlClient;\n}\n\nfunction connectionNodeSelection(selection: ParsedSqlMapping): ParsedSqlMapping {\n const nodes = nestedSelection(selection, 'nodes');\n if (nodes.entries.length) return nodes;\n const edgeNode = nestedSelection(nestedSelection(selection, 'edges'), 'node');\n if (edgeNode.entries.length) return edgeNode;\n return selection;\n}\n\nexport function getSqlExecutor({ subgraph, cwd, client }: GetSqlExecutorOpts): DisposableExecutor {\n const transportDirectives = getDirective(subgraph, subgraph, 'transport');\n if (!transportDirectives?.length) {\n throw new Error('No @transport directive found on SQL subgraph schema');\n }\n const transport = transportDirectives[0] as {\n location?: string;\n options?: { dialect?: SqlDialect };\n };\n const dialect: SqlDialect =\n transport.options?.dialect || inferDialectFromLocation(transport.location) || 'sqlite';\n if (!transport.location) {\n throw new Error('@transport(kind: \"sql\") requires location (connection URI or file path)');\n }\n\n const sqlClient = client || createSqlClient({ dialect, location: transport.location, cwd });\n\n subgraph = mapSchema(subgraph, {\n [MapperKind.OBJECT_FIELD](fieldConfig) {\n const directives = getDefDirectives(subgraph, fieldConfig);\n for (const directive of directives) {\n switch (directive.name) {\n case 'sql__query': {\n const table = directive.args.table as string;\n const kind = (directive.args.kind || 'ROWS') as SqlQueryKind;\n const { argsMapping, selection } = parseArgsAndSelection(\n directive.args.args,\n directive.args.selection,\n );\n fieldConfig.resolve = async function sqlQueryResolver(root, args) {\n const selectSelection =\n kind === 'CONNECTION' ? connectionNodeSelection(selection) : selection;\n const query = buildSelect(sqlClient.dialect, {\n table,\n kind,\n selection: selectSelection,\n argsMapping,\n graphqlArgs: args,\n parent: root,\n });\n const result = await sqlClient.query(query.sql, query.params);\n\n if (kind === 'COUNT') {\n const row = result.rows[0] as Record<string, unknown> | undefined;\n const count = row?.count ?? row?.COUNT ?? Object.values(row || {})[0] ?? 0;\n return Number(count);\n }\n if (kind === 'ROW') {\n const row = result.rows[0] as Record<string, unknown> | undefined;\n return row ? mapRowToGraphql(row, selectSelection) : null;\n }\n if (kind === 'CONNECTION') {\n const first = Number(args.first ?? 10);\n const after = typeof args.after === 'string' ? args.after : '';\n const offset = after ? decodeCursor(after) : 0;\n const rows = result.rows as Record<string, unknown>[];\n const hasNextPage = rows.length > first;\n const pageRows = hasNextPage ? rows.slice(0, first) : rows;\n const nodes = pageRows.map(r => mapRowToGraphql(r, selectSelection));\n const edges = nodes.map((node, i) => ({\n cursor: encodeCursor(offset + i),\n node,\n }));\n const endCursor = edges.length ? edges[edges.length - 1].cursor : null;\n const startCursor = edges.length ? edges[0].cursor : null;\n\n let totalCount = offset + pageRows.length + (hasNextPage ? 1 : 0);\n if (selection.entries.some(e => e.key === 'totalCount')) {\n const countQ = buildSelect(sqlClient.dialect, {\n table,\n kind: 'COUNT',\n selection: selectSelection,\n argsMapping,\n graphqlArgs: args,\n parent: root,\n });\n const countRes = await sqlClient.query(countQ.sql, countQ.params);\n const crow = countRes.rows[0] as Record<string, unknown> | undefined;\n totalCount = Number(\n crow?.count ?? crow?.COUNT ?? Object.values(crow || {})[0] ?? 0,\n );\n }\n\n return {\n nodes,\n edges,\n pageInfo: {\n hasNextPage,\n hasPreviousPage: offset > 0,\n startCursor,\n endCursor,\n },\n totalCount,\n };\n }\n return (result.rows as Record<string, unknown>[]).map(r =>\n mapRowToGraphql(r, selectSelection),\n );\n };\n break;\n }\n case 'sql__relation': {\n const table = directive.args.table as string;\n const kind = (directive.args.kind || 'ROW') as SqlQueryKind;\n const { argsMapping, selection } = parseArgsAndSelection(\n directive.args.args,\n directive.args.selection,\n );\n fieldConfig.resolve = async function sqlRelationResolver(root, args) {\n const query = buildSelect(sqlClient.dialect, {\n table,\n kind: kind === 'ROWS' ? 'ROWS' : 'ROW',\n selection,\n argsMapping,\n graphqlArgs: args,\n parent: root,\n });\n const result = await sqlClient.query(query.sql, query.params);\n if (kind === 'ROWS') {\n return (result.rows as Record<string, unknown>[]).map(r =>\n mapRowToGraphql(r, selection),\n );\n }\n const row = result.rows[0] as Record<string, unknown> | undefined;\n return row ? mapRowToGraphql(row, selection) : null;\n };\n break;\n }\n case 'sql__mutation': {\n const table = directive.args.table as string;\n const kind = directive.args.kind as SqlMutationKind;\n const { argsMapping, selection } = parseArgsAndSelection(\n directive.args.args,\n directive.args.selection,\n );\n fieldConfig.resolve = async function sqlMutationResolver(_root, args) {\n if (kind === 'DELETE') {\n const query = buildDelete(sqlClient.dialect, table, argsMapping, args);\n const result = await sqlClient.query(query.sql, query.params);\n const affected = result.rowCount;\n return {\n ok: affected > 0,\n affectedRows: affected,\n };\n }\n\n const returningCols = collectReturningColumns(selection);\n const query =\n kind === 'INSERT'\n ? buildInsert(sqlClient.dialect, table, argsMapping, args, returningCols)\n : buildUpdate(sqlClient.dialect, table, argsMapping, args, returningCols);\n\n let row: Record<string, unknown> | undefined;\n if (returningCols.length && (dialect === 'sqlite' || dialect === 'postgres')) {\n const result = await sqlClient.query(query.sql, query.params);\n row = result.rows[0] as Record<string, unknown> | undefined;\n } else {\n await sqlClient.query(query.sql, query.params);\n }\n\n const payloadKey = selection.entries.find(e => e.children)?.key;\n if (payloadKey) {\n const nested = nestedSelection(selection, payloadKey);\n return {\n [payloadKey]: row ? mapRowToGraphql(row, nested) : null,\n };\n }\n return row ? mapRowToGraphql(row, selection) : null;\n };\n break;\n }\n }\n }\n return fieldConfig;\n },\n });\n\n const defaultExecutor = createDefaultExecutor(subgraph);\n const executor: DisposableExecutor = async function sqlExecutor(executionRequest) {\n return defaultExecutor(executionRequest);\n };\n executor[DisposableSymbols.dispose] = () => sqlClient.dispose();\n executor[DisposableSymbols.asyncDispose] = async () => sqlClient.dispose();\n return executor;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,8BAA+D;AAC/D,mBAAiC;AACjC,IAAAA,gBAAoD;AACpD,6BAAkC;AAClC,oBAAgC;AAChC,qBAAyC;AACzC,yBAWO;AAeP,SAAS,wBAAwB,WAA+C;AAC9E,QAAM,YAAQ,oCAAgB,WAAW,OAAO;AAChD,MAAI,MAAM,QAAQ,OAAQ,QAAO;AACjC,QAAM,eAAW,wCAAgB,oCAAgB,WAAW,OAAO,GAAG,MAAM;AAC5E,MAAI,SAAS,QAAQ,OAAQ,QAAO;AACpC,SAAO;AACT;AAEO,SAAS,eAAe,EAAE,UAAU,KAAK,OAAO,GAA2C;AAChG,QAAM,0BAAsB,4BAAa,UAAU,UAAU,WAAW;AACxE,MAAI,CAAC,qBAAqB,QAAQ;AAChC,UAAM,IAAI,MAAM,sDAAsD;AAAA,EACxE;AACA,QAAM,YAAY,oBAAoB,CAAC;AAIvC,QAAM,UACJ,UAAU,SAAS,eAAW,yCAAyB,UAAU,QAAQ,KAAK;AAChF,MAAI,CAAC,UAAU,UAAU;AACvB,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC3F;AAEA,QAAM,YAAY,cAAU,+BAAgB,EAAE,SAAS,UAAU,UAAU,UAAU,IAAI,CAAC;AAE1F,iBAAW,yBAAU,UAAU;AAAA,IAC7B,CAAC,yBAAW,YAAY,EAAE,aAAa;AACrC,YAAM,iBAAa,+BAAiB,UAAU,WAAW;AACzD,iBAAW,aAAa,YAAY;AAClC,gBAAQ,UAAU,MAAM;AAAA,UACtB,KAAK,cAAc;AACjB,kBAAM,QAAQ,UAAU,KAAK;AAC7B,kBAAM,OAAQ,UAAU,KAAK,QAAQ;AACrC,kBAAM,EAAE,aAAa,UAAU,QAAI;AAAA,cACjC,U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ACd,sBAAM,aAAS,oCAAgB,WAAW,UAAU;AACpD,uBAAO;AAAA,kBACL,CAAC,UAAU,GAAG,UAAM,oCAAgB,KAAK,MAAM,IAAI;AAAA,gBACrD;AAAA,cACF;AACA,qBAAO,UAAM,oCAAgB,KAAK,SAAS,IAAI;AAAA,YACjD;AACA;AAAA,UACF;AAAA,QACF;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AAED,QAAM,sBAAkB,+CAAsB,QAAQ;AACtD,QAAM,WAA+B,eAAe,YAAY,kBAAkB;AAChF,WAAO,gBAAgB,gBAAgB;AAAA,EACzC;AACA,WAAS,yCAAkB,OAAO,IAAI,MAAM,UAAU,QAAQ;AAC9D,WAAS,yCAAkB,YAAY,IAAI,YAAY,UAAU,QAAQ;AACzE,SAAO;AACT;",
|
|
6
|
+
"names": ["import_utils", "query"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const tslib_1 = require("tslib");
|
|
4
|
+
const execution_js_1 = require("./execution.js");
|
|
5
|
+
tslib_1.__exportStar(require("./adapter.js"), exports);
|
|
6
|
+
tslib_1.__exportStar(require("./batch.js"), exports);
|
|
7
|
+
tslib_1.__exportStar(require("./client.js"), exports);
|
|
8
|
+
tslib_1.__exportStar(require("./entity.js"), exports);
|
|
9
|
+
tslib_1.__exportStar(require("./execution.js"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./mapping.js"), exports);
|
|
11
|
+
tslib_1.__exportStar(require("./plan.js"), exports);
|
|
12
|
+
tslib_1.__exportStar(require("./sql-builder.js"), exports);
|
|
13
|
+
tslib_1.__exportStar(require("./uri.js"), exports);
|
|
14
|
+
// pg-executor / pg-registry / pg-plans stay internal: they pull grafast +
|
|
15
|
+
// @dataplan/pg, which register process-lifetime state that fails Jest --detectLeaks.
|
|
16
|
+
exports.default = {
|
|
17
|
+
getSubgraphExecutor({ subgraph, cwd }) {
|
|
18
|
+
return (0, execution_js_1.getSqlExecutor)({
|
|
19
|
+
subgraph,
|
|
20
|
+
cwd,
|
|
21
|
+
});
|
|
22
|
+
},
|
|
23
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Transport } from '@graphql-mesh/transport-common';\nimport { getSqlExecutor } from './execution.js';\nimport type { SqlTransportOptions } from './types.js';\n\nexport * from './client.js';\nexport * from './dialect.js';\nexport * from './execution.js';\nexport * from './mapping.js';\nexport * from './sql-builder.js';\nexport type * from './types.js';\n\nexport default {\n getSubgraphExecutor({ subgraph, cwd }) {\n return getSqlExecutor({\n subgraph,\n cwd,\n });\n },\n} satisfies Transport<SqlTransportOptions>;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,uBAA+B;AAG/B,0BAAc,wBAJd;AAKA,0BAAc,yBALd;AAMA,0BAAc,2BANd;AAOA,0BAAc,yBAPd;AAQA,0BAAc,6BARd;AAWA,IAAO,gBAAQ;AAAA,EACb,oBAAoB,EAAE,UAAU,IAAI,GAAG;AACrC,eAAO,iCAAe;AAAA,MACpB;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseSqlMapping = parseSqlMapping;
|
|
4
|
+
exports.columnMapFromSelection = columnMapFromSelection;
|
|
5
|
+
exports.resolveMappingValue = resolveMappingValue;
|
|
6
|
+
/**
|
|
7
|
+
* Parse `@sql` `where` / `set` / `selection` block strings.
|
|
8
|
+
* Skips `# ...` comments to EOL. Supports nested `{ ... }` blocks and `$args` / `$this` / `$pseudo`.
|
|
9
|
+
*/
|
|
10
|
+
function parseSqlMapping(source) {
|
|
11
|
+
if (source == null || !String(source).trim()) {
|
|
12
|
+
return { entries: [] };
|
|
13
|
+
}
|
|
14
|
+
const text = stripComments(String(source));
|
|
15
|
+
const { entries, next } = parseBlock(text, 0, false);
|
|
16
|
+
if (next < text.length && text.slice(next).trim()) {
|
|
17
|
+
throw new Error(`Unexpected trailing content in SQL mapping: ${text.slice(next, next + 40)}`);
|
|
18
|
+
}
|
|
19
|
+
return { entries };
|
|
20
|
+
}
|
|
21
|
+
function stripComments(source) {
|
|
22
|
+
return source
|
|
23
|
+
.split('\n')
|
|
24
|
+
.map(line => {
|
|
25
|
+
const idx = line.indexOf('#');
|
|
26
|
+
if (idx === -1)
|
|
27
|
+
return line;
|
|
28
|
+
// Keep `#` inside quotes
|
|
29
|
+
let inQuote = null;
|
|
30
|
+
for (let i = 0; i < line.length; i++) {
|
|
31
|
+
const c = line[i];
|
|
32
|
+
if (inQuote) {
|
|
33
|
+
if (c === '\\') {
|
|
34
|
+
i++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (c === inQuote)
|
|
38
|
+
inQuote = null;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
if (c === '"' || c === "'") {
|
|
42
|
+
inQuote = c;
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
if (c === '#') {
|
|
46
|
+
return line.slice(0, i);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return line;
|
|
50
|
+
})
|
|
51
|
+
.join('\n');
|
|
52
|
+
}
|
|
53
|
+
function parseBlock(text, start, expectClosing) {
|
|
54
|
+
const entries = [];
|
|
55
|
+
let i = skipWs(text, start);
|
|
56
|
+
while (i < text.length) {
|
|
57
|
+
if (text[i] === '}') {
|
|
58
|
+
if (!expectClosing) {
|
|
59
|
+
throw new Error(`Unexpected "}" in SQL mapping at ${i}`);
|
|
60
|
+
}
|
|
61
|
+
return { entries, next: i + 1 };
|
|
62
|
+
}
|
|
63
|
+
if (expectClosing === false && text[i] === '{') {
|
|
64
|
+
throw new Error(`Unexpected "{" in SQL mapping at ${i}`);
|
|
65
|
+
}
|
|
66
|
+
// Bare pseudo `$` (COUNT selection) or `$token`
|
|
67
|
+
if (text[i] === '$' && !isIdentStart(text[i + 1] ?? '')) {
|
|
68
|
+
// look ahead for ident after $
|
|
69
|
+
}
|
|
70
|
+
if (text[i] === '$') {
|
|
71
|
+
const pseudo = readPseudoOrPath(text, i);
|
|
72
|
+
entries.push({
|
|
73
|
+
key: pseudo.raw,
|
|
74
|
+
value: pseudo.value,
|
|
75
|
+
});
|
|
76
|
+
i = skipWs(text, pseudo.next);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const key = readIdent(text, i);
|
|
80
|
+
i = skipWs(text, key.next);
|
|
81
|
+
if (i < text.length && text[i] === '{') {
|
|
82
|
+
const nested = parseBlock(text, i + 1, true);
|
|
83
|
+
entries.push({ key: key.value, children: nested.entries });
|
|
84
|
+
i = skipWs(text, nested.next);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (i >= text.length || text[i] !== ':') {
|
|
88
|
+
// bare field pick (rare) — treat as identity column
|
|
89
|
+
entries.push({
|
|
90
|
+
key: key.value,
|
|
91
|
+
value: { kind: 'column', value: key.value },
|
|
92
|
+
});
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
i = skipWs(text, i + 1);
|
|
96
|
+
if (i < text.length && text[i] === '{') {
|
|
97
|
+
const nested = parseBlock(text, i + 1, true);
|
|
98
|
+
entries.push({ key: key.value, children: nested.entries });
|
|
99
|
+
i = skipWs(text, nested.next);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (i < text.length && text[i] === '$') {
|
|
103
|
+
const rhs = readPseudoOrPath(text, i);
|
|
104
|
+
entries.push({ key: key.value, value: rhs.value });
|
|
105
|
+
i = skipWs(text, rhs.next);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (i < text.length && (text[i] === '"' || text[i] === "'")) {
|
|
109
|
+
const lit = readQuoted(text, i);
|
|
110
|
+
entries.push({
|
|
111
|
+
key: key.value,
|
|
112
|
+
value: { kind: 'literal', value: lit.value },
|
|
113
|
+
});
|
|
114
|
+
i = skipWs(text, lit.next);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const col = readIdent(text, i);
|
|
118
|
+
entries.push({
|
|
119
|
+
key: key.value,
|
|
120
|
+
value: { kind: 'column', value: col.value },
|
|
121
|
+
});
|
|
122
|
+
i = skipWs(text, col.next);
|
|
123
|
+
}
|
|
124
|
+
if (expectClosing) {
|
|
125
|
+
throw new Error('Unclosed "{" in SQL mapping');
|
|
126
|
+
}
|
|
127
|
+
return { entries, next: i };
|
|
128
|
+
}
|
|
129
|
+
function readPseudoOrPath(text, start) {
|
|
130
|
+
if (text[start] !== '$') {
|
|
131
|
+
throw new Error(`Expected "$" at ${start}`);
|
|
132
|
+
}
|
|
133
|
+
// `$` alone
|
|
134
|
+
if (start + 1 >= text.length || !isIdentStart(text[start + 1])) {
|
|
135
|
+
return {
|
|
136
|
+
raw: '$',
|
|
137
|
+
value: { kind: 'pseudo', value: '$' },
|
|
138
|
+
next: start + 1,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
let i = start + 1;
|
|
142
|
+
const head = readIdent(text, i);
|
|
143
|
+
i = head.next;
|
|
144
|
+
if (head.value === 'args' || head.value === 'this') {
|
|
145
|
+
const path = [];
|
|
146
|
+
while (i < text.length && text[i] === '.') {
|
|
147
|
+
i++;
|
|
148
|
+
const seg = readIdent(text, i);
|
|
149
|
+
path.push(seg.value);
|
|
150
|
+
i = seg.next;
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
raw: `$${head.value}${path.length ? '.' + path.join('.') : ''}`,
|
|
154
|
+
value: {
|
|
155
|
+
kind: head.value === 'args' ? 'args' : 'this',
|
|
156
|
+
value: path[0] ?? '',
|
|
157
|
+
path,
|
|
158
|
+
},
|
|
159
|
+
next: i,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
// $cursor, $totalCount, ...
|
|
163
|
+
return {
|
|
164
|
+
raw: `$${head.value}`,
|
|
165
|
+
value: { kind: 'pseudo', value: head.value },
|
|
166
|
+
next: i,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function readIdent(text, start) {
|
|
170
|
+
let i = skipWs(text, start);
|
|
171
|
+
if (i >= text.length || !isIdentStart(text[i])) {
|
|
172
|
+
throw new Error(`Expected identifier at ${i} near "${text.slice(i, i + 20)}"`);
|
|
173
|
+
}
|
|
174
|
+
const from = i;
|
|
175
|
+
i++;
|
|
176
|
+
while (i < text.length && isIdentCont(text[i]))
|
|
177
|
+
i++;
|
|
178
|
+
return { value: text.slice(from, i), next: i };
|
|
179
|
+
}
|
|
180
|
+
function readQuoted(text, start) {
|
|
181
|
+
const q = text[start];
|
|
182
|
+
let i = start + 1;
|
|
183
|
+
let out = '';
|
|
184
|
+
while (i < text.length) {
|
|
185
|
+
const c = text[i];
|
|
186
|
+
if (c === '\\' && i + 1 < text.length) {
|
|
187
|
+
out += text[i + 1];
|
|
188
|
+
i += 2;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (c === q) {
|
|
192
|
+
return { value: out, next: i + 1 };
|
|
193
|
+
}
|
|
194
|
+
out += c;
|
|
195
|
+
i++;
|
|
196
|
+
}
|
|
197
|
+
throw new Error('Unclosed string in SQL mapping');
|
|
198
|
+
}
|
|
199
|
+
function skipWs(text, start) {
|
|
200
|
+
let i = start;
|
|
201
|
+
while (i < text.length && /\s/.test(text[i]))
|
|
202
|
+
i++;
|
|
203
|
+
return i;
|
|
204
|
+
}
|
|
205
|
+
function isIdentStart(c) {
|
|
206
|
+
return /[A-Za-z_]/.test(c);
|
|
207
|
+
}
|
|
208
|
+
function isIdentCont(c) {
|
|
209
|
+
return /[A-Za-z0-9_]/.test(c);
|
|
210
|
+
}
|
|
211
|
+
/** Flatten selection entries that map GraphQL field -> SQL column (ignore nested/pseudo). */
|
|
212
|
+
function columnMapFromSelection(selection) {
|
|
213
|
+
const map = new Map();
|
|
214
|
+
const walk = (entries) => {
|
|
215
|
+
for (const entry of entries) {
|
|
216
|
+
if (entry.children) {
|
|
217
|
+
walk(entry.children);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (entry.value?.kind === 'column') {
|
|
221
|
+
map.set(entry.key, entry.value.value);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
walk(selection.entries);
|
|
226
|
+
return map;
|
|
227
|
+
}
|
|
228
|
+
/** Resolve `$args.path` / `$this.path` / literal against runtime. */
|
|
229
|
+
function resolveMappingValue(value, ctx) {
|
|
230
|
+
if (!value)
|
|
231
|
+
return undefined;
|
|
232
|
+
switch (value.kind) {
|
|
233
|
+
case 'literal':
|
|
234
|
+
return value.value;
|
|
235
|
+
case 'args': {
|
|
236
|
+
let cur = ctx.args;
|
|
237
|
+
for (const seg of value.path || []) {
|
|
238
|
+
if (cur == null)
|
|
239
|
+
return undefined;
|
|
240
|
+
cur = cur[seg];
|
|
241
|
+
}
|
|
242
|
+
return cur;
|
|
243
|
+
}
|
|
244
|
+
case 'this': {
|
|
245
|
+
let cur = ctx.parent;
|
|
246
|
+
for (const seg of value.path || []) {
|
|
247
|
+
if (cur == null)
|
|
248
|
+
return undefined;
|
|
249
|
+
cur = cur[seg];
|
|
250
|
+
}
|
|
251
|
+
return cur;
|
|
252
|
+
}
|
|
253
|
+
case 'column':
|
|
254
|
+
return value.value;
|
|
255
|
+
case 'pseudo':
|
|
256
|
+
return undefined;
|
|
257
|
+
default:
|
|
258
|
+
return undefined;
|
|
259
|
+
}
|
|
260
|
+
}
|