@stonecrop/graphql-middleware 0.35.0 → 0.38.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 +351 -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]);
|
|
@@ -563,9 +713,17 @@ var typeDefs = gql`
|
|
|
563
713
|
|
|
564
714
|
type StonecropActionResult {
|
|
565
715
|
success: Boolean!
|
|
716
|
+
"""
|
|
717
|
+
What the action's registered handler returned, verbatim, or the outcome the doctype declared.
|
|
718
|
+
"""
|
|
566
719
|
data: JSON
|
|
567
720
|
error: String
|
|
568
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
|
+
"""
|
|
569
727
|
Keys the write discarded because the doctype declares no column for them, or because the
|
|
570
728
|
value was a nested relation rather than a column value. Null when everything sent was
|
|
571
729
|
stored. The action still succeeded — this is what it did not keep, and a client that
|
|
@@ -614,7 +772,7 @@ var ActionRolledBack = class extends Error {
|
|
|
614
772
|
};
|
|
615
773
|
/**
|
|
616
774
|
* Column-alias prefix for a foreign key the record SELECT carries only so the link expansion can
|
|
617
|
-
* 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`
|
|
618
776
|
* omits its FK column by design — but the expansion needs the value to find the target. Aliasing
|
|
619
777
|
* keeps that need from changing the payload: every alias is stripped before the record is returned.
|
|
620
778
|
*/
|
|
@@ -650,11 +808,141 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
650
808
|
} : (pgClient, query) => pgClient.query(query);
|
|
651
809
|
const defaultRowLimit = options.defaultRecordLimit === void 0 ? 200 : options.defaultRecordLimit;
|
|
652
810
|
return extendSchema((build) => {
|
|
653
|
-
const
|
|
654
|
-
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;
|
|
655
813
|
if (!executor) throw new Error("StonecropPlugin: no pgExecutors found — ensure pgServices is configured");
|
|
814
|
+
const columns = createColumnReader(pgRegistry?.pgCodecs ?? {}, executor, options.tables);
|
|
656
815
|
if (options.actionHandlers) assertActionHandlersResolve(options.actionHandlers);
|
|
657
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
|
+
};
|
|
658
946
|
return {
|
|
659
947
|
typeDefs,
|
|
660
948
|
objects: {
|
|
@@ -672,129 +960,7 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
672
960
|
doctype: $doctype,
|
|
673
961
|
id: $id,
|
|
674
962
|
options: $options
|
|
675
|
-
}),
|
|
676
|
-
const byDoctype = /* @__PURE__ */ new Map();
|
|
677
|
-
for (let i = 0; i < specs.length; i++) {
|
|
678
|
-
const d = String(specs[i].doctype);
|
|
679
|
-
if (!byDoctype.has(d)) byDoctype.set(d, []);
|
|
680
|
-
byDoctype.get(d).push(i);
|
|
681
|
-
}
|
|
682
|
-
const results = Array.from({ length: specs.length });
|
|
683
|
-
for (const [doctype, indices] of byDoctype) {
|
|
684
|
-
const meta = getMeta(doctype);
|
|
685
|
-
if (!meta) {
|
|
686
|
-
for (const i of indices) results[i] = {
|
|
687
|
-
data: null,
|
|
688
|
-
doctype
|
|
689
|
-
};
|
|
690
|
-
continue;
|
|
691
|
-
}
|
|
692
|
-
const pkMeta = getPkMeta(meta);
|
|
693
|
-
if (!pkMeta) throw unresolvableIdentityError(doctype);
|
|
694
|
-
const pkColumn = camelToSnake(pkMeta.fieldname);
|
|
695
|
-
const columns = getSqlColumns(meta);
|
|
696
|
-
const ids = indices.map((i) => String(specs[i].id));
|
|
697
|
-
const fieldByName = new Map(flattenFields$1(meta.fields).map((f) => [f.fieldname, f]));
|
|
698
|
-
const linkFkAliases = [];
|
|
699
|
-
for (const [linkName, link] of Object.entries(meta.links ?? {})) {
|
|
700
|
-
if (link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne") continue;
|
|
701
|
-
const fieldname = link.fieldname ?? linkName;
|
|
702
|
-
if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
|
|
703
|
-
linkFkAliases.push({
|
|
704
|
-
fieldname,
|
|
705
|
-
alias: `${LINK_FK_ALIAS}${fieldname}`
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
const selectList = [columns, ...linkFkAliases.map(({ fieldname, alias }) => `"${camelToSnake(fieldname)}" AS "${alias}"`)].filter(Boolean).join(", ");
|
|
709
|
-
const { rows } = await debugSql(pgClient, {
|
|
710
|
-
text: `SELECT ${selectList} FROM ${resolveTableName(meta.name, options.tables)} WHERE "${pkColumn}"::text = ANY($1::text[])`,
|
|
711
|
-
values: [ids]
|
|
712
|
-
});
|
|
713
|
-
const rowByPk = new Map(rows.map((r) => [String(r[pkMeta.fieldname]), r]));
|
|
714
|
-
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.`);
|
|
715
|
-
const enrichedRows = [];
|
|
716
|
-
for (const i of indices) {
|
|
717
|
-
const specId = String(specs[i].id);
|
|
718
|
-
const row = rowByPk.get(specId);
|
|
719
|
-
if (!row) {
|
|
720
|
-
results[i] = {
|
|
721
|
-
data: null,
|
|
722
|
-
doctype
|
|
723
|
-
};
|
|
724
|
-
continue;
|
|
725
|
-
}
|
|
726
|
-
const rowData = { ...row };
|
|
727
|
-
enrichedRows.push(rowData);
|
|
728
|
-
const truncatedLinks = [];
|
|
729
|
-
const recordOptions = specs[i].options ?? {};
|
|
730
|
-
const includeAll = recordOptions.includeNested === true;
|
|
731
|
-
const includeSet = Array.isArray(recordOptions.includeNested) ? new Set(recordOptions.includeNested) : null;
|
|
732
|
-
if (meta.links) for (const [linkName, link] of Object.entries(meta.links)) {
|
|
733
|
-
const fieldname = link.fieldname ?? linkName;
|
|
734
|
-
const fetch = link.fetch;
|
|
735
|
-
const isMany = link.cardinality === "noneOrMany" || link.cardinality === "atLeastOne";
|
|
736
|
-
const effectiveMethod = fetch?.method ?? (isMany ? "sync" : "lazy");
|
|
737
|
-
const declaredLimit = fetch?.method === "sync" ? fetch.limit : void 0;
|
|
738
|
-
const effectiveLimit = isMany ? declaredLimit ?? defaultRowLimit : void 0;
|
|
739
|
-
if (!(includeAll || (includeSet ? includeSet.has(linkName) : effectiveMethod === "sync"))) continue;
|
|
740
|
-
if (effectiveMethod === "custom" && fetch?.method === "custom") {
|
|
741
|
-
const handlerName = fetch.handler;
|
|
742
|
-
const handler = getFetchHandler(handlerName);
|
|
743
|
-
if (handler) rowData[fieldname] = await handler(pgClient, rowData, link);
|
|
744
|
-
continue;
|
|
745
|
-
}
|
|
746
|
-
if (resolveLinkRenderMode(link, fieldByName.get(fieldname)?.component) === "inline") continue;
|
|
747
|
-
const targetMeta = getMeta(link.target);
|
|
748
|
-
if (!targetMeta) continue;
|
|
749
|
-
const targetColumns = getSqlColumns(targetMeta);
|
|
750
|
-
if (isMany) {
|
|
751
|
-
if (!link.backlink) continue;
|
|
752
|
-
const backlinkCol = camelToSnake(link.backlink);
|
|
753
|
-
let sql = `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${backlinkCol}"::text = $1`;
|
|
754
|
-
const linkValues = [specId];
|
|
755
|
-
const linkPkMeta = getPkMeta(targetMeta);
|
|
756
|
-
if (linkPkMeta) sql += ` ORDER BY "${camelToSnake(linkPkMeta.fieldname)}" ASC`;
|
|
757
|
-
if (effectiveLimit != null) {
|
|
758
|
-
sql += ` LIMIT $2`;
|
|
759
|
-
linkValues.push(effectiveLimit + 1);
|
|
760
|
-
}
|
|
761
|
-
const { rows: linked } = await debugSql(pgClient, {
|
|
762
|
-
text: sql,
|
|
763
|
-
values: linkValues
|
|
764
|
-
});
|
|
765
|
-
if (effectiveLimit != null && linked.length > effectiveLimit) {
|
|
766
|
-
truncatedLinks.push(fieldname);
|
|
767
|
-
rowData[fieldname] = linked.slice(0, effectiveLimit);
|
|
768
|
-
} else rowData[fieldname] = linked;
|
|
769
|
-
} else {
|
|
770
|
-
const fkValue = rowData[`${LINK_FK_ALIAS}${fieldname}`];
|
|
771
|
-
if (fkValue == null) {
|
|
772
|
-
rowData[fieldname] = null;
|
|
773
|
-
continue;
|
|
774
|
-
}
|
|
775
|
-
const targetPkMeta = getPkMeta(targetMeta);
|
|
776
|
-
if (!targetPkMeta) throw unresolvableIdentityError(targetMeta.name);
|
|
777
|
-
const targetPkColumn = camelToSnake(targetPkMeta.fieldname);
|
|
778
|
-
const { rows: linked } = await debugSql(pgClient, {
|
|
779
|
-
text: `SELECT ${targetColumns} FROM ${resolveTableName(targetMeta.name, options.tables)} WHERE "${targetPkColumn}" = $1`,
|
|
780
|
-
values: [fkValue]
|
|
781
|
-
});
|
|
782
|
-
rowData[fieldname] = linked[0] ?? null;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
for (const { alias } of linkFkAliases) delete rowData[alias];
|
|
786
|
-
const unknownLinks = includeSet && meta.links ? [...includeSet].filter((name) => !(name in meta.links)) : void 0;
|
|
787
|
-
results[i] = {
|
|
788
|
-
data: rowData,
|
|
789
|
-
doctype,
|
|
790
|
-
unknownLinks: unknownLinks?.length ? unknownLinks : void 0,
|
|
791
|
-
truncatedLinks: truncatedLinks.length ? truncatedLinks : void 0
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
await enrichLinkDisplayFields(pgClient, meta, enrichedRows, options.tables, debugSql);
|
|
795
|
-
}
|
|
796
|
-
return results;
|
|
797
|
-
});
|
|
963
|
+
}), readRecords);
|
|
798
964
|
},
|
|
799
965
|
stonecropRecords(_, { $doctype, $filters, $orderBy, $limit, $offset, $includeTotal }) {
|
|
800
966
|
return loadOneWithPgClient(executor, object({
|
|
@@ -815,15 +981,17 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
815
981
|
count: spec.includeTotal === true ? 0 : null
|
|
816
982
|
};
|
|
817
983
|
const knownFields = new Set(flattenFields$1(meta.fields).map((f) => f.fieldname));
|
|
818
|
-
const
|
|
819
|
-
const
|
|
984
|
+
const select = columns.select(meta.name, getColumnSelections(meta));
|
|
985
|
+
const filterValues = [];
|
|
820
986
|
const whereClauses = [];
|
|
821
987
|
if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
|
|
822
988
|
if (!knownFields.has(field)) throw new Error(`Unknown filter field: ${field} for doctype ${meta.name}`);
|
|
823
|
-
|
|
824
|
-
|
|
989
|
+
filterValues.push(value);
|
|
990
|
+
const column = camelToSnake(field);
|
|
991
|
+
whereClauses.push(`"${column}" = ${columns.bind(meta.name, column, `$${filterValues.length}`)}`);
|
|
825
992
|
}
|
|
826
993
|
const whereClause = whereClauses.length > 0 ? ` WHERE ${whereClauses.join(" AND ")}` : "";
|
|
994
|
+
const values = [...filterValues];
|
|
827
995
|
let orderByClause = "";
|
|
828
996
|
if (spec.orderBy != null) {
|
|
829
997
|
if (typeof spec.orderBy !== "string") throw new Error(`Invalid orderBy: expected string, got ${typeof spec.orderBy}`);
|
|
@@ -852,25 +1020,18 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
852
1020
|
pagingClause += ` OFFSET $${values.length}`;
|
|
853
1021
|
}
|
|
854
1022
|
const { rows } = await debugSql(pgClient, {
|
|
855
|
-
text: `SELECT ${
|
|
1023
|
+
text: `SELECT ${select.list} FROM ${select.table}${whereClause}${orderByClause}${pagingClause}`,
|
|
856
1024
|
values
|
|
857
1025
|
});
|
|
1026
|
+
select.decodeRows(rows);
|
|
858
1027
|
const hasMore = effectiveLimit != null && rows.length > effectiveLimit;
|
|
859
1028
|
const data = [...hasMore ? rows.slice(0, effectiveLimit ?? rows.length) : rows];
|
|
860
|
-
await enrichLinkDisplayFields(pgClient, meta, data,
|
|
1029
|
+
await enrichLinkDisplayFields(pgClient, meta, data, columns, debugSql);
|
|
861
1030
|
let count = null;
|
|
862
1031
|
if (spec.includeTotal === true) {
|
|
863
|
-
const countValues = [];
|
|
864
|
-
const countWhere = [];
|
|
865
|
-
if (spec.filters != null) for (const [field, value] of Object.entries(spec.filters)) {
|
|
866
|
-
if (!knownFields.has(field)) continue;
|
|
867
|
-
countValues.push(value);
|
|
868
|
-
countWhere.push(`"${camelToSnake(field)}" = $${countValues.length}`);
|
|
869
|
-
}
|
|
870
|
-
const countWhereClause = countWhere.length > 0 ? ` WHERE ${countWhere.join(" AND ")}` : "";
|
|
871
1032
|
const { rows: countRows } = await debugSql(pgClient, {
|
|
872
|
-
text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${
|
|
873
|
-
values:
|
|
1033
|
+
text: `SELECT COUNT(*) AS row_count FROM ${resolveTableName(meta.name, options.tables)}${whereClause}`,
|
|
1034
|
+
values: filterValues
|
|
874
1035
|
});
|
|
875
1036
|
count = parseInt(countRows[0]?.row_count ?? "0", 10);
|
|
876
1037
|
}
|
|
@@ -960,28 +1121,31 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
960
1121
|
},
|
|
961
1122
|
writeData: async (patch, exists) => {
|
|
962
1123
|
const { cols, values } = partitionPatch(patch);
|
|
963
|
-
const returning =
|
|
1124
|
+
const returning = columns.select(meta.name, getColumnSelections(meta));
|
|
964
1125
|
if (!exists) {
|
|
965
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.`);
|
|
966
|
-
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}`;
|
|
967
1128
|
const { rows } = await debugSql(tx, {
|
|
968
1129
|
text,
|
|
969
1130
|
values
|
|
970
1131
|
});
|
|
1132
|
+
returning.decodeRows(rows);
|
|
971
1133
|
return rows[0] ?? {};
|
|
972
1134
|
}
|
|
973
1135
|
if (cols.length === 0) {
|
|
974
1136
|
const { rows } = await debugSql(tx, {
|
|
975
|
-
text: `SELECT ${returning} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
|
|
1137
|
+
text: `SELECT ${returning.list} FROM ${table} WHERE "${pkColumn()}"::text = $1`,
|
|
976
1138
|
values: [String(recordId)]
|
|
977
1139
|
});
|
|
1140
|
+
returning.decodeRows(rows);
|
|
978
1141
|
return rows[0] ?? {};
|
|
979
1142
|
}
|
|
980
|
-
const assignments = cols.map((c, i) => `"${c}" =
|
|
1143
|
+
const assignments = cols.map((c, i) => `"${c}" = ${columns.bind(meta.name, c, `$${i + 1}`)}`).join(", ");
|
|
981
1144
|
const { rows } = await debugSql(tx, {
|
|
982
|
-
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}`,
|
|
983
1146
|
values: [...values, String(recordId)]
|
|
984
1147
|
});
|
|
1148
|
+
returning.decodeRows(rows);
|
|
985
1149
|
return rows[0] ?? {};
|
|
986
1150
|
},
|
|
987
1151
|
runEffect: handler ? (currentState) => handler({
|
|
@@ -998,12 +1162,22 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
998
1162
|
if (!outcome.success) throw new ActionRolledBack(outcome);
|
|
999
1163
|
if (outcome.success && outcome.data !== null && typeof outcome.data === "object") {
|
|
1000
1164
|
const written = (Array.isArray(outcome.data) ? outcome.data : [outcome.data]).filter((row) => row !== null && typeof row === "object");
|
|
1001
|
-
await enrichLinkDisplayFields(tx, meta, written,
|
|
1165
|
+
await enrichLinkDisplayFields(tx, meta, written, columns, debugSql);
|
|
1002
1166
|
}
|
|
1003
|
-
|
|
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 = {
|
|
1004
1174
|
...outcome,
|
|
1175
|
+
record
|
|
1176
|
+
};
|
|
1177
|
+
return droppedFields.length ? {
|
|
1178
|
+
...reply,
|
|
1005
1179
|
droppedFields
|
|
1006
|
-
} :
|
|
1180
|
+
} : reply;
|
|
1007
1181
|
});
|
|
1008
1182
|
} catch (err) {
|
|
1009
1183
|
if (err instanceof ActionRolledBack) return err.outcome;
|
|
@@ -1020,7 +1194,7 @@ var createStonecropPlugin = (options = {}) => {
|
|
|
1020
1194
|
});
|
|
1021
1195
|
};
|
|
1022
1196
|
/**
|
|
1023
|
-
* Derive
|
|
1197
|
+
* Derive column selections from a flat field array.
|
|
1024
1198
|
* Skips non-scalar fields (kind !== 'field'), `computed` fields
|
|
1025
1199
|
* (no backing DB column), and *expanding* links
|
|
1026
1200
|
* (relations fetched separately, not scalar columns on this table).
|
|
@@ -1030,25 +1204,27 @@ function collectColumns(fields, links) {
|
|
|
1030
1204
|
for (const f of columnBackedFields(fields)) {
|
|
1031
1205
|
const link = links.get(f.fieldname);
|
|
1032
1206
|
if (link && resolveLinkRenderMode(link, f.component) !== "inline") continue;
|
|
1033
|
-
|
|
1034
|
-
|
|
1207
|
+
columns.push({
|
|
1208
|
+
column: camelToSnake(f.fieldname),
|
|
1209
|
+
alias: f.fieldname
|
|
1210
|
+
});
|
|
1035
1211
|
}
|
|
1036
1212
|
return columns;
|
|
1037
1213
|
}
|
|
1038
1214
|
/**
|
|
1039
|
-
* Derive a
|
|
1040
|
-
* Applies camelToSnake to each fieldname to get the DB column name,
|
|
1041
|
-
*
|
|
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.
|
|
1042
1218
|
* Excludes `computed` fields (no backing DB column), Fieldset
|
|
1043
1219
|
* containers (recursing into their children instead), and *expanding* links
|
|
1044
1220
|
* (relations fetched separately). An inline link keeps its FK column here.
|
|
1045
1221
|
*
|
|
1046
1222
|
* Exported for unit testing (not re-exported from the package index).
|
|
1047
1223
|
*/
|
|
1048
|
-
function
|
|
1224
|
+
function getColumnSelections(meta) {
|
|
1049
1225
|
const links = /* @__PURE__ */ new Map();
|
|
1050
1226
|
if (meta.links) for (const [key, link] of Object.entries(meta.links)) links.set(link.fieldname ?? key, link);
|
|
1051
|
-
return collectColumns(meta.fields, links)
|
|
1227
|
+
return collectColumns(meta.fields, links);
|
|
1052
1228
|
}
|
|
1053
1229
|
/**
|
|
1054
1230
|
* Resolve the declared field this doctype's records are looked up by.
|
|
@@ -1060,11 +1236,11 @@ function getSqlColumns(meta) {
|
|
|
1060
1236
|
* like a record that does not exist.
|
|
1061
1237
|
*
|
|
1062
1238
|
* Returns `undefined` only when the resolved name is not a declared field — a doctype with no
|
|
1063
|
-
* `primaryKey` and no `id`. That case cannot be served: `
|
|
1239
|
+
* `primaryKey` and no `id`. That case cannot be served: `getColumnSelections` selects declared fields
|
|
1064
1240
|
* only, so the row map would key on a column the SELECT never returned and every lookup would miss
|
|
1065
1241
|
* silently. Callers must say so rather than answer `null`.
|
|
1066
1242
|
*
|
|
1067
|
-
* 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
|
|
1068
1244
|
* a fieldset's children, and `getRecordIdField` resolves a key declared among them. While this
|
|
1069
1245
|
* scanned top level only it could refuse a name that helper had just resolved, so a doctype whose
|
|
1070
1246
|
* SELECT carried its own key column had no identity to look that column up by.
|