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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/cjs/adapter.js +60 -0
  3. package/dist/cjs/batch.js +113 -0
  4. package/dist/cjs/client.js +205 -0
  5. package/dist/cjs/client.js.map +7 -0
  6. package/dist/cjs/dialect.js +60 -0
  7. package/dist/cjs/dialect.js.map +7 -0
  8. package/dist/cjs/entity.js +186 -0
  9. package/dist/cjs/execution.js +307 -0
  10. package/dist/cjs/execution.js.map +7 -0
  11. package/dist/cjs/index.js +23 -0
  12. package/dist/cjs/index.js.map +7 -0
  13. package/dist/cjs/mapping.js +260 -0
  14. package/dist/cjs/mapping.js.map +7 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/pg-executor.js +53 -0
  17. package/dist/cjs/pg-plans.js +103 -0
  18. package/dist/cjs/pg-registry.js +239 -0
  19. package/dist/cjs/plan.js +359 -0
  20. package/dist/cjs/sql-builder.js +653 -0
  21. package/dist/cjs/sql-builder.js.map +7 -0
  22. package/dist/cjs/types.js +0 -0
  23. package/dist/cjs/types.js.map +7 -0
  24. package/dist/cjs/uri.js +267 -0
  25. package/dist/esm/adapter.js +54 -0
  26. package/dist/esm/batch.js +107 -0
  27. package/dist/esm/client.js +197 -0
  28. package/dist/esm/client.js.map +7 -0
  29. package/dist/esm/dialect.js +54 -0
  30. package/dist/esm/dialect.js.map +7 -0
  31. package/dist/esm/entity.js +180 -0
  32. package/dist/esm/execution.js +303 -0
  33. package/dist/esm/execution.js.map +7 -0
  34. package/dist/esm/index.js +20 -0
  35. package/dist/esm/index.js.map +7 -0
  36. package/dist/esm/mapping.js +255 -0
  37. package/dist/esm/mapping.js.map +7 -0
  38. package/dist/esm/pg-executor.js +49 -0
  39. package/dist/esm/pg-plans.js +100 -0
  40. package/dist/esm/pg-registry.js +236 -0
  41. package/dist/esm/plan.js +351 -0
  42. package/dist/esm/sql-builder.js +636 -0
  43. package/dist/esm/sql-builder.js.map +7 -0
  44. package/dist/esm/types.js +0 -0
  45. package/dist/esm/types.js.map +7 -0
  46. package/dist/esm/uri.js +261 -0
  47. package/dist/package.json +57 -0
  48. package/dist/typings/adapter.d.cts +9 -0
  49. package/dist/typings/adapter.d.ts +9 -0
  50. package/dist/typings/batch.d.cts +21 -0
  51. package/dist/typings/batch.d.ts +21 -0
  52. package/dist/typings/client.d.cts +36 -0
  53. package/dist/typings/client.d.ts +36 -0
  54. package/dist/typings/dialect.d.cts +9 -0
  55. package/dist/typings/dialect.d.ts +9 -0
  56. package/dist/typings/entity.d.cts +24 -0
  57. package/dist/typings/entity.d.ts +24 -0
  58. package/dist/typings/execution.d.cts +9 -0
  59. package/dist/typings/execution.d.ts +9 -0
  60. package/dist/typings/index.d.cts +15 -0
  61. package/dist/typings/index.d.ts +15 -0
  62. package/dist/typings/mapping.d.cts +13 -0
  63. package/dist/typings/mapping.d.ts +13 -0
  64. package/dist/typings/pg-executor.d.cts +19 -0
  65. package/dist/typings/pg-executor.d.ts +19 -0
  66. package/dist/typings/pg-plans.d.cts +12 -0
  67. package/dist/typings/pg-plans.d.ts +12 -0
  68. package/dist/typings/pg-registry.d.cts +16 -0
  69. package/dist/typings/pg-registry.d.ts +16 -0
  70. package/dist/typings/plan.d.cts +47 -0
  71. package/dist/typings/plan.d.ts +47 -0
  72. package/dist/typings/sql-builder.d.cts +75 -0
  73. package/dist/typings/sql-builder.d.ts +75 -0
  74. package/dist/typings/types.d.cts +50 -0
  75. package/dist/typings/types.d.ts +50 -0
  76. package/dist/typings/uri.d.cts +42 -0
  77. package/dist/typings/uri.d.ts +42 -0
  78. package/package.json +67 -4
  79. package/src/adapter.ts +56 -0
  80. package/src/batch.ts +150 -0
  81. package/src/client.ts +233 -0
  82. package/src/entity.ts +235 -0
  83. package/src/execution.ts +411 -0
  84. package/src/index.ts +25 -0
  85. package/src/mapping.ts +291 -0
  86. package/src/pg-executor.ts +68 -0
  87. package/src/pg-plans.ts +118 -0
  88. package/src/pg-registry.ts +290 -0
  89. package/src/plan.ts +466 -0
  90. package/src/sql-builder.ts +809 -0
  91. package/src/types.ts +63 -0
  92. package/src/uri.ts +301 -0
  93. package/test/client-bun.test.ts +8 -0
  94. package/test/client.bun.test.ts +46 -0
  95. package/test/execution.test.ts +277 -0
  96. package/test/mapping.test.ts +79 -0
  97. package/test/pg-registry.test.ts +103 -0
  98. package/test/sql-builder.test.ts +131 -0
  99. package/test/uri.test.ts +123 -0
  100. package/README.md +0 -3
