@stonecrop/graphql-middleware 0.12.8 → 0.13.1

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.
@@ -1,25 +1,41 @@
1
- import { snakeToCamel, toPascalCase } from '@stonecrop/schema';
2
- import { constant, lambda, object, loadOne } from 'postgraphile/grafast';
1
+ import { camelToSnake, pascalToSnake } from '@stonecrop/schema';
2
+ import { loadOneWithPgClient, sideEffectWithPgClient } from '@dataplan/pg';
3
+ import { constant, lambda, object } from 'postgraphile/grafast';
3
4
  import { extendSchema } from 'postgraphile/utils';
4
- import pluralize from 'pluralize';
5
5
  import { getHandler } from '../registry/actions';
6
+ import { getFetchHandler } from '../registry/fetchHandlers';
6
7
  import { getMeta, getAllMeta } from '../registry/doctypes';
7
8
  import { typeDefs } from '../typeDefs';
8
9
  /**
9
- * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality
10
- * @param options - Plugin configuration options
10
+ * Create a PostGraphile plugin that extends the GraphQL schema with Stonecrop functionality.
11
+ *
12
+ * The `PgExecutor` is obtained automatically from `build.input.pgRegistry.pgExecutors`
13
+ * during schema construction — it does not need to be supplied by the caller.
14
+ *
15
+ * @param options - Optional plugin configuration
11
16
  * @returns A PostGraphile plugin
12
17
  * @public
13
18
  */
