@omnigraph/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 (66) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/cjs/directives.js +59 -0
  3. package/dist/cjs/directives.js.map +7 -0
  4. package/dist/cjs/index.js +22 -0
  5. package/dist/cjs/index.js.map +7 -0
  6. package/dist/cjs/introspect/mysql.js +93 -0
  7. package/dist/cjs/introspect/postgres.js +106 -0
  8. package/dist/cjs/introspect/sqlite.js +60 -0
  9. package/dist/cjs/introspect/sqlite.js.map +7 -0
  10. package/dist/cjs/introspect/types.js +0 -0
  11. package/dist/cjs/introspect/types.js.map +7 -0
  12. package/dist/cjs/naming.js +54 -0
  13. package/dist/cjs/naming.js.map +7 -0
  14. package/dist/cjs/package.json +1 -0
  15. package/dist/cjs/schema.js +712 -0
  16. package/dist/cjs/schema.js.map +7 -0
  17. package/dist/cjs/type-map.js +40 -0
  18. package/dist/cjs/type-map.js.map +7 -0
  19. package/dist/esm/directives.js +55 -0
  20. package/dist/esm/directives.js.map +7 -0
  21. package/dist/esm/index.js +15 -0
  22. package/dist/esm/index.js.map +7 -0
  23. package/dist/esm/introspect/mysql.js +90 -0
  24. package/dist/esm/introspect/postgres.js +102 -0
  25. package/dist/esm/introspect/sqlite.js +57 -0
  26. package/dist/esm/introspect/sqlite.js.map +7 -0
  27. package/dist/esm/introspect/types.js +0 -0
  28. package/dist/esm/introspect/types.js.map +7 -0
  29. package/dist/esm/naming.js +50 -0
  30. package/dist/esm/naming.js.map +7 -0
  31. package/dist/esm/schema.js +707 -0
  32. package/dist/esm/schema.js.map +7 -0
  33. package/dist/esm/type-map.js +37 -0
  34. package/dist/esm/type-map.js.map +7 -0
  35. package/dist/package.json +54 -0
  36. package/dist/typings/directives.d.cts +17 -0
  37. package/dist/typings/directives.d.ts +17 -0
  38. package/dist/typings/index.d.cts +10 -0
  39. package/dist/typings/index.d.ts +10 -0
  40. package/dist/typings/introspect/mysql.d.cts +7 -0
  41. package/dist/typings/introspect/mysql.d.ts +7 -0
  42. package/dist/typings/introspect/postgres.d.cts +9 -0
  43. package/dist/typings/introspect/postgres.d.ts +9 -0
  44. package/dist/typings/introspect/sqlite.d.cts +8 -0
  45. package/dist/typings/introspect/sqlite.d.ts +8 -0
  46. package/dist/typings/introspect/types.d.cts +26 -0
  47. package/dist/typings/introspect/types.d.ts +26 -0
  48. package/dist/typings/naming.d.cts +17 -0
  49. package/dist/typings/naming.d.ts +17 -0
  50. package/dist/typings/schema.d.cts +39 -0
  51. package/dist/typings/schema.d.ts +39 -0
  52. package/dist/typings/type-map.d.cts +4 -0
  53. package/dist/typings/type-map.d.ts +4 -0
  54. package/package.json +61 -4
  55. package/src/directives.ts +67 -0
  56. package/src/index.ts +20 -0
  57. package/src/introspect/mysql.ts +110 -0
  58. package/src/introspect/postgres.ts +142 -0
  59. package/src/introspect/sqlite.ts +90 -0
  60. package/src/introspect/types.ts +31 -0
  61. package/src/naming.ts +67 -0
  62. package/src/schema.ts +834 -0
  63. package/src/type-map.ts +50 -0
  64. package/test/__snapshots__/sqlite-chinook.spec.ts.snap +328 -0
  65. package/test/sqlite-chinook.spec.ts +33 -0
  66. package/README.md +0 -3