package/src/adapter.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { isAbsolute as pathIsAbsolute, join as pathJoin } from 'node:path';
2
+ import type { SqlAdapter } from './types.js';
3
+ import { inferAdapterFromConnectionString } from './uri.js';
4
+
5
+ /**
6
+ * Infer adapter from a transport `location` / connection URI.
7
+ * Prefer {@link inferAdapterFromConnectionString} for full Bun-compatible rules.
8
+ */
9
+ export function inferAdapterFromLocation(location: string | undefined): SqlAdapter | undefined {
10
+ if (!location) return undefined;
11
+ try {
12
+ return inferAdapterFromConnectionString(location);
13
+ } catch {
14
+ return undefined;
15
+ }
16
+ }
17
+
18
+ export function quoteIdent(adapter: SqlAdapter, name: string): string {
19
+ switch (adapter) {
20
+ case 'mysql':
21
+ return `\`${name.replace(/`/g, '``')}\``;
22
+ case 'postgres':
23
+ case 'sqlite':
24
+ default:
25
+ return `"${name.replace(/"/g, '""')}"`;
26
+ }
27
+ }
28
+
29
+ export function placeholder(adapter: SqlAdapter, index: number): string {
30
+ // index is 1-based for postgres
31
+ if (adapter === 'postgres') {
32
+ return `$${index}`;
33
+ }
34
+ return '?';
35
+ }
36
+
37
+ export function resolveSqlitePath(location: string, cwd?: string): string {
38
+ let path = location;
39
+ if (path.startsWith('file:')) {
40
+ path = path.slice('file:'.length);
41
+ } else if (path.toLowerCase().startsWith('sqlite:')) {
42
+ path = path.slice(path.indexOf(':') + 1);
43
+ }
44
+ if (path.startsWith('//')) {
45
+ // file://absolute or file:///absolute
46
+ path = path.replace(/^\/\/+/, '/');
47
+ }
48
+ const qIdx = path.indexOf('?');
49
+ if (qIdx !== -1) {
50
+ path = path.slice(0, qIdx);
51
+ }
52
+ if (!pathIsAbsolute(path) && cwd && path !== ':memory:') {
53
+ return pathJoin(cwd, path);
54
+ }
55
+ return path;
56
+ }
package/src/batch.ts ADDED
@@ -0,0 +1,150 @@
1
+ import DataLoader from 'dataloader';
2
+ import { resolveMappingValue } from './mapping.js';
3
+ import { buildSelectByColumnIn, mapRowToGraphql, type SqlPlanners } from './sql-builder.js';
4
+ import type { ParsedSqlMapping, SqlClient, SqlQueryKind } from './types.js';
5
+
6
+ const LOADERS = Symbol.for('mesh.sql.loaders');
7
+
8
+ type AnyLoader = DataLoader<unknown, unknown>;
9
+ type LoaderMap = Map<string, AnyLoader>;
10
+
11
+ function getLoaderMap(context: any): LoaderMap {
12
+ if (!context || typeof context !== 'object') {
13
+ throw new Error('SQL DataLoader batching requires a mutable GraphQL context object');
14
+ }
15
+ if (!context[LOADERS]) {
16
+ context[LOADERS] = new Map();
17
+ }
18
+ return context[LOADERS] as LoaderMap;
19
+ }
20
+
21
+ function stableArgsKey(args: Record<string, any> | undefined): string {
22
+ if (!args) return '';
23
+ const { where, filter, orderBy, limit, offset, first, after } = args;
24
+ return JSON.stringify({ where, filter, orderBy, limit, offset, first, after });
25
+ }
26
+
27
+ const PLANNER_KEYS = new Set([
28
+ 'filter',
29
+ 'orderBy',
30
+ 'first',
31
+ 'after',
32
+ 'last',
33
+ 'before',
34
+ 'limit',
35
+ 'offset',
36
+ 'set',
37
+ 'where',
38
+ ]);
39
+
40
+ /**
41
+ * Detect a single equality column binder suitable for `WHERE col IN (...)` batching.
42
+ */
43
+ export function batchableEqualityColumn(whereMapping: ParsedSqlMapping): string | undefined {
44
+ const cols: string[] = [];
45
+ for (const entry of whereMapping.entries) {
46
+ if (
47
+ entry.spread ||
48
+ entry.key.startsWith('$') ||
49
+ PLANNER_KEYS.has(entry.key) ||
50
+ entry.children
51
+ ) {
52
+ continue;
53
+ }
54
+ cols.push(entry.key);
55
+ }
56
+ return cols.length === 1 ? cols[0] : undefined;
57
+ }
58
+
59
+ export function resolveEqualityKey(
60
+ whereMapping: ParsedSqlMapping,
61
+ column: string,
62
+ graphqlArgs: Record<string, any>,
63
+ parent: any,
64
+ ): unknown {
65
+ const entry = whereMapping.entries.find(e => e.key === column);
66
+ if (!entry) return undefined;
67
+ return resolveMappingValue(entry.value, { args: graphqlArgs, parent });
68
+ }
69
+
70
+ export interface BatchSelectOpts {
71
+ client: SqlClient;
72
+ table: string;
73
+ kind: 'ROW' | 'ROWS';
74
+ selection: ParsedSqlMapping;
75
+ whereMapping: ParsedSqlMapping;
76
+ planners?: SqlPlanners;
77
+ column: string;
78
+ graphqlArgs?: Record<string, any>;
79
+ }
80
+
81
+ /**
82
+ * Per-request DataLoader that batches ROW/ROWS lookups sharing the same table/column/args.
83
+ */
84
+ export function loadBatchedByColumn(
85
+ context: any,
86
+ opts: BatchSelectOpts,
87
+ key: unknown,
88
+ ): Promise<any> {
89
+ const loaderKey = [
90
+ opts.kind,
91
+ opts.table,
92
+ opts.column,
93
+ stableArgsKey(opts.graphqlArgs),
94
+ JSON.stringify(opts.selection.entries.map(e => [e.key, e.value])),
95
+ ].join('\0');
96
+
97
+ const map = getLoaderMap(context);
98
+ let loader = map.get(loaderKey);
99
+ if (!loader) {
100
+ loader = new DataLoader<unknown, unknown>(
101
+ async (keys: readonly unknown[]): Promise<unknown[]> => {
102
+ const unique = [...new Set(keys.filter(k => k !== undefined && k !== null))];
103
+ if (!unique.length) {
104
+ return keys.map(() => (opts.kind === 'ROWS' ? [] : null));
105
+ }
106
+
107
+ const query = buildSelectByColumnIn(opts.client.adapter, {
108
+ table: opts.table,
109
+ kind: 'ROWS' as SqlQueryKind,
110
+ selection: opts.selection,
111
+ whereMapping: opts.whereMapping,
112
+ planners: opts.planners,
113
+ graphqlArgs: opts.graphqlArgs || {},
114
+ column: opts.column,
115
+ values: unique,
116
+ });
117
+ const result = await opts.client.query(query.sql, query.params);
118
+ const rows = result.rows as Record<string, unknown>[];
119
+
120
+ const byKey = new Map<string, Record<string, unknown>[]>();
121
+ for (const row of rows) {
122
+ const raw =
123
+ row[opts.column] ?? row[opts.column.toLowerCase()] ?? row[opts.column.toUpperCase()];
124
+ const k = String(raw);
125
+ let list = byKey.get(k);
126
+ if (!list) {
127
+ list = [];
128
+ byKey.set(k, list);
129
+ }
130
+ list.push(row);
131
+ }
132
+
133
+ return keys.map(k => {
134
+ if (k === undefined || k === null) {
135
+ return opts.kind === 'ROWS' ? [] : null;
136
+ }
137
+ const matched = byKey.get(String(k)) || [];
138
+ if (opts.kind === 'ROW') {
139
+ const row = matched[0];
140
+ return row ? mapRowToGraphql(row, opts.selection) : null;
141
+ }
142
+ return matched.map(r => mapRowToGraphql(r, opts.selection));
143
+ });
144
+ },
145
+ { cache: true },
146
+ );
147
+ map.set(loaderKey, loader);
148
+ }
149
+ return loader.load(key);
150
+ }
package/src/client.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { createPool, type Pool as Mysql2Pool, type Pool } from 'mysql2/promise';
3
+ import pg from 'pg';
4
+ import { resolveSqlitePath } from './adapter.js';
5
+ import type { SqlAdapter, SqlClient, SqlTransportOptions } from './types.js';
6
+ import { parseSqlUri } from './uri.js';
7
+
8
+ export interface CreateSqlClientOptions extends SqlTransportOptions {
9
+ adapter: SqlAdapter;
10
+ location: string;
11
+ cwd?: string;
12
+ /** Force Node drivers even when `Bun.SQL` is present. */
13
+ preferNode?: boolean;
14
+ }
15
+
16
+ type BunSqlCtor = new (
17
+ url?: string | object,
18
+ options?: Record<string, unknown>,
19
+ ) => {
20
+ unsafe: (query: string, params?: unknown[] | Record<string, unknown>) => Promise<any>;
21
+ close?: () => void | Promise<void>;
22
+ end?: () => void | Promise<void>;
23
+ };
24
+
25
+ function getBunSqlCtor(): BunSqlCtor | undefined {
26
+ const bun = (globalThis as { Bun?: { SQL?: BunSqlCtor } }).Bun;
27
+ return typeof bun?.SQL === 'function' ? bun.SQL : undefined;
28
+ }
29
+
30
+ export function isBunSqlAvailable(): boolean {
31
+ return getBunSqlCtor() != null;
32
+ }
33
+
34
+ export function createSqlClient(opts: CreateSqlClientOptions): SqlClient {
35
+ if (!opts.preferNode && isBunSqlAvailable()) {
36
+ return createBunSqlClient(opts);
37
+ }
38
+ switch (opts.adapter) {
39
+ case 'sqlite':
40
+ return createSqliteClient(opts.location, opts.cwd);
41
+ case 'mysql':
42
+ return createMysqlClient(opts);
43
+ case 'postgres':
44
+ return createPostgresClient(opts);
45
+ default:
46
+ throw new Error(`Unknown SQL adapter: ${opts.adapter as string}`);
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Wrap Bun's native `SQL` client when running under Bun.
52
+ * Uses `sql.unsafe(query, params)` so our adapter placeholders (`$1` / `?`) work as-is.
53
+ */
54
+ export function createBunSqlClient(opts: CreateSqlClientOptions): SqlClient {
55
+ const BunSQL = getBunSqlCtor();
56
+ if (!BunSQL) {
57
+ throw new Error('Bun.SQL is not available in this runtime');
58
+ }
59
+
60
+ const bunOpts: Record<string, unknown> = {
61
+ adapter: opts.adapter === 'mysql' ? 'mysql' : opts.adapter,
62
+ };
63
+ if (opts.max != null) bunOpts.max = opts.max;
64
+ if (opts.idleTimeout != null) bunOpts.idleTimeout = opts.idleTimeout;
65
+ if (opts.connectionTimeout != null) bunOpts.connectionTimeout = opts.connectionTimeout;
66
+ if (opts.tls != null) bunOpts.tls = opts.tls === 'true' ? true : opts.tls;
67
+
68
+ const sql = new BunSQL(opts.location, bunOpts);
69
+
70
+ return {
71
+ adapter: opts.adapter,
72
+ async query<T = Record<string, unknown>>(query: string, params: unknown[] = []) {
73
+ const result = await sql.unsafe(query, params);
74
+ const rows = normalizeBunRows<T>(result);
75
+ const rowCount =
76
+ typeof result?.count === 'number'
77
+ ? result.count
78
+ : typeof result?.affectedRows === 'number'
79
+ ? result.affectedRows
80
+ : rows.length;
81
+ return { rows, rowCount };
82
+ },
83
+ async dispose() {
84
+ if (typeof sql.close === 'function') {
85
+ await sql.close();
86
+ } else if (typeof sql.end === 'function') {
87
+ await sql.end();
88
+ }
89
+ },
90
+ };
91
+ }
92
+
93
+ function normalizeBunRows<T>(result: any): T[] {
94
+ if (result == null) return [];
95
+ // Copy into a plain array — Bun results are array-like and may carry extra props (`count`).
96
+ if (typeof result.length === 'number') {
97
+ return Array.from({ length: result.length }, (_, i) => result[i] as T);
98
+ }
99
+ if (Array.isArray(result)) {
100
+ return [...(result as T[])];
101
+ }
102
+ return [];
103
+ }
104
+
105
+ /**
106
+ * Wrap an existing `pg.Pool` (or compatible) as SqlClient.
107
+ */
108
+ export function wrapPgPoolAsSqlClient(pool: {
109
+ query: (sql: string, params?: unknown[]) => Promise<{ rows: any[]; rowCount?: number | null }>;
110
+ end?: () => Promise<void>;
111
+ }): SqlClient {
112
+ const client: SqlClient = {
113
+ adapter: 'postgres',
114
+ // Expose real pg.Pool when present for `@dataplan/pg`.
115
+ pgPool: 'connect' in pool ? (pool as import('pg').Pool) : undefined,
116
+ async query<T = Record<string, unknown>>(sql: string, params: unknown[] = []) {
117
+ const result = await pool.query(sql, params);
118
+ return {
119
+ rows: (result.rows || []) as T[],
120
+ rowCount: Number(result.rowCount ?? result.rows?.length ?? 0),
121
+ };
122
+ },
123
+ async dispose() {
124
+ if (typeof pool.end === 'function') {
125
+ await pool.end();
126
+ }
127
+ },
128
+ };
129
+ return client;
130
+ }
131
+
132
+ /**
133
+ * Wrap an existing `mysql` / `mysql2` pool (legacy handler `pool` config) as SqlClient.
134
+ */
135
+ export function wrapMysqlPoolAsSqlClient(pool: {
136
+ query: (...args: any[]) => any;
137
+ end?: (...args: any[]) => any;
138
+ promise?: () => { query: (...args: any[]) => any; end?: (...args: any[]) => any };
139
+ }): SqlClient {
140
+ // mysql (non-promise) exposes .promise(); mysql2/promise is already thenable
141
+ const p = typeof pool.promise === 'function' ? pool.promise() : (pool as unknown as Mysql2Pool);
142
+
143
+ return {
144
+ adapter: 'mysql',
145
+ async query<T = Record<string, unknown>>(sql: string, params: unknown[] = []) {
146
+ const [result] = await p.query(sql, params);
147
+ if (Array.isArray(result)) {
148
+ return { rows: result as T[], rowCount: result.length };
149
+ }
150
+ const header = result as { affectedRows?: number };
151
+ return { rows: [] as T[], rowCount: Number(header.affectedRows ?? 0) };
152
+ },
153
+ async dispose() {
154
+ if (typeof p.end === 'function') {
155
+ await p.end();
156
+ }
157
+ },
158
+ };
159
+ }
160
+
161
+ function createSqliteClient(location: string, cwd?: string): SqlClient {
162
+ const dbPath = resolveSqlitePath(location, cwd);
163
+ const db = new DatabaseSync(dbPath);
164
+ return {
165
+ adapter: 'sqlite',
166
+ async query<T = Record<string, unknown>>(sql: string, params: unknown[] = []) {
167
+ const stmt = db.prepare(sql);
168
+ const bind = params as Array<null | number | bigint | string | Uint8Array>;
169
+ const returnsRows = /^\s*(SELECT|PRAGMA|WITH)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
170
+ if (returnsRows) {
171
+ const rows = stmt.all(...bind) as T[];
172
+ return { rows, rowCount: rows.length };
173
+ }
174
+ const result = stmt.run(...bind) as { changes?: number };
175
+ return {
176
+ rows: [] as T[],
177
+ rowCount: Number(result.changes ?? 0),
178
+ };
179
+ },
180
+ dispose() {
181
+ db.close();
182
+ },
183
+ };
184
+ }
185
+
186
+ function createMysqlClient(opts: CreateSqlClientOptions): SqlClient {
187
+ const parsed = parseSqlUri(opts.location);
188
+ if (parsed.adapter !== 'mysql') {
189
+ throw new Error(`Expected mysql URI, got ${parsed.adapter}`);
190
+ }
191
+ const tls = resolveTlsFlag(opts.tls, parsed.ssl);
192
+ const pool: Pool = createPool({
193
+ host: parsed.host,
194
+ port: parsed.port,
195
+ user: parsed.user,
196
+ password: parsed.password,
197
+ database: parsed.database,
198
+ ssl: tls ? { rejectUnauthorized: false } : undefined,
199
+ supportBigNumbers: true,
200
+ bigNumberStrings: true,
201
+ connectionLimit: opts.max ?? 10,
202
+ idleTimeout: opts.idleTimeout != null ? opts.idleTimeout * 1000 : undefined,
203
+ connectTimeout: opts.connectionTimeout != null ? opts.connectionTimeout * 1000 : undefined,
204
+ });
205
+ return wrapMysqlPoolAsSqlClient(pool);
206
+ }
207
+
208
+ function createPostgresClient(opts: CreateSqlClientOptions): SqlClient {
209
+ const parsed = parseSqlUri(opts.location);
210
+ if (parsed.adapter !== 'postgres') {
211
+ throw new Error(`Expected postgres URI, got ${parsed.adapter}`);
212
+ }
213
+ const tls = resolveTlsFlag(opts.tls, parsed.ssl);
214
+ const pool = new pg.Pool({
215
+ connectionString: opts.location,
216
+ max: opts.max ?? 10,
217
+ idleTimeoutMillis: opts.idleTimeout != null ? opts.idleTimeout * 1000 : undefined,
218
+ connectionTimeoutMillis:
219
+ opts.connectionTimeout != null ? opts.connectionTimeout * 1000 : undefined,
220
+ ssl: tls ? { rejectUnauthorized: false } : undefined,
221
+ });
222
+ return wrapPgPoolAsSqlClient(pool);
223
+ }
224
+
225
+ function resolveTlsFlag(
226
+ option: boolean | string | undefined,
227
+ fromUri: boolean | undefined,
228
+ ): boolean {
229
+ if (option === false || option === 'disable') return false;
230
+ if (option === true || option === 'true') return true;
231
+ if (typeof option === 'string' && option.length > 0 && option !== 'false') return true;
232
+ return Boolean(fromUri);
233
+ }
package/src/entity.ts ADDED
@@ -0,0 +1,235 @@
1
+ import {
2
+ GraphQLList,
3
+ GraphQLNonNull,
4
+ GraphQLScalarType,
5
+ GraphQLUnionType,
6
+ isObjectType,
7
+ type GraphQLField,
8
+ type GraphQLNamedType,
9
+ type GraphQLObjectType,
10
+ type GraphQLResolveInfo,
11
+ type GraphQLSchema,
12
+ } from 'graphql';
13
+ import { entitiesResolver } from '@apollo/subgraph';
14
+ import { getDefDirectives } from '@graphql-mesh/utils';
15
+ import { fakePromise } from '@whatwg-node/promise-helpers';
16
+
17
+ type ResolveReferenceFn = (reference: any, context: any, info: GraphQLResolveInfo) => any;
18
+
19
+ /**
20
+ * Record `__resolveReference` the way `@apollo/subgraph` expects
21
+ * (`extensions.apollo.subgraph.resolveReference`) so we can reuse
22
+ * `entitiesResolver` instead of maintaining our own `_entities` dispatch.
23
+ * Also mirror on `type.resolveReference` for Hive stub hydration helpers / tests.
24
+ */
25
+ export function setTypeResolveReference(
26
+ type: GraphQLNamedType,
27
+ resolveReference: ResolveReferenceFn,
28
+ ) {
29
+ const extensions = (type.extensions ??= {}) as Record<string, any>;
30
+ const apollo = (extensions.apollo ??= {});
31
+ const subgraph = (apollo.subgraph ??= {});
32
+ subgraph.resolveReference = resolveReference;
33
+ (type as any).resolveReference = resolveReference;
34
+ }
35
+
36
+ export function getTypeResolveReference(type: GraphQLNamedType): ResolveReferenceFn | undefined {
37
+ const fromExtensions = (type.extensions as any)?.apollo?.subgraph?.resolveReference;
38
+ if (typeof fromExtensions === 'function') {
39
+ return fromExtensions;
40
+ }
41
+ const fromType = (type as any).resolveReference;
42
+ return typeof fromType === 'function' ? fromType : undefined;
43
+ }
44
+
45
+ type JoinDirectiveArgs = { name?: string; args?: Record<string, unknown> };
46
+
47
+ /** Raw `@sql` plus composed `@join__directive(name: "sql")` payloads. */
48
+ export function getSqlDirectiveArgs(
49
+ schema: GraphQLSchema,
50
+ node: {
51
+ astNode?: unknown;
52
+ extensions?: unknown;
53
+ },
54
+ ): Record<string, unknown>[] {
55
+ const fromDef = getDefDirectives(schema, node as any)
56
+ .filter(d => d.name === 'sql')
57
+ .map(d => d.args || {});
58
+ const joins = (node.extensions as any)?.directives?.join__directive as
59
+ JoinDirectiveArgs[] | undefined;
60
+ const fromJoin: Record<string, unknown>[] = [];
61
+ if (Array.isArray(joins)) {
62
+ for (const join of joins) {
63
+ if (join?.name === 'sql' && join.args && typeof join.args === 'object') {
64
+ fromJoin.push(join.args);
65
+ }
66
+ }
67
+ }
68
+ const rootJoins = (node.extensions as any)?.join__directive as JoinDirectiveArgs[] | undefined;
69
+ if (Array.isArray(rootJoins)) {
70
+ for (const join of rootJoins) {
71
+ if (join?.name === 'sql' && join.args && typeof join.args === 'object') {
72
+ fromJoin.push(join.args);
73
+ }
74
+ }
75
+ }
76
+ return [...fromDef, ...fromJoin];
77
+ }
78
+
79
+ const MESH_ENTITY_FILL = Symbol.for('mesh.sql.entityFill');
80
+
81
+ /**
82
+ * For types with `resolveReference`, resolve missing fields by fetching the entity
83
+ * once per parent object (deduped). Lets Hive honor entity stubs the way Router does.
84
+ */
85
+ function hydrateEntityStubFieldResolvers(schema: GraphQLSchema) {
86
+ for (const type of Object.values(schema.getTypeMap())) {
87
+ if (!isObjectType(type) || type.name.startsWith('__')) {
88
+ continue;
89
+ }
90
+ const resolveReference = getTypeResolveReference(type);
91
+ if (!resolveReference) {
92
+ continue;
93
+ }
94
+ const fields = type.getFields();
95
+ for (const fieldName of Object.keys(fields)) {
96
+ const field = fields[fieldName] as GraphQLField<any, any>;
97
+ if (typeof field.resolve === 'function') {
98
+ continue;
99
+ }
100
+ field.resolve = (parent, _args, context, info) => {
101
+ if (parent == null || typeof parent !== 'object') {
102
+ return parent?.[fieldName];
103
+ }
104
+ if (Object.prototype.hasOwnProperty.call(parent, fieldName)) {
105
+ return parent[fieldName];
106
+ }
107
+ let fill = (parent as any)[MESH_ENTITY_FILL];
108
+ if (!fill) {
109
+ fill = fakePromise(resolveReference(parent, context, info)).then((full: any) => {
110
+ if (full && typeof full === 'object') {
111
+ Object.assign(parent, full);
112
+ }
113
+ return parent;
114
+ });
115
+ (parent as any)[MESH_ENTITY_FILL] = fill;
116
+ }
117
+ return fill.then((full: any) => full?.[fieldName]);
118
+ };
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Add / repair Federation `Query._entities` (same contract as Connectors REST transport).
125
+ */
126
+ function ensureFederationEntitiesField(schema: GraphQLSchema) {
127
+ const queryType = schema.getQueryType();
128
+ if (!queryType) {
129
+ return;
130
+ }
131
+ const queryFields = queryType.getFields();
132
+ const entityTypes = Object.values(schema.getTypeMap()).filter(
133
+ (t): t is GraphQLObjectType =>
134
+ isObjectType(t) && !t.name.startsWith('__') && !!getTypeResolveReference(t),
135
+ );
136
+ if (!entityTypes.length) {
137
+ return;
138
+ }
139
+
140
+ const typeMap = schema.getTypeMap() as Record<string, any>;
141
+ let anyType = typeMap._Any as GraphQLScalarType | undefined;
142
+ if (!anyType) {
143
+ anyType = new GraphQLScalarType({
144
+ name: '_Any',
145
+ serialize: value => value,
146
+ parseValue: value => value,
147
+ });
148
+ typeMap._Any = anyType;
149
+ }
150
+
151
+ let entityUnion = typeMap._Entity as GraphQLUnionType | undefined;
152
+ if (!entityUnion) {
153
+ entityUnion = new GraphQLUnionType({
154
+ name: '_Entity',
155
+ types: entityTypes,
156
+ resolveType(obj) {
157
+ return obj?.__typename || undefined;
158
+ },
159
+ });
160
+ typeMap._Entity = entityUnion;
161
+ }
162
+
163
+ const entitiesResolve = (
164
+ _root: unknown,
165
+ args: { representations?: unknown },
166
+ context: any,
167
+ info: GraphQLResolveInfo,
168
+ ) => {
169
+ const representations = args?.representations;
170
+ if (!Array.isArray(representations)) {
171
+ return [];
172
+ }
173
+ return entitiesResolver({ representations, context, info });
174
+ };
175
+
176
+ if (queryFields._entities) {
177
+ queryFields._entities.resolve = entitiesResolve;
178
+ return;
179
+ }
180
+
181
+ queryFields._entities = {
182
+ name: '_entities',
183
+ description: 'Federation entity resolver for SQL transport (Hive `_entities` path)',
184
+ type: new GraphQLNonNull(new GraphQLList(entityUnion)),
185
+ args: [
186
+ {
187
+ name: 'representations',
188
+ description: undefined,
189
+ type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(anyType))),
190
+ defaultValue: undefined,
191
+ deprecationReason: undefined,
192
+ extensions: {},
193
+ astNode: undefined,
194
+ },
195
+ ],
196
+ resolve: entitiesResolve,
197
+ deprecationReason: undefined,
198
+ extensions: {},
199
+ astNode: undefined,
200
+ };
201
+ }
202
+
203
+ export type TypeLevelSqlExecutor = (
204
+ sqlArgs: Record<string, unknown>,
205
+ reference: any,
206
+ context: any,
207
+ info: GraphQLResolveInfo,
208
+ ) => any;
209
+
210
+ /**
211
+ * Wire Federation entity resolution from type-level `@sql` (Connectors type-level pattern).
212
+ * Query `entity: true` is no longer used — presence of OBJECT `@sql` is the signal.
213
+ */
214
+ export function wireSqlEntityResolvers(
215
+ schema: GraphQLSchema,
216
+ opts: { executeTypeLevelRow: TypeLevelSqlExecutor },
217
+ ): GraphQLSchema {
218
+ for (const type of Object.values(schema.getTypeMap())) {
219
+ if (!isObjectType(type) || type.name.startsWith('__')) continue;
220
+ if (getTypeResolveReference(type)) continue;
221
+ const sqlArgsList = getSqlDirectiveArgs(schema, type as any);
222
+ if (!sqlArgsList.length) continue;
223
+ const sqlArgs = sqlArgsList[0];
224
+ const kind = (sqlArgs.kind as string) || 'ROW';
225
+ if (kind !== 'ROW') continue;
226
+
227
+ setTypeResolveReference(type, (reference, context, info) =>
228
+ opts.executeTypeLevelRow(sqlArgs, reference, context, info),
229
+ );
230
+ }
231
+
232
+ ensureFederationEntitiesField(schema);
233
+ hydrateEntityStubFieldResolvers(schema);
234
+ return schema;
235
+ }