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