14
- export const createStonecropPlugin = (options) => {
15
- // Resolve inflection callbacks with Amber defaults
16
- const recordFieldName = options.inflection?.recordFieldName ?? defaultRecordFieldName;
17
- const connectionFieldName = options.inflection?.connectionFieldName ?? defaultConnectionFieldName;
18
- const orderByTypeName = options.inflection?.orderByTypeName ?? defaultOrderByTypeName;
19
- const recordArgName = options.inflection?.recordArgName ?? defaultRecordArgName;
20
- const recordArgType = options.inflection?.recordArgType ?? defaultRecordArgType;
21
- const reverseConnectionName = options.inflection?.reverseConnectionName ?? defaultReverseConnectionName;
22
- return extendSchema(() => {
19
+ export const createStonecropPlugin = (options = {}) => {
20
+ /**
21
+ * SQL debug helper — mirrors PostGraphile's `@dataplan/pg:PgExecutor` logging
22
+ * for queries that run inside custom loadOneWithPgClient callbacks, which
23
+ * bypass the executor's native instrumentation.
24
+ */
25
+ const debugSql = options.debug
26
+ ? (pgClient, query) => {
27
+ // eslint-disable-next-line no-console
28
+ console.log(`[@stonecrop/graphql-middleware] ${query.text}`, query.values ?? []);
29
+ return pgClient.query(query);
30
+ }
31
+ : (pgClient, query) => pgClient.query(query);
32
+ return extendSchema(build => {
33
+ // Obtain the PgExecutor from pgExecutors — one entry exists per configured pgService.
34
+ const pgExecutors = build.input?.pgRegistry?.pgExecutors;
35
+ const executor = pgExecutors ? Object.values(pgExecutors)[0] : undefined;
36
+ if (!executor) {
37
+ throw new Error('StonecropPlugin: no pgExecutors found — ensure pgServices is configured');
38
+ }
23
39
  return {
24
40
  typeDefs,
25
41
  objects: {
@@ -35,78 +51,204 @@ export const createStonecropPlugin = (options) => {
35
51
  return constant(getAllMeta());
36
52
  },
37
53
  stonecropRecord(_, { $doctype, $id, $options }) {
38
- return loadOne(object({ doctype: $doctype, id: $id, options: $options }), async (specs) => {
39
- return await Promise.all(specs.map(async (spec) => {
40
- const meta = getMeta(spec.doctype);
54
+ return loadOneWithPgClient(executor, object({ doctype: $doctype, id: $id, options: $options }), async (pgClient, specs) => {
55
+ // Group specs by doctype to batch the main SELECT per table
56
+ const byDoctype = new Map();
57
+ for (let i = 0; i < specs.length; i++) {
58
+ const d = specs[i].doctype;
59
+ if (!byDoctype.has(d))
60
+ byDoctype.set(d, []);
61
+ byDoctype.get(d).push(i);
62
+ }
63
+ const results = new Array(specs.length);
64
+ for (const [doctype, indices] of byDoctype) {
65
+ const meta = getMeta(doctype);
41
66
  if (!meta) {
42
- throw new Error(`Unknown doctype: ${spec.doctype}`);
67
+ for (const i of indices)
68
+ results[i] = { data: null, doctype };
69
+ continue;
43
70
  }
44
- if (!meta.tableName) {
45
- throw new Error(`Doctype ${spec.doctype} has no table mapping`);
71
+ const pkMeta = getPkMeta(meta);
72
+ if (!pkMeta) {
73
+ for (const i of indices)
74
+ results[i] = { data: null, doctype };
75
+ continue;
46
76
  }
47
- const recordOptions = spec.options ?? {};
48
- const query = buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType, getMeta, recordOptions.includeNested
49
- ? {
50
- includeNested: recordOptions.includeNested,
51
- maxDepth: recordOptions.maxDepth,
52
- }
53
- : undefined, reverseConnectionName);
54
- const result = await options.executor.query(query, {
55
- [recordArgName(meta.tableName)]: spec.id,
77
+ const pkColumn = camelToSnake(pkMeta.fieldname);
78
+ const columns = getSqlColumns(meta);
79
+ const ids = indices.map(i => specs[i].id);
80
+ const { rows } = await debugSql(pgClient, {
81
+ text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
82
+ values: [ids],
56
83
  });
57
- let data = extractSingleResult({ result, meta, recordFieldName });
58
- if (recordOptions.includeNested && data && meta.links) {
59
- data = mergeNestedResults({
60
- record: data,
61
- meta,
62
- getMeta,
63
- reverseConnectionNameFn: reverseConnectionName,
64
- });
84
+ // Use String() so integer PKs (e.g. serial) match the string ids from GraphQL
85
+ const rowByPk = new Map(rows.map(r => [String(r[pkMeta.fieldname]), r]));
86
+ for (const i of indices) {
87
+ const specId = specs[i].id;
88
+ const row = rowByPk.get(specId);
89
+ if (!row) {
90
+ results[i] = { data: null, doctype };
91
+ continue;
92
+ }
93
+ const rowData = { ...row };
94
+ const recordOptions = (specs[i].options ?? {});
95
+ const includeAll = recordOptions.includeNested === true;
96
+ const includeSet = Array.isArray(recordOptions.includeNested)
97
+ ? new Set(recordOptions.includeNested)
98
+ : null;
99
+ // FetchStrategy dispatch over link declarations
100
+ if (meta.links) {
101
+ for (const [linkName, link] of Object.entries(meta.links)) {
102
+ const fetch = link.fetch;
103
+ const isMany = link.cardinality === 'noneOrMany' || link.cardinality === 'atLeastOne';
104
+ const effectiveMethod = fetch?.method ?? (isMany ? 'sync' : 'lazy');
105
+ const effectiveLimit = fetch?.method === 'sync' ? fetch.limit : isMany ? 50 : undefined;
106
+ const shouldInclude = includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === 'sync');
107
+ if (!shouldInclude)
108
+ continue;
109
+ if (effectiveMethod === 'custom') {
110
+ const handlerName = fetch.handler;
111
+ const handler = getFetchHandler(handlerName);
112
+ if (handler) {
113
+ rowData[linkName] = await handler(pgClient, rowData, link);
114
+ }
115
+ continue;
116
+ }
117
+ if (effectiveMethod !== 'sync' && !includeSet?.has(linkName))
118
+ continue;
119
+ const targetMeta = getMeta(link.target);
120
+ if (!targetMeta)
121
+ continue;
122
+ const targetColumns = getSqlColumns(targetMeta);
123
+ if (isMany) {
124
+ if (!link.backlink)
125
+ continue;
126
+ const backlinkCol = camelToSnake(link.backlink);
127
+ let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
128
+ const linkValues = [specId];
129
+ if (effectiveLimit != null) {
130
+ sql += ` LIMIT $2`;
131
+ linkValues.push(effectiveLimit);
132
+ }
133
+ const { rows: linked } = await debugSql(pgClient, {
134
+ text: sql,
135
+ values: linkValues,
136
+ });
137
+ rowData[linkName] = linked;
138
+ }
139
+ else {
140
+ if (!link.fieldname)
141
+ continue;
142
+ const fkValue = rowData[link.fieldname];
143
+ if (fkValue == null) {
144
+ rowData[linkName] = null;
145
+ continue;
146
+ }
147
+ const targetPkMeta = getPkMeta(targetMeta);
148
+ if (!targetPkMeta)
149
+ continue;
150
+ const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
151
+ const { rows: linked } = await debugSql(pgClient, {
152
+ text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
153
+ values: [fkValue],
154
+ });
155
+ rowData[linkName] = linked[0] ?? null;
156
+ }
157
+ }
158
+ }
159
+ // Names in includeNested that don't correspond to any link
160
+ const unknownLinks = includeSet && meta.links ? [...includeSet].filter(name => !(name in meta.links)) : undefined;
161
+ results[i] = {
162
+ data: rowData,
163
+ doctype,
164
+ unknownLinks: unknownLinks?.length ? unknownLinks : undefined,
165
+ };
65
166
  }
66
- const unknownLinks = Array.isArray(recordOptions.includeNested) && meta.links
67
- ? recordOptions.includeNested.filter((name) => !(name in meta.links))
68
- : undefined;
69
- return {
70
- data,
71
- doctype: spec.doctype,
72
- ...(unknownLinks ? { unknownLinks } : {}),
73
- };
74
- }));
167
+ }
168
+ return results;
75
169
  });
76
170
  },
77
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $options }) {
78
- return loadOne(object({
171
+ stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset }) {
172
+ return loadOneWithPgClient(executor, object({
79
173
  doctype: $doctype,
80
174
  filters: $filters,
81
175
  orderBy: $orderBy,
82
176
  limit: $limit,
83
177
  offset: $offset,
84
- options: $options,
85
- }), async (specs) => {
178
+ }), async (pgClient, specs) => {
86
179
  return await Promise.all(specs.map(async (spec) => {
87
180
  const meta = getMeta(spec.doctype);
88
181
  if (!meta) {
89
- throw new Error(`Unknown doctype: ${spec.doctype}`);
182
+ return { data: [], doctype: spec.doctype, count: 0 };
90
183
  }
91
- if (!meta.tableName) {
92
- throw new Error(`Doctype ${spec.doctype} has no table mapping`);
184
+ const knownFields = new Set(meta.fields.map(f => f.fieldname));
185
+ const columns = getSqlColumns(meta);
186
+ const values = [];
187
+ // WHERE from filters (parameterised — safe against SQL injection)
188
+ const whereClauses = [];
189
+ if (spec.filters != null) {
190
+ for (const [field, value] of Object.entries(spec.filters)) {
191
+ if (!knownFields.has(field)) {
192
+ throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
193
+ }
194
+ values.push(value);
195
+ whereClauses.push(`"${camelToSnake(field)}" = $${values.length}`);
196
+ }
93
197
  }
94
- const query = buildListQuery(meta, {
95
- limit: spec.limit,
96
- offset: spec.offset,
97
- orderBy: spec.orderBy,
98
- }, connectionFieldName, orderByTypeName);
99
- const result = await options.executor.query(query, {
100
- limit: spec.limit,
101
- offset: spec.offset,
102
- orderBy: spec.orderBy,
198
+ const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(' AND ')}` : '';
199
+ // ORDER BY (field name whitelisted — column names cannot be parameterised)
200
+ let orderByClause = '';
201
+ if (spec.orderBy != null) {
202
+ const orderByStr = spec.orderBy;
203
+ const lastUnder = orderByStr.lastIndexOf('_');
204
+ if (lastUnder <= 0) {
205
+ throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
206
+ }
207
+ const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
208
+ if (dir !== 'ASC' && dir !== 'DESC') {
209
+ throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
210
+ }
211
+ const fieldName = orderByStr.slice(0, lastUnder);
212
+ if (!knownFields.has(fieldName)) {
213
+ throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
214
+ }
215
+ orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
216
+ }
217
+ // LIMIT / OFFSET
218
+ let pagingClause = '';
219
+ if (spec.limit != null) {
220
+ values.push(spec.limit);
221
+ pagingClause += ` LIMIT $${values.length}`;
222
+ }
223
+ if (spec.offset != null) {
224
+ values.push(spec.offset);
225
+ pagingClause += ` OFFSET $${values.length}`;
226
+ }
227
+ const { rows } = await debugSql(pgClient, {
228
+ text: `SELECT ${columns} FROM ${resolveTableName(meta.name, options.tables)}${whereClause}${orderByClause}${pagingClause}`,
229
+ values,
103
230
  });
104
- const data = extractListResult({ result, meta, connectionFieldName });
105
- return {
106
- data,
107
- doctype: spec.doctype,
108
- count: data.length,
109
- };
231
+ // Total count matching filters (independent of LIMIT/OFFSET)
232
+ let count = rows.length;
233
+ if (spec.limit != null || spec.offset != null) {
234
+ const countValues = [];
235
+ const countWhere = [];
236
+ if (spec.filters != null) {
237
+ for (const [field, value] of Object.entries(spec.filters)) {
238
+ if (!knownFields.has(field))
239
+ continue;
240
+ countValues.push(value);
241
+ countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
242
+ }
243
+ }
244
+ const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(' AND ')}` : '';
245
+ const { rows: countRows } = await debugSql(pgClient, {
246
+ text: `SELECT COUNT(*) AS __count FROM ${resolveTableName(meta.name, options.tables)}${countWhereClause}`,
247
+ values: countValues,
248
+ });
249
+ count = parseInt(countRows[0]?.__count ?? '0', 10);
250
+ }
251
+ return { data: rows, doctype: spec.doctype, count };
110
252
  }));
111
253
  });
112
254
  },
@@ -115,57 +257,43 @@ export const createStonecropPlugin = (options) => {
115
257
  Mutation: {
116
258
  plans: {
117
259
  stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
118
- return loadOne(object({
119
- doctype: $doctype,
120
- action: $action,
121
- actionArgs: $actionArgs,
122
- }), async (specs) => {
123
- return await Promise.all(specs.map(async (spec) => {
124
- const meta = getMeta(spec.doctype);
125
- if (!meta) {
126
- return {
127
- success: false,
128
- data: null,
129
- error: `Unknown doctype: ${spec.doctype}`,
130
- };
131
- }
132
- const actionDef = meta.workflow?.actions?.[spec.action];
133
- if (!actionDef) {
134
- return {
135
- success: false,
136
- data: null,
137
- error: `Unknown action: ${spec.action} on ${spec.doctype}`,
138
- };
139
- }
140
- const handlerName = actionDef.handler;
141
- const handler = getHandler(handlerName);
142
- if (!handler) {
143
- return {
144
- success: false,
145
- data: null,
146
- error: `Handler not registered: ${handlerName}`,
147
- };
148
- }
149
- const actionContext = {
150
- doctype: meta,
151
- executor: options.executor,
260
+ return sideEffectWithPgClient(executor, object({ doctype: $doctype, action: $action, actionArgs: $actionArgs }), async (pgClient, spec) => {
261
+ const meta = getMeta(spec.doctype);
262
+ if (!meta) {
263
+ return {
264
+ success: false,
265
+ data: null,
266
+ error: `Unknown doctype: ${spec.doctype}`,
152
267
  };
153
- try {
154
- const result = await handler(spec.actionArgs ?? [], actionContext);
155
- return {
156
- success: true,
157
- data: result,
158
- error: null,
159
- };
160
- }
161
- catch (err) {
162
- return {
163
- success: false,
164
- data: null,
165
- error: err instanceof Error ? err.message : String(err),
166
- };
167
- }
168
- }));
268
+ }
269
+ const actionDef = meta.workflow?.actions?.[spec.action];
270
+ if (!actionDef) {
271
+ return {
272
+ success: false,
273
+ data: null,
274
+ error: `Unknown action: ${spec.action} on ${spec.doctype}`,
275
+ };
276
+ }
277
+ const handler = getHandler(actionDef.handler);
278
+ if (!handler) {
279
+ return {
280
+ success: false,
281
+ data: null,
282
+ error: `Handler not registered: ${actionDef.handler}`,
283
+ };
284
+ }
285
+ const actionContext = { doctype: meta, pgClient };
286
+ try {
287
+ const result = await handler(spec.actionArgs ?? [], actionContext);
288
+ return { success: true, data: result, error: null };
289
+ }
290
+ catch (err) {
291
+ return {
292
+ success: false,
293
+ data: null,
294
+ error: err instanceof Error ? err.message : String(err),
295
+ };
296
+ }
169
297
  });
170
298
  },
171
299
  },
@@ -174,351 +302,56 @@ export const createStonecropPlugin = (options) => {
174
302
  };
175
303
  });
176
304
  };
177
- // =============================================================================
178
- // Inflection helpers — default to PostGraphile Amber preset conventions
179
- // Uses `pluralize` for proper English singularization (handles irregular
180
- // plurals like statuses→status, categories→category, addresses→address).
181
- // snakeToCamel / toPascalCase are imported from @stonecrop/schema.
182
- // =============================================================================
183
- /**
184
- * Amber default: sales_orders → salesOrderById
185
- * Uses `pluralize` for proper singularization of irregular plurals.
186
- * Override via `StonecropInflectionConfig.recordFieldName` for non-standard PK columns.
187
- * @public
188
- */
189
- function defaultRecordFieldName(tableName) {
190
- const singular = pluralize.singular(tableName);
191
- return `${snakeToCamel(singular)}ById`;
192
- }
193
- /**
194
- * Amber default: sales_orders → allSalesOrders
195
- * @public
196
- */
197
- function defaultConnectionFieldName(tableName) {
198
- return `all${toPascalCase(tableName)}`;
199
- }
200
- /**
201
- * Amber default: sales_orders → SalesOrdersOrderBy
202
- * @public
203
- */
204
- function defaultOrderByTypeName(tableName) {
205
- return `${toPascalCase(tableName)}OrderBy`;
206
- }
207
- /**
208
- * Default PK argument name: 'id' (standard Relay Global ID pattern).
209
- * Override via `StonecropInflectionConfig.recordArgName` when using row_id columns;
210
- * PostGraphile Amber generates `rowId: UUID!` for those fields.
211
- * @public
212
- */
213
- function defaultRecordArgName(_tableName) {
214
- return 'id';
215
- }
216
- /**
217
- * Default PK argument type: 'UUID!' (PostGraphile Amber default for UUID PKs).
218
- * Override via `StonecropInflectionConfig.recordArgType` when using non-UUID PKs
219
- * such as integer serials or Relay Global IDs ('ID!').
220
- * @public
221
- */
222
- function defaultRecordArgType(_tableName) {
223
- return 'UUID!';
224
- }
225
- /**
226
- * Default reverse connection name: derives PostGraphile's connection field convention.
227
- * PostGraphile convention: `{targetPlural}By{FkColumnPascal}Id`
228
- * - When backlink is defined: FK column is derived from the backlink field name
229
- * - When backlink is absent: FK column is derived from the parent doctype's table name
230
- * @public
231
- */
232
- function defaultReverseConnectionName(params) {
233
- const targetPlural = pluralize.plural(params.target.replace(/-/g, '_'));
234
- // Use camelCase for target (matches PostGraphile Amber convention: recipeTasksByRecipeId)
235
- const targetCamel = snakeToCamel(targetPlural);
236
- // Use backlink if provided, otherwise derive from parent table name
237
- const fkSource = params.backlink || params.doctype;
238
- // FK column name: uppercase first char, preserve rest of camelCase
239
- const fkPascal = fkSource.charAt(0).toUpperCase() + snakeToCamel(fkSource).slice(1);
240
- return `${targetCamel}By${fkPascal}Id`;
241
- }
242
- /**
243
- * Check if a cardinality represents a "many" relationship
244
- */
245
- function isManyCardinality(cardinality) {
246
- return cardinality === 'noneOrMany' || cardinality === 'atLeastOne';
247
- }
248
- // =============================================================================
249
- // Query builders — generate GraphQL queries to send to the underlying schema
250
- // =============================================================================
251
- const DEFAULT_SYNC_LIMIT = 50;
305
+ // ===========================================================================
306
+ // SQL column helpers
307
+ // ===========================================================================
252
308
  /**
253
- * Fieldtypes unconditionally excluded from the generated scalar query selection set.
254
- * - `'Display'`: display-only composite component with no backing DB column
255
- *
256
- * Note: `'Link'` fields are NOT blanket-excluded here. Scalar FK UUID columns use
257
- * `fieldtype: 'Link'` and ARE queryable. Only Link fields that also appear in the
258
- * doctype's `links` declaration (i.e. those that resolve to a sub-object or connection)
259
- * are excluded — that logic lives in `queryableFieldNames`.
260
- * @public
261
- */
262
- const RELATION_FIELDTYPES = new Set(['Display']);
263
- /**
264
- * Filter fields to only those directly queryable as scalars.
309
+ * Derive a quoted SQL column list from doctype field definitions.
310
+ * Applies camelToSnake to each fieldname to get the DB column name, then
311
+ * aliases it back to the fieldname so result rows carry API-layer keys.
265
312
  * Excludes Display fields (no backing DB column) and Link fields that have an
266
- * explicit `links` declaration (those require sub-selection, not scalar reads).
267
- * Link fields without a `links` declaration are scalar FK UUID columns and ARE included.
268
- * @public
313
+ * explicit `links` declaration (those are FK references, not scalar columns).
314
+ *
315
+ * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
269
316
  */
270
- function queryableFieldNames(meta) {
317
+ function getSqlColumns(meta) {
271
318
  const linkedFieldnames = new Set();
272
319
  if (meta.links) {
273
320
  for (const [key, link] of Object.entries(meta.links)) {
274
321
  linkedFieldnames.add(link.fieldname ?? key);
275
322
  }
276
323
  }
277
- return meta.fields
278
- .filter(f => {
279
- if (RELATION_FIELDTYPES.has(f.fieldtype))
280
- return false;
281
- if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
282
- return false;
283
- return true;
284
- })
285
- .map(f => f.fieldname)
286
- .join('\n ');
287
- }
288
- /**
289
- * Get the effective fetch strategy for a link, applying cardinality-based defaults.
290
- */
291
- function getEffectiveFetchStrategy(link) {
292
- if (link.fetch !== undefined) {
293
- return link.fetch;
294
- }
295
- if (isManyCardinality(link.cardinality)) {
296
- return { method: 'sync', limit: DEFAULT_SYNC_LIMIT };
297
- }
298
- else {
299
- return { method: 'lazy' };
300
- }
301
- }
302
- /**
303
- * Get the effective blockWorkflows value for a link.
304
- */
305
- function getEffectiveBlockWorkflows(link) {
306
- if (link.blockWorkflows !== undefined) {
307
- return link.blockWorkflows;
308
- }
309
- const effectiveFetch = getEffectiveFetchStrategy(link);
310
- return effectiveFetch.method === 'sync';
311
- }
312
- /**
313
- * Build nested sub-selections for descendant links
314
- */
315
- function buildNestedSelections(params) {
316
- const { links, meta, includeSet, getMeta, seen, depth, maxDepth, reverseConnectionNameFn } = params;
317
- if (maxDepth !== undefined && depth >= maxDepth)
318
- return '';
319
- const selections = [];
320
- for (const [fieldname, link] of Object.entries(links)) {
321
- if (maxDepth !== undefined && depth >= maxDepth)
322
- break;
323
- const effectiveBlockWorkflows = getEffectiveBlockWorkflows(link);
324
- const linkBlockWorkflowsExplicitTrue = link.blockWorkflows === true;
325
- if (includeSet && !includeSet.has(fieldname) && !linkBlockWorkflowsExplicitTrue) {
326
- continue;
327
- }
328
- const effectiveFetch = getEffectiveFetchStrategy(link);
329
- const shouldSkip = effectiveBlockWorkflows === false || (effectiveFetch.method !== 'sync' && !linkBlockWorkflowsExplicitTrue);
330
- if (shouldSkip) {
324
+ const columns = [];
325
+ for (const f of meta.fields) {
326
+ if (f.fieldtype === 'Display')
331
327
  continue;
332
- }
333
- const targetMeta = getMeta(link.target);
334
- if (!targetMeta)
328
+ if (f.fieldtype === 'Link' && linkedFieldnames.has(f.fieldname))
335
329
  continue;
336
- const alreadySeen = seen.has(link.target);
337
- if (!alreadySeen) {
338
- seen.add(link.target);
339
- }
340
- const scalarFields = queryableFieldNames(targetMeta);
341
- let nestedLinks = '';
342
- if (!alreadySeen && targetMeta.links && targetMeta.tableName && (maxDepth === undefined || depth + 1 < maxDepth)) {
343
- const innerSelections = buildNestedSelections({
344
- links: targetMeta.links,
345
- meta: targetMeta,
346
- includeSet: null,
347
- getMeta,
348
- seen,
349
- depth: depth + 1,
350
- maxDepth,
351
- reverseConnectionNameFn,
352
- });
353
- if (innerSelections) {
354
- nestedLinks = '\n ' + innerSelections;
355
- }
356
- seen.delete(link.target);
357
- }
358
- const fullSelection = scalarFields + nestedLinks;
359
- if (isManyCardinality(link.cardinality)) {
360
- const reverseParams = {
361
- doctype: meta.slug || meta.name,
362
- linkName: fieldname,
363
- backlink: link.backlink,
364
- target: link.target,
365
- };
366
- const connectionField = reverseConnectionNameFn
367
- ? reverseConnectionNameFn(reverseParams)
368
- : defaultReverseConnectionName(reverseParams);
369
- const limitArg = effectiveFetch.method === 'sync' && effectiveFetch.limit !== undefined
370
- ? `first: ${effectiveFetch.limit}`
371
- : effectiveFetch.method === 'sync'
372
- ? `first: ${DEFAULT_SYNC_LIMIT}`
373
- : '';
374
- selections.push(`
375
- ${connectionField}${limitArg ? `(${limitArg})` : ''} {
376
- nodes {
377
- ${fullSelection}
378
- }
379
- }`);
380
- }
381
- else {
382
- selections.push(`
383
- ${fieldname} {
384
- ${fullSelection}
385
- }`);
386
- }
387
- }
388
- return selections.join('');
389
- }
390
- /**
391
- * Build a GraphQL query to fetch a single record by ID.
392
- * When includeNested is set, recursively includes descendant link sub-selections.
393
- * @public
394
- */
395
- function buildRecordQuery(meta, recordFieldName, recordArgName, recordArgType, getMeta, options, reverseConnectionNameFn) {
396
- const queryName = recordFieldName(meta.tableName);
397
- const argName = recordArgName(meta.tableName);
398
- const argType = recordArgType(meta.tableName);
399
- const seen = new Set([meta.slug || meta.name]);
400
- let selection = queryableFieldNames(meta);
401
- if (options?.includeNested && meta.links) {
402
- const includeSet = Array.isArray(options.includeNested) ? new Set(options.includeNested) : null;
403
- const nestedSelections = buildNestedSelections({
404
- links: meta.links,
405
- meta,
406
- includeSet,
407
- getMeta,
408
- seen,
409
- depth: 0,
410
- maxDepth: options.maxDepth,
411
- reverseConnectionNameFn,
412
- });
413
- if (nestedSelections) {
414
- selection += '\n ' + nestedSelections;
415
- }
330
+ const col = camelToSnake(f.fieldname);
331
+ columns.push(col !== f.fieldname ? `"${col}" AS "${f.fieldname}"` : `"${f.fieldname}"`);
416
332
  }
417
- return `
418
- query GetRecord($${argName}: ${argType}) {
419
- ${queryName}(${argName}: $${argName}) {
420
- ${selection}
421
- }
422
- }
423
- `;
333
+ return columns.join(', ');
424
334
  }
425
335
  /**
426
- * Build a GraphQL connection query to fetch a list of records.
427
- * Only declares variables ($limit, $offset, $orderBy) that are actually used in the query,
428
- * avoiding GraphQL spec §5.8.3 violations from unused variable declarations.
429
- * Excludes Link relation fields and Display fields from the selection set.
430
- * @public
336
+ * Find the field declared with fieldtype 'PrimaryKey' in the doctype.
337
+ * Returns undefined when no PrimaryKey field is declared (PK-less doctypes).
338
+ *
339
+ * TODO(schema-types Phase 4): add f.kind === 'field' narrowing when DoctypeField union lands
431
340
  */
432
- function buildListQuery(meta, args, connectionFieldName, orderByTypeName) {
433
- const fieldNames = queryableFieldNames(meta);
434
- const connectionName = connectionFieldName(meta.tableName);
435
- const orderByType = orderByTypeName(meta.tableName);
436
- const varDecls = [];
437
- const queryArgs = [];
438
- if (args.limit) {
439
- varDecls.push('$limit: Int');
440
- queryArgs.push(`first: $limit`);
441
- }
442
- if (args.offset) {
443
- varDecls.push('$offset: Int');
444
- queryArgs.push(`offset: $offset`);
445
- }
446
- if (args.orderBy) {
447
- varDecls.push(`$orderBy: [${orderByType}!]`);
448
- queryArgs.push(`orderBy: $orderBy`);
449
- }
450
- const varStr = varDecls.length > 0 ? `(${varDecls.join(', ')})` : '';
451
- const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(', ')})` : '';
452
- return `
453
- query GetRecords${varStr} {
454
- ${connectionName}${argsStr} {
455
- nodes {
456
- ${fieldNames}
457
- }
458
- }
459
- }
460
- `;
341
+ function getPkMeta(meta) {
342
+ return meta.fields.find(f => f.fieldtype === 'PrimaryKey');
461
343
  }
462
344
  /**
463
- * Merge nested connection results into flat arrays.
464
- * For `noneOrMany`/`atLeastOne` links, the query returns `{ nodes: [...] }`.
465
- * This flattens them to just `[]` for easier consumption.
466
- * @public
345
+ * Resolve the PostgreSQL FROM clause target for a doctype.
346
+ * Uses the `tables` override map first; falls back to camelToSnake(name).
347
+ * Schema-qualified names (e.g. "orpin.plan") are emitted as "schema"."table".
348
+ * Values must be bare identifiers or schema.table pairs — not SQL fragments.
467
349
  */
468
- function mergeNestedResults(params) {
469
- const { record, meta, getMeta, reverseConnectionNameFn } = params;
470
- if (!meta.links)
471
- return record;
472
- const merged = { ...record };
473
- for (const [fieldname, link] of Object.entries(meta.links)) {
474
- const isMany = isManyCardinality(link.cardinality);
475
- if (isMany) {
476
- const targetMeta = getMeta(link.target);
477
- if (!targetMeta)
478
- continue;
479
- const reverseParams = {
480
- doctype: meta.slug || meta.name,
481
- linkName: fieldname,
482
- backlink: link.backlink || fieldname,
483
- target: link.target,
484
- };
485
- const connectionField = reverseConnectionNameFn
486
- ? reverseConnectionNameFn(reverseParams)
487
- : defaultReverseConnectionName(reverseParams);
488
- const connectionResult = merged[connectionField];
489
- if (connectionResult?.nodes) {
490
- merged[fieldname] = connectionResult.nodes;
491
- delete merged[connectionField];
492
- }
493
- else {
494
- merged[fieldname] = [];
495
- delete merged[connectionField];
496
- }
497
- }
350
+ function resolveTableName(name, tables) {
351
+ const target = tables?.[name] ?? pascalToSnake(name);
352
+ const dotIndex = target.indexOf('.');
353
+ if (dotIndex > 0) {
354
+ return `"${target.slice(0, dotIndex)}"."${target.slice(dotIndex + 1)}"`;
498
355
  }
499
- return merged;
500
- }
501
- /**
502
- * Extract a single record from a PostGraphile query result using the record field name.
503
- * @public
504
- */
505
- function extractSingleResult(params) {
506
- const { result, meta, recordFieldName } = params;
507
- const queryName = recordFieldName(meta.tableName);
508
- return result[queryName];
509
- }
510
- /**
511
- * Extract the list of nodes from a PostGraphile connection query result.
512
- * Returns an empty array if the connection field is absent.
513
- * @public
514
- */
515
- function extractListResult(params) {
516
- const { result, meta, connectionFieldName } = params;
517
- const connectionName = connectionFieldName(meta.tableName);
518
- const connection = result[connectionName];
519
- return connection?.nodes ?? [];
356
+ return `"${target}"`;
520
357
  }
521
- // =============================================================================
522
- // Exported for testing and advanced usage
523
- // =============================================================================
524
- export { defaultRecordFieldName, defaultConnectionFieldName, defaultOrderByTypeName, defaultRecordArgName, defaultRecordArgType, defaultReverseConnectionName, buildRecordQuery, buildListQuery, queryableFieldNames, RELATION_FIELDTYPES, extractSingleResult, extractListResult, mergeNestedResults, };