@stonecrop/graphql-middleware 0.44.0 → 0.45.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.
package/dist/index.js CHANGED
@@ -499,10 +499,10 @@ function createColumnReader(codecs, executor, tables) {
499
499
  const schemas = matches.map((codec) => codec.extensions?.pg?.schemaName).join(", ");
500
500
  throw new Error(`Doctype "${doctype}" reads ${quoted}, a name PostGraphile knows in more than one schema (${schemas}). Map the doctype in \`tables\` to "schema.table".`);
501
501
  };
502
- const findColumnCodec = (doctype, tableCodec, column) => {
502
+ const findAttribute = (doctype, tableCodec, column) => {
503
503
  const attribute = tableCodec.attributes?.[column];
504
504
  if (!attribute) throw new Error(`Doctype "${doctype}" declares a field for column "${column}", which ${resolveTableName(doctype, tables)} does not have.`);
505
- return attribute.codec;
505
+ return attribute;
506
506
  };
507
507
  return {
508
508
  select(doctype, selections) {
@@ -512,7 +512,7 @@ function createColumnReader(codecs, executor, tables) {
512
512
  return {
513
513
  table,
514
514
  list: selections.map(({ column, alias }) => {
515
- const columnCodec = findColumnCodec(doctype, tableCodec, column);
515
+ const columnCodec = findAttribute(doctype, tableCodec, column).codec;
516
516
  const conversion = momentConversion(columnCodec);
517
517
  const readCodec = conversion?.codec ?? columnCodec;
518
518
  const columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column);
@@ -535,8 +535,12 @@ function createColumnReader(codecs, executor, tables) {
535
535
  };
536
536
  },
537
537
  bind(doctype, column, placeholder) {
538
- const conversion = momentConversion(findColumnCodec(doctype, findTableCodec(doctype), column));
538
+ const conversion = momentConversion(findAttribute(doctype, findTableCodec(doctype), column).codec);
539
539
  return conversion ? `${placeholder}::${conversion.type}` : placeholder;
540
+ },
541
+ writable(doctype, column) {
542
+ const { extensions } = findAttribute(doctype, findTableCodec(doctype), column);
543
+ return extensions?.isInsertable !== false || extensions?.isUpdatable !== false;
540
544
  }
541
545
  };
542
546
  }
@@ -807,391 +811,400 @@ var createStonecropPlugin = (options = {}) => {
807
811
  return pgClient.query(query);
808
812
  } : (pgClient, query) => pgClient.query(query);
809
813
  const defaultRowLimit = options.defaultRecordLimit === void 0 ? 200 : options.defaultRecordLimit;
810
- return extendSchema((build) => {
811
- const pgRegistry = build.input?.pgRegistry;
812
- const executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : void 0;
813
- if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
814
- const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
815
- if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
816
- assertReferencesResolve();
817
- /** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */
818
- const readRecords = async (pgClient, specs) => {
819
- const byDoctype = /* @__PURE__ */ new Map();
820
- for (let i = 0; i < specs.length; i++) {
821
- const d = String(specs[i].doctype);
822
- if (!byDoctype.has(d)) byDoctype.set(d, []);
823
- byDoctype.get(d).push(i);
824
- }
825
- const results = Array.from({ length: specs.length });
826
- for (const [doctype, indices] of byDoctype) {
827
- const meta = getMeta(doctype);
828
- if (!meta) {
829
- for (const i of indices) results[i] = {
830
- data: null,
831
- doctype
832
- };
833
- continue;
834
- }
835
- const pkMeta = getPkMeta(meta);
836
- if (!pkMeta) throw unresolvableIdentityError(doctype);
837
- const pkColumn = camelToSnake(pkMeta.fieldname);
838
- const ids = indices.map((i) => String(specs[i].id));
839
- const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
840
- const linkFkAliases = [];
841
- for (const [linkName, link] of Object.entries(meta.links ?? {})) {
842
- if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
843
- const fieldname = link.fieldname ?? linkName;
844
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
845
- linkFkAliases.push({
846
- fieldname,
847
- alias: `${LINK_FK_ALIAS}${fieldname}`
848
- });
814
+ return {
815
+ ...extendSchema((build) => {
816
+ const pgRegistry = build.input?.pgRegistry;
817
+ const executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : void 0;
818
+ if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
819
+ const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
820
+ if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
821
+ assertReferencesResolve();
822
+ /** Reads each requested record, batched by doctype: what `stonecropRecord` serves, and what an action replies with. */
823
+ const readRecords = async (pgClient, specs) => {
824
+ const byDoctype = /* @__PURE__ */ new Map();
825
+ for (let i = 0; i < specs.length; i++) {
826
+ const d = String(specs[i].doctype);
827
+ if (!byDoctype.has(d)) byDoctype.set(d, []);
828
+ byDoctype.get(d).push(i);
849
829
  }
850
- const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases.map(({ fieldname, alias }) => ({
851
- column: camelToSnake(fieldname),
852
- alias
853
- }))]);
854
- const { rows } = await debugSql(pgClient, {
855
- text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
856
- values: [ids]
857
- });
858
- select.decodeRows(rows);
859
- const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
860
- if (rows.length !== rowByPk.size) throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. Declare a field that uniquely identifies a record, or add a unique constraint.`);
861
- const enrichedRows = [];
862
- for (const i of indices) {
863
- const specId = String(specs[i].id);
864
- const row = rowByPk.get(specId);
865
- if (!row) {
866
- results[i] = {
830
+ const results = Array.from({ length: specs.length });
831
+ for (const [doctype, indices] of byDoctype) {
832
+ const meta = getMeta(doctype);
833
+ if (!meta) {
834
+ for (const i of indices) results[i] = {
867
835
  data: null,
868
836
  doctype
869
837
  };
870
838
  continue;
871
839
  }
872
- const rowData = { ...row };
873
- enrichedRows.push(rowData);
874
- const truncatedLinks = [];
875
- const recordOptions = specs[i].options ?? {};
876
- const includeAll = recordOptions.includeNested === true;
877
- const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
878
- if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
840
+ const pkMeta = getPkMeta(meta);
841
+ if (!pkMeta) throw unresolvableIdentityError(doctype);
842
+ const pkColumn = camelToSnake(pkMeta.fieldname);
843
+ const ids = indices.map((i) => String(specs[i].id));
844
+ const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
845
+ const linkFkAliases = [];
846
+ for (const [linkName, link] of Object.entries(meta.links ?? {})) {
847
+ if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
879
848
  const fieldname = link.fieldname ?? linkName;
880
- const fetch = link.fetch;
881
- const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
882
- const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
883
- const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
884
- const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
885
- if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
886
- if (effectiveMethod === "custom" && fetch?.method === "custom") {
887
- const handlerName = fetch.handler;
888
- const handler = getFetchHandler(handlerName);
889
- if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
849
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
850
+ linkFkAliases.push({
851
+ fieldname,
852
+ alias: `${LINK_FK_ALIAS}${fieldname}`
853
+ });
854
+ }
855
+ const select = columns.select(meta.name, [...getColumnSelections(meta), ...linkFkAliases.map(({ fieldname, alias }) => ({
856
+ column: camelToSnake(fieldname),
857
+ alias
858
+ }))]);
859
+ const { rows } = await debugSql(pgClient, {
860
+ text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
861
+ values: [ids]
862
+ });
863
+ select.decodeRows(rows);
864
+ const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
865
+ if (rows.length !== rowByPk.size) throw new Error(`Doctype "${doctype}" declares "${pkMeta.fieldname}" as its identity, but that column is not unique in ${resolveTableName(meta.name, options.tables)} — ${rows.length} rows matched ${rowByPk.size} distinct values, so a lookup cannot say which record it means. Declare a field that uniquely identifies a record, or add a unique constraint.`);
866
+ const enrichedRows = [];
867
+ for (const i of indices) {
868
+ const specId = String(specs[i].id);
869
+ const row = rowByPk.get(specId);
870
+ if (!row) {
871
+ results[i] = {
872
+ data: null,
873
+ doctype
874
+ };
890
875
  continue;
891
876
  }
892
- if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
893
- const targetMeta = getMeta(link.target);
894
- if (!targetMeta) continue;
895
- const targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta));
896
- if (isMany) {
897
- if (!link.backlink) continue;
898
- const backlinkCol = camelToSnake(link.backlink);
899
- let sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${backlinkCol}"::text = $1`;
900
- const linkValues = [specId];
901
- const linkPkMeta = getPkMeta(targetMeta);
902
- if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
903
- if (effectiveLimit != null) {
904
- sql += ` LIMIT $2`;
905
- linkValues.push(effectiveLimit + 1);
906
- }
907
- const { rows: linked } = await debugSql(pgClient, {
908
- text: sql,
909
- values: linkValues
910
- });
911
- targetSelect.decodeRows(linked);
912
- if (effectiveLimit != null && linked.length > effectiveLimit) {
913
- truncatedLinks.push(fieldname);
914
- rowData[fieldname] = linked.slice(0, effectiveLimit);
915
- } else rowData[fieldname] = linked;
916
- } else {
917
- const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
918
- if (fkValue == null) {
919
- rowData[fieldname] = null;
877
+ const rowData = { ...row };
878
+ enrichedRows.push(rowData);
879
+ const truncatedLinks = [];
880
+ const recordOptions = specs[i].options ?? {};
881
+ const includeAll = recordOptions.includeNested === true;
882
+ const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
883
+ if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
884
+ const fieldname = link.fieldname ?? linkName;
885
+ const fetch = link.fetch;
886
+ const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
887
+ const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
888
+ const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
889
+ const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
890
+ if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
891
+ if (effectiveMethod === "custom" && fetch?.method === "custom") {
892
+ const handlerName = fetch.handler;
893
+ const handler = getFetchHandler(handlerName);
894
+ if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
920
895
  continue;
921
896
  }
922
- const targetPkMeta = getPkMeta(targetMeta);
923
- if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
924
- const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
925
- const { rows: linked } = await debugSql(pgClient, {
926
- text: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${targetPkColumn}" = $1`,
927
- values: [fkValue]
928
- });
929
- targetSelect.decodeRows(linked);
930
- rowData[fieldname] = linked[0] ?? null;
931
- }
932
- }
933
- for (const { alias } of linkFkAliases) delete rowData[alias];
934
- const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
935
- results[i] = {
936
- data: rowData,
937
- doctype,
938
- unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
939
- truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
940
- };
941
- }
942
- await enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql);
943
- }
944
- return results;
945
- };
946
- return {
947
- typeDefs,
948
- objects: {
949
- Query: { plans: {
950
- stonecropMeta(_, { $doctype }) {
951
- return lambda($doctype, (doctype) => {
952
- return getMeta(String(doctype)) ?? null;
953
- });
954
- },
955
- stonecropAllMeta() {
956
- return constant(getAllMeta());
957
- },
958
- stonecropRecord(_, { $doctype, $id, $options }) {
959
- return loadOneWithPgClient(executor, object({
960
- doctype: $doctype,
961
- id: $id,
962
- options: $options
963
- }), readRecords);
964
- },
965
- stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
966
- return loadOneWithPgClient(executor, object({
967
- doctype: $doctype,
968
- filters: $filters,
969
- orderBy: $orderBy,
970
- limit: $limit,
971
- offset: $offset,
972
- includeTotal: $includeTotal
973
- }), async (pgClient, specs) => {
974
- return await Promise.all(specs.map(async (spec) => {
975
- const doctype = String(spec.doctype);
976
- const meta = getMeta(doctype);
977
- if (!meta) return {
978
- data: [],
979
- doctype,
980
- hasMore: false,
981
- count: spec.includeTotal === true ? 0 : null
982
- };
983
- const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
984
- const select = columns.select(meta.name, getColumnSelections(meta));
985
- const filterValues = [];
986
- const whereClauses = [];
987
- if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
988
- if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
989
- filterValues.push(value);
990
- const column = camelToSnake(field);
991
- whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
992
- }
993
- const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
994
- const values = [...filterValues];
995
- let orderByClause = "";
996
- if (spec.orderBy != null) {
997
- if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
998
- const orderByStr = spec.orderBy;
999
- const lastUnder = orderByStr.lastIndexOf("_");
1000
- if (lastUnder <= 0) throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
1001
- const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
1002
- if (dir !== "ASC" && dir !== "DESC") throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
1003
- const fieldName = orderByStr.slice(0, lastUnder);
1004
- if (!knownFields.has(fieldName)) throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
1005
- orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
1006
- }
1007
- if (orderByClause === "") {
1008
- const listPkMeta = getPkMeta(meta);
1009
- if (listPkMeta) orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
1010
- }
1011
- if (spec.limit != null && typeof spec.limit !== "number") throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
1012
- const effectiveLimit = spec.limit ?? defaultRowLimit;
1013
- let pagingClause = "";
897
+ if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
898
+ const targetMeta = getMeta(link.target);
899
+ if (!targetMeta) continue;
900
+ const targetSelect = columns.select(targetMeta.name, getColumnSelections(targetMeta));
901
+ if (isMany) {
902
+ if (!link.backlink) continue;
903
+ const backlinkCol = camelToSnake(link.backlink);
904
+ let sql = `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${backlinkCol}"::text = $1`;
905
+ const linkValues = [specId];
906
+ const linkPkMeta = getPkMeta(targetMeta);
907
+ if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
1014
908
  if (effectiveLimit != null) {
1015
- values.push(effectiveLimit + 1);
1016
- pagingClause += ` LIMIT $${values.length}`;
909
+ sql += ` LIMIT $2`;
910
+ linkValues.push(effectiveLimit + 1);
1017
911
  }
1018
- if (spec.offset != null) {
1019
- values.push(spec.offset);
1020
- pagingClause += ` OFFSET $${values.length}`;
912
+ const { rows: linked } = await debugSql(pgClient, {
913
+ text: sql,
914
+ values: linkValues
915
+ });
916
+ targetSelect.decodeRows(linked);
917
+ if (effectiveLimit != null && linked.length > effectiveLimit) {
918
+ truncatedLinks.push(fieldname);
919
+ rowData[fieldname] = linked.slice(0, effectiveLimit);
920
+ } else rowData[fieldname] = linked;
921
+ } else {
922
+ const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
923
+ if (fkValue == null) {
924
+ rowData[fieldname] = null;
925
+ continue;
1021
926
  }
1022
- const { rows } = await debugSql(pgClient, {
1023
- text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
1024
- values
927
+ const targetPkMeta = getPkMeta(targetMeta);
928
+ if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
929
+ const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
930
+ const { rows: linked } = await debugSql(pgClient, {
931
+ text: `SELECT ${targetSelect.list} FROM ${targetSelect.table} WHERE "${targetPkColumn}" = $1`,
932
+ values: [fkValue]
1025
933
  });
1026
- select.decodeRows(rows);
1027
- const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
1028
- const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
1029
- await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
1030
- let count = null;
1031
- if (spec.includeTotal === true) {
1032
- const { rows: countRows } = await debugSql(pgClient, {
1033
- text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
1034
- values: filterValues
934
+ targetSelect.decodeRows(linked);
935
+ rowData[fieldname] = linked[0] ?? null;
936
+ }
937
+ }
938
+ for (const { alias } of linkFkAliases) delete rowData[alias];
939
+ const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
940
+ results[i] = {
941
+ data: rowData,
942
+ doctype,
943
+ unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
944
+ truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
945
+ };
946
+ }
947
+ await enrichLinkDisplayFields(pgClient, meta, enrichedRows, columns, debugSql);
948
+ }
949
+ return results;
950
+ };
951
+ return {
952
+ typeDefs,
953
+ objects: {
954
+ Query: { plans: {
955
+ stonecropMeta(_, { $doctype }) {
956
+ return lambda($doctype, (doctype) => {
957
+ return getMeta(String(doctype)) ?? null;
958
+ });
959
+ },
960
+ stonecropAllMeta() {
961
+ return constant(getAllMeta());
962
+ },
963
+ stonecropRecord(_, { $doctype, $id, $options }) {
964
+ return loadOneWithPgClient(executor, object({
965
+ doctype: $doctype,
966
+ id: $id,
967
+ options: $options
968
+ }), readRecords);
969
+ },
970
+ stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
971
+ return loadOneWithPgClient(executor, object({
972
+ doctype: $doctype,
973
+ filters: $filters,
974
+ orderBy: $orderBy,
975
+ limit: $limit,
976
+ offset: $offset,
977
+ includeTotal: $includeTotal
978
+ }), async (pgClient, specs) => {
979
+ return await Promise.all(specs.map(async (spec) => {
980
+ const doctype = String(spec.doctype);
981
+ const meta = getMeta(doctype);
982
+ if (!meta) return {
983
+ data: [],
984
+ doctype,
985
+ hasMore: false,
986
+ count: spec.includeTotal === true ? 0 : null
987
+ };
988
+ const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
989
+ const select = columns.select(meta.name, getColumnSelections(meta));
990
+ const filterValues = [];
991
+ const whereClauses = [];
992
+ if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
993
+ if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
994
+ filterValues.push(value);
995
+ const column = camelToSnake(field);
996
+ whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
997
+ }
998
+ const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
999
+ const values = [...filterValues];
1000
+ let orderByClause = "";
1001
+ if (spec.orderBy != null) {
1002
+ if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
1003
+ const orderByStr = spec.orderBy;
1004
+ const lastUnder = orderByStr.lastIndexOf("_");
1005
+ if (lastUnder <= 0) throw new Error(`Invalid orderBy format: "${orderByStr}". Expected FIELD_ASC or FIELD_DESC`);
1006
+ const dir = orderByStr.slice(lastUnder + 1).toUpperCase();
1007
+ if (dir !== "ASC" && dir !== "DESC") throw new Error(`Invalid orderBy direction: "${dir}". Must be ASC or DESC`);
1008
+ const fieldName = orderByStr.slice(0, lastUnder);
1009
+ if (!knownFields.has(fieldName)) throw new Error(`Unknown orderBy field: "${fieldName}" for doctype ${meta.name}`);
1010
+ orderByClause = ` ORDER BY "${camelToSnake(fieldName)}" ${dir}`;
1011
+ }
1012
+ if (orderByClause === "") {
1013
+ const listPkMeta = getPkMeta(meta);
1014
+ if (listPkMeta) orderByClause = ` ORDER BY "${camelToSnake(listPkMeta.fieldname)}" ASC`;
1015
+ }
1016
+ if (spec.limit != null && typeof spec.limit !== "number") throw new Error(`Invalid limit: expected number, got ${typeof spec.limit}`);
1017
+ const effectiveLimit = spec.limit ?? defaultRowLimit;
1018
+ let pagingClause = "";
1019
+ if (effectiveLimit != null) {
1020
+ values.push(effectiveLimit + 1);
1021
+ pagingClause += ` LIMIT $${values.length}`;
1022
+ }
1023
+ if (spec.offset != null) {
1024
+ values.push(spec.offset);
1025
+ pagingClause += ` OFFSET $${values.length}`;
1026
+ }
1027
+ const { rows } = await debugSql(pgClient, {
1028
+ text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
1029
+ values
1035
1030
  });
1036
- count = parseInt(countRows[0]?.row_count ?? "0", 10);
1031
+ select.decodeRows(rows);
1032
+ const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
1033
+ const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
1034
+ await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
1035
+ let count = null;
1036
+ if (spec.includeTotal === true) {
1037
+ const { rows: countRows } = await debugSql(pgClient, {
1038
+ text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
1039
+ values: filterValues
1040
+ });
1041
+ count = parseInt(countRows[0]?.row_count ?? "0", 10);
1042
+ }
1043
+ return {
1044
+ data,
1045
+ doctype,
1046
+ hasMore,
1047
+ count
1048
+ };
1049
+ }));
1050
+ });
1051
+ }
1052
+ } },
1053
+ Mutation: { plans: { stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
1054
+ return sideEffectWithPgClient(executor, object({
1055
+ doctype: $doctype,
1056
+ action: $action,
1057
+ actionArgs: $actionArgs
1058
+ }), async (pgClient, spec) => {
1059
+ const meta = getMeta(String(spec.doctype));
1060
+ if (!meta) return {
1061
+ success: false,
1062
+ data: null,
1063
+ error: `Unknown doctype: ${spec.doctype}`
1064
+ };
1065
+ const actionDef = meta.workflow?.actions?.[spec.action];
1066
+ if (!actionDef) return {
1067
+ success: false,
1068
+ data: null,
1069
+ error: `Unknown action: ${spec.action} on ${spec.doctype}`
1070
+ };
1071
+ const table = resolveTableName(meta.name, options.tables);
1072
+ const pkColumn = () => {
1073
+ const pkMeta = getPkMeta(meta);
1074
+ if (!pkMeta) throw unresolvableIdentityError(String(spec.doctype));
1075
+ return camelToSnake(pkMeta.fieldname);
1076
+ };
1077
+ const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []).map((entry) => entry?.data ? {
1078
+ ...entry,
1079
+ data: unwrapInlineLinks(meta.fields, entry.data)
1080
+ } : entry);
1081
+ const recordId = argList[0]?.id;
1082
+ const recordData = argList[0]?.data ?? {};
1083
+ const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
1084
+ const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
1085
+ const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
1086
+ const droppedFields = [];
1087
+ const partitionPatch = (patch) => {
1088
+ const cols = [];
1089
+ const values = [];
1090
+ for (const [key, value] of Object.entries(patch)) {
1091
+ if (!writable.has(key) || !columns.writable(meta.name, camelToSnake(key))) {
1092
+ droppedFields.push(key);
1093
+ continue;
1094
+ }
1095
+ if (value !== null && typeof value === "object") {
1096
+ droppedFields.push(key);
1097
+ continue;
1098
+ }
1099
+ cols.push(camelToSnake(key));
1100
+ values.push(value);
1037
1101
  }
1038
1102
  return {
1039
- data,
1040
- doctype,
1041
- hasMore,
1042
- count
1103
+ cols,
1104
+ values
1043
1105
  };
1044
- }));
1045
- });
1046
- }
1047
- } },
1048
- Mutation: { plans: { stonecropAction(_, { $doctype, $action, $args: $actionArgs }) {
1049
- return sideEffectWithPgClient(executor, object({
1050
- doctype: $doctype,
1051
- action: $action,
1052
- actionArgs: $actionArgs
1053
- }), async (pgClient, spec) => {
1054
- const meta = getMeta(String(spec.doctype));
1055
- if (!meta) return {
1056
- success: false,
1057
- data: null,
1058
- error: `Unknown doctype: ${spec.doctype}`
1059
- };
1060
- const actionDef = meta.workflow?.actions?.[spec.action];
1061
- if (!actionDef) return {
1062
- success: false,
1063
- data: null,
1064
- error: `Unknown action: ${spec.action} on ${spec.doctype}`
1065
- };
1066
- const table = resolveTableName(meta.name, options.tables);
1067
- const pkColumn = () => {
1068
- const pkMeta = getPkMeta(meta);
1069
- if (!pkMeta) throw unresolvableIdentityError(String(spec.doctype));
1070
- return camelToSnake(pkMeta.fieldname);
1071
- };
1072
- const argList = (Array.isArray(spec.actionArgs) ? spec.actionArgs : []).map((entry) => entry?.data ? {
1073
- ...entry,
1074
- data: unwrapInlineLinks(meta.fields, entry.data)
1075
- } : entry);
1076
- const recordId = argList[0]?.id;
1077
- const recordData = argList[0]?.data ?? {};
1078
- const handler = options.actionHandlers?.[meta.name]?.[String(spec.action)];
1079
- const writable = new Map(columnBackedFields(meta.fields).filter((f) => camelToSnake(f.fieldname) !== STATE_COLUMN).map((f) => [f.fieldname, f]));
1080
- const declaresState = columnBackedFields(meta.fields).some((f) => camelToSnake(f.fieldname) === STATE_COLUMN);
1081
- const droppedFields = [];
1082
- const partitionPatch = (patch) => {
1083
- const cols = [];
1084
- const values = [];
1085
- for (const [key, value] of Object.entries(patch)) {
1086
- if (!writable.has(key)) {
1087
- droppedFields.push(key);
1088
- continue;
1089
- }
1090
- if (value !== null && typeof value === "object") {
1091
- droppedFields.push(key);
1092
- continue;
1093
- }
1094
- cols.push(camelToSnake(key));
1095
- values.push(value);
1096
- }
1097
- return {
1098
- cols,
1099
- values
1100
1106
  };
1101
- };
1102
- try {
1103
- return await pgClient.withTransaction(async (tx) => {
1104
- const outcome = await applyGuardedTransition(actionDef, {
1105
- readState: async () => {
1106
- if (recordId == null) return null;
1107
- const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
1108
- const { rows } = await debugSql(tx, {
1109
- text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
1110
- values: [String(recordId)]
1111
- });
1112
- if (rows.length === 0) return null;
1113
- if (!declaresState) return void 0;
1114
- return rows[0][STATE_COLUMN] ?? void 0;
1115
- },
1116
- writeState: async (nextState) => {
1117
- await debugSql(tx, {
1118
- text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
1119
- values: [nextState, String(recordId)]
1120
- });
1121
- },
1122
- writeData: async (patch, exists) => {
1123
- const { cols, values } = partitionPatch(patch);
1124
- const returning = columns.select(meta.name, getColumnSelections(meta));
1125
- if (!exists) {
1126
- if (recordId != null) throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", which no longer exists. Nothing was created — a record dispatched with an identity is an update, and creating one is what dispatching no identity means.`);
1127
- const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
1107
+ try {
1108
+ return await pgClient.withTransaction(async (tx) => {
1109
+ const outcome = await applyGuardedTransition(actionDef, {
1110
+ readState: async () => {
1111
+ if (recordId == null) return null;
1112
+ const projection = declaresState ? `"${STATE_COLUMN}"` : `"${pkColumn()}"`;
1128
1113
  const { rows } = await debugSql(tx, {
1129
- text,
1130
- values
1114
+ text: `SELECT ${projection} FROM ${table} WHERE "${pkColumn()}"::text = $1 FOR UPDATE`,
1115
+ values: [String(recordId)]
1131
1116
  });
1132
- returning.decodeRows(rows);
1133
- return rows[0] ?? {};
1134
- }
1135
- if (cols.length === 0) {
1117
+ if (rows.length === 0) return null;
1118
+ if (!declaresState) return void 0;
1119
+ return rows[0][STATE_COLUMN] ?? void 0;
1120
+ },
1121
+ writeState: async (nextState) => {
1122
+ await debugSql(tx, {
1123
+ text: `UPDATE ${table} SET "${STATE_COLUMN}" = $1 WHERE "${pkColumn()}"::text = $2`,
1124
+ values: [nextState, String(recordId)]
1125
+ });
1126
+ },
1127
+ writeData: async (patch, exists) => {
1128
+ const { cols, values } = partitionPatch(patch);
1129
+ const returning = columns.select(meta.name, getColumnSelections(meta));
1130
+ if (!exists) {
1131
+ if (recordId != null) throw new Error(`Action "${actionDef.label ?? spec.action}" targets ${meta.name} "${String(recordId)}", which no longer exists. Nothing was created — a record dispatched with an identity is an update, and creating one is what dispatching no identity means.`);
1132
+ const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((c, i) => columns.bind(meta.name, c, `$${i + 1}`)).join(", ")}) RETURNING ${returning.list}` : `INSERT INTO ${table} DEFAULT VALUES RETURNING ${returning.list}`;
1133
+ const { rows } = await debugSql(tx, {
1134
+ text,
1135
+ values
1136
+ });
1137
+ returning.decodeRows(rows);
1138
+ return rows[0] ?? {};
1139
+ }
1140
+ if (cols.length === 0) {
1141
+ const { rows } = await debugSql(tx, {
1142
+ text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
1143
+ values: [String(recordId)]
1144
+ });
1145
+ returning.decodeRows(rows);
1146
+ return rows[0] ?? {};
1147
+ }
1148
+ const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
1136
1149
  const { rows } = await debugSql(tx, {
1137
- text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
1138
- values: [String(recordId)]
1150
+ text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
1151
+ values: [...values, String(recordId)]
1139
1152
  });
1140
1153
  returning.decodeRows(rows);
1141
1154
  return rows[0] ?? {};
1142
- }
1143
- const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
1144
- const { rows } = await debugSql(tx, {
1145
- text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
1146
- values: [...values, String(recordId)]
1147
- });
1148
- returning.decodeRows(rows);
1149
- return rows[0] ?? {};
1150
- },
1151
- runEffect: handler ? (currentState) => handler({
1152
- pgClient: tx,
1153
- doctype: String(spec.doctype),
1154
- action: String(spec.action),
1155
- meta,
1156
- recordId,
1157
- data: recordData,
1158
- args: argList,
1159
- currentState
1160
- }) : void 0
1161
- }, recordData);
1162
- if (!outcome.success) throw new ActionRolledBack(outcome);
1163
- if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
1164
- const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
1165
- await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
1166
- }
1167
- const pkField = getPkMeta(meta)?.fieldname;
1168
- const readId = (pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0) ?? recordId;
1169
- const record = readId == null ? null : (await readRecords(tx, [{
1170
- doctype: meta.name,
1171
- id: readId
1172
- }]))[0]?.data ?? null;
1173
- const reply = {
1174
- ...outcome,
1175
- record
1155
+ },
1156
+ runEffect: handler ? (currentState) => handler({
1157
+ pgClient: tx,
1158
+ doctype: String(spec.doctype),
1159
+ action: String(spec.action),
1160
+ meta,
1161
+ recordId,
1162
+ data: recordData,
1163
+ args: argList,
1164
+ currentState
1165
+ }) : void 0
1166
+ }, recordData);
1167
+ if (!outcome.success) throw new ActionRolledBack(outcome);
1168
+ if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
1169
+ const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
1170
+ await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
1171
+ }
1172
+ const pkField = getPkMeta(meta)?.fieldname;
1173
+ const readId = (pkField !== void 0 && outcome.data !== null && typeof outcome.data === "object" ? Reflect.get(outcome.data, pkField) : void 0) ?? recordId;
1174
+ const record = readId == null ? null : (await readRecords(tx, [{
1175
+ doctype: meta.name,
1176
+ id: readId
1177
+ }]))[0]?.data ?? null;
1178
+ const reply = {
1179
+ ...outcome,
1180
+ record
1181
+ };
1182
+ return droppedFields.length ? {
1183
+ ...reply,
1184
+ droppedFields
1185
+ } : reply;
1186
+ });
1187
+ } catch (err) {
1188
+ if (err instanceof ActionRolledBack) return err.outcome;
1189
+ return {
1190
+ success: false,
1191
+ data: null,
1192
+ error: err instanceof Error ? err.message : String(err)
1176
1193
  };
1177
- return droppedFields.length ? {
1178
- ...reply,
1179
- droppedFields
1180
- } : reply;
1181
- });
1182
- } catch (err) {
1183
- if (err instanceof ActionRolledBack) return err.outcome;
1184
- return {
1185
- success: false,
1186
- data: null,
1187
- error: err instanceof Error ? err.message : String(err)
1188
- };
1189
- }
1190
- });
1191
- } } }
1192
- }
1193
- };
1194
- });
1194
+ }
1195
+ });
1196
+ } } }
1197
+ }
1198
+ };
1199
+ }),
1200
+ gather: { hooks: { pgCodecs_attribute(_info, event) {
1201
+ const { attgenerated } = event.pgAttribute;
1202
+ if (attgenerated == null || attgenerated === "") return;
1203
+ event.attribute.extensions ??= {};
1204
+ event.attribute.extensions.isInsertable = false;
1205
+ event.attribute.extensions.isUpdatable = false;
1206
+ } } }
1207
+ };
1195
1208
  };
1196
1209
  /**
1197
1210
  * Derive column selections from a flat field array.
@@ -1442,6 +1455,23 @@ var StonecropOwnedRelationsPlugin = {
1442
1455
  relation.extensions.tags.behavior = "+manyRelation:resource:connection";
1443
1456
  } } }
1444
1457
  };
1458
+ /**
1459
+ * Offers no database function as a mutation.
1460
+ *
1461
+ * PostGraphile makes a mutation of every `VOLATILE` function, which writes past the doctype's guard
1462
+ * as Amber's table mutations do. Not done by disabling `PgCustomTypeFieldPlugin`, which also builds
1463
+ * the queries and computed fields of `STABLE` and `IMMUTABLE` functions.
1464
+ */
1465
+ var StonecropNoFunctionMutationsPlugin = {
1466
+ name: "StonecropNoFunctionMutationsPlugin",
1467
+ version: "0.0.0",
1468
+ schema: { entityBehavior: { pgResource: { override: {
1469
+ after: ["PgBasicsPlugin"],
1470
+ callback(behavior) {
1471
+ return [behavior, "-mutationField"];
1472
+ }
1473
+ } } } }
1474
+ };
1445
1475
  var StonecropFieldCasingPlugin = {
1446
1476
  name: "StonecropFieldCasingPlugin",
1447
1477
  version: "0.0.0",
@@ -1453,7 +1483,9 @@ var StonecropFieldCasingPlugin = {
1453
1483
  * Creates a Stonecrop-flavoured PostGraphile preset.
1454
1484
  *
1455
1485
  * The returned preset extends `PostGraphileAmberPreset` and applies Stonecrop's
1456
- * recommended defaults. Pass it to `extends` in your PostGraphile configuration:
1486
+ * recommended defaults. It turns off the mutations Amber generates, a create, update and delete for
1487
+ * every table and one for every `VOLATILE` database function, so `stonecropAction` is the only write
1488
+ * the API offers. Pass it to `extends` in your PostGraphile configuration:
1457
1489
  *
1458
1490
  * ```typescript
1459
1491
  * import { createStonecropPreset, makePgService, createStonecropPlugin } from '@stonecrop/graphql-middleware'
@@ -1471,11 +1503,13 @@ var StonecropFieldCasingPlugin = {
1471
1503
  */
1472
1504
  var createStonecropPreset = (options) => ({
1473
1505
  extends: [PostGraphileAmberPreset],
1474
- plugins: options?.fieldCasing === "pascal" ? [
1506
+ plugins: [
1475
1507
  StonecropNaturalIdPlugin,
1476
1508
  StonecropOwnedRelationsPlugin,
1477
- StonecropFieldCasingPlugin
1478
- ] : [StonecropNaturalIdPlugin, StonecropOwnedRelationsPlugin]
1509
+ StonecropNoFunctionMutationsPlugin,
1510
+ ...options?.fieldCasing === "pascal" ? [StonecropFieldCasingPlugin] : []
1511
+ ],
1512
+ disablePlugins: ["PgMutationCreatePlugin", "PgMutationUpdateDeletePlugin"]
1479
1513
  });
1480
1514
  /**
1481
1515
  * The default Stonecrop PostGraphile preset with camelCase field names.