@stonecrop/graphql-middleware 0.34.0 → 0.36.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/graphql-middleware.d.ts +7 -5
- package/dist/index.js +352 -175
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { camelToSnake, flattenFields, flattenFields as flattenFields$1, getDisplayField, getRecordIdField, isActionAllowedInState, parseDoctype, pascalToSnake, resolveLinkRenderMode, unwrapInlineLinks, validateDoctype } from "@stonecrop/schema";
|
|
4
|
-
import { loadOneWithPgClient, sideEffectWithPgClient } from "@dataplan/pg";
|
|
4
|
+
import { LIST_TYPES, TYPES, loadOneWithPgClient, sideEffectWithPgClient } from "@dataplan/pg";
|
|
5
5
|
import { constant, lambda, object } from "postgraphile/grafast";
|
|
6
6
|
import { extendSchema, gql, wrapPlans } from "postgraphile/utils";
|
|
7
|
+
import { sql } from "postgraphile/pg-sql2";
|
|
8
|
+
import { Temporal } from "temporal-polyfill";
|
|
7
9
|
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
|
|
8
10
|
import { makePgService } from "postgraphile/adaptors/pg";
|
|
9
11
|
//#region src/fields.ts
|
|
@@ -379,22 +381,164 @@ async function applyGuardedTransition(actionDef, io, data) {
|
|
|
379
381
|
//#endregion
|
|
380
382
|
//#region src/tables.ts
|
|
381
383
|
/**
|
|
382
|
-
* The
|
|
383
|
-
*
|
|
384
|
+
* The table a doctype reads from: the `tables` override when the adapter supplies one, otherwise the
|
|
385
|
+
* doctype name snake-cased.
|
|
384
386
|
*
|
|
385
387
|
* The one definition of that mapping. It lives in its own module rather than beside either caller
|
|
386
388
|
* because the plugin imports the link-display enrichment, so the enrichment cannot import back —
|
|
387
389
|
* and the copy it made instead was byte-identical, which is the state a mapping is in right before
|
|
388
390
|
* one side learns about schema-qualified names and the other does not.
|
|
389
391
|
*
|
|
390
|
-
* A dotted override is read as `schema.table
|
|
391
|
-
*
|
|
392
|
+
* A dotted override is read as `schema.table`, so a table in a non-default Postgres schema keeps
|
|
393
|
+
* its schema instead of becoming one name containing a dot.
|
|
392
394
|
*/
|
|
393
|
-
function
|
|
395
|
+
function resolveTable(name, tables) {
|
|
394
396
|
const target = tables?.[name] ?? pascalToSnake(name);
|
|
395
397
|
const dotIndex = target.indexOf(".");
|
|
396
|
-
if (dotIndex > 0) return
|
|
397
|
-
|
|
398
|
+
if (dotIndex > 0) return {
|
|
399
|
+
schema: target.slice(0, dotIndex),
|
|
400
|
+
name: target.slice(dotIndex + 1)
|
|
401
|
+
};
|
|
402
|
+
return { name: target };
|
|
403
|
+
}
|
|
404
|
+
/** The quoted SQL table a doctype reads from (see `resolveTable`). */
|
|
405
|
+
function resolveTableName(name, tables) {
|
|
406
|
+
const table = resolveTable(name, tables);
|
|
407
|
+
return table.schema === void 0 ? `"${table.name}"` : `"${table.schema}"."${table.name}"`;
|
|
408
|
+
}
|
|
409
|
+
//#endregion
|
|
410
|
+
//#region src/columns.ts
|
|
411
|
+
/** A domain's underlying type, through any domains stacked on it. */
|
|
412
|
+
var baseCodec = (codec) => codec.domainOfCodec ? baseCodec(codec.domainOfCodec) : codec;
|
|
413
|
+
/**
|
|
414
|
+
* The conversion for a `timestamp` column, or a list of them: a clock reading with no zone, which
|
|
415
|
+
* names no moment until a zone is chosen. It is read and bound through `timestamptz`, the cast
|
|
416
|
+
* Postgres itself makes through the database's zone, so a value leaves as a moment and a moment
|
|
417
|
+
* comes back to the same reading. Every other column needs none.
|
|
418
|
+
*
|
|
419
|
+
* Not PostGraphile's own text for it: that carries no zone, so a browser reads it in its own zone
|
|
420
|
+
* and sends back UTC, and every save moved the stored time by the user's offset.
|
|
421
|
+
*/
|
|
422
|
+
var momentConversion = (codec) => {
|
|
423
|
+
if (baseCodec(codec) === TYPES.timestamp) return {
|
|
424
|
+
type: "timestamptz",
|
|
425
|
+
castSql: sql`::timestamptz`,
|
|
426
|
+
codec: TYPES.timestamptz
|
|
427
|
+
};
|
|
428
|
+
if (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.timestamp) return {
|
|
429
|
+
type: "timestamptz[]",
|
|
430
|
+
castSql: sql`::timestamptz[]`,
|
|
431
|
+
codec: LIST_TYPES.timestamptz
|
|
432
|
+
};
|
|
433
|
+
};
|
|
434
|
+
var INTERVAL_PARTS = [
|
|
435
|
+
"years",
|
|
436
|
+
"months",
|
|
437
|
+
"days",
|
|
438
|
+
"hours",
|
|
439
|
+
"minutes",
|
|
440
|
+
"seconds"
|
|
441
|
+
];
|
|
442
|
+
/**
|
|
443
|
+
* An interval, as PostGraphile decodes it, written as an ISO 8601 duration (`P1DT2H30M`): the value
|
|
444
|
+
* a duration field holds whatever the backend, as a day is `YYYY-MM-DD`. Not PostGraphile's object,
|
|
445
|
+
* which every other backend would have to imitate. Postgres writes an ISO 8601 duration back natively.
|
|
446
|
+
*
|
|
447
|
+
* Postgres signs each part apart, so it can hold "a day less an hour", which no ISO 8601 duration can.
|
|
448
|
+
* Such an interval throws rather than being read as some other length.
|
|
449
|
+
*/
|
|
450
|
+
var isoDuration = (interval, describe) => {
|
|
451
|
+
const part = (name) => {
|
|
452
|
+
const value = interval instanceof Object ? Reflect.get(interval, name) : void 0;
|
|
453
|
+
return typeof value === "number" ? value : 0;
|
|
454
|
+
};
|
|
455
|
+
const parts = INTERVAL_PARTS.map(part);
|
|
456
|
+
if (parts.some((value) => value > 0) && parts.some((value) => value < 0)) throw new Error(`${describe()} is an interval whose parts differ in sign, which no ISO 8601 duration can hold.`);
|
|
457
|
+
const microseconds = Math.round(part("seconds") * 1e6);
|
|
458
|
+
return Temporal.Duration.from({
|
|
459
|
+
years: part("years"),
|
|
460
|
+
months: part("months"),
|
|
461
|
+
days: part("days"),
|
|
462
|
+
hours: part("hours"),
|
|
463
|
+
minutes: part("minutes"),
|
|
464
|
+
seconds: Math.trunc(microseconds / 1e6),
|
|
465
|
+
milliseconds: Math.trunc(microseconds % 1e6 / 1e3),
|
|
466
|
+
microseconds: microseconds % 1e3
|
|
467
|
+
}).toString();
|
|
468
|
+
};
|
|
469
|
+
var readIntervalList = (intervals, describe) => Array.isArray(intervals) ? intervals.map((interval) => interval === null ? null : isoDuration(interval, describe)) : intervals;
|
|
470
|
+
/** Whether a column holds an interval or a list of them, each served as an ISO 8601 duration. */
|
|
471
|
+
var intervalShape = (codec) => {
|
|
472
|
+
if (baseCodec(codec) === TYPES.interval) return "one";
|
|
473
|
+
if (codec.arrayOfCodec && baseCodec(codec.arrayOfCodec) === TYPES.interval) return "list";
|
|
474
|
+
};
|
|
475
|
+
/**
|
|
476
|
+
* Reads a doctype's columns through the codecs PostGraphile introspected for its table, so each
|
|
477
|
+
* value is the one PostGraphile's own query serves for that row, in any server zone: a `date` is
|
|
478
|
+
* `2026-01-01`. Two exceptions: a `timestamp`, or a list of them, served as the moment each names in
|
|
479
|
+
* the database's zone (`2026-01-01T09:00:00.000000+00:00`; see `momentConversion`), and an
|
|
480
|
+
* `interval`, or a list of them, served as an ISO 8601 duration (see `isoDuration`).
|
|
481
|
+
*
|
|
482
|
+
* Not `pg`'s type parsers: they turn `date` and `timestamp` into a Date at the server's local time,
|
|
483
|
+
* which names another day or hour outside UTC, and a save writes that shifted value back. Not a
|
|
484
|
+
* process-wide `setTypeParser` either, which changes every other `pg` query in the host.
|
|
485
|
+
*/
|
|
486
|
+
function createColumnReader(codecs, executor, tables) {
|
|
487
|
+
const tableCodecsByName = /* @__PURE__ */ new Map();
|
|
488
|
+
for (const codec of Object.values(codecs)) {
|
|
489
|
+
const pg = codec.extensions?.pg;
|
|
490
|
+
if (!codec.attributes || !codec.extensions?.isTableLike || !pg || codec.executor !== executor) continue;
|
|
491
|
+
tableCodecsByName.set(pg.name, [...tableCodecsByName.get(pg.name) ?? [], codec]);
|
|
492
|
+
}
|
|
493
|
+
const findTableCodec = (doctype) => {
|
|
494
|
+
const table = resolveTable(doctype, tables);
|
|
495
|
+
const matches = (tableCodecsByName.get(table.name) ?? []).filter((codec) => table.schema === void 0 || codec.extensions?.pg?.schemaName === table.schema);
|
|
496
|
+
if (matches.length === 1) return matches[0];
|
|
497
|
+
const quoted = resolveTableName(doctype, tables);
|
|
498
|
+
if (matches.length === 0) throw new Error(`Doctype "${doctype}" reads ${quoted}, which PostGraphile has not introspected, so its columns cannot be read the way PostGraphile reads them. Add the table's schema to the pgService, or map the doctype in \`tables\` to a table PostGraphile knows.`);
|
|
499
|
+
const schemas = matches.map((codec) => codec.extensions?.pg?.schemaName).join(", ");
|
|
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
|
+
};
|
|
502
|
+
const findColumnCodec = (doctype, tableCodec, column) => {
|
|
503
|
+
const attribute = tableCodec.attributes?.[column];
|
|
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;
|
|
506
|
+
};
|
|
507
|
+
return {
|
|
508
|
+
select(doctype, selections) {
|
|
509
|
+
const tableCodec = findTableCodec(doctype);
|
|
510
|
+
const table = resolveTableName(doctype, tables);
|
|
511
|
+
const decoders = /* @__PURE__ */ new Map();
|
|
512
|
+
return {
|
|
513
|
+
table,
|
|
514
|
+
list: selections.map(({ column, alias }) => {
|
|
515
|
+
const columnCodec = findColumnCodec(doctype, tableCodec, column);
|
|
516
|
+
const conversion = momentConversion(columnCodec);
|
|
517
|
+
const readCodec = conversion?.codec ?? columnCodec;
|
|
518
|
+
const columnSql = conversion ? sql`${sql.identifier(column)}${conversion.castSql}` : sql.identifier(column);
|
|
519
|
+
const cast = readCodec.castFromPg?.(columnSql) ?? sql`${columnSql}::text`;
|
|
520
|
+
const compiled = sql.compile(sql`${cast} AS ${sql.identifier(alias)}`);
|
|
521
|
+
if (compiled.values.length > 0) throw new Error(`The codec for ${table}."${column}" casts with a bound value, which this adapter cannot select.`);
|
|
522
|
+
const shape = intervalShape(columnCodec);
|
|
523
|
+
const describe = (text) => () => `"${alias}" from ${table} (${text})`;
|
|
524
|
+
decoders.set(alias, shape === "one" ? (text) => isoDuration(readCodec.fromPg(text), describe(text)) : shape === "list" ? (text) => readIntervalList(readCodec.fromPg(text), describe(text)) : readCodec.fromPg);
|
|
525
|
+
return compiled.text;
|
|
526
|
+
}).join(", "),
|
|
527
|
+
decodeRows(rows) {
|
|
528
|
+
for (const row of rows) for (const [alias, fromPg] of decoders) {
|
|
529
|
+
const value = row[alias];
|
|
530
|
+
if (value === null) continue;
|
|
531
|
+
if (typeof value !== "string") throw new Error(`"${alias}" from ${table} is ${typeof value}, not the text its select returns.`);
|
|
532
|
+
row[alias] = fromPg(value);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
},
|
|
537
|
+
bind(doctype, column, placeholder) {
|
|
538
|
+
const conversion = momentConversion(findColumnCodec(doctype, findTableCodec(doctype), column));
|
|
539
|
+
return conversion ? `${placeholder}::${conversion.type}` : placeholder;
|
|
540
|
+
}
|
|
541
|
+
};
|
|
398
542
|
}
|
|
399
543
|
//#endregion
|
|
400
544
|
//#region src/link-display.ts
|
|
@@ -412,7 +556,7 @@ function scalarText(value) {
|
|
|
412
556
|
if (typeof value === "string") return value === "" ? void 0 : value;
|
|
413
557
|
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
414
558
|
}
|
|
415
|
-
function collectLinkDisplaySpecs(meta
|
|
559
|
+
function collectLinkDisplaySpecs(meta) {
|
|
416
560
|
const specs = [];
|
|
417
561
|
for (const field of flattenFields(meta.fields)) {
|
|
418
562
|
if (field.kind !== "field" || !field.doctype) continue;
|
|
@@ -424,7 +568,7 @@ function collectLinkDisplaySpecs(meta, tables) {
|
|
|
424
568
|
fieldname: field.fieldname,
|
|
425
569
|
displayField: displayField.fieldname,
|
|
426
570
|
targetPkFieldname: getRecordIdField(targetMeta.fields),
|
|
427
|
-
|
|
571
|
+
targetDoctype: targetMeta.name
|
|
428
572
|
});
|
|
429
573
|
}
|
|
430
574
|
return specs;
|
|
@@ -437,8 +581,8 @@ function collectLinkDisplaySpecs(meta, tables) {
|
|
|
437
581
|
* must pass the whole batch: called per row inside a loader's own loop it reinstates the N+1 the
|
|
438
582
|
* loader exists to prevent, and does so invisibly, since the result is identical either way.
|
|
439
583
|
*/
|
|
440
|
-
async function enrichLinkDisplayFields(pgClient, meta, rows,
|
|
441
|
-
const specs = collectLinkDisplaySpecs(meta
|
|
584
|
+
async function enrichLinkDisplayFields(pgClient, meta, rows, columns, debugSql) {
|
|
585
|
+
const specs = collectLinkDisplaySpecs(meta);
|
|
442
586
|
if (specs.length === 0 || rows.length === 0) return;
|
|
443
587
|
await Promise.all(specs.map(async (spec) => {
|
|
444
588
|
const ids = /* @__PURE__ */ new Set();
|
|
@@ -448,12 +592,18 @@ async function enrichLinkDisplayFields(pgClient, meta, rows, tables, debugSql) {
|
|
|
448
592
|
}
|
|
449
593
|
if (ids.size === 0) return;
|
|
450
594
|
const pkColumn = camelToSnake(spec.targetPkFieldname);
|
|
451
|
-
const
|
|
452
|
-
|
|
595
|
+
const select = columns.select(spec.targetDoctype, [{
|
|
596
|
+
column: pkColumn,
|
|
597
|
+
alias: spec.targetPkFieldname
|
|
598
|
+
}, {
|
|
599
|
+
column: camelToSnake(spec.displayField),
|
|
600
|
+
alias: spec.displayField
|
|
601
|
+
}]);
|
|
453
602
|
const { rows: displayRows } = await debugSql(pgClient, {
|
|
454
|
-
text: `SELECT
|
|
603
|
+
text: `SELECT ${select.list} FROM ${select.table} WHERE "${pkColumn}"::text = ANY($1::text[])`,
|
|
455
604
|
values: [Array.from(ids)]
|
|
456
605
|
});
|
|
606
|
+
select.decodeRows(displayRows);
|
|
457
607
|
const displayById = /* @__PURE__ */ new Map();
|
|
458
608
|
for (const displayRow of displayRows) {
|
|
459
609
|
const key = scalarText(displayRow[spec.targetPkFieldname]);
|
|
@@ -506,6 +656,7 @@ var typeDefs = gql`
|
|
|
506
656
|
validation: JSON
|
|
507
657
|
cardinality: String
|
|
508
658
|
source: String
|
|
659
|
+
config: JSON
|
|
509
660
|
}
|
|
510
661
|
|
|
511
662
|
type StonecropWorkflowAction {
|
|
@@ -562,9 +713,17 @@ var typeDefs = gql`
|
|
|
562
713
|
|
|
563
714
|
type StonecropActionResult {
|
|
564
715
|
success: Boolean!
|
|
716
|
+
"""
|
|
717
|
+
What the action's registered handler returned, verbatim, or the outcome the doctype declared.
|
|
718
|
+
"""
|
|
565
719
|
data: JSON
|
|
566
720
|
error: String
|
|
567
721
|
"""
|
|
722
|
+
The record as stonecropRecord returns it after the action, whoever wrote it. The client stores
|
|
723
|
+
this, never data. Null when the action failed or targets no record.
|
|
724
|
+
"""
|
|
725
|
+
record: JSON
|
|
726
|
+
"""
|
|
568
727
|
Keys the write discarded because the doctype declares no column for them, or because the
|
|
569
728
|
value was a nested relation rather than a column value. Null when everything sent was
|
|
570
729
|
stored. The action still succeeded — this is what it did not keep, and a client that
|
|
@@ -613,7 +772,7 @@ var ActionRolledBack = class extends Error {
|
|
|
613
772
|
};
|
|
614
773
|
/**
|
|
615
774
|
* Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
|
|
616
|
-
* read it. An *expanding* link is a relation in the payload rather than a scalar, so `
|
|
775
|
+
* read it. An *expanding* link is a relation in the payload rather than a scalar, so `getColumnSelections`
|
|
617
776
|
* omits its FK column by design — but the expansion needs the value to find the target. Aliasing
|
|
618
777
|
* keeps that need from changing the payload: every alias is stripped before the record is returned.
|
|
619
778
|
*/
|
|
@@ -649,11 +808,141 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
649
808
|
} : (pgClient, query) => pgClient.query(query);
|
|
650
809
|
const defaultRowLimit = options.defaultRecordLimit === void 0 ? 200 : options.defaultRecordLimit;
|
|
651
810
|
return extendSchema((build) => {
|
|
652
|
-
const
|
|
653
|
-
const executor = pgExecutors ? Object.values(pgExecutors)[0] : void 0;
|
|
811
|
+
const pgRegistry = build.input?.pgRegistry;
|
|
812
|
+
const executor = pgRegistry?.pgExecutors ? Object.values(pgRegistry.pgExecutors)[0] : void 0;
|
|
654
813
|
if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
|
|
814
|
+
const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
|
|
655
815
|
if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
|
|
656
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
|
+
});
|
|
849
|
+
}
|
|
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] = {
|
|
867
|
+
data: null,
|
|
868
|
+
doctype
|
|
869
|
+
};
|
|
870
|
+
continue;
|
|
871
|
+
}
|
|
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)) {
|
|
879
|
+
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);
|
|
890
|
+
continue;
|
|
891
|
+
}
|
|
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;
|
|
920
|
+
continue;
|
|
921
|
+
}
|
|
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
|
+
};
|
|
657
946
|
return {
|
|
658
947
|
typeDefs,
|
|
659
948
|
objects: {
|
|
@@ -671,129 +960,7 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
671
960
|
doctype: $doctype,
|
|
672
961
|
id: $id,
|
|
673
962
|
options: $options
|
|
674
|
-
}),
|
|
675
|
-
const byDoctype = /* @__PURE__ */ new Map();
|
|
676
|
-
for (let i = 0; i < specs.length; i++) {
|
|
677
|
-
const d = String(specs[i].doctype);
|
|
678
|
-
if (!byDoctype.has(d)) byDoctype.set(d, []);
|
|
679
|
-
byDoctype.get(d).push(i);
|
|
680
|
-
}
|
|
681
|
-
const results = Array.from({ length: specs.length });
|
|
682
|
-
for (const [doctype, indices] of byDoctype) {
|
|
683
|
-
const meta = getMeta(doctype);
|
|
684
|
-
if (!meta) {
|
|
685
|
-
for (const i of indices) results[i] = {
|
|
686
|
-
data: null,
|
|
687
|
-
doctype
|
|
688
|
-
};
|
|
689
|
-
continue;
|
|
690
|
-
}
|
|
691
|
-
const pkMeta = getPkMeta(meta);
|
|
692
|
-
if (!pkMeta) throw unresolvableIdentityError(doctype);
|
|
693
|
-
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
694
|
-
const columns = getSqlColumns(meta);
|
|
695
|
-
const ids = indices.map((i) => String(specs[i].id));
|
|
696
|
-
const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
|
|
697
|
-
const linkFkAliases = [];
|
|
698
|
-
for (const [linkName, link] of Object.entries(meta.links ?? {})) {
|
|
699
|
-
if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
|
|
700
|
-
const fieldname = link.fieldname ?? linkName;
|
|
701
|
-
if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
|
|
702
|
-
linkFkAliases.push({
|
|
703
|
-
fieldname,
|
|
704
|
-
alias: `${LINK_FK_ALIAS}${fieldname}`
|
|
705
|
-
});
|
|
706
|
-
}
|
|
707
|
-
const selectList = [columns, ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`)].filter(Boolean).join(", ");
|
|
708
|
-
const { rows } = await debugSql(pgClient, {
|
|
709
|
-
text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
|
|
710
|
-
values: [ids]
|
|
711
|
-
});
|
|
712
|
-
const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
|
|
713
|
-
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.`);
|
|
714
|
-
const enrichedRows = [];
|
|
715
|
-
for (const i of indices) {
|
|
716
|
-
const specId = String(specs[i].id);
|
|
717
|
-
const row = rowByPk.get(specId);
|
|
718
|
-
if (!row) {
|
|
719
|
-
results[i] = {
|
|
720
|
-
data: null,
|
|
721
|
-
doctype
|
|
722
|
-
};
|
|
723
|
-
continue;
|
|
724
|
-
}
|
|
725
|
-
const rowData = { ...row };
|
|
726
|
-
enrichedRows.push(rowData);
|
|
727
|
-
const truncatedLinks = [];
|
|
728
|
-
const recordOptions = specs[i].options ?? {};
|
|
729
|
-
const includeAll = recordOptions.includeNested === true;
|
|
730
|
-
const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
|
|
731
|
-
if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
|
|
732
|
-
const fieldname = link.fieldname ?? linkName;
|
|
733
|
-
const fetch = link.fetch;
|
|
734
|
-
const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
|
|
735
|
-
const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
|
|
736
|
-
const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
|
|
737
|
-
const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
|
|
738
|
-
if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
|
|
739
|
-
if (effectiveMethod === "custom" && fetch?.method === "custom") {
|
|
740
|
-
const handlerName = fetch.handler;
|
|
741
|
-
const handler = getFetchHandler(handlerName);
|
|
742
|
-
if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
|
|
743
|
-
continue;
|
|
744
|
-
}
|
|
745
|
-
if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
|
|
746
|
-
const targetMeta = getMeta(link.target);
|
|
747
|
-
if (!targetMeta) continue;
|
|
748
|
-
const targetColumns = getSqlColumns(targetMeta);
|
|
749
|
-
if (isMany) {
|
|
750
|
-
if (!link.backlink) continue;
|
|
751
|
-
const backlinkCol = camelToSnake(link.backlink);
|
|
752
|
-
let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
|
|
753
|
-
const linkValues = [specId];
|
|
754
|
-
const linkPkMeta = getPkMeta(targetMeta);
|
|
755
|
-
if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
|
|
756
|
-
if (effectiveLimit != null) {
|
|
757
|
-
sql += ` LIMIT $2`;
|
|
758
|
-
linkValues.push(effectiveLimit + 1);
|
|
759
|
-
}
|
|
760
|
-
const { rows: linked } = await debugSql(pgClient, {
|
|
761
|
-
text: sql,
|
|
762
|
-
values: linkValues
|
|
763
|
-
});
|
|
764
|
-
if (effectiveLimit != null && linked.length > effectiveLimit) {
|
|
765
|
-
truncatedLinks.push(fieldname);
|
|
766
|
-
rowData[fieldname] = linked.slice(0, effectiveLimit);
|
|
767
|
-
} else rowData[fieldname] = linked;
|
|
768
|
-
} else {
|
|
769
|
-
const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
|
|
770
|
-
if (fkValue == null) {
|
|
771
|
-
rowData[fieldname] = null;
|
|
772
|
-
continue;
|
|
773
|
-
}
|
|
774
|
-
const targetPkMeta = getPkMeta(targetMeta);
|
|
775
|
-
if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
|
|
776
|
-
const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
|
|
777
|
-
const { rows: linked } = await debugSql(pgClient, {
|
|
778
|
-
text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
|
|
779
|
-
values: [fkValue]
|
|
780
|
-
});
|
|
781
|
-
rowData[fieldname] = linked[0] ?? null;
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
for (const { alias } of linkFkAliases) delete rowData[alias];
|
|
785
|
-
const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
|
|
786
|
-
results[i] = {
|
|
787
|
-
data: rowData,
|
|
788
|
-
doctype,
|
|
789
|
-
unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
|
|
790
|
-
truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
|
|
791
|
-
};
|
|
792
|
-
}
|
|
793
|
-
await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
|
|
794
|
-
}
|
|
795
|
-
return results;
|
|
796
|
-
});
|
|
963
|
+
}), readRecords);
|
|
797
964
|
},
|
|
798
965
|
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
|
|
799
966
|
return loadOneWithPgClient(executor, object({
|
|
@@ -814,15 +981,17 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
814
981
|
count: spec.includeTotal === true ? 0 : null
|
|
815
982
|
};
|
|
816
983
|
const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
|
|
817
|
-
const
|
|
818
|
-
const
|
|
984
|
+
const select = columns.select(meta.name, getColumnSelections(meta));
|
|
985
|
+
const filterValues = [];
|
|
819
986
|
const whereClauses = [];
|
|
820
987
|
if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
|
|
821
988
|
if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
|
|
822
|
-
|
|
823
|
-
|
|
989
|
+
filterValues.push(value);
|
|
990
|
+
const column = camelToSnake(field);
|
|
991
|
+
whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
|
|
824
992
|
}
|
|
825
993
|
const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
|
|
994
|
+
const values = [...filterValues];
|
|
826
995
|
let orderByClause = "";
|
|
827
996
|
if (spec.orderBy != null) {
|
|
828
997
|
if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
|
|
@@ -851,25 +1020,18 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
851
1020
|
pagingClause += ` OFFSET $${values.length}`;
|
|
852
1021
|
}
|
|
853
1022
|
const { rows } = await debugSql(pgClient, {
|
|
854
|
-
text: `SELECT ${
|
|
1023
|
+
text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
|
|
855
1024
|
values
|
|
856
1025
|
});
|
|
1026
|
+
select.decodeRows(rows);
|
|
857
1027
|
const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
|
|
858
1028
|
const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
|
|
859
|
-
await enrichLinkDisplayFields(pgClient, meta, data,
|
|
1029
|
+
await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
|
|
860
1030
|
let count = null;
|
|
861
1031
|
if (spec.includeTotal === true) {
|
|
862
|
-
const countValues = [];
|
|
863
|
-
const countWhere = [];
|
|
864
|
-
if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
|
|
865
|
-
if (!knownFields.has(field)) continue;
|
|
866
|
-
countValues.push(value);
|
|
867
|
-
countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
|
|
868
|
-
}
|
|
869
|
-
const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(" AND ")}` : "";
|
|
870
1032
|
const { rows: countRows } = await debugSql(pgClient, {
|
|
871
|
-
text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${
|
|
872
|
-
values:
|
|
1033
|
+
text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
|
|
1034
|
+
values: filterValues
|
|
873
1035
|
});
|
|
874
1036
|
count = parseInt(countRows[0]?.row_count ?? "0", 10);
|
|
875
1037
|
}
|
|
@@ -959,28 +1121,31 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
959
1121
|
},
|
|
960
1122
|
writeData: async (patch, exists) => {
|
|
961
1123
|
const { cols, values } = partitionPatch(patch);
|
|
962
|
-
const returning =
|
|
1124
|
+
const returning = columns.select(meta.name, getColumnSelections(meta));
|
|
963
1125
|
if (!exists) {
|
|
964
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.`);
|
|
965
|
-
const text = cols.length ? `INSERT INTO ${table} (${cols.map((c) => `"${c}"`).join(", ")}) VALUES (${cols.map((
|
|
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}`;
|
|
966
1128
|
const { rows } = await debugSql(tx, {
|
|
967
1129
|
text,
|
|
968
1130
|
values
|
|
969
1131
|
});
|
|
1132
|
+
returning.decodeRows(rows);
|
|
970
1133
|
return rows[0] ?? {};
|
|
971
1134
|
}
|
|
972
1135
|
if (cols.length === 0) {
|
|
973
1136
|
const { rows } = await debugSql(tx, {
|
|
974
|
-
text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
|
|
1137
|
+
text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
|
|
975
1138
|
values: [String(recordId)]
|
|
976
1139
|
});
|
|
1140
|
+
returning.decodeRows(rows);
|
|
977
1141
|
return rows[0] ?? {};
|
|
978
1142
|
}
|
|
979
|
-
const assignments = cols.map((c, i) => `"${c}" =
|
|
1143
|
+
const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
|
|
980
1144
|
const { rows } = await debugSql(tx, {
|
|
981
|
-
text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning}`,
|
|
1145
|
+
text: `UPDATE ${table} SET ${assignments} WHERE "${pkColumn()}"::text = $${cols.length + 1} RETURNING ${returning.list}`,
|
|
982
1146
|
values: [...values, String(recordId)]
|
|
983
1147
|
});
|
|
1148
|
+
returning.decodeRows(rows);
|
|
984
1149
|
return rows[0] ?? {};
|
|
985
1150
|
},
|
|
986
1151
|
runEffect: handler ? (currentState) => handler({
|
|
@@ -997,12 +1162,22 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
997
1162
|
if (!outcome.success) throw new ActionRolledBack(outcome);
|
|
998
1163
|
if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
|
|
999
1164
|
const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
|
|
1000
|
-
await enrichLinkDisplayFields(tx, meta, written,
|
|
1165
|
+
await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
|
|
1001
1166
|
}
|
|
1002
|
-
|
|
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 = {
|
|
1003
1174
|
...outcome,
|
|
1175
|
+
record
|
|
1176
|
+
};
|
|
1177
|
+
return droppedFields.length ? {
|
|
1178
|
+
...reply,
|
|
1004
1179
|
droppedFields
|
|
1005
|
-
} :
|
|
1180
|
+
} : reply;
|
|
1006
1181
|
});
|
|
1007
1182
|
} catch (err) {
|
|
1008
1183
|
if (err instanceof ActionRolledBack) return err.outcome;
|
|
@@ -1019,7 +1194,7 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1019
1194
|
});
|
|
1020
1195
|
};
|
|
1021
1196
|
/**
|
|
1022
|
-
* Derive
|
|
1197
|
+
* Derive column selections from a flat field array.
|
|
1023
1198
|
* Skips non-scalar fields (kind !== 'field'), `computed` fields
|
|
1024
1199
|
* (no backing DB column), and *expanding* links
|
|
1025
1200
|
* (relations fetched separately, not scalar columns on this table).
|
|
@@ -1029,25 +1204,27 @@ function collectColumns(fields, links) {
|
|
|
1029
1204
|
for (const f of columnBackedFields(fields)) {
|
|
1030
1205
|
const link = links.get(f.fieldname);
|
|
1031
1206
|
if (link && resolveLinkRenderMode(link, f.component) !== "inline") continue;
|
|
1032
|
-
|
|
1033
|
-
|
|
1207
|
+
columns.push({
|
|
1208
|
+
column: camelToSnake(f.fieldname),
|
|
1209
|
+
alias: f.fieldname
|
|
1210
|
+
});
|
|
1034
1211
|
}
|
|
1035
1212
|
return columns;
|
|
1036
1213
|
}
|
|
1037
1214
|
/**
|
|
1038
|
-
* Derive a
|
|
1039
|
-
* Applies camelToSnake to each fieldname to get the DB column name,
|
|
1040
|
-
*
|
|
1215
|
+
* Derive the columns a record payload selects from doctype field definitions.
|
|
1216
|
+
* Applies camelToSnake to each fieldname to get the DB column name, and keeps
|
|
1217
|
+
* the fieldname as its alias so result rows carry API-layer keys.
|
|
1041
1218
|
* Excludes `computed` fields (no backing DB column), Fieldset
|
|
1042
1219
|
* containers (recursing into their children instead), and *expanding* links
|
|
1043
1220
|
* (relations fetched separately). An inline link keeps its FK column here.
|
|
1044
1221
|
*
|
|
1045
1222
|
* Exported for unit testing (not re-exported from the package index).
|
|
1046
1223
|
*/
|
|
1047
|
-
function
|
|
1224
|
+
function getColumnSelections(meta) {
|
|
1048
1225
|
const links = /* @__PURE__ */ new Map();
|
|
1049
1226
|
if (meta.links) for (const [key, link] of Object.entries(meta.links)) links.set(link.fieldname ?? key, link);
|
|
1050
|
-
return collectColumns(meta.fields, links)
|
|
1227
|
+
return collectColumns(meta.fields, links);
|
|
1051
1228
|
}
|
|
1052
1229
|
/**
|
|
1053
1230
|
* Resolve the declared field this doctype's records are looked up by.
|
|
@@ -1059,11 +1236,11 @@ function getSqlColumns(meta) {
|
|
|
1059
1236
|
* like a record that does not exist.
|
|
1060
1237
|
*
|
|
1061
1238
|
* Returns `undefined` only when the resolved name is not a declared field — a doctype with no
|
|
1062
|
-
* `primaryKey` and no `id`. That case cannot be served: `
|
|
1239
|
+
* `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields
|
|
1063
1240
|
* only, so the row map would key on a column the SELECT never returned and every lookup would miss
|
|
1064
1241
|
* silently. Callers must say so rather than answer `null`.
|
|
1065
1242
|
*
|
|
1066
|
-
* Descends into fieldsets, because both halves of the question already do — `
|
|
1243
|
+
* Descends into fieldsets, because both halves of the question already do — `getColumnSelections` selects
|
|
1067
1244
|
* a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this
|
|
1068
1245
|
* scanned top level only it could refuse a name that helper had just resolved, so a doctype whose
|
|
1069
1246
|
* SELECT carried its own key column had no identity to look that column up by.
|