@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
@@ -0,0 +1,653 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSelect = buildSelect;
4
+ exports.escapeSqlStringLiteral = escapeSqlStringLiteral;
5
+ exports.buildSelectByColumnIn = buildSelectByColumnIn;
6
+ exports.buildInsert = buildInsert;
7
+ exports.buildUpdate = buildUpdate;
8
+ exports.buildDelete = buildDelete;
9
+ exports.encodeCursor = encodeCursor;
10
+ exports.decodeCursor = decodeCursor;
11
+ exports.mapRowToGraphql = mapRowToGraphql;
12
+ exports.mapRowToGraphqlWithJoins = mapRowToGraphqlWithJoins;
13
+ exports.selectionHasNested = selectionHasNested;
14
+ exports.nestedSelection = nestedSelection;
15
+ exports.collectReturningColumns = collectReturningColumns;
16
+ exports.parseSqlDirectiveMappings = parseSqlDirectiveMappings;
17
+ exports.parseArgsAndSelection = parseArgsAndSelection;
18
+ const adapter_js_1 = require("./adapter.js");
19
+ const mapping_js_1 = require("./mapping.js");
20
+ const plan_js_1 = require("./plan.js");
21
+ const PLANNER_KEYS = new Set([
22
+ 'filter',
23
+ 'orderBy',
24
+ 'first',
25
+ 'after',
26
+ 'last',
27
+ 'before',
28
+ 'limit',
29
+ 'offset',
30
+ ]);
31
+ function buildSelect(adapter, plan) {
32
+ const columns = (0, mapping_js_1.columnMapFromSelection)(plan.selection);
33
+ const joins = plan.joins?.length ? plan.joins : undefined;
34
+ const hasMany = plan.hasMany?.length ? plan.hasMany : undefined;
35
+ const needsAlias = Boolean(joins?.length || hasMany?.length);
36
+ const rootAlias = needsAlias ? 't' : undefined;
37
+ const flatJoins = joins?.length ? (0, plan_js_1.flattenJoins)(joins) : [];
38
+ const params = [];
39
+ const whereParts = [];
40
+ const qualify = (col) => rootAlias
41
+ ? `${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, col)}`
42
+ : (0, adapter_js_1.quoteIdent)(adapter, col);
43
+ // Equality / join predicates from `where` mapping (non-planner keys)
44
+ for (const entry of plan.whereMapping.entries) {
45
+ if (PLANNER_KEYS.has(entry.key) || entry.children) {
46
+ continue;
47
+ }
48
+ const resolved = (0, mapping_js_1.resolveMappingValue)(entry.value, {
49
+ args: plan.graphqlArgs,
50
+ parent: plan.parent,
51
+ });
52
+ if (resolved === undefined)
53
+ continue;
54
+ params.push(resolved);
55
+ whereParts.push(`${qualify(entry.key)} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
56
+ }
57
+ const filterVal = resolvePlannerArg(plan, 'filter');
58
+ if (filterVal && typeof filterVal === 'object') {
59
+ appendFilter(adapter, filterVal, columns, whereParts, params, {
60
+ qualifyColumn: rootAlias ? qualify : undefined,
61
+ });
62
+ }
63
+ const selectCols = buildSelectList(adapter, plan.selection, joins, hasMany, rootAlias);
64
+ let sql = `SELECT ${selectCols.join(', ')} FROM ${(0, adapter_js_1.quoteIdent)(adapter, plan.table)}`;
65
+ if (rootAlias) {
66
+ sql += ` AS ${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}`;
67
+ for (const join of flatJoins) {
68
+ const parentAlias = join.parentAlias || rootAlias;
69
+ sql += ` LEFT JOIN ${(0, adapter_js_1.quoteIdent)(adapter, join.table)} AS ${(0, adapter_js_1.quoteIdent)(adapter, join.alias)}`;
70
+ sql += ` ON ${(0, adapter_js_1.quoteIdent)(adapter, join.alias)}.${(0, adapter_js_1.quoteIdent)(adapter, join.joinColumn)}`;
71
+ sql += ` = ${(0, adapter_js_1.quoteIdent)(adapter, parentAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, join.parentColumn)}`;
72
+ }
73
+ }
74
+ if (whereParts.length) {
75
+ sql += ` WHERE ${whereParts.join(' AND ')}`;
76
+ }
77
+ if (plan.kind === 'COUNT') {
78
+ // Joins must not multiply COUNT — count root table only.
79
+ sql = `SELECT COUNT(*) AS ${(0, adapter_js_1.quoteIdent)(adapter, 'count')} FROM ${(0, adapter_js_1.quoteIdent)(adapter, plan.table)}`;
80
+ if (rootAlias) {
81
+ sql = `SELECT COUNT(*) AS ${(0, adapter_js_1.quoteIdent)(adapter, 'count')} FROM ${(0, adapter_js_1.quoteIdent)(adapter, plan.table)} AS ${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}`;
82
+ }
83
+ if (whereParts.length) {
84
+ sql += ` WHERE ${whereParts.join(' AND ')}`;
85
+ }
86
+ return { sql, params };
87
+ }
88
+ const orderBy = resolvePlannerArg(plan, 'orderBy');
89
+ let orderSql = buildOrderBy(adapter, orderBy, columns, rootAlias ? qualify : undefined);
90
+ // Stable pagination: JOINs / JSON subselects can reshuffle unordered LIMIT results.
91
+ if (!orderSql) {
92
+ const idCol = columns.get('id');
93
+ if (idCol) {
94
+ orderSql = rootAlias ? qualify(idCol) : (0, adapter_js_1.quoteIdent)(adapter, idCol);
95
+ }
96
+ }
97
+ if (orderSql) {
98
+ sql += ` ORDER BY ${orderSql}`;
99
+ }
100
+ if (plan.kind === 'CONNECTION') {
101
+ const first = Number(resolvePlannerArg(plan, 'first') ?? 10);
102
+ const after = resolvePlannerArg(plan, 'after');
103
+ // Cursor = offset for phase 1 (opaque base64 of offset)
104
+ let offset = 0;
105
+ if (typeof after === 'string' && after.length) {
106
+ offset = decodeCursor(after);
107
+ }
108
+ const limit = Math.max(0, first);
109
+ // fetch one extra to detect hasNextPage
110
+ params.push(limit + 1);
111
+ sql += ` LIMIT ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
112
+ params.push(offset);
113
+ sql += ` OFFSET ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
114
+ return { sql, params };
115
+ }
116
+ const limit = resolvePlannerArg(plan, 'limit');
117
+ const offset = resolvePlannerArg(plan, 'offset');
118
+ if (limit != null) {
119
+ params.push(Number(limit));
120
+ sql += ` LIMIT ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
121
+ }
122
+ else if (plan.kind === 'ROW') {
123
+ params.push(1);
124
+ sql += ` LIMIT ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
125
+ }
126
+ if (offset != null) {
127
+ params.push(Number(offset));
128
+ sql += ` OFFSET ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
129
+ }
130
+ return { sql, params };
131
+ }
132
+ function buildSelectList(adapter, selection, joins, hasMany, rootAlias) {
133
+ const columns = (0, mapping_js_1.columnMapFromSelection)(selection);
134
+ if ((!joins?.length && !hasMany?.length) || !rootAlias) {
135
+ return columns.size === 0
136
+ ? ['*']
137
+ : [...new Set(columns.values())].map(c => (0, adapter_js_1.quoteIdent)(adapter, c));
138
+ }
139
+ const cols = [];
140
+ const seen = new Set();
141
+ const pushRoot = (sqlCol) => {
142
+ if (seen.has(`t:${sqlCol}`))
143
+ return;
144
+ seen.add(`t:${sqlCol}`);
145
+ cols.push(`${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, sqlCol)} AS ${(0, adapter_js_1.quoteIdent)(adapter, `t__${sqlCol}`)}`);
146
+ };
147
+ for (const sqlCol of columns.values())
148
+ pushRoot(sqlCol);
149
+ const flat = (0, plan_js_1.flattenJoins)(joins || []);
150
+ for (const join of flat) {
151
+ if (join.parentAlias === rootAlias) {
152
+ pushRoot(join.parentColumn);
153
+ }
154
+ else {
155
+ // Nested hop: ensure the FK column is selected from the parent join alias.
156
+ const key = `${join.parentAlias}:${join.parentColumn}`;
157
+ if (!seen.has(key)) {
158
+ seen.add(key);
159
+ cols.push(`${(0, adapter_js_1.quoteIdent)(adapter, join.parentAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, join.parentColumn)} AS ${(0, adapter_js_1.quoteIdent)(adapter, `${join.parentAlias}__${join.parentColumn}`)}`);
160
+ }
161
+ }
162
+ const relCols = (0, mapping_js_1.columnMapFromSelection)(join.selection);
163
+ for (const sqlCol of relCols.values()) {
164
+ const key = `${join.alias}:${sqlCol}`;
165
+ if (seen.has(key))
166
+ continue;
167
+ seen.add(key);
168
+ cols.push(`${(0, adapter_js_1.quoteIdent)(adapter, join.alias)}.${(0, adapter_js_1.quoteIdent)(adapter, sqlCol)} AS ${(0, adapter_js_1.quoteIdent)(adapter, `${join.alias}__${sqlCol}`)}`);
169
+ }
170
+ }
171
+ for (const hm of hasMany || []) {
172
+ pushRoot(hm.parentColumn);
173
+ cols.push(`${buildHasManyJsonSubselect(adapter, hm, rootAlias)} AS ${(0, adapter_js_1.quoteIdent)(adapter, `hm__${hm.fieldName}`)}`);
174
+ }
175
+ if (!cols.length) {
176
+ throw new Error('SQL join plan requires a column selection mapping on the root table');
177
+ }
178
+ return cols;
179
+ }
180
+ /**
181
+ * Escape a value embedded in a single-quoted SQL string literal.
182
+ * Backslashes must be escaped before quotes (CodeQL js/incomplete-sanitization).
183
+ */
184
+ function escapeSqlStringLiteral(value, style = 'sqlite') {
185
+ // Always escape `\` first so later quote escapes cannot be undone by a trailing `\`.
186
+ let out = value.replace(/\\/g, '\\\\');
187
+ if (style === 'mysql') {
188
+ out = out.replace(/'/g, "\\'");
189
+ }
190
+ else {
191
+ out = out.replace(/'/g, "''");
192
+ }
193
+ return out;
194
+ }
195
+ function buildHasManyJsonSubselect(adapter, hm, rootAlias) {
196
+ const relCols = [...(0, mapping_js_1.columnMapFromSelection)(hm.selection).entries()];
197
+ const innerAlias = 'hm';
198
+ const limitSql = hm.limit != null ? ` LIMIT ${Number(hm.limit)}` : '';
199
+ if (adapter === 'postgres') {
200
+ const selectList = relCols
201
+ .map(([gql, sqlCol]) => `${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, sqlCol)} AS ${(0, adapter_js_1.quoteIdent)(adapter, gql)}`)
202
+ .join(', ');
203
+ return `(SELECT COALESCE(json_agg(row_to_json(${(0, adapter_js_1.quoteIdent)(adapter, 'x')})), '[]'::json) FROM (SELECT ${selectList} FROM ${(0, adapter_js_1.quoteIdent)(adapter, hm.table)} AS ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)} WHERE ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.joinColumn)} = ${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.parentColumn)}${limitSql}) AS ${(0, adapter_js_1.quoteIdent)(adapter, 'x')})`;
204
+ }
205
+ if (adapter === 'mysql') {
206
+ const objArgs = relCols
207
+ .flatMap(([gql, sqlCol]) => [
208
+ `'${escapeSqlStringLiteral(gql, 'mysql')}'`,
209
+ `${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, sqlCol)}`,
210
+ ])
211
+ .join(', ');
212
+ return `(SELECT COALESCE(json_arrayagg(json_object(${objArgs})), json_array()) FROM (SELECT ${relCols.map(([, c]) => `${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, c)}`).join(', ')} FROM ${(0, adapter_js_1.quoteIdent)(adapter, hm.table)} AS ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)} WHERE ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.joinColumn)} = ${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.parentColumn)}${limitSql}) AS ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)})`;
213
+ }
214
+ // sqlite — aggregate over a limited inner select; json_object reads projected column names.
215
+ const objArgs = relCols
216
+ .flatMap(([gql, sqlCol]) => [
217
+ `'${escapeSqlStringLiteral(gql, 'sqlite')}'`,
218
+ (0, adapter_js_1.quoteIdent)(adapter, sqlCol),
219
+ ])
220
+ .join(', ');
221
+ const innerSelect = relCols.map(([, c]) => (0, adapter_js_1.quoteIdent)(adapter, c)).join(', ');
222
+ return `(SELECT COALESCE(json_group_array(json_object(${objArgs})), json_array()) FROM (SELECT ${innerSelect} FROM ${(0, adapter_js_1.quoteIdent)(adapter, hm.table)} AS ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)} WHERE ${(0, adapter_js_1.quoteIdent)(adapter, innerAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.joinColumn)} = ${(0, adapter_js_1.quoteIdent)(adapter, rootAlias)}.${(0, adapter_js_1.quoteIdent)(adapter, hm.parentColumn)}${limitSql}))`;
223
+ }
224
+ /**
225
+ * Batch helper: same filters/order/limit as `buildSelect`, but replace the single
226
+ * equality binder for `column` with `WHERE column IN (...)`.
227
+ */
228
+ function buildSelectByColumnIn(adapter, plan) {
229
+ const columns = (0, mapping_js_1.columnMapFromSelection)(plan.selection);
230
+ const selectCols = columns.size === 0 ? ['*'] : [...new Set(columns.values())].map(c => (0, adapter_js_1.quoteIdent)(adapter, c));
231
+ const params = [];
232
+ const whereParts = [];
233
+ for (const entry of plan.whereMapping.entries) {
234
+ if (PLANNER_KEYS.has(entry.key) || entry.children)
235
+ continue;
236
+ if (entry.key === plan.column)
237
+ continue; // replaced by IN list
238
+ const resolved = (0, mapping_js_1.resolveMappingValue)(entry.value, {
239
+ args: plan.graphqlArgs,
240
+ parent: plan.parent,
241
+ });
242
+ if (resolved === undefined)
243
+ continue;
244
+ params.push(resolved);
245
+ whereParts.push(`${(0, adapter_js_1.quoteIdent)(adapter, entry.key)} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
246
+ }
247
+ const filterVal = resolvePlannerArg(plan, 'filter');
248
+ if (filterVal && typeof filterVal === 'object') {
249
+ appendFilter(adapter, filterVal, columns, whereParts, params);
250
+ }
251
+ const inPhs = plan.values.map(v => {
252
+ params.push(v);
253
+ return (0, adapter_js_1.placeholder)(adapter, params.length);
254
+ });
255
+ whereParts.push(`${(0, adapter_js_1.quoteIdent)(adapter, plan.column)} IN (${inPhs.join(', ')})`);
256
+ // Always include the batch column so we can regroup rows by key.
257
+ const batchColSql = (0, adapter_js_1.quoteIdent)(adapter, plan.column);
258
+ if (!selectCols.includes(batchColSql) && selectCols[0] !== '*') {
259
+ selectCols.push(batchColSql);
260
+ }
261
+ let sql = `SELECT ${selectCols.join(', ')} FROM ${(0, adapter_js_1.quoteIdent)(adapter, plan.table)}`;
262
+ if (whereParts.length) {
263
+ sql += ` WHERE ${whereParts.join(' AND ')}`;
264
+ }
265
+ const orderBy = resolvePlannerArg(plan, 'orderBy');
266
+ const orderSql = buildOrderBy(adapter, orderBy, columns);
267
+ if (orderSql) {
268
+ sql += ` ORDER BY ${orderSql}`;
269
+ }
270
+ const limit = resolvePlannerArg(plan, 'limit');
271
+ const offset = resolvePlannerArg(plan, 'offset');
272
+ if (limit != null) {
273
+ params.push(Number(limit));
274
+ sql += ` LIMIT ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
275
+ }
276
+ if (offset != null) {
277
+ params.push(Number(offset));
278
+ sql += ` OFFSET ${(0, adapter_js_1.placeholder)(adapter, params.length)}`;
279
+ }
280
+ return { sql, params };
281
+ }
282
+ function buildInsert(adapter, table, setMapping, graphqlArgs, returningColumns) {
283
+ const cols = [];
284
+ const params = [];
285
+ for (const entry of setMapping.entries) {
286
+ if (entry.children)
287
+ continue;
288
+ const val = (0, mapping_js_1.resolveMappingValue)(entry.value, { args: graphqlArgs });
289
+ if (val === undefined)
290
+ continue;
291
+ cols.push(entry.key);
292
+ params.push(val);
293
+ }
294
+ if (!cols.length) {
295
+ throw new Error(`@sql INSERT on ${table} has no column values`);
296
+ }
297
+ const colSql = cols.map(c => (0, adapter_js_1.quoteIdent)(adapter, c)).join(', ');
298
+ const ph = cols.map((_, i) => (0, adapter_js_1.placeholder)(adapter, i + 1)).join(', ');
299
+ let sql = `INSERT INTO ${(0, adapter_js_1.quoteIdent)(adapter, table)} (${colSql}) VALUES (${ph})`;
300
+ if (returningColumns.length && (adapter === 'postgres' || adapter === 'sqlite')) {
301
+ sql += ` RETURNING ${returningColumns.map(c => (0, adapter_js_1.quoteIdent)(adapter, c)).join(', ')}`;
302
+ }
303
+ return { sql, params };
304
+ }
305
+ function buildUpdate(adapter, table, setMapping, whereMapping, graphqlArgs, returningColumns) {
306
+ const params = [];
307
+ const sets = [];
308
+ for (const entry of setMapping.entries) {
309
+ if (entry.children)
310
+ continue;
311
+ const val = (0, mapping_js_1.resolveMappingValue)(entry.value, { args: graphqlArgs });
312
+ if (val === undefined)
313
+ continue;
314
+ params.push(val);
315
+ sets.push(`${(0, adapter_js_1.quoteIdent)(adapter, entry.key)} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
316
+ }
317
+ if (!sets.length) {
318
+ throw new Error(`@sql UPDATE on ${table} has no SET columns`);
319
+ }
320
+ const whereParts = [];
321
+ for (const entry of whereMapping.entries) {
322
+ if (entry.children || PLANNER_KEYS.has(entry.key))
323
+ continue;
324
+ const val = (0, mapping_js_1.resolveMappingValue)(entry.value, { args: graphqlArgs });
325
+ if (val === undefined)
326
+ continue;
327
+ params.push(val);
328
+ whereParts.push(`${(0, adapter_js_1.quoteIdent)(adapter, entry.key)} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
329
+ }
330
+ let sql = `UPDATE ${(0, adapter_js_1.quoteIdent)(adapter, table)} SET ${sets.join(', ')}`;
331
+ if (whereParts.length) {
332
+ sql += ` WHERE ${whereParts.join(' AND ')}`;
333
+ }
334
+ if (returningColumns.length && (adapter === 'postgres' || adapter === 'sqlite')) {
335
+ sql += ` RETURNING ${returningColumns.map(c => (0, adapter_js_1.quoteIdent)(adapter, c)).join(', ')}`;
336
+ }
337
+ return { sql, params };
338
+ }
339
+ function buildDelete(adapter, table, whereMapping, graphqlArgs) {
340
+ const params = [];
341
+ const whereParts = [];
342
+ for (const entry of whereMapping.entries) {
343
+ if (entry.children || PLANNER_KEYS.has(entry.key))
344
+ continue;
345
+ const val = (0, mapping_js_1.resolveMappingValue)(entry.value, { args: graphqlArgs });
346
+ if (val === undefined)
347
+ continue;
348
+ params.push(val);
349
+ whereParts.push(`${(0, adapter_js_1.quoteIdent)(adapter, entry.key)} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
350
+ }
351
+ let sql = `DELETE FROM ${(0, adapter_js_1.quoteIdent)(adapter, table)}`;
352
+ if (whereParts.length) {
353
+ sql += ` WHERE ${whereParts.join(' AND ')}`;
354
+ }
355
+ return { sql, params };
356
+ }
357
+ function resolvePlannerArg(plan, key) {
358
+ const ctx = { args: plan.graphqlArgs, parent: plan.parent };
359
+ const binder = plan.planners?.[key];
360
+ if (binder != null && String(binder).trim()) {
361
+ const fromBinder = resolvePlannerBinder(String(binder), ctx);
362
+ if (fromBinder !== undefined)
363
+ return fromBinder;
364
+ }
365
+ // Compat: planner keys stuffed into `where` before the split.
366
+ const entry = plan.whereMapping.entries.find(e => e.key === key);
367
+ if (entry) {
368
+ return (0, mapping_js_1.resolveMappingValue)(entry.value, ctx);
369
+ }
370
+ return plan.graphqlArgs[key];
371
+ }
372
+ /**
373
+ * Resolve `@sql(filter: "$args.filter")` style binders.
374
+ * Also accepts a one-line mapping (`filter: $args.filter`) for symmetry with `where`.
375
+ */
376
+ function resolvePlannerBinder(binder, ctx) {
377
+ const trimmed = binder.trim();
378
+ if (!trimmed)
379
+ return undefined;
380
+ if (trimmed.startsWith('$')) {
381
+ const mapping = (0, mapping_js_1.parseSqlMapping)(`_: ${trimmed}`);
382
+ return (0, mapping_js_1.resolveMappingValue)(mapping.entries[0]?.value, ctx);
383
+ }
384
+ const mapping = (0, mapping_js_1.parseSqlMapping)(trimmed);
385
+ if (mapping.entries.length === 1) {
386
+ return (0, mapping_js_1.resolveMappingValue)(mapping.entries[0].value, ctx);
387
+ }
388
+ return undefined;
389
+ }
390
+ function buildOrderBy(adapter, orderBy, columns, qualifyColumn) {
391
+ if (!orderBy)
392
+ return '';
393
+ const list = Array.isArray(orderBy) ? orderBy : [orderBy];
394
+ const parts = [];
395
+ for (const item of list) {
396
+ if (typeof item !== 'string')
397
+ continue;
398
+ const desc = item.endsWith('_DESC');
399
+ const asc = item.endsWith('_ASC');
400
+ if (!asc && !desc)
401
+ continue;
402
+ const fieldConst = item.replace(/_DESC$|_ASC$/, '');
403
+ const graphqlField = constToCamel(fieldConst);
404
+ const col = columns.get(graphqlField) || columns.get(fieldConst.toLowerCase());
405
+ if (!col) {
406
+ // fall back: try id
407
+ if (graphqlField === 'id') {
408
+ const idCol = columns.get('id');
409
+ if (idCol) {
410
+ const q = qualifyColumn ? qualifyColumn(idCol) : (0, adapter_js_1.quoteIdent)(adapter, idCol);
411
+ parts.push(`${q} ${desc ? 'DESC' : 'ASC'}`);
412
+ }
413
+ }
414
+ continue;
415
+ }
416
+ const q = qualifyColumn ? qualifyColumn(col) : (0, adapter_js_1.quoteIdent)(adapter, col);
417
+ parts.push(`${q} ${desc ? 'DESC' : 'ASC'}`);
418
+ }
419
+ return parts.join(', ');
420
+ }
421
+ function constToCamel(constant) {
422
+ const lower = constant.toLowerCase();
423
+ return lower.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
424
+ }
425
+ function appendFilter(adapter, filter, columns, whereParts, params, opts) {
426
+ if (!filter || typeof filter !== 'object')
427
+ return;
428
+ const qualify = opts?.qualifyColumn;
429
+ if (Array.isArray(filter.and)) {
430
+ const parts = [];
431
+ for (const sub of filter.and) {
432
+ const inner = [];
433
+ appendFilter(adapter, sub, columns, inner, params, opts);
434
+ if (inner.length)
435
+ parts.push(`(${inner.join(' AND ')})`);
436
+ }
437
+ if (parts.length)
438
+ whereParts.push(`(${parts.join(' AND ')})`);
439
+ }
440
+ if (Array.isArray(filter.or)) {
441
+ const parts = [];
442
+ for (const sub of filter.or) {
443
+ const inner = [];
444
+ appendFilter(adapter, sub, columns, inner, params, opts);
445
+ if (inner.length)
446
+ parts.push(`(${inner.join(' AND ')})`);
447
+ }
448
+ if (parts.length)
449
+ whereParts.push(`(${parts.join(' OR ')})`);
450
+ }
451
+ if (filter.not && typeof filter.not === 'object') {
452
+ const inner = [];
453
+ appendFilter(adapter, filter.not, columns, inner, params, opts);
454
+ if (inner.length)
455
+ whereParts.push(`NOT (${inner.join(' AND ')})`);
456
+ }
457
+ for (const [field, ops] of Object.entries(filter)) {
458
+ if (field === 'and' || field === 'or' || field === 'not')
459
+ continue;
460
+ if (ops == null || typeof ops !== 'object')
461
+ continue;
462
+ const col = columns.get(field);
463
+ if (!col)
464
+ continue;
465
+ const q = qualify ? qualify(col) : (0, adapter_js_1.quoteIdent)(adapter, col);
466
+ const o = ops;
467
+ if ('eq' in o) {
468
+ params.push(o.eq);
469
+ whereParts.push(`${q} = ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
470
+ }
471
+ if ('ne' in o) {
472
+ params.push(o.ne);
473
+ whereParts.push(`${q} <> ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
474
+ }
475
+ if ('lt' in o) {
476
+ params.push(o.lt);
477
+ whereParts.push(`${q} < ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
478
+ }
479
+ if ('lte' in o) {
480
+ params.push(o.lte);
481
+ whereParts.push(`${q} <= ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
482
+ }
483
+ if ('gt' in o) {
484
+ params.push(o.gt);
485
+ whereParts.push(`${q} > ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
486
+ }
487
+ if ('gte' in o) {
488
+ params.push(o.gte);
489
+ whereParts.push(`${q} >= ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
490
+ }
491
+ if ('in' in o && Array.isArray(o.in)) {
492
+ const phs = o.in.map((v) => {
493
+ params.push(v);
494
+ return (0, adapter_js_1.placeholder)(adapter, params.length);
495
+ });
496
+ whereParts.push(`${q} IN (${phs.join(', ')})`);
497
+ }
498
+ if ('nin' in o && Array.isArray(o.nin)) {
499
+ const phs = o.nin.map((v) => {
500
+ params.push(v);
501
+ return (0, adapter_js_1.placeholder)(adapter, params.length);
502
+ });
503
+ whereParts.push(`${q} NOT IN (${phs.join(', ')})`);
504
+ }
505
+ if ('includes' in o) {
506
+ params.push(`%${o.includes}%`);
507
+ whereParts.push(`${q} LIKE ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
508
+ }
509
+ if ('startsWith' in o) {
510
+ params.push(`${o.startsWith}%`);
511
+ whereParts.push(`${q} LIKE ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
512
+ }
513
+ if ('endsWith' in o) {
514
+ params.push(`%${o.endsWith}`);
515
+ whereParts.push(`${q} LIKE ${(0, adapter_js_1.placeholder)(adapter, params.length)}`);
516
+ }
517
+ if ('isNull' in o) {
518
+ whereParts.push(o.isNull ? `${q} IS NULL` : `${q} IS NOT NULL`);
519
+ }
520
+ }
521
+ }
522
+ function encodeCursor(offset) {
523
+ return Buffer.from(String(offset), 'utf8').toString('base64');
524
+ }
525
+ function decodeCursor(cursor) {
526
+ const n = Number(Buffer.from(cursor, 'base64').toString('utf8'));
527
+ return Number.isFinite(n) ? n : 0;
528
+ }
529
+ function mapRowToGraphql(row, selection) {
530
+ const out = {};
531
+ for (const entry of selection.entries) {
532
+ if (entry.children)
533
+ continue;
534
+ if (!entry.value || entry.value.kind !== 'column')
535
+ continue;
536
+ const raw = row[entry.value.value] ?? row[`t__${entry.value.value}`];
537
+ out[entry.key] = raw != null && entry.key === 'id' ? String(raw) : raw;
538
+ }
539
+ return out;
540
+ }
541
+ function mapRowToGraphqlWithJoins(row, selection, joins, hasMany = []) {
542
+ const out = mapRowToGraphql(row, selection);
543
+ for (const join of joins) {
544
+ out[join.fieldName] = mapJoinedObject(row, join);
545
+ }
546
+ const stamped = (0, plan_js_1.stampJoinedFields)(out, joins);
547
+ for (const hm of hasMany) {
548
+ stamped[hm.fieldName] = parseHasManyJson(row[`hm__${hm.fieldName}`], hm);
549
+ }
550
+ if (hasMany.length) {
551
+ const existing = stamped[Symbol.for('mesh.sql.joinedFields')];
552
+ const names = new Set(existing ? [...existing] : []);
553
+ for (const hm of hasMany)
554
+ names.add(hm.fieldName);
555
+ Object.defineProperty(stamped, Symbol.for('mesh.sql.joinedFields'), {
556
+ value: names,
557
+ enumerable: false,
558
+ configurable: true,
559
+ });
560
+ }
561
+ return stamped;
562
+ }
563
+ function mapJoinedObject(row, join) {
564
+ const nested = {};
565
+ let any = false;
566
+ for (const entry of join.selection.entries) {
567
+ if (!entry.value || entry.value.kind !== 'column')
568
+ continue;
569
+ const raw = row[`${join.alias}__${entry.value.value}`];
570
+ if (raw !== undefined && raw !== null)
571
+ any = true;
572
+ nested[entry.key] = raw != null && entry.key === 'id' ? String(raw) : raw;
573
+ }
574
+ if (!any)
575
+ return null;
576
+ if (join.joins?.length) {
577
+ for (const child of join.joins) {
578
+ nested[child.fieldName] = mapJoinedObject(row, child);
579
+ }
580
+ (0, plan_js_1.stampJoinedFields)(nested, join.joins);
581
+ }
582
+ return nested;
583
+ }
584
+ function parseHasManyJson(raw, hm) {
585
+ if (raw == null)
586
+ return [];
587
+ let parsed = raw;
588
+ if (typeof raw === 'string') {
589
+ try {
590
+ parsed = JSON.parse(raw);
591
+ }
592
+ catch {
593
+ return [];
594
+ }
595
+ }
596
+ if (!Array.isArray(parsed))
597
+ return [];
598
+ return parsed.map((item) => {
599
+ if (!item || typeof item !== 'object')
600
+ return {};
601
+ const out = {};
602
+ for (const entry of hm.selection.entries) {
603
+ if (!entry.value || entry.value.kind !== 'column')
604
+ continue;
605
+ const v = item[entry.key] ?? item[entry.value.value];
606
+ out[entry.key] = v != null && entry.key === 'id' ? String(v) : v;
607
+ }
608
+ return out;
609
+ });
610
+ }
611
+ function selectionHasNested(selection, key) {
612
+ return selection.entries.some(e => e.key === key && e.children);
613
+ }
614
+ function nestedSelection(selection, key) {
615
+ const entry = selection.entries.find(e => e.key === key);
616
+ return { entries: entry?.children || [] };
617
+ }
618
+ function collectReturningColumns(selection) {
619
+ // Prefer nested payload object (album { ... })
620
+ for (const entry of selection.entries) {
621
+ if (entry.children?.length) {
622
+ return [...(0, mapping_js_1.columnMapFromSelection)({ entries: entry.children }).values()];
623
+ }
624
+ }
625
+ return [...(0, mapping_js_1.columnMapFromSelection)(selection).values()];
626
+ }
627
+ function parseSqlDirectiveMappings(opts) {
628
+ const planners = {};
629
+ for (const key of [
630
+ 'filter',
631
+ 'orderBy',
632
+ 'limit',
633
+ 'offset',
634
+ 'first',
635
+ 'after',
636
+ 'last',
637
+ 'before',
638
+ ]) {
639
+ const v = opts[key];
640
+ if (v != null && String(v).trim())
641
+ planners[key] = String(v);
642
+ }
643
+ return {
644
+ whereMapping: (0, mapping_js_1.parseSqlMapping)(opts.where),
645
+ setMapping: (0, mapping_js_1.parseSqlMapping)(opts.set),
646
+ selection: (0, mapping_js_1.parseSqlMapping)(opts.selection),
647
+ planners,
648
+ };
649
+ }
650
+ /** @deprecated use parseSqlDirectiveMappings */
651
+ function parseArgsAndSelection(argsStr, selectionStr) {
652
+ return parseSqlDirectiveMappings({ where: argsStr, selection: selectionStr });
653
+ }