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