@stonecrop/graphql-middleware 0.24.0 → 0.26.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.
@@ -76,7 +76,9 @@ export interface StonecropPluginOptions {
76
76
  * Override the PostgreSQL FROM clause target for specific doctypes, keyed by doctype name.
77
77
  * Values may be a bare table name (`'plan'`) or a schema-qualified name (`'orpin.plan'`).
78
78
  * SQL fragments and subqueries are not supported.
79
- * When absent for a doctype, the table name is derived as `camelToSnake(doctype.name)`.
79
+ * When absent for a doctype, the table name is derived as `pascalToSnake(doctype.name)`, so
80
+ * `SalesOrder` becomes `sales_order`. (Not `camelToSnake`, which prefixes a leading underscore on a
81
+ * PascalCase name: `camelToSnake('User')` is `_user`.)
80
82
  */
81
83
  tables?: Record<string, string>;
82
84
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"postgraphile.d.ts","sourceRoot":"","sources":["../../../src/plugin/postgraphile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,WAAW,EAAiD,MAAM,mBAAmB,CAAA;AAGjH,OAAO,KAAK,EAAE,QAAQ,EAAc,MAAM,cAAc,CAAA;AAExD,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AAW5D;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACpC;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,EAAE,QAAQ,CAAA;IAClB,4EAA4E;IAC5E,OAAO,EAAE,MAAM,CAAA;IACf,iGAAiG;IACjG,MAAM,EAAE,MAAM,CAAA;IACd,yFAAyF;IACzF,IAAI,EAAE,WAAW,CAAA;IACjB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IAC1B;;;;;;OAMG;IACH,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,wFAAwF;IACxF,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,kGAAkG;IAClG,Y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zF,IAAI,EAAE,WAAW,CAAA;IACjB,8GAA8G;IAC9G,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IAC1B;;;;;;OAMG;IACH,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC7B,wFAAwF;IACxF,IAAI,EAAE,OAAO,EAAE,CAAA;IACf,kGAAkG;IAClG,YAAY,CAAC,EAAE,MAAM,CAAA;CACrB;AAED;;;;;;;;;;GAUG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;AAE/E;;;GAGG;AACH,MAAM,WAAW,sBAAsB;IACtC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAA;IACf;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoCG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,CAAA;IAC9D;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAClC;AAmCD;;;;;;;;;GASG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAS,sBAA2B,KAAG,cAAc,CAAC,MAwsB3F,CAAA;AA0BD;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM,CAQvD;AAkID;;;;;GAKG"}
@@ -250,6 +250,15 @@ export const createStonecropPlugin = (options = {}) => {
250
250
  const backlinkCol = camelToSnake(link.backlink);
251
251
  let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
252
252
  const linkValues = [specId];
253
+ // Same reason the list path orders: a capped relation without a fixed order
254
+ // returns an arbitrary subset of the children, and a different one each time
255
+ // a child row is updated. `truncatedLinks` says the tail was cut; it cannot
256
+ // say the head kept changing. Skipped when the target declares no identity —
257
+ // there is no stable key to order by, and inventing one would be a guess.
258
+ const linkPkMeta = getPkMeta(targetMeta);
259
+ if (linkPkMeta) {
260
+ sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
261
+ }
253
262
  if (effectiveLimit != null) {
254
263
  // One row more than the cap, same probe the list path uses: its presence
255
264
  // is the whole truncation answer and costs no second query.
@@ -378,6 +387,22 @@ export const createStonecropPlugin = (options = {}) => {
378
387
  }
379
388
  orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
380
389
  }
390
+ // A page is only meaningful against a fixed order, and LIMIT/OFFSET without one
391
+ // is two independent scans of heap order — an UPDATE between them moves that row
392
+ // to the tail, so the row it displaced is never returned and nothing in the
393
+ // payload says a record was skipped. The declared identity is the right default
394
+ // because it is unique: it gives a total order, which is what makes page 2 start
395
+ // exactly where page 1 stopped.
396
+ //
397
+ // Only when the doctype declares an identity. Without one there is no stable key
398
+ // to order by, and inventing one here would be a guess; such a doctype cannot be
399
+ // paged stably by any means.
400
+ if (orderByClause === '') {
401
+ const listPkMeta = getPkMeta(meta);
402
+ if (listPkMeta) {
403
+ orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
404
+ }
405
+ }
381
406
  // LIMIT / OFFSET. A caller that names no limit gets the configured default rather
382
407
  // than the whole table: omission is how an unbounded scan used to happen, and the
383
408
  // only guard against it lived in the scaffold's fetch helper, which is neither the
@@ -724,14 +749,19 @@ export function getSqlColumns(meta) {
724
749
  * client and refused outright by this adapter, so every fetch answered `null` and looked exactly
725
750
  * like a record that does not exist.
726
751
  *
727
- * Returns `undefined` only when the resolved name is not a declared top-level field — a doctype
728
- * with no `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared
729
- * fields only, so the row map would key on a column the SELECT never returned and every lookup
730
- * would miss silently. Callers must say so rather than answer `null`.
752
+ * Returns `undefined` only when the resolved name is not a declared field — a doctype with no
753
+ * `primaryKey` and no `id`. That case cannot be served: `getSqlColumns` selects declared fields
754
+ * only, so the row map would key on a column the SELECT never returned and every lookup would miss
755
+ * silently. Callers must say so rather than answer `null`.
756
+ *
757
+ * Descends into fieldsets, because both halves of the question already do — `getSqlColumns` selects
758
+ * a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this
759
+ * scanned top level only it could refuse a name that helper had just resolved, so a doctype whose
760
+ * SELECT carried its own key column had no identity to look that column up by.
731
761
  */
732
762
  function getPkMeta(meta) {
733
763
  const fieldname = getRecordIdField(meta.fields);
734
- return meta.fields.find((f) => f.kind === 'field' && f.fieldname === fieldname);
764
+ return flattenFields(meta.fields).find((f) => f.kind === 'field' && f.fieldname === fieldname);
735
765
  }
736
766
  /**
737
767
  * Assert that every registered action handler names a doctype and an action that exist.
@@ -1 +1 @@
1
- {"version":3,"file":"preset.d.ts","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,QAAQ,CAAA;AAc5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAU;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,KAAG,cAAc,CAAC,MAG7F,CAAA;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,eAAe,EAAE,cAAc,CAAC,MAAgC,CAAA"}
1
+ {"version":3,"file":"preset.d.ts","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,MAAM,MAAM,WAAW,GAAG,OAAO,GAAG,QAAQ,CAAA;AA4G5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,qBAAqB,GAAI,UAAU;IAAE,WAAW,CAAC,EAAE,WAAW,CAAA;CAAE,KAAG,cAAc,CAAC,MAM7F,CAAA;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,eAAe,EAAE,cAAc,CAAC,MAAgC,CAAA"}
@@ -1,4 +1,96 @@
1
1
  import { PostGraphileAmberPreset } from 'postgraphile/presets/amber';
2
+ /**
3
+ * Stops Amber taking `id` for Relay's global object identifier.
4
+ *
5
+ * Amber points `nodeIdFieldName` at `id`, so `PgAttributesPlugin` renames any real column called
6
+ * `id` out of the way to `row_id` -> `rowId`. Stonecrop can use neither name: the middleware
7
+ * resolves columns with raw SQL through `camelToSnake` and never reads the GraphQL surface, so `id`
8
+ * is an opaque base64 node id with no column behind it, and `rowId` names a `row_id` that does not
9
+ * exist. A doctype generated from the un-overridden schema is stamped `primaryKey: true` on that
10
+ * node id and every read of it then fails on a missing column.
11
+ *
12
+ * Both inflectors must move together. Undoing the rename alone collides with the Relay field still
13
+ * sitting on `id`; disabling `NodePlugin` alone removes the Relay field but leaves the column called
14
+ * `rowId`, which is strictly worse — it drops the one case that used to warn. Moving the identifier
15
+ * to `nodeId` keeps Relay working and is the name the schema converter already skips.
16
+ *
17
+ * Mirrors `postgraphile/presets/v4`, which reverses exactly these two inflectors.
18
+ */
19
+ const StonecropNaturalIdPlugin = {
20
+ name: 'StonecropNaturalIdPlugin',
21
+ version: '0.0.0',
22
+ after: ['PgAttributesPlugin'],
23
+ inflection: {
24
+ replace: {
25
+ // Move Relay's global identifier off `id`...
26
+ nodeIdFieldName() {
27
+ return 'nodeId';
28
+ },
29
+ // ...so the real column can keep its own name.
30
+ _attributeName(previous, options, details) {
31
+ // `previous` is optional in the inflector signature because a replacement may be the first
32
+ // implementation. It never is here — `after: ['PgAttributesPlugin']` guarantees Amber's runs
33
+ // first — but the raw attribute name is the correct identity fallback.
34
+ const name = previous?.(details) ?? details.attributeName;
35
+ if (!details.skipRowId && name === 'row_id') {
36
+ const { codec, attributeName } = details;
37
+ const baseName = codec.attributes[attributeName]?.extensions?.tags?.name ?? attributeName;
38
+ if (typeof baseName === 'string' && baseName.toLowerCase() === 'id' && !codec.isAnonymous) {
39
+ return 'id';
40
+ }
41
+ }
42
+ return name;
43
+ },
44
+ },
45
+ },
46
+ };
47
+ /**
48
+ * Exposes the many side of a foreign key the database declares as owning.
49
+ *
50
+ * PostGraphile registers both directions of every foreign key, but Amber gives the many side no
51
+ * `manyRelation:resource:connection` behavior — for a non-unique relation `PgRelationsPlugin`'s
52
+ * inferred behavior is `["resource:select", behavior]` and nothing more. So a parent type carries
53
+ * no field for its children, and a doctype generated from that schema can never contain a child
54
+ * table. Every one a consumer has is hand-authored.
55
+ *
56
+ * `ON DELETE CASCADE` is the discriminator because it is the only place a schema states ownership.
57
+ * `sc_tag.item_id` cascades: the tags are the item's rows and die with it. `sc_order.customer_id`
58
+ * does not: an order references a party that outlives it. The two are otherwise the same shape, so
59
+ * no amount of reading the relation itself can separate them — and turning the many side on for
60
+ * *every* foreign key would make each referenced table look like somebody's child.
61
+ *
62
+ * Read at the gather phase rather than from the built relation: `confdeltype` is on the raw
63
+ * `pg_constraint` and does not survive into `relation.extensions`, which carries only `isIndexed`.
64
+ *
65
+ * Connection only, deliberately. The converter recognises a Connection type through
66
+ * `getConnectionNodeType`; a list field is not a shape it knows, so `+manyRelation:resource:list`
67
+ * would add a second field per relation that generation then drops on the floor.
68
+ *
69
+ * A global `preset.schema.defaultBehavior` cannot do this. Inferred behaviors are applied after the
70
+ * global default and take precedence, so `+manyRelation:resource:connection` there is overridden
71
+ * for every relation — verified, it changes nothing, while `-connection +list` through the same
72
+ * option visibly rewrites the Query fields.
73
+ */
74
+ const StonecropOwnedRelationsPlugin = {
75
+ name: 'StonecropOwnedRelationsPlugin',
76
+ version: '0.0.0',
77
+ gather: {
78
+ hooks: {
79
+ pgRelations_relation(_info, event) {
80
+ const { relation, pgConstraint } = event;
81
+ // The hook fires once per direction of each constraint; only the backwards one has a
82
+ // many side to expose. `confdeltype` is Postgres' own code: 'c' is CASCADE.
83
+ if (!relation.isReferencee)
84
+ return;
85
+ if (pgConstraint.confdeltype !== 'c')
86
+ return;
87
+ relation.extensions ??= {};
88
+ relation.extensions.tags ??= {};
89
+ relation.extensions.tags.behavior = '+manyRelation:resource:connection';
90
+ },
91
+ },
92
+ },
93
+ };
2
94
  const StonecropFieldCasingPlugin = {
3
95
  name: 'StonecropFieldCasingPlugin',
4
96
  version: '0.0.0',
@@ -32,7 +124,9 @@ const StonecropFieldCasingPlugin = {
32
124
  */
33
125
  export const createStonecropPreset = (options) => ({
34
126
  extends: [PostGraphileAmberPreset],
35
- plugins: options?.fieldCasing === 'pascal' ? [StonecropFieldCasingPlugin] : [],
127
+ plugins: options?.fieldCasing === 'pascal'
128
+ ? [StonecropNaturalIdPlugin, StonecropOwnedRelationsPlugin, StonecropFieldCasingPlugin]
129
+ : [StonecropNaturalIdPlugin, StonecropOwnedRelationsPlugin],
36
130
  });
37
131
  /**
38
132
  * The default Stonecrop PostGraphile preset with camelCase field names.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stonecrop/graphql-middleware",
3
- "version": "0.24.0",
3
+ "version": "0.26.0",
4
4
  "description": "GraphQL middleware for PostGraphile and Stonecrop schema",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,16 +21,14 @@
21
21
  "dependencies": {
22
22
  "@dataplan/pg": "^1.0.3",
23
23
  "graphql": "^16.14.0",
24
- "pluralize": "^8.0.0",
25
24
  "postgraphile": "^5.0.3",
26
- "@stonecrop/schema": "0.24.0"
25
+ "@stonecrop/schema": "0.26.0"
27
26
  },
28
27
  "devDependencies": {
29
28
  "@electric-sql/pglite": "^0.4.5",
30
29
  "@rushstack/heft": "^1.2.17",
31
30
  "@types/node": "^24.12.4",
32
31
  "@types/pg": "^8.11.0",
33
- "@types/pluralize": "^0.0.33",
34
32
  "@vitest/coverage-istanbul": "^4.1.5",
35
33
  "@vitest/ui": "^4.1.5",
36
34
  "oxlint": "1.67.0",