package/src/schema.ts ADDED
@@ -0,0 +1,834 @@
1
+ import {
2
+ GraphQLBoolean,
3
+ GraphQLInt,
4
+ GraphQLNonNull,
5
+ GraphQLObjectType,
6
+ GraphQLSchema,
7
+ GraphQLString,
8
+ } from 'graphql';
9
+ import { SchemaComposer } from 'graphql-compose';
10
+ import { GraphQLBigInt, GraphQLDate, GraphQLDateTime, GraphQLJSON } from 'graphql-scalars';
11
+ import { path as pathHelper } from '@graphql-mesh/cross-helpers';
12
+ import {
13
+ inferAdapterFromConnectionString,
14
+ resolveConnectionStringFromEnv,
15
+ type SqlAdapter,
16
+ type SqlTransportOptions,
17
+ } from '@graphql-mesh/transport-sql';
18
+ import { SqlDirective, SqlKindEnum, TransportDirective } from './directives.js';
19
+ import { introspectMysql } from './introspect/mysql.js';
20
+ import { introspectPostgres } from './introspect/postgres.js';
21
+ import { introspectSqlite } from './introspect/sqlite.js';
22
+ import type { SqlColumnMeta, SqlSchemaMeta, SqlTableMeta } from './introspect/types.js';
23
+ import { createDefaultNaming, type SqlNaming } from './naming.js';
24
+ import { mapSqlTypeToGraphQL } from './type-map.js';
25
+
26
+ const FEDERATION_LINK_URL = 'https://specs.apollo.dev/federation/v2.6';
27
+
28
+ export interface LoadSqlSubgraphOpts extends Pick<
29
+ SqlTransportOptions,
30
+ 'max' | 'idleTimeout' | 'connectionTimeout' | 'tls'
31
+ > {
32
+ /**
33
+ * Bun-style adapter override. When omitted, inferred from the connection URI
34
+ * protocol (`postgres://`, `mysql://` / `mysql2://` / `mariadb://`,
35
+ * `sqlite://` / `file:`, host-style → postgres, `*.db` → sqlite).
36
+ */
37
+ adapter?: SqlAdapter;
38
+ /**
39
+ * Connection URI / path — becomes `@transport(location)`.
40
+ * When omitted, resolved from Bun-compatible env vars (`DATABASE_URL`,
41
+ * `POSTGRES_URL` / `PGURL`, `MYSQL_URL`, `SQLITE_URL`, …) or `PG*` / `MYSQL_*` fields.
42
+ * Sqlite: `file:…`, `sqlite:…`, `:memory:`, or a `*.db` path.
43
+ * Mysql/Postgres: `mysql(2|s)://…`, `mariadb://…`, `postgres(ql)://…`, or host-style.
44
+ */
45
+ endpoint?: string;
46
+ cwd?: string;
47
+ schema?: string;
48
+ includeTables?: string[];
49
+ excludeTables?: string[];
50
+ /** Limit columns per table (legacy mysql `tableFields` shape). */
51
+ tableFields?: Array<{ table: string; fields: string[] }>;
52
+ naming?: Partial<SqlNaming>;
53
+ }
54
+
55
+ export async function loadGraphQLSchemaFromSql(subgraphName: string, opts: LoadSqlSubgraphOpts) {
56
+ const naming: SqlNaming = { ...createDefaultNaming(), ...opts.naming };
57
+ const withEndpoint = resolveOptsEndpoint(opts);
58
+ const adapter = resolveAdapter(withEndpoint);
59
+ const resolved: LoadSqlSubgraphOpts & { adapter: SqlAdapter } = {
60
+ ...withEndpoint,
61
+ adapter,
62
+ };
63
+ const meta = applyTableFieldsFilter(await introspect(resolved), opts.tableFields);
64
+ const location = resolveLocation(resolved);
65
+ const schemaComposer = new SchemaComposer();
66
+
67
+ schemaComposer.add(GraphQLBigInt);
68
+ schemaComposer.add(GraphQLJSON);
69
+ schemaComposer.add(GraphQLDate);
70
+ schemaComposer.add(GraphQLDateTime);
71
+ schemaComposer.addDirective(TransportDirective);
72
+ schemaComposer.addDirective(SqlDirective);
73
+ schemaComposer.add(SqlKindEnum);
74
+
75
+ ensureSharedFilterInputs(schemaComposer);
76
+ ensurePageInfo(schemaComposer);
77
+
78
+ const tableByName = new Map(meta.tables.map(t => [t.name, t]));
79
+ const typeNameByTable = new Map(meta.tables.map(t => [t.name, naming.typeName(t.name)] as const));
80
+
81
+ // Pass 1: object types + column fields
82
+ for (const table of meta.tables) {
83
+ const typeName = typeNameByTable.get(table.name)!;
84
+ const pkCols = table.columns.filter(c => c.primaryKey);
85
+ const solePk = pkCols.length === 1 ? pkCols[0] : undefined;
86
+
87
+ const otc = schemaComposer.createObjectTC({
88
+ name: typeName,
89
+ fields: {},
90
+ });
91
+ const typeDirectives: Array<{ name: string; args: Record<string, unknown> }> = [
92
+ {
93
+ name: 'key',
94
+ args: {
95
+ fields: solePk
96
+ ? naming.pkFieldName(solePk.name, true)
97
+ : pkCols.map(c => naming.fieldName(c.name)).join(' '),
98
+ },
99
+ },
100
+ ];
101
+ // Type-level `@sql` = Federation entity resolver (Connectors-style `$this` keys).
102
+ if (pkCols.length) {
103
+ const keyArgs = pkCols
104
+ .map(col => {
105
+ const field =
106
+ solePk && col.name === solePk.name
107
+ ? naming.pkFieldName(col.name, true)
108
+ : naming.fieldName(col.name);
109
+ return `${col.name}: $this.${field}`;
110
+ })
111
+ .join('\n');
112
+ typeDirectives.push({
113
+ name: 'sql',
114
+ args: {
115
+ subgraph: subgraphName,
116
+ table: table.name,
117
+ kind: 'ROW',
118
+ where: blockArg(keyArgs),
119
+ selection: selectionBlock(naming, table),
120
+ },
121
+ });
122
+ }
123
+ otc.setDirectives(typeDirectives);
124
+
125
+ for (const col of table.columns) {
126
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
127
+ const fieldName = isSolePkCol
128
+ ? naming.pkFieldName(col.name, true)
129
+ : naming.fieldName(col.name);
130
+ const gqlType = mapSqlTypeToGraphQL(col.dataType, { asId: isSolePkCol });
131
+ otc.setField(fieldName, {
132
+ type: col.notNull || isSolePkCol ? new GraphQLNonNull(gqlType) : gqlType,
133
+ });
134
+ }
135
+
136
+ createFilterAndOrder(schemaComposer, naming, typeName, table, solePk);
137
+ createConnectionTypes(schemaComposer, typeName);
138
+ createMutationInputs(schemaComposer, naming, typeName, table, solePk);
139
+ }
140
+
141
+ // Pass 2: relations
142
+ for (const table of meta.tables) {
143
+ const typeName = typeNameByTable.get(table.name)!;
144
+ const otc = schemaComposer.getOTC(typeName);
145
+ const solePk = table.columns.filter(c => c.primaryKey);
146
+ const solePkCol = solePk.length === 1 ? solePk[0] : undefined;
147
+
148
+ for (const fk of table.foreignKeys) {
149
+ if (fk.columns.length !== 1 || fk.refColumns.length !== 1) continue;
150
+ const refTable = tableByName.get(fk.refTable);
151
+ if (!refTable) continue;
152
+ const refTypeName = typeNameByTable.get(fk.refTable)!;
153
+ const localCol = fk.columns[0];
154
+ const refCol = fk.refColumns[0];
155
+ const localField =
156
+ solePkCol && localCol === solePkCol.name
157
+ ? naming.pkFieldName(localCol, true)
158
+ : naming.fieldName(localCol);
159
+ const refSolePk = refTable.columns.filter(c => c.primaryKey);
160
+ const refField =
161
+ refSolePk.length === 1 && refCol === refSolePk[0].name
162
+ ? naming.pkFieldName(refCol, true)
163
+ : naming.fieldName(refCol);
164
+
165
+ // belongsTo on local table
166
+ const belongsToName = naming.singularField(refTypeName);
167
+ if (!otc.hasField(belongsToName)) {
168
+ otc.setField(belongsToName, {
169
+ type: refTypeName,
170
+ directives: [
171
+ {
172
+ name: 'sql',
173
+ args: {
174
+ subgraph: subgraphName,
175
+ table: fk.refTable,
176
+ kind: 'ROW',
177
+ where: blockArg(`${refCol}: $this.${localField}`),
178
+ selection: selectionBlock(naming, refTable),
179
+ },
180
+ },
181
+ ],
182
+ });
183
+ }
184
+
185
+ // hasMany on referenced table
186
+ const refOtc = schemaComposer.getOTC(refTypeName);
187
+ const hasManyName = naming.pluralField(typeName);
188
+ if (!refOtc.hasField(hasManyName)) {
189
+ refOtc.setField(hasManyName, {
190
+ type: `[${typeName}!]!`,
191
+ args: {
192
+ where: naming.filterInput(typeName),
193
+ orderBy: `[${naming.orderByEnum(typeName)}!]`,
194
+ limit: 'Int',
195
+ offset: 'Int',
196
+ },
197
+ directives: [
198
+ {
199
+ name: 'sql',
200
+ args: {
201
+ subgraph: subgraphName,
202
+ table: table.name,
203
+ kind: 'ROWS',
204
+ // Spread only when merging fixed join predicates with client where.
205
+ where: blockArg(`${localCol}: $this.${refField}\n...$args.where`),
206
+ orderBy: '$args.orderBy',
207
+ limit: '$args.limit',
208
+ offset: '$args.offset',
209
+ selection: selectionBlock(naming, table),
210
+ },
211
+ },
212
+ ],
213
+ });
214
+ }
215
+ }
216
+ }
217
+
218
+ // Pass 3: Query + Mutation roots
219
+ const queryTC = schemaComposer.Query;
220
+ const mutationTC = schemaComposer.Mutation;
221
+
222
+ for (const table of meta.tables) {
223
+ const typeName = typeNameByTable.get(table.name)!;
224
+ const pkCols = table.columns.filter(c => c.primaryKey);
225
+ const solePk = pkCols.length === 1 ? pkCols[0] : undefined;
226
+ const selectionRaw = selectionLines(naming, table);
227
+ const selection = blockArg(selectionRaw);
228
+ const plural = naming.pluralField(typeName);
229
+ const singular = naming.singularField(typeName);
230
+
231
+ if (solePk) {
232
+ const pkField = naming.pkFieldName(solePk.name, true);
233
+ queryTC.setField(singular, {
234
+ type: typeName,
235
+ args: {
236
+ [pkField]: 'ID!',
237
+ },
238
+ directives: [
239
+ {
240
+ name: 'sql',
241
+ args: {
242
+ subgraph: subgraphName,
243
+ table: table.name,
244
+ kind: 'ROW',
245
+ where: blockArg(`${solePk.name}: $args.${pkField}`),
246
+ selection,
247
+ },
248
+ },
249
+ ],
250
+ });
251
+ }
252
+
253
+ queryTC.setField(plural, {
254
+ type: `[${typeName}!]!`,
255
+ args: {
256
+ where: naming.filterInput(typeName),
257
+ orderBy: `[${naming.orderByEnum(typeName)}!]`,
258
+ limit: { type: GraphQLInt, defaultValue: 10 },
259
+ offset: { type: GraphQLInt, defaultValue: 0 },
260
+ },
261
+ directives: [
262
+ {
263
+ name: 'sql',
264
+ args: {
265
+ subgraph: subgraphName,
266
+ table: table.name,
267
+ kind: 'ROWS',
268
+ // Sole binder: bare `$args.where` (Connectors-style; no spread needed).
269
+ where: '$args.where',
270
+ orderBy: '$args.orderBy',
271
+ limit: '$args.limit',
272
+ offset: '$args.offset',
273
+ selection,
274
+ },
275
+ },
276
+ ],
277
+ });
278
+
279
+ queryTC.setField(naming.connectionField(typeName), {
280
+ type: `${typeName}Connection!`,
281
+ args: {
282
+ where: naming.filterInput(typeName),
283
+ orderBy: `[${naming.orderByEnum(typeName)}!]`,
284
+ first: GraphQLInt,
285
+ after: GraphQLString,
286
+ },
287
+ directives: [
288
+ {
289
+ name: 'sql',
290
+ args: {
291
+ subgraph: subgraphName,
292
+ table: table.name,
293
+ kind: 'CONNECTION',
294
+ where: '$args.where',
295
+ orderBy: '$args.orderBy',
296
+ first: '$args.first',
297
+ after: '$args.after',
298
+ selection: blockArg(
299
+ [
300
+ `nodes {`,
301
+ indent(selectionRaw),
302
+ `}`,
303
+ `edges {`,
304
+ ` cursor: $cursor`,
305
+ ` node {`,
306
+ indent(selectionRaw, 2),
307
+ ` }`,
308
+ `}`,
309
+ `pageInfo {`,
310
+ ` hasNextPage: $hasNextPage`,
311
+ ` hasPreviousPage: $hasPreviousPage`,
312
+ ` startCursor: $startCursor`,
313
+ ` endCursor: $endCursor`,
314
+ `}`,
315
+ `totalCount: $totalCount`,
316
+ ].join('\n'),
317
+ ),
318
+ },
319
+ },
320
+ ],
321
+ });
322
+
323
+ queryTC.setField(naming.countField(typeName), {
324
+ type: 'Int!',
325
+ args: {
326
+ where: naming.filterInput(typeName),
327
+ },
328
+ directives: [
329
+ {
330
+ name: 'sql',
331
+ args: {
332
+ subgraph: subgraphName,
333
+ table: table.name,
334
+ kind: 'COUNT',
335
+ where: '$args.where',
336
+ selection: blockArg(`$`),
337
+ },
338
+ },
339
+ ],
340
+ });
341
+
342
+ // Mutations
343
+ const payloadKey = singular;
344
+ mutationTC.setField(`create${typeName}`, {
345
+ type: `${naming.payloadType(typeName)}!`,
346
+ args: {
347
+ input: `${naming.createInput(typeName)}!`,
348
+ },
349
+ directives: [
350
+ {
351
+ name: 'sql',
352
+ args: {
353
+ subgraph: subgraphName,
354
+ table: table.name,
355
+ kind: 'INSERT',
356
+ set: insertSetBlock(naming, table, solePk),
357
+ selection: blockArg(`${payloadKey} {\n${indent(selectionRaw)}\n}`),
358
+ },
359
+ },
360
+ ],
361
+ });
362
+
363
+ if (solePk) {
364
+ const pkField = naming.pkFieldName(solePk.name, true);
365
+ mutationTC.setField(`update${typeName}`, {
366
+ type: `${naming.payloadType(typeName)}!`,
367
+ args: {
368
+ [pkField]: 'ID!',
369
+ input: `${naming.updateInput(typeName)}!`,
370
+ },
371
+ directives: [
372
+ {
373
+ name: 'sql',
374
+ args: {
375
+ subgraph: subgraphName,
376
+ table: table.name,
377
+ kind: 'UPDATE',
378
+ set: blockArg(updateSetBlock(naming, table, solePk)),
379
+ where: blockArg(`${solePk.name}: $args.${pkField}`),
380
+ selection: blockArg(`${payloadKey} {\n${indent(selectionRaw)}\n}`),
381
+ },
382
+ },
383
+ ],
384
+ });
385
+
386
+ mutationTC.setField(`delete${typeName}`, {
387
+ type: `${naming.deletePayloadType(typeName)}!`,
388
+ args: {
389
+ [pkField]: 'ID!',
390
+ },
391
+ directives: [
392
+ {
393
+ name: 'sql',
394
+ args: {
395
+ subgraph: subgraphName,
396
+ table: table.name,
397
+ kind: 'DELETE',
398
+ where: blockArg(`${solePk.name}: $args.${pkField}`),
399
+ selection: blockArg([`ok: $affectedRows`, `affectedRows: $affectedRows`].join('\n')),
400
+ },
401
+ },
402
+ ],
403
+ });
404
+ }
405
+ }
406
+
407
+ const schema = schemaComposer.buildSchema();
408
+ const extensions: any = (schema.extensions ||= {});
409
+ extensions.directives ||= {};
410
+ extensions.directives.transport = {
411
+ subgraph: subgraphName,
412
+ kind: 'sql',
413
+ location,
414
+ options: buildTransportOptions(resolved, adapter),
415
+ };
416
+ extensions.directives.link = [
417
+ {
418
+ url: FEDERATION_LINK_URL,
419
+ import: ['@key'],
420
+ },
421
+ ];
422
+ // graphql-compose emits StringValue without `block: true`, so printers escape
423
+ // newlines as `\n`. Mark @sql args/selection as block strings for readable """ SDL.
424
+ markSqlDirectiveStringsAsBlocks(schema);
425
+ return schema;
426
+ }
427
+
428
+ async function introspect(
429
+ opts: LoadSqlSubgraphOpts & { adapter: SqlAdapter },
430
+ ): Promise<SqlSchemaMeta> {
431
+ switch (opts.adapter) {
432
+ case 'sqlite': {
433
+ if (!opts.endpoint) {
434
+ throw new Error(`loadSqlSubgraph sqlite requires endpoint (file:… / *.db)`);
435
+ }
436
+ return introspectSqlite({
437
+ db: opts.endpoint,
438
+ cwd: opts.cwd,
439
+ includeTables: opts.includeTables,
440
+ excludeTables: opts.excludeTables,
441
+ });
442
+ }
443
+ case 'mysql': {
444
+ if (!opts.endpoint) {
445
+ throw new Error(`loadSqlSubgraph mysql requires endpoint (mysql://…)`);
446
+ }
447
+ return introspectMysql({
448
+ connectionString: opts.endpoint,
449
+ includeTables: opts.includeTables,
450
+ excludeTables: opts.excludeTables,
451
+ });
452
+ }
453
+ case 'postgres': {
454
+ if (!opts.endpoint) {
455
+ throw new Error(`loadSqlSubgraph postgres requires endpoint (postgres://…)`);
456
+ }
457
+ return introspectPostgres({
458
+ connectionString: opts.endpoint,
459
+ includeTables: opts.includeTables,
460
+ excludeTables: opts.excludeTables,
461
+ });
462
+ }
463
+ default:
464
+ throw new Error(`Unknown SQL adapter: ${(opts as any).adapter}`);
465
+ }
466
+ }
467
+
468
+ /**
469
+ * Fill `endpoint` from Bun-compatible env vars when omitted.
470
+ */
471
+ export function resolveOptsEndpoint(opts: LoadSqlSubgraphOpts): LoadSqlSubgraphOpts {
472
+ if (opts.endpoint) return opts;
473
+ const fromEnv = resolveConnectionStringFromEnv(undefined, { adapter: opts.adapter });
474
+ if (!fromEnv) {
475
+ throw new Error(
476
+ 'loadSqlSubgraph requires endpoint or a Bun-compatible env URL (DATABASE_URL, POSTGRES_URL, MYSQL_URL, SQLITE_URL, …)',
477
+ );
478
+ }
479
+ return { ...opts, endpoint: fromEnv };
480
+ }
481
+
482
+ /**
483
+ * Resolve adapter: explicit `adapter` wins; otherwise Bun-style protocol detection
484
+ * from `endpoint` (or env-resolved endpoint).
485
+ */
486
+ export function resolveAdapter(opts: LoadSqlSubgraphOpts): SqlAdapter {
487
+ if (opts.adapter) return opts.adapter;
488
+ const endpoint = opts.endpoint || resolveConnectionStringFromEnv();
489
+ if (!endpoint) {
490
+ throw new Error('loadSqlSubgraph requires adapter or endpoint (or DATABASE_URL / …)');
491
+ }
492
+ return inferAdapterFromConnectionString(endpoint);
493
+ }
494
+
495
+ function buildTransportOptions(
496
+ opts: LoadSqlSubgraphOpts,
497
+ adapter: SqlAdapter,
498
+ ): SqlTransportOptions {
499
+ const options: SqlTransportOptions = { adapter };
500
+ if (opts.max != null) options.max = opts.max;
501
+ if (opts.idleTimeout != null) options.idleTimeout = opts.idleTimeout;
502
+ if (opts.connectionTimeout != null) options.connectionTimeout = opts.connectionTimeout;
503
+ if (opts.tls != null) options.tls = opts.tls;
504
+ return options;
505
+ }
506
+
507
+ function resolveLocation(opts: LoadSqlSubgraphOpts): string {
508
+ const raw = opts.endpoint;
509
+ if (!raw) {
510
+ throw new Error('SQL loader requires endpoint');
511
+ }
512
+ // Normalize bare sqlite paths to absolute file: URIs for @transport(location).
513
+ try {
514
+ if (inferAdapterFromConnectionString(raw) === 'sqlite') {
515
+ if (raw === ':memory:' || raw.toLowerCase().startsWith('sqlite:')) {
516
+ return raw;
517
+ }
518
+ if (raw.toLowerCase().startsWith('file:')) {
519
+ const cwd = opts.cwd || process.cwd();
520
+ const rest = raw.slice('file:'.length).replace(/^\/\/+/, '/');
521
+ if (pathHelper.isAbsolute(rest) || rest === ':memory:') return raw;
522
+ return `file:${pathHelper.join(cwd, rest)}`;
523
+ }
524
+ const cwd = opts.cwd || process.cwd();
525
+ const abs = pathHelper.isAbsolute(raw) ? raw : pathHelper.join(cwd, raw);
526
+ return `file:${abs}`;
527
+ }
528
+ } catch {
529
+ // non-sqlite / unknown — return as given
530
+ }
531
+ return raw;
532
+ }
533
+
534
+ function applyTableFieldsFilter(
535
+ meta: SqlSchemaMeta,
536
+ tableFields?: Array<{ table: string; fields: string[] }>,
537
+ ): SqlSchemaMeta {
538
+ if (!tableFields?.length) return meta;
539
+ const allow = new Map(tableFields.map(tf => [tf.table, new Set(tf.fields)]));
540
+ return {
541
+ ...meta,
542
+ tables: meta.tables.map(table => {
543
+ const fields = allow.get(table.name);
544
+ if (!fields) return table;
545
+ return {
546
+ ...table,
547
+ columns: table.columns.filter(c => fields.has(c.name) || c.primaryKey),
548
+ };
549
+ }),
550
+ };
551
+ }
552
+
553
+ function ensureSharedFilterInputs(schemaComposer: SchemaComposer) {
554
+ if (!schemaComposer.has('StringFilter')) {
555
+ schemaComposer.createInputTC({
556
+ name: 'StringFilter',
557
+ fields: {
558
+ eq: 'String',
559
+ ne: 'String',
560
+ in: '[String!]',
561
+ nin: '[String!]',
562
+ lt: 'String',
563
+ lte: 'String',
564
+ gt: 'String',
565
+ gte: 'String',
566
+ includes: 'String',
567
+ startsWith: 'String',
568
+ endsWith: 'String',
569
+ isNull: 'Boolean',
570
+ },
571
+ });
572
+ }
573
+ if (!schemaComposer.has('IntFilter')) {
574
+ schemaComposer.createInputTC({
575
+ name: 'IntFilter',
576
+ fields: {
577
+ eq: 'Int',
578
+ ne: 'Int',
579
+ in: '[Int!]',
580
+ nin: '[Int!]',
581
+ lt: 'Int',
582
+ lte: 'Int',
583
+ gt: 'Int',
584
+ gte: 'Int',
585
+ isNull: 'Boolean',
586
+ },
587
+ });
588
+ }
589
+ }
590
+
591
+ function ensurePageInfo(schemaComposer: SchemaComposer) {
592
+ if (!schemaComposer.has('PageInfo')) {
593
+ schemaComposer.createObjectTC({
594
+ name: 'PageInfo',
595
+ fields: {
596
+ hasNextPage: 'Boolean!',
597
+ hasPreviousPage: 'Boolean!',
598
+ startCursor: 'String',
599
+ endCursor: 'String',
600
+ },
601
+ });
602
+ }
603
+ }
604
+
605
+ function createFilterAndOrder(
606
+ schemaComposer: SchemaComposer,
607
+ naming: SqlNaming,
608
+ typeName: string,
609
+ table: SqlTableMeta,
610
+ solePk?: SqlColumnMeta,
611
+ ) {
612
+ const filterFields: Record<string, string> = {
613
+ and: `[${naming.filterInput(typeName)}!]`,
614
+ or: `[${naming.filterInput(typeName)}!]`,
615
+ not: naming.filterInput(typeName),
616
+ };
617
+ const orderValues: Record<string, { value: string }> = {};
618
+
619
+ for (const col of table.columns) {
620
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
621
+ const fieldName = isSolePkCol ? naming.pkFieldName(col.name, true) : naming.fieldName(col.name);
622
+ const gql = mapSqlTypeToGraphQL(col.dataType, { asId: isSolePkCol });
623
+ const filterType =
624
+ gql === GraphQLInt || gql.name === 'Int' || gql.name === 'BigInt'
625
+ ? 'IntFilter'
626
+ : gql === GraphQLBoolean
627
+ ? 'IntFilter'
628
+ : 'StringFilter';
629
+ filterFields[fieldName] = filterType;
630
+ orderValues[naming.orderValue(fieldName, 'ASC')] = {
631
+ value: naming.orderValue(fieldName, 'ASC'),
632
+ };
633
+ orderValues[naming.orderValue(fieldName, 'DESC')] = {
634
+ value: naming.orderValue(fieldName, 'DESC'),
635
+ };
636
+ }
637
+
638
+ schemaComposer.createInputTC({
639
+ name: naming.filterInput(typeName),
640
+ fields: filterFields,
641
+ });
642
+ schemaComposer.createEnumTC({
643
+ name: naming.orderByEnum(typeName),
644
+ values: orderValues,
645
+ });
646
+ }
647
+
648
+ function createConnectionTypes(schemaComposer: SchemaComposer, typeName: string) {
649
+ if (!schemaComposer.has(`${typeName}Edge`)) {
650
+ schemaComposer.createObjectTC({
651
+ name: `${typeName}Edge`,
652
+ fields: {
653
+ cursor: 'String!',
654
+ node: `${typeName}!`,
655
+ },
656
+ });
657
+ }
658
+ if (!schemaComposer.has(`${typeName}Connection`)) {
659
+ schemaComposer.createObjectTC({
660
+ name: `${typeName}Connection`,
661
+ fields: {
662
+ edges: `[${typeName}Edge!]!`,
663
+ pageInfo: 'PageInfo!',
664
+ nodes: `[${typeName}!]!`,
665
+ totalCount: 'Int!',
666
+ },
667
+ });
668
+ }
669
+ }
670
+
671
+ function createMutationInputs(
672
+ schemaComposer: SchemaComposer,
673
+ naming: SqlNaming,
674
+ typeName: string,
675
+ table: SqlTableMeta,
676
+ solePk?: SqlColumnMeta,
677
+ ) {
678
+ const createFields: Record<string, any> = {};
679
+ const updateFields: Record<string, any> = {};
680
+ for (const col of table.columns) {
681
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
682
+ if (isSolePkCol && col.autoIncrement) continue;
683
+ const fieldName = isSolePkCol ? naming.pkFieldName(col.name, true) : naming.fieldName(col.name);
684
+ const gqlType = mapSqlTypeToGraphQL(col.dataType, { asId: isSolePkCol });
685
+ createFields[fieldName] = {
686
+ type: col.notNull && !col.autoIncrement ? new GraphQLNonNull(gqlType) : gqlType,
687
+ };
688
+ updateFields[fieldName] = { type: gqlType };
689
+ }
690
+ schemaComposer.createInputTC({
691
+ name: naming.createInput(typeName),
692
+ fields: createFields,
693
+ });
694
+ schemaComposer.createInputTC({
695
+ name: naming.updateInput(typeName),
696
+ fields: updateFields,
697
+ });
698
+ const singular = naming.singularField(typeName);
699
+ schemaComposer.createObjectTC({
700
+ name: naming.payloadType(typeName),
701
+ fields: {
702
+ [singular]: typeName,
703
+ },
704
+ });
705
+ schemaComposer.createObjectTC({
706
+ name: naming.deletePayloadType(typeName),
707
+ fields: {
708
+ ok: 'Boolean!',
709
+ affectedRows: 'Int!',
710
+ },
711
+ });
712
+ }
713
+
714
+ function markSqlDirectiveStringsAsBlocks(schema: GraphQLSchema): void {
715
+ const markNode = (astNode: { directives?: readonly any[] } | null | undefined) => {
716
+ const directives = astNode?.directives;
717
+ if (!directives) return;
718
+ for (const directive of directives) {
719
+ if (directive.name.value !== 'sql' || !directive.arguments) continue;
720
+ for (const arg of directive.arguments) {
721
+ if (arg.value.kind !== 'StringValue') continue;
722
+ if (
723
+ arg.name.value !== 'where' &&
724
+ arg.name.value !== 'set' &&
725
+ arg.name.value !== 'selection'
726
+ ) {
727
+ continue;
728
+ }
729
+ // Bare binders like `$args.where` stay as normal `"..."` (same as orderBy).
730
+ // Only real mapping blocks get `"""`.
731
+ if (isBareSqlBinder(arg.value.value)) continue;
732
+ (arg.value as { block?: boolean }).block = true;
733
+ }
734
+ }
735
+ };
736
+ for (const type of Object.values(schema.getTypeMap())) {
737
+ if (!(type instanceof GraphQLObjectType)) continue;
738
+ markNode(type.astNode);
739
+ for (const field of Object.values(type.getFields())) {
740
+ markNode(field.astNode);
741
+ }
742
+ }
743
+ }
744
+
745
+ /** `$args.where` / `$this.id` — single path, not a multi-entry mapping block. */
746
+ function isBareSqlBinder(value: string): boolean {
747
+ const trimmed = value.trim();
748
+ // Reject mapping bodies / spreads without a backtracking regex (CodeQL).
749
+ if (
750
+ !trimmed.startsWith('$') ||
751
+ trimmed.includes('\n') ||
752
+ trimmed.includes(':') ||
753
+ trimmed.includes(' ')
754
+ ) {
755
+ return false;
756
+ }
757
+ if (trimmed.includes('...')) return false;
758
+ const segments = trimmed.slice(1).split('.');
759
+ if (!segments.length || segments.some(s => !s)) return false;
760
+ for (const seg of segments) {
761
+ const c0 = seg.charCodeAt(0);
762
+ const okStart = (c0 >= 65 && c0 <= 90) || (c0 >= 97 && c0 <= 122) || c0 === 95; /* A-Z a-z _ */
763
+ if (!okStart) return false;
764
+ for (let i = 1; i < seg.length; i++) {
765
+ const c = seg.charCodeAt(i);
766
+ const ok = (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;
767
+ if (!ok) return false;
768
+ }
769
+ }
770
+ return true;
771
+ }
772
+
773
+ /**
774
+ * Format `@sql` where/set/selection for Connectors-style `"""` block strings.
775
+ * Indent body lines; for single-line values prefix a newline so the printer
776
+ * emits a multiline `"""` block (not `"""value"""`) without a trailing blank.
777
+ */
778
+ function blockArg(body: string): string {
779
+ const trimmed = body.replace(/^\n+|\n+$/g, '');
780
+ const indented = trimmed
781
+ .split('\n')
782
+ .map(line => (line.length ? ` ${line}` : line))
783
+ .join('\n');
784
+ return indented.includes('\n') ? indented : `\n${indented}`;
785
+ }
786
+
787
+ /** Raw column mapping lines (no block wrapping / indent). */
788
+ function selectionLines(naming: SqlNaming, table: SqlTableMeta): string {
789
+ const pkCols = table.columns.filter(c => c.primaryKey);
790
+ const solePk = pkCols.length === 1 ? pkCols[0] : undefined;
791
+ return table.columns
792
+ .map(col => {
793
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
794
+ const fieldName = isSolePkCol
795
+ ? naming.pkFieldName(col.name, true)
796
+ : naming.fieldName(col.name);
797
+ return `${fieldName}: ${col.name}`;
798
+ })
799
+ .join('\n');
800
+ }
801
+
802
+ function selectionBlock(naming: SqlNaming, table: SqlTableMeta): string {
803
+ return blockArg(selectionLines(naming, table));
804
+ }
805
+
806
+ function insertSetBlock(naming: SqlNaming, table: SqlTableMeta, solePk?: SqlColumnMeta): string {
807
+ const lines: string[] = [];
808
+ for (const col of table.columns) {
809
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
810
+ if (isSolePkCol && col.autoIncrement) continue;
811
+ const fieldName = isSolePkCol ? naming.pkFieldName(col.name, true) : naming.fieldName(col.name);
812
+ lines.push(`${col.name}: $args.input.${fieldName}`);
813
+ }
814
+ return blockArg(lines.join('\n'));
815
+ }
816
+
817
+ function updateSetBlock(naming: SqlNaming, table: SqlTableMeta, solePk?: SqlColumnMeta): string {
818
+ const lines: string[] = [];
819
+ for (const col of table.columns) {
820
+ const isSolePkCol = Boolean(solePk && col.name === solePk.name);
821
+ if (isSolePkCol) continue;
822
+ const fieldName = naming.fieldName(col.name);
823
+ lines.push(`${col.name}: $args.input.${fieldName}`);
824
+ }
825
+ return lines.join('\n');
826
+ }
827
+
828
+ function indent(text: string, spaces = 1): string {
829
+ const pad = ' '.repeat(spaces);
830
+ return text
831
+ .split('\n')
832
+ .map(l => (l ? pad + l : l))
833
+ .join('\n');
834
+ }