simetra 0.3.0-next.7 → 0.3.0-next.8

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.
@@ -5980,8 +5980,8 @@ function readSqlUnits(sources, parse, known) {
5980
5980
  }
5981
5981
  const declared = files.flatMap(({ source, statements }) => statements.flatMap(({ stmt }) => {
5982
5982
  if ("CreateDomainStmt" in stmt) return [qualify$1(strings$4(stmt.CreateDomainStmt.domainname), source.schema)];
5983
- if ("ViewStmt" in stmt) return [relation$5(stmt.ViewStmt.view, source.schema)];
5984
- if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") return [relation$5(stmt.CreateTableAsStmt.into?.rel, source.schema)];
5983
+ if ("ViewStmt" in stmt) return [relation$6(stmt.ViewStmt.view, source.schema)];
5984
+ if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") return [relation$6(stmt.CreateTableAsStmt.into?.rel, source.schema)];
5985
5985
  return [];
5986
5986
  }));
5987
5987
  const types = modelTypes([...known, ...declared]);
@@ -6302,7 +6302,7 @@ function classify(stmt, scope) {
6302
6302
  }
6303
6303
  if ("CreateTrigStmt" in stmt) {
6304
6304
  const node = stmt.CreateTrigStmt;
6305
- const table = relation$5(node.relation, schema);
6305
+ const table = relation$6(node.relation, schema);
6306
6306
  const name = node.trigname ?? "";
6307
6307
  return unit("trigger", {
6308
6308
  schema: table.schema,
@@ -6311,7 +6311,7 @@ function classify(stmt, scope) {
6311
6311
  }
6312
6312
  if ("CreatePolicyStmt" in stmt) {
6313
6313
  const node = stmt.CreatePolicyStmt;
6314
- const table = relation$5(node.table, schema);
6314
+ const table = relation$6(node.table, schema);
6315
6315
  const name = node.policy_name ?? "";
6316
6316
  return unit("policy", {
6317
6317
  schema: table.schema,
@@ -6319,11 +6319,11 @@ function classify(stmt, scope) {
6319
6319
  }, qualifiedName(table.schema, table.name, name));
6320
6320
  }
6321
6321
  if ("ViewStmt" in stmt) {
6322
- const view = relation$5(stmt.ViewStmt.view, schema);
6322
+ const view = relation$6(stmt.ViewStmt.view, schema);
6323
6323
  return unit("view", view, qualifiedName(view.schema, view.name));
6324
6324
  }
6325
6325
  if ("CreateTableAsStmt" in stmt && stmt.CreateTableAsStmt.objtype === "OBJECT_MATVIEW") {
6326
- const view = relation$5(stmt.CreateTableAsStmt.into?.rel, schema);
6326
+ const view = relation$6(stmt.CreateTableAsStmt.into?.rel, schema);
6327
6327
  return unit("materializedView", view, qualifiedName(view.schema, view.name));
6328
6328
  }
6329
6329
  if ("GrantStmt" in stmt) {
@@ -6378,7 +6378,7 @@ function classify(stmt, scope) {
6378
6378
  }, quoteIdent(name));
6379
6379
  }
6380
6380
  if ("CreateSeqStmt" in stmt) {
6381
- const seq = relation$5(stmt.CreateSeqStmt.sequence, schema);
6381
+ const seq = relation$6(stmt.CreateSeqStmt.sequence, schema);
6382
6382
  return unit("sequence", seq, qualifiedName(seq.schema, seq.name));
6383
6383
  }
6384
6384
  if ("AlterSeqStmt" in stmt) {
@@ -6388,7 +6388,7 @@ function classify(stmt, scope) {
6388
6388
  notAllowed: statement,
6389
6389
  detail: "only OWNED BY is allowed"
6390
6390
  };
6391
- const seq = relation$5(node.sequence, schema);
6391
+ const seq = relation$6(node.sequence, schema);
6392
6392
  return unit("sequenceOwnedBy", seq, qualifiedName(seq.schema, seq.name));
6393
6393
  }
6394
6394
  if ("CreateDomainStmt" in stmt) {
@@ -6407,7 +6407,7 @@ function classify(stmt, scope) {
6407
6407
  if (!("PublicationObjSpec" in o)) return "";
6408
6408
  const spec = o.PublicationObjSpec;
6409
6409
  if (spec.pubtable !== void 0) {
6410
- const table = relation$5(spec.pubtable.relation, schema);
6410
+ const table = relation$6(spec.pubtable.relation, schema);
6411
6411
  return qualifiedName(table.schema, table.name);
6412
6412
  }
6413
6413
  return `schema ${quoteIdent(spec.name ?? schema)}`;
@@ -6425,7 +6425,7 @@ function classify(stmt, scope) {
6425
6425
  notAllowed: statement,
6426
6426
  detail: "rowRuleName"
6427
6427
  };
6428
- const table = relation$5(node.relation, schema);
6428
+ const table = relation$6(node.relation, schema);
6429
6429
  return { rowRule: {
6430
6430
  schema: table.schema,
6431
6431
  table: table.name,
@@ -6439,7 +6439,7 @@ function classify(stmt, scope) {
6439
6439
  detail: "only REPLICA IDENTITY is allowed",
6440
6440
  ...subtypes.some((s) => ROW_SECURITY.has(s)) ? { feature: "rowLevelSecurity" } : {}
6441
6441
  };
6442
- const table = relation$5(node.relation, schema);
6442
+ const table = relation$6(node.relation, schema);
6443
6443
  return unit("replicaIdentity", table, qualifiedName(table.schema, table.name));
6444
6444
  }
6445
6445
  if ("AlterFunctionStmt" in stmt) {
@@ -6485,7 +6485,7 @@ function qualify$1(names, schema) {
6485
6485
  name
6486
6486
  };
6487
6487
  }
6488
- function relation$5(rv, schema) {
6488
+ function relation$6(rv, schema) {
6489
6489
  return {
6490
6490
  schema: rv?.schemaname ?? schema,
6491
6491
  name: rv?.relname ?? ""
@@ -6546,7 +6546,7 @@ function targetParts(node) {
6546
6546
  function targetName$1(node, objtype, scope) {
6547
6547
  const { schema } = scope;
6548
6548
  if ("RangeVar" in node) {
6549
- const { schema: s, name } = relation$5(node.RangeVar, schema);
6549
+ const { schema: s, name } = relation$6(node.RangeVar, schema);
6550
6550
  return qualifiedName(s, name);
6551
6551
  }
6552
6552
  if ("ObjectWithArgs" in node) return functionObject(node.ObjectWithArgs, scope);
@@ -10275,6 +10275,21 @@ function bindingValue(hops, index) {
10275
10275
  return index === hops.length - 1 ? direct.column : carrierCopyName(hops[index].column, direct.column);
10276
10276
  }
10277
10277
  /**
10278
+ * Ланцюжкові нащадки кожного виду за id (Р-К1-8): вид лежить на ланцюжку
10279
+ * нащадка вище за його перший крок. Транзитивне замикання вже записане в
10280
+ * кроках ланцюжків стадії 3 — другого обходу графа немає. Контейнер нащадків
10281
+ * не має: ланцюжок кінчається на ньому, тож він лише ціль кроку. Нащадки — у
10282
+ * порядку id: генератор впорядковує їх за міткою сам.
10283
+ */
10284
+ function bindingDescendants(bindings) {
10285
+ const descendants = /* @__PURE__ */ new Map();
10286
+ for (const [id, binding] of [...bindings].sort(([a], [b]) => compareStrings(a, b))) {
10287
+ if (!binding.ok) continue;
10288
+ for (const hop of binding.hops.slice(1)) descendants.set(hop.object, [...descendants.get(hop.object) ?? [], id]);
10289
+ }
10290
+ return descendants;
10291
+ }
10292
+ /**
10278
10293
  * Прив'язка об'єкта в контракті: контейнер — кінцевий, носій — колонка
10279
10294
  * реквізиту, а в ланцюжку — копія зі значенням прив'язки цілі (`via`); з
10280
10295
  * фізичного знімка — лише ім'я основної таблиці цілі. `undefined` — ланцюжок
@@ -12822,22 +12837,32 @@ const DERIVE_LABEL = "simetra_carriers";
12822
12837
  const PROPAGATE_LABEL = "simetra_carriers_out";
12823
12838
  const PROPAGATE_INSERT_LABEL = "simetra_carriers_out_insert";
12824
12839
  /**
12840
+ * Мітка тригера переприв'язування (Р-К1-8): тієї самої довжини, що
12841
+ * `PROPAGATE_LABEL`, тож алгоритм імен обрізає таблицю до того самого
12842
+ * префікса на будь-якій довжині, а `bnd` < `out` — і тригер одного моменту
12843
+ * спрацьовує раніше за поширення (Postgres запускає їх за іменем).
12844
+ */
12845
+ const REBIND_LABEL = "simetra_carriers_bnd";
12846
+ /**
12825
12847
  * Імена тригерів копій носіїв на таблиці: `derive` — на таблиці з копіями,
12826
- * обидва тригери поширення — на таблиці-джерелі. `derive` — рядковий
12827
- * `BEFORE`, тож іде спільним префіксом групи: інакше на довгій назві він
12828
- * спрацював би не між авторством і механікою. Поширення — `AFTER`, на `NEW`
12829
- * не впливає, і лишається на алгоритмі Postgres, що тримає мітку цілою.
12848
+ * обидва тригери поширення й переприв'язування — на таблиці-джерелі.
12849
+ * `derive` — рядковий `BEFORE`, тож іде спільним префіксом групи: інакше на
12850
+ * довгій назві він спрацював би не між авторством і механікою. Поширення й
12851
+ * переприв'язування — `AFTER`, на `NEW` не впливають, і лишаються на
12852
+ * алгоритмі Postgres, що тримає мітку цілою.
12830
12853
  */
12831
12854
  function carrierTriggerNames(table) {
12832
12855
  return {
12833
12856
  derive: platformBeforeTriggerName(table.name, DERIVE_LABEL),
12834
12857
  propagate: makeObjectName(table.name, void 0, PROPAGATE_LABEL),
12835
- propagateInsert: makeObjectName(table.name, void 0, PROPAGATE_INSERT_LABEL)
12858
+ propagateInsert: makeObjectName(table.name, void 0, PROPAGATE_INSERT_LABEL),
12859
+ rebind: makeObjectName(table.name, void 0, REBIND_LABEL)
12836
12860
  };
12837
12861
  }
12838
12862
  /**
12839
12863
  * Функції носіїв у схемі таблиці: виведення — на таблиці з копіями,
12840
- * поширення — одна на джерело для обох його тригерів.
12864
+ * поширення — одна на джерело для обох його тригерів, переприв'язування —
12865
+ * на джерелі ланцюжка.
12841
12866
  */
12842
12867
  function carrierFunctionNames(table) {
12843
12868
  const names = carrierTriggerNames(table);
@@ -12849,6 +12874,10 @@ function carrierFunctionNames(table) {
12849
12874
  propagate: {
12850
12875
  schema: table.schema,
12851
12876
  name: names.propagate
12877
+ },
12878
+ rebind: {
12879
+ schema: table.schema,
12880
+ name: names.rebind
12852
12881
  }
12853
12882
  };
12854
12883
  }
@@ -12903,7 +12932,10 @@ function carrierLinks(physical) {
12903
12932
  }
12904
12933
  /**
12905
12934
  * Функції носіїв знімка — спільні для генератора й перевірки колізій імен
12906
- * функцій стадії 4 (`derivedFunctions`).
12935
+ * функцій стадії 4 (`derivedFunctions`). Переприв'язування — з запасом, на
12936
+ * кожному джерелі: чи має джерело ланцюжкових нащадків, вирішують контракти,
12937
+ * яких перевірка колізій не має, а джерело ланцюжка завжди є джерелом копії.
12938
+ * Як і функція ефектів, зайве ім'я лише резервується.
12907
12939
  */
12908
12940
  function carrierFunctions(physical) {
12909
12941
  const links = carrierLinks(physical);
@@ -12917,14 +12949,18 @@ function carrierFunctions(physical) {
12917
12949
  table,
12918
12950
  fn: carrierFunctionNames(table).derive,
12919
12951
  role: "derive"
12920
- })), ...[...sources.values()].map((table) => ({
12952
+ })), ...[...sources.values()].flatMap((table) => [{
12921
12953
  table,
12922
12954
  fn: carrierFunctionNames(table).propagate,
12923
12955
  role: "propagate"
12924
- }))];
12956
+ }, {
12957
+ table,
12958
+ fn: carrierFunctionNames(table).rebind,
12959
+ role: "rebind"
12960
+ }])];
12925
12961
  }
12926
- const q$11 = quoteIdent;
12927
- const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
12962
+ const q$12 = quoteIdent;
12963
+ const relation$5 = (t) => `${q$12(t.schema)}.${q$12(t.name)}`;
12928
12964
  /** Функція джерел копій від авторства (спека П4 §6.7). */
12929
12965
  const AUTHOR_CARRIER_SOURCES_FUNCTION = {
12930
12966
  schema: PLATFORM_SCHEMA,
@@ -12983,14 +13019,14 @@ function authorSourcesUnits(physical, attributeCase, provider, module, parse) {
12983
13019
  const sources = authorCarrierSources(physical, attributeCase);
12984
13020
  if (sources === void 0) return [];
12985
13021
  const users = authorSource(authorCarrierLinks(physical, attributeCase));
12986
- const fn = relation$4(sources.fn);
13022
+ const fn = relation$5(sources.fn);
12987
13023
  const body = [
12988
- `SELECT ${sources.columns.map((c) => `s.${q$11(c.name)}`).join(", ")}`,
12989
- `FROM ${relation$4(users)} s`,
12990
- `WHERE s.${q$11(users.key)} = ${CURRENT_USER$1}`
13024
+ `SELECT ${sources.columns.map((c) => `s.${q$12(c.name)}`).join(", ")}`,
13025
+ `FROM ${relation$5(users)} s`,
13026
+ `WHERE s.${q$12(users.key)} = ${CURRENT_USER$1}`
12991
13027
  ].join("\n");
12992
13028
  const tag = dollarTag$1(body);
12993
- const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$11(c.name)} ${c.type}`).join(", ")})\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
13029
+ const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$12(c.name)} ${c.type}`).join(", ")})\nLANGUAGE sql STABLE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
12994
13030
  const requires = [{
12995
13031
  type: "table",
12996
13032
  schema: users.schema,
@@ -13045,7 +13081,7 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
13045
13081
  const table = group[0].table;
13046
13082
  const fn = carrierFunctionNames(table).derive;
13047
13083
  const sources = uniqueTables(group.map((l) => l.source));
13048
- units.push(unit(table, deriveFunction(fn, group), sources.map(tableNode)), ...executeGrants(`${relation$4(fn)}()`, [], provider).map((sql) => unit(table, sql)), unit(table, `CREATE TRIGGER ${q$11(carrierTriggerNames(table).derive)} BEFORE INSERT OR UPDATE ON ${relation$4(table)} FOR EACH ROW EXECUTE FUNCTION ${relation$4(fn)}();`));
13084
+ units.push(unit(table, deriveFunction(fn, group), sources.map(tableNode)), ...executeGrants(`${relation$5(fn)}()`, [], provider).map((sql) => unit(table, sql)), unit(table, `CREATE TRIGGER ${q$12(carrierTriggerNames(table).derive)} BEFORE INSERT OR UPDATE ON ${relation$5(table)} FOR EACH ROW EXECUTE FUNCTION ${relation$5(fn)}();`));
13049
13085
  }
13050
13086
  for (const group of byTable((l) => l.source)) {
13051
13087
  const source = group[0].source;
@@ -13053,9 +13089,9 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
13053
13089
  const names = carrierTriggerNames(source);
13054
13090
  const dependents = uniqueTables(group.map((l) => l.table));
13055
13091
  const read = new Set(group.flatMap((l) => l.copies.map((c) => c.column)));
13056
- const changed = source.columns.filter((c) => read.has(c.name)).map((c) => `(OLD.${q$11(c.name)} IS DISTINCT FROM NEW.${q$11(c.name)})`).join(" OR ");
13057
- const execute = `EXECUTE FUNCTION ${relation$4(fn)}();`;
13058
- units.push(unit(source, propagateFunction(fn, group), dependents.map(tableNode)), ...executeGrants(`${relation$4(fn)}()`, [], provider).map((sql) => unit(source, sql)), unit(source, `CREATE TRIGGER ${q$11(names.propagate)} AFTER UPDATE ON ${relation$4(source)} FOR EACH ROW WHEN (${changed}) ${execute}`), unit(source, `CREATE TRIGGER ${q$11(names.propagateInsert)} AFTER INSERT ON ${relation$4(source)} FOR EACH ROW ${execute}`));
13092
+ const changed = source.columns.filter((c) => read.has(c.name)).map((c) => `(OLD.${q$12(c.name)} IS DISTINCT FROM NEW.${q$12(c.name)})`).join(" OR ");
13093
+ const execute = `EXECUTE FUNCTION ${relation$5(fn)}();`;
13094
+ units.push(unit(source, propagateFunction(fn, group), dependents.map(tableNode)), ...executeGrants(`${relation$5(fn)}()`, [], provider).map((sql) => unit(source, sql)), unit(source, `CREATE TRIGGER ${q$12(names.propagate)} AFTER UPDATE ON ${relation$5(source)} FOR EACH ROW WHEN (${changed}) ${execute}`), unit(source, `CREATE TRIGGER ${q$12(names.propagateInsert)} AFTER INSERT ON ${relation$5(source)} FOR EACH ROW ${execute}`));
13059
13095
  }
13060
13096
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
13061
13097
  }
@@ -13064,7 +13100,7 @@ function uniqueTables(tables) {
13064
13100
  }
13065
13101
  /** `s.<джерело> = <row>.<локальна> AND …` за колонками FK зв'язку. */
13066
13102
  function sourceRow(link, row) {
13067
- return link.pairs.map((p) => `s.${q$11(p.source)} = ${row}.${q$11(p.local)}`).join(" AND ");
13103
+ return link.pairs.map((p) => `s.${q$12(p.source)} = ${row}.${q$12(p.local)}`).join(" AND ");
13068
13104
  }
13069
13105
  /**
13070
13106
  * Читання всіх копій зв'язку з рядка джерела в `row` — один будівник для
@@ -13075,9 +13111,9 @@ function sourceRow(link, row) {
13075
13111
  */
13076
13112
  function carrierCopyRead(link, row, lock) {
13077
13113
  return [
13078
- `SELECT ${link.copies.map((c) => `s.${q$11(c.column)}`).join(", ")}`,
13079
- ` INTO ${link.copies.map((c) => `${row}.${q$11(c.name)}`).join(", ")}`,
13080
- ` FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
13114
+ `SELECT ${link.copies.map((c) => `s.${q$12(c.column)}`).join(", ")}`,
13115
+ ` INTO ${link.copies.map((c) => `${row}.${q$12(c.name)}`).join(", ")}`,
13116
+ ` FROM ${relation$5(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
13081
13117
  ...lock ? [" FOR SHARE;"] : []
13082
13118
  ].join("\n");
13083
13119
  }
@@ -13092,10 +13128,10 @@ function carrierCopyRead(link, row, lock) {
13092
13128
  function deriveFunction(fn, links) {
13093
13129
  const body = ["BEGIN"];
13094
13130
  for (const link of links) {
13095
- const from = `FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
13096
- const linkChanged = link.pairs.map((p) => `NEW.${q$11(p.local)} IS DISTINCT FROM OLD.${q$11(p.local)}`).join(" OR ");
13131
+ const from = `FROM ${relation$5(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
13132
+ const linkChanged = link.pairs.map((p) => `NEW.${q$12(p.local)} IS DISTINCT FROM OLD.${q$12(p.local)}`).join(" OR ");
13097
13133
  body.push(` IF TG_OP = 'INSERT' OR ${linkChanged} THEN`, ` ${carrierCopyRead(link, "NEW", true)}`, " ELSE");
13098
- for (const copy of link.copies) body.push(` IF NEW.${q$11(copy.name)} IS DISTINCT FROM OLD.${q$11(copy.name)} THEN`, ` SELECT s.${q$11(copy.column)} INTO NEW.${q$11(copy.name)} ${from};`, " END IF;");
13134
+ for (const copy of link.copies) body.push(` IF NEW.${q$12(copy.name)} IS DISTINCT FROM OLD.${q$12(copy.name)} THEN`, ` SELECT s.${q$12(copy.column)} INTO NEW.${q$12(copy.name)} ${from};`, " END IF;");
13099
13135
  body.push(" END IF;");
13100
13136
  }
13101
13137
  body.push(" RETURN NEW;", "END");
@@ -13111,10 +13147,10 @@ function propagateFunction(fn, links) {
13111
13147
  const ordered = [...links].sort((a, b) => compareStrings(tableKey$1(a.table), tableKey$1(b.table)) || compareStrings(a.through, b.through));
13112
13148
  const body = ["BEGIN"];
13113
13149
  for (const link of ordered) {
13114
- const set = link.copies.map((c) => `${q$11(c.name)} = NEW.${q$11(c.column)}`).join(", ");
13115
- const row = link.pairs.map((p) => `d.${q$11(p.local)} = NEW.${q$11(p.source)}`).join(" AND ");
13116
- const differs = link.copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM NEW.${q$11(c.column)}`).join(" OR ");
13117
- body.push(` UPDATE ${relation$4(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
13150
+ const set = link.copies.map((c) => `${q$12(c.name)} = NEW.${q$12(c.column)}`).join(", ");
13151
+ const row = link.pairs.map((p) => `d.${q$12(p.local)} = NEW.${q$12(p.source)}`).join(" AND ");
13152
+ const differs = link.copies.map((c) => `d.${q$12(c.name)} IS DISTINCT FROM NEW.${q$12(c.column)}`).join(" OR ");
13153
+ body.push(` UPDATE ${relation$5(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
13118
13154
  }
13119
13155
  body.push(" RETURN NULL;", "END");
13120
13156
  return definerTrigger(fn, body.join("\n"));
@@ -13178,8 +13214,8 @@ function carrierBackfillStatements(physical, pending) {
13178
13214
  };
13179
13215
  for (const b of backfills) visit(b);
13180
13216
  return ordered.map(({ link, copies }) => {
13181
- const from = `FROM ${relation$4(link.source)} AS s WHERE ` + link.pairs.map((p) => `s.${q$11(p.source)} OPERATOR(pg_catalog.=) d.${q$11(p.local)}`).join(" AND ");
13182
- const differs = copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM (SELECT s.${q$11(c.column)} ${from})`).join(" OR ");
13217
+ const from = `FROM ${relation$5(link.source)} AS s WHERE ` + link.pairs.map((p) => `s.${q$12(p.source)} OPERATOR(pg_catalog.=) d.${q$12(p.local)}`).join(" AND ");
13218
+ const differs = copies.map((c) => `d.${q$12(c.name)} IS DISTINCT FROM (SELECT s.${q$12(c.column)} ${from})`).join(" OR ");
13183
13219
  return {
13184
13220
  table: {
13185
13221
  schema: link.table.schema,
@@ -13190,7 +13226,7 @@ function carrierBackfillStatements(physical, pending) {
13190
13226
  name: link.source.name
13191
13227
  },
13192
13228
  columns: copies.map((c) => c.name),
13193
- sql: `UPDATE ${relation$4(link.table)} AS d SET (${copies.map((c) => q$11(c.name)).join(", ")}) = (SELECT ${copies.map((c) => `s.${q$11(c.column)}`).join(", ")} ${from}) WHERE ${differs};`
13229
+ sql: `UPDATE ${relation$5(link.table)} AS d SET (${copies.map((c) => q$12(c.name)).join(", ")}) = (SELECT ${copies.map((c) => `s.${q$12(c.column)}`).join(", ")} ${from}) WHERE ${differs};`
13194
13230
  };
13195
13231
  });
13196
13232
  }
@@ -31510,8 +31546,8 @@ function hierarchyNames(table) {
31510
31546
  }
31511
31547
  };
31512
31548
  }
31513
- const q$10 = quoteIdent;
31514
- const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31549
+ const q$11 = quoteIdent;
31550
+ const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
31515
31551
  /**
31516
31552
  * Виклик advisory-замка ієрархії таблиці — одне джерело ключа для тригера й
31517
31553
  * ядра команд (спека П4 §6.6): інший вираз ключа в ядрі не серіалізував би його з
@@ -31519,7 +31555,7 @@ const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31519
31555
  * стабільний.
31520
31556
  */
31521
31557
  function hierarchyLockSql(table) {
31522
- return `pg_advisory_xact_lock(${HIERARCHY_LOCK_SPACE}, ${sqlLiteral(relation$3(table))}::regclass::oid::int)`;
31558
+ return `pg_advisory_xact_lock(${HIERARCHY_LOCK_SPACE}, ${sqlLiteral(relation$4(table))}::regclass::oid::int)`;
31523
31559
  }
31524
31560
  /**
31525
31561
  * Ієрархічні основні таблиці знімка: колонка батька — стандартна колонка
@@ -31576,8 +31612,8 @@ function buildHierarchyUnits(physical, objects, attributeCase, provider, module,
31576
31612
  name: table.name
31577
31613
  }] } : {}
31578
31614
  });
31579
- const execute = `EXECUTE FUNCTION ${relation$3(names.fn)}();`;
31580
- units.push(unit(definerTrigger(names.fn, hierarchyBody(entry), { rowSecurity: "off" }), true), ...executeGrants(`${relation$3(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$10(names.insert)} AFTER INSERT ON ${relation$3(table)} FOR EACH ROW WHEN (NEW.${q$10(parent)} IS NOT NULL) ${execute}`), unit(`CREATE TRIGGER ${q$10(names.update)} AFTER UPDATE ON ${relation$3(table)} FOR EACH ROW WHEN (NEW.${q$10(parent)} IS DISTINCT FROM OLD.${q$10(parent)}) ${execute}`));
31615
+ const execute = `EXECUTE FUNCTION ${relation$4(names.fn)}();`;
31616
+ units.push(unit(definerTrigger(names.fn, hierarchyBody(entry), { rowSecurity: "off" }), true), ...executeGrants(`${relation$4(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$11(names.insert)} AFTER INSERT ON ${relation$4(table)} FOR EACH ROW WHEN (NEW.${q$11(parent)} IS NOT NULL) ${execute}`), unit(`CREATE TRIGGER ${q$11(names.update)} AFTER UPDATE ON ${relation$4(table)} FOR EACH ROW WHEN (NEW.${q$11(parent)} IS DISTINCT FROM OLD.${q$11(parent)}) ${execute}`));
31581
31617
  }
31582
31618
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
31583
31619
  }
@@ -31594,11 +31630,11 @@ function hierarchyBody({ table, parent, key }) {
31594
31630
  " IF current_setting('transaction_isolation') <> 'read committed' THEN",
31595
31631
  ` RAISE EXCEPTION USING ERRCODE = '${HIERARCHY_ISOLATION_ERROR.errcode}', MESSAGE = '${HIERARCHY_ISOLATION_ERROR.message}';`,
31596
31632
  " END IF;",
31597
- ` IF NEW.${q$10(parent)} = NEW.${q$10(key)} THEN`,
31633
+ ` IF NEW.${q$11(parent)} = NEW.${q$11(key)} THEN`,
31598
31634
  ` ${invalid}`,
31599
31635
  " END IF;",
31600
31636
  ` PERFORM ${hierarchyLockSql(table)};`,
31601
- ` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$10(parent)} FROM ${relation$3(table)} p WHERE p.${q$10(key)} = NEW.${q$10(parent)} UNION ALL SELECT p.${q$10(parent)} FROM ${relation$3(table)} p JOIN up ON p.${q$10(key)} = up.node) CYCLE node SET looped USING trail SELECT 1 FROM up WHERE up.node = NEW.${q$10(key)}) THEN`,
31637
+ ` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$11(parent)} FROM ${relation$4(table)} p WHERE p.${q$11(key)} = NEW.${q$11(parent)} UNION ALL SELECT p.${q$11(parent)} FROM ${relation$4(table)} p JOIN up ON p.${q$11(key)} = up.node) CYCLE node SET looped USING trail SELECT 1 FROM up WHERE up.node = NEW.${q$11(key)}) THEN`,
31602
31638
  ` ${invalid}`,
31603
31639
  " END IF;",
31604
31640
  " RETURN NULL;",
@@ -31670,8 +31706,8 @@ function languageStateTables(physical, objects, attributeCase) {
31670
31706
  }
31671
31707
  return result.sort((a, b) => compareStrings(a.table.schema, b.table.schema) || compareStrings(a.table.name, b.table.name));
31672
31708
  }
31673
- const q$9 = quoteIdent;
31674
- const relation$2 = (t) => `${q$9(t.schema)}.${q$9(t.name)}`;
31709
+ const q$10 = quoteIdent;
31710
+ const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
31675
31711
  /**
31676
31712
  * Тригер стану мови (Р-B2-4, спека багатомовності §5.2): незмінність основної
31677
31713
  * й коду, переходи стану за матрицею факту ролі, заборона позначки видалення,
@@ -31693,8 +31729,8 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
31693
31729
  module,
31694
31730
  generator: "mechanics"
31695
31731
  });
31696
- const execute = `EXECUTE FUNCTION ${relation$2(names.fn)}();`;
31697
- units.push(unit(definerTrigger(names.fn, languageStateBody(entry), { rowSecurity: "off" })), ...executeGrants(`${relation$2(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$9(names.row)} BEFORE INSERT OR UPDATE OR DELETE ON ${relation$2(table)} FOR EACH ROW ${execute}`), unit(`CREATE TRIGGER ${q$9(names.truncate)} BEFORE TRUNCATE ON ${relation$2(table)} FOR EACH STATEMENT ${execute}`));
31732
+ const execute = `EXECUTE FUNCTION ${relation$3(names.fn)}();`;
31733
+ units.push(unit(definerTrigger(names.fn, languageStateBody(entry), { rowSecurity: "off" })), ...executeGrants(`${relation$3(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$10(names.row)} BEFORE INSERT OR UPDATE OR DELETE ON ${relation$3(table)} FOR EACH ROW ${execute}`), unit(`CREATE TRIGGER ${q$10(names.truncate)} BEFORE TRUNCATE ON ${relation$3(table)} FOR EACH STATEMENT ${execute}`));
31698
31734
  }
31699
31735
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
31700
31736
  }
@@ -31707,7 +31743,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
31707
31743
  function languageStateBody({ state, columns }) {
31708
31744
  const E = COMMAND_CORE_ERRORS.invalid;
31709
31745
  const refuse = `RAISE EXCEPTION USING ERRCODE = '${E.errcode}', MESSAGE = '${E.message}', DETAIL = ${sqlLiteral(E.languageState)};`;
31710
- const col = (row, name) => `${row}.${q$9(name)}`;
31746
+ const col = (row, name) => `${row}.${q$10(name)}`;
31711
31747
  const branch = (condition, body, indent = " ") => [
31712
31748
  `${indent}IF ${condition} THEN`,
31713
31749
  ...body.map((line) => `${indent} ${line}`),
@@ -32028,6 +32064,12 @@ function derivedFunctionLabels(object) {
32028
32064
  });
32029
32065
  return labels;
32030
32066
  }
32067
+ /** Опис функції носіїв у діагностиці колізії імен — за її роллю. */
32068
+ const CARRIER_FUNCTION_ROLES = {
32069
+ derive: "carrier copies",
32070
+ propagate: "carrier propagation",
32071
+ rebind: "carrier rebinding check"
32072
+ };
32031
32073
  /**
32032
32074
  * Усі похідні імена функцій, що їх породжує модель, — для перевірки колізій
32033
32075
  * на стадії 4 (спека §7). Обгортки запитів беруться з оголошених
@@ -32048,7 +32090,7 @@ function derivedFunctions(objects, references, physical, wrapperName, scopeKinds
32048
32090
  for (const { table, fn, role } of carrierFunctions(physical)) {
32049
32091
  const object = byId.get(table.origin.objectId);
32050
32092
  if (object === void 0) continue;
32051
- add(object, fn, `${role === "derive" ? "carrier copies" : "carrier propagation"} of ${table.schema}.${table.name}`);
32093
+ add(object, fn, `${CARRIER_FUNCTION_ROLES[role]} of ${table.schema}.${table.name}`);
32052
32094
  }
32053
32095
  for (const { table } of hierarchyTables(physical, objects, attributeCase)) {
32054
32096
  const object = byId.get(table.origin.objectId);
@@ -33174,22 +33216,11 @@ function rightsPredicates(contract, action, table, main, dml) {
33174
33216
  }))
33175
33217
  ];
33176
33218
  const scope = contract.scopeKindId === void 0 ? void 0 : must$9(table.columns.find((c) => c.origin.scopeKindId === contract.scopeKindId)).name;
33177
- const atScope = inners.map(({ extent, carrier, mine }) => {
33178
- const grant = scope === void 0 ? {
33179
- kind: "boolean",
33180
- expression: call$1(F.hasRight, [...head, ...extentArgs(extent)])
33181
- } : {
33182
- kind: "column",
33183
- column: scope,
33184
- set: scopeSet(extent, head),
33185
- grantDependent: true
33186
- };
33187
- return {
33188
- extent,
33189
- ...carrier === void 0 ? {} : { carrier },
33190
- conditions: [...mine, grant]
33191
- };
33192
- });
33219
+ const atScope = inners.map(({ extent, carrier, mine }) => ({
33220
+ extent,
33221
+ ...carrier === void 0 ? {} : { carrier },
33222
+ conditions: [...mine, scopeGrant(extent, head, scope)]
33223
+ }));
33193
33224
  const asContainer = action === "read" && dml === "select" && contract.container === true && table.schema === contract.table.schema && table.name === contract.table.name ? [{
33194
33225
  extent: "as_container",
33195
33226
  conditions: [{
@@ -33212,15 +33243,7 @@ function rightsPredicates(contract, action, table, main, dml) {
33212
33243
  inner: extent
33213
33244
  },
33214
33245
  carrier: carrier ?? bound,
33215
- conditions: [...mine, {
33216
- kind: "column",
33217
- column: bound,
33218
- set: {
33219
- fn: F.container,
33220
- args: [...head, ...extentArgs(extent)]
33221
- },
33222
- grantDependent: true
33223
- }]
33246
+ conditions: [...mine, containerGrant(extent, head, bound)]
33224
33247
  }));
33225
33248
  return [
33226
33249
  ...atScope,
@@ -33360,6 +33383,46 @@ function actionHead(contract, action) {
33360
33383
  function anyScopeSet(contract, action) {
33361
33384
  return scopeSet("any", actionHead(contract, action));
33362
33385
  }
33386
+ /**
33387
+ * Грант рівня скоупу в обсязі: колонка скоупу в множині скоупів з правом, а
33388
+ * нескоуплений об'єкт — булева перевірка `has_right`.
33389
+ */
33390
+ function scopeGrant(extent, head, scope) {
33391
+ return scope === void 0 ? {
33392
+ kind: "boolean",
33393
+ expression: call$1(RIGHTS_FUNCTIONS.hasRight, [...head, ...extentArgs(extent)])
33394
+ } : {
33395
+ kind: "column",
33396
+ column: scope,
33397
+ set: scopeSet(extent, head),
33398
+ grantDependent: true
33399
+ };
33400
+ }
33401
+ /** Грант у контейнері: колонка прив'язки в множині контейнерів з правом. */
33402
+ function containerGrant(extent, head, carrier) {
33403
+ return {
33404
+ kind: "column",
33405
+ column: carrier,
33406
+ set: {
33407
+ fn: RIGHTS_FUNCTIONS.container,
33408
+ args: [...head, ...extentArgs(extent)]
33409
+ },
33410
+ grantDependent: true
33411
+ };
33412
+ }
33413
+ /**
33414
+ * Право дії в обсязі `any` над рядком без його власного носія (спека прав
33415
+ * контейнера §2, переприв'язування): у контейнері `carrier` чи на рівні
33416
+ * скоупу `scope` (нескоуплений об'єкт — `has_right`). Ті самі будівники
33417
+ * грантів, що й політики, тож множини не розійдуться.
33418
+ */
33419
+ function anyGrants(contract, action, carrier, scope) {
33420
+ const head = actionHead(contract, action);
33421
+ return {
33422
+ container: containerGrant("any", head, carrier),
33423
+ scope: scopeGrant("any", head, scope)
33424
+ };
33425
+ }
33363
33426
  /** Скоупи з правом в обсязі: своя функція множини на кожну форму (§5.1). */
33364
33427
  function scopeSet(extent, head) {
33365
33428
  const F = RIGHTS_FUNCTIONS;
@@ -36383,7 +36446,7 @@ function effectiveHolderRows(catalog, contracts, physical, attributeCase) {
36383
36446
  ].filter(Boolean).join("\n");
36384
36447
  }
36385
36448
  // src/compiler/rights/guard-units.ts
36386
- const q$8 = quoteIdent;
36449
+ const q$9 = quoteIdent;
36387
36450
  const platform = (name) => ({
36388
36451
  schema: PLATFORM_SCHEMA,
36389
36452
  name
@@ -36505,17 +36568,17 @@ function journalRelation(table) {
36505
36568
  return `${table.schema}.${table.name}`;
36506
36569
  }
36507
36570
  function scopeSql(config, alias) {
36508
- return [sqlLiteral(config.catalog.level.level === "scope" ? config.catalog.level.scopeKindId : ZERO_UUID) + "::uuid", config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `${alias}.${q$8(config.scope)}`];
36571
+ return [sqlLiteral(config.catalog.level.level === "scope" ? config.catalog.level.scopeKindId : ZERO_UUID) + "::uuid", config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `${alias}.${q$9(config.scope)}`];
36509
36572
  }
36510
36573
  function transitionSql(config, operation) {
36511
36574
  const old = operation !== "INSERT";
36512
36575
  const next = operation !== "DELETE";
36513
- const source = operation === "INSERT" ? "new_rows n" : operation === "DELETE" ? "old_rows o" : `old_rows o FULL JOIN new_rows n ON n.${q$8(config.key)} = o.${q$8(config.key)}`;
36514
- const key = next && old ? `coalesce(n.${q$8(config.key)}, o.${q$8(config.key)})` : `${next ? "n" : "o"}.${q$8(config.key)}`;
36576
+ const source = operation === "INSERT" ? "new_rows n" : operation === "DELETE" ? "old_rows o" : `old_rows o FULL JOIN new_rows n ON n.${q$9(config.key)} = o.${q$9(config.key)}`;
36577
+ const key = next && old ? `coalesce(n.${q$9(config.key)}, o.${q$9(config.key)})` : `${next ? "n" : "o"}.${q$9(config.key)}`;
36515
36578
  const [scopeKind, oldScope] = scopeSql(config, "o");
36516
36579
  const [, newScope] = scopeSql(config, "n");
36517
36580
  const scope = next && old ? `coalesce(${newScope}, ${oldScope})` : next ? newScope : oldScope;
36518
- const rows = `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope, ${key} AS row_id, ${config.parent === void 0 ? "NULL::uuid" : next && old ? `coalesce(n.${q$8(config.parent)}, o.${q$8(config.parent)})` : `${next ? "n" : "o"}.${q$8(config.parent)}`} AS parent_id, ${old ? "to_jsonb(o)" : "NULL::jsonb"} AS before, ${next ? "to_jsonb(n)" : "NULL::jsonb"} AS after FROM ${source}`;
36581
+ const rows = `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope, ${key} AS row_id, ${config.parent === void 0 ? "NULL::uuid" : next && old ? `coalesce(n.${q$9(config.parent)}, o.${q$9(config.parent)})` : `${next ? "n" : "o"}.${q$9(config.parent)}`} AS parent_id, ${old ? "to_jsonb(o)" : "NULL::jsonb"} AS before, ${next ? "to_jsonb(n)" : "NULL::jsonb"} AS after FROM ${source}`;
36519
36582
  const versionRows = operation === "UPDATE" ? `SELECT ${scopeKind} AS scope_kind_id, ${oldScope} AS scope FROM old_rows o UNION SELECT ${scopeKind}, ${newScope} FROM new_rows n` : `SELECT ${scopeKind} AS scope_kind_id, ${scope} AS scope FROM ${source}`;
36520
36583
  const relation = journalRelation(config.table);
36521
36584
  const creator = config.kind === "assignment" && operation === "INSERT" ? ` WHEN EXISTS (SELECT 1 FROM ${ref(SNAPSHOT_TABLES.typed)} t WHERE t.xid = txid_current() AND t.provenance = ${sqlLiteral(ROOT_CREATOR_REASON)} AND t.assignment = r.row_id) AND NOT EXISTS (SELECT 1 FROM ${ref(platform("rights_journal"))} j WHERE j.xid = txid_current() AND j.relation = ${sqlLiteral(relation)} AND j.row_id = r.row_id) THEN ${sqlLiteral(ROOT_CREATOR_REASON)}` : "";
@@ -36737,12 +36800,12 @@ function pendingSql(config, operation) {
36737
36800
  const after = operation !== "DELETE";
36738
36801
  const [kind] = scopeSql(config, "r");
36739
36802
  const events = [...before ? [`SELECT o.*, 1 AS image FROM old_rows o`] : [], ...after ? [`SELECT n.*, 0 AS image FROM new_rows n`] : []].join(" UNION ALL ");
36740
- const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(config.scope)}`;
36741
- const roleKey = config.kind === "delta" ? `r.${q$8(config.parent)}` : `r.${q$8(config.key)}`;
36803
+ const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$9(config.scope)}`;
36804
+ const roleKey = config.kind === "delta" ? `r.${q$9(config.parent)}` : `r.${q$9(config.key)}`;
36742
36805
  return pendingInsert([
36743
- `SELECT ${sqlLiteral(config.kind === "assignment" ? "assignment" : "role")}::text AS kind, ${config.kind === "assignment" ? `r.${q$8(config.key)}` : roleKey} AS key, ${kind} AS scope_kind_id, ${scope} AS scope, r.image FROM (${events}) r`,
36744
- ...config.kind === "assignment" ? [`SELECT 'role'::text, r.${q$8(config.customRole)}, ${kind}, ${scope}, r.image FROM (${events}) r WHERE r.${q$8(config.customRole)} IS NOT NULL`] : [],
36745
- ...config.kind === "assignment" && before ? [`SELECT 'holders'::text, ${scope}, ${kind}, ${scope}, 1 FROM old_rows r WHERE r.${q$8(config.customRole)} IS NULL AND EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.fullAccessRoles)}() f WHERE f.role_id = r.${q$8(config.archetype)} AND f.storage_id IS NOT DISTINCT FROM ${config.catalog.level.level === "scope" ? kind : "NULL::uuid"})`] : [],
36806
+ `SELECT ${sqlLiteral(config.kind === "assignment" ? "assignment" : "role")}::text AS kind, ${config.kind === "assignment" ? `r.${q$9(config.key)}` : roleKey} AS key, ${kind} AS scope_kind_id, ${scope} AS scope, r.image FROM (${events}) r`,
36807
+ ...config.kind === "assignment" ? [`SELECT 'role'::text, r.${q$9(config.customRole)}, ${kind}, ${scope}, r.image FROM (${events}) r WHERE r.${q$9(config.customRole)} IS NOT NULL`] : [],
36808
+ ...config.kind === "assignment" && before ? [`SELECT 'holders'::text, ${scope}, ${kind}, ${scope}, 1 FROM old_rows r WHERE r.${q$9(config.customRole)} IS NULL AND EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.fullAccessRoles)}() f WHERE f.role_id = r.${q$9(config.archetype)} AND f.storage_id IS NOT DISTINCT FROM ${config.catalog.level.level === "scope" ? kind : "NULL::uuid"})`] : [],
36746
36809
  actorPending()
36747
36810
  ], "v_maintenance");
36748
36811
  }
@@ -36758,7 +36821,7 @@ function pendingSql(config, operation) {
36758
36821
  function stateRows(table, state, match, style) {
36759
36822
  const name = ref(tableName(table));
36760
36823
  const equals = match.any === true ? `= ANY (${match.value})` : `= ${match.value}`;
36761
- const live = `l.${q$8(match.column)} ${equals}`;
36824
+ const live = `l.${q$9(match.column)} ${equals}`;
36762
36825
  if (state === "after") return `SELECT to_jsonb(l) AS doc FROM ${name} l WHERE ${live}`;
36763
36826
  const key = column(table, KEY$1, style);
36764
36827
  const journal = [`${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.reason IN ('command', ${sqlLiteral(ROOT_CREATOR_REASON)})`, `AND j.relation = ${sqlLiteral(journalRelation(table))}`].join(" ");
@@ -36766,7 +36829,7 @@ function stateRows(table, state, match, style) {
36766
36829
  `(SELECT DISTINCT ON (j.row_id) j.before AS doc FROM ${journal}${match.column === key ? ` AND j.row_id ${equals}` : ""} ORDER BY j.row_id, j.seq)`,
36767
36830
  "UNION ALL",
36768
36831
  `SELECT to_jsonb(l) FROM ${name} l WHERE ${live}`,
36769
- ` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$8(key)})`
36832
+ ` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$9(key)})`
36770
36833
  ].join("\n");
36771
36834
  }
36772
36835
  /** Звуження за ключем рядка: перевірка судить один рядок черги. */
@@ -36848,7 +36911,7 @@ function rootExists(catalog, physical) {
36848
36911
  return `EXISTS (SELECT 1 FROM ${ref({
36849
36912
  schema: fk.references.schema,
36850
36913
  name: fk.references.table
36851
- })} root WHERE root.${q$8(fk.references.columns[index])} = v_pending.scope)`;
36914
+ })} root WHERE root.${q$9(fk.references.columns[index])} = v_pending.scope)`;
36852
36915
  }
36853
36916
  function assignmentBeforeSet(catalog, physical, style) {
36854
36917
  const table = tableOf$2(physical, catalog.assignments.table);
@@ -36920,15 +36983,15 @@ function escalationSql(after, before, storageKind) {
36920
36983
  function deltaDomainSql(catalog, physical, style) {
36921
36984
  const roles = tableOf$2(physical, catalog.roles.table);
36922
36985
  const delta = tableOf$2(physical, catalog.roles.delta);
36923
- const r = (def) => `r.${q$8(column(roles, def, style))}`;
36924
- const l = (def) => `l.${q$8(column(delta, def, style))}`;
36986
+ const r = (def) => `r.${q$9(column(roles, def, style))}`;
36987
+ const l = (def) => `l.${q$9(column(delta, def, style))}`;
36925
36988
  const roleScope = scopeColumn(roles);
36926
36989
  const deltaScope = scopeColumn(delta);
36927
36990
  const journal = (table) => `${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.relation = ${sqlLiteral(journalRelation(table))}`;
36928
36991
  const storage = catalog.level.level === "scope" ? `m.storage = 'scope' AND m.storage_id = ${sqlLiteral(catalog.level.scopeKindId)}::uuid` : "m.storage = 'global'";
36929
36992
  return [
36930
- `IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r JOIN ${ref(catalog.roles.delta)} l ON ${l(PARENT)} = ${r(KEY$1)}${deltaScope === void 0 ? "" : ` AND l.${q$8(deltaScope)} = v_pending.scope`}`,
36931
- ` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$8(roleScope)} = v_pending.scope`}`,
36993
+ `IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r JOIN ${ref(catalog.roles.delta)} l ON ${l(PARENT)} = ${r(KEY$1)}${deltaScope === void 0 ? "" : ` AND l.${q$9(deltaScope)} = v_pending.scope`}`,
36994
+ ` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$9(roleScope)} = v_pending.scope`}`,
36932
36995
  ` AND (EXISTS (SELECT 1 FROM ${journal(delta)} AND j.row_id = ${l(KEY$1)} AND j.after IS NOT NULL)`,
36933
36996
  ` OR EXISTS (SELECT 1 FROM (SELECT DISTINCT ON (j.row_id) j.before FROM ${journal(roles)} AND j.row_id = v_pending.key ORDER BY j.row_id, j.seq) f WHERE (f.before ->> ${sqlLiteral(column(roles, R.archetype, style))})::uuid IS DISTINCT FROM ${r(R.archetype)}))`,
36934
36997
  ` AND NOT EXISTS (SELECT 1 FROM ${ref(RIGHTS_FUNCTIONS.roles)}() m JOIN ${ref(RIGHTS_FUNCTIONS.domain)}() d ON d.level = m.level AND d.level_id IS NOT DISTINCT FROM m.level_id`,
@@ -36940,17 +37003,17 @@ function catalogCheck(catalog, contracts, physical, style) {
36940
37003
  const roles = tableOf$2(physical, catalog.roles.table);
36941
37004
  const assignments = tableOf$2(physical, catalog.assignments.table);
36942
37005
  const scope = catalog.level.level === "scope" ? `${sqlLiteral(catalog.level.scopeKindId)}::uuid` : `${sqlLiteral(ZERO_UUID)}::uuid`;
36943
- const roleId = `r.${q$8(column(roles, KEY$1, style))}`;
37006
+ const roleId = `r.${q$9(column(roles, KEY$1, style))}`;
36944
37007
  const assignmentScope = scopeColumn(assignments);
36945
37008
  const roleScope = scopeColumn(roles);
36946
- const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$8(roleScope)} = v_pending.scope`;
36947
- const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$8(assignmentScope)} = v_pending.scope`;
37009
+ const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$9(roleScope)} = v_pending.scope`;
37010
+ const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$9(assignmentScope)} = v_pending.scope`;
36948
37011
  const root = rootExists(catalog, physical);
36949
37012
  return [
36950
37013
  `IF v_pending.scope_kind_id = ${scope} THEN`,
36951
37014
  " IF v_pending.kind = 'role' THEN",
36952
- ` IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r WHERE ${roleId} = v_pending.key AND ${sameRole} AND r.${q$8(column(roles, DELETION, style))})`,
36953
- ` AND EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignments, R.customRole, style))} = v_pending.key AND ${sameAssignment} AND NOT a.${q$8(column(assignments, DELETION, style))})`,
37015
+ ` IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r WHERE ${roleId} = v_pending.key AND ${sameRole} AND r.${q$9(column(roles, DELETION, style))})`,
37016
+ ` AND EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$9(column(assignments, R.customRole, style))} = v_pending.key AND ${sameAssignment} AND NOT a.${q$9(column(assignments, DELETION, style))})`,
36954
37017
  ` THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.roleInUse)} END IF;`,
36955
37018
  ` ${deltaDomainSql(catalog, physical, style)}`,
36956
37019
  ` ${escalationSql(roleGrantSet(catalog, physical, "after", style), roleGrantSet(catalog, physical, "before", style), catalogStorageKind(catalog))}`,
@@ -37072,7 +37135,7 @@ function eventRows(operation, alias, source) {
37072
37135
  }
37073
37136
  function bumpRows(operation, scopeKindId, scope) {
37074
37137
  const rows = [...eventRows(operation, "r", "old"), ...eventRows(operation, "r", "new")].join(" UNION ALL ");
37075
- const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(scope)}`;
37138
+ const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$9(scope)}`;
37076
37139
  return `PERFORM ${ref(RIGHTS_FUNCTIONS.bump)}(${sqlLiteral(scopeKindId)}::uuid, s.scope) FROM (SELECT DISTINCT ${value} AS scope FROM (${rows}) r) s;`;
37077
37140
  }
37078
37141
  /**
@@ -37086,13 +37149,13 @@ function bumpRows(operation, scopeKindId, scope) {
37086
37149
  * ключем рядка: зміну самого ключа тримає row-level тригер `_id`.
37087
37150
  */
37088
37151
  function memberEventBody(member, contracts, physical, operation, provider, style) {
37089
- const key = q$8(member.keyColumn);
37090
- const scope = q$8(member.scopeColumn);
37091
- const user = q$8(member.userColumn);
37152
+ const key = q$9(member.keyColumn);
37153
+ const scope = q$9(member.scopeColumn);
37154
+ const user = q$9(member.userColumn);
37092
37155
  const assignments = contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "scope" && catalog.level.scopeKindId === member.scopeKindId).map((catalog) => {
37093
37156
  const table = catalog.assignments.table;
37094
37157
  const actual = tableOf$2(physical, table);
37095
- return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$8(column(actual, R.subject, style))} = n.${key} AND a.${q$8(scopeColumn(actual))} = n.${scope})`;
37158
+ return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$9(column(actual, R.subject, style))} = n.${key} AND a.${q$9(scopeColumn(actual))} = n.${scope})`;
37096
37159
  });
37097
37160
  const repeated = operation === "INSERT" && assignments.length > 0 ? `IF EXISTS (SELECT 1 FROM new_rows n WHERE ${assignments.join(" OR ")}) THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.rightsContext)} END IF;` : "";
37098
37161
  const changed = operation === "UPDATE" ? [
@@ -37121,13 +37184,13 @@ function memberEventBody(member, contracts, physical, operation, provider, style
37121
37184
  * видалення облікового запису) і режим обслуговування.
37122
37185
  */
37123
37186
  function usersEventBody(users, contracts, physical, operation, attributeCase, provider) {
37124
- const key = q$8(users.keyColumn);
37125
- const invalid = q$8(users.invalidColumn);
37187
+ const key = q$9(users.keyColumn);
37188
+ const invalid = q$9(users.invalidColumn);
37126
37189
  const table = tableOf$2(physical, users.table);
37127
- const kind = q$8(column(table, USER_PLATFORM_COLUMNS.userKind, attributeCase));
37128
- const repeated = operation === "INSERT" ? [...contracts.membership.map((member) => `EXISTS (SELECT 1 FROM ${ref(member.table)} m WHERE m.${q$8(member.userColumn)} = n.${key})`), ...contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "global").map((catalog) => {
37190
+ const kind = q$9(column(table, USER_PLATFORM_COLUMNS.userKind, attributeCase));
37191
+ const repeated = operation === "INSERT" ? [...contracts.membership.map((member) => `EXISTS (SELECT 1 FROM ${ref(member.table)} m WHERE m.${q$9(member.userColumn)} = n.${key})`), ...contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "global").map((catalog) => {
37129
37192
  const assignment = tableOf$2(physical, catalog.assignments.table);
37130
- return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignment, R.subject, attributeCase))} = n.${key})`;
37193
+ return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$9(column(assignment, R.subject, attributeCase))} = n.${key})`;
37131
37194
  })] : [];
37132
37195
  const update = operation === "UPDATE" ? [
37133
37196
  `IF v_action IS NULL AND NOT v_maintenance AND EXISTS (SELECT 1 FROM old_rows o JOIN new_rows n ON n.${key} = o.${key}`,
@@ -37178,7 +37241,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37178
37241
  const name = tableName(table);
37179
37242
  const fn = functionName(name, labels.truncate);
37180
37243
  addFunction(fn, truncateBody(table), table.origin.objectId);
37181
- add(`CREATE TRIGGER ${q$8(triggerName(name, labels.truncate))} BEFORE TRUNCATE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37244
+ add(`CREATE TRIGGER ${q$9(triggerName(name, labels.truncate))} BEFORE TRUNCATE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37182
37245
  };
37183
37246
  for (const { table, facts } of sources.sources) {
37184
37247
  const name = tableName(table);
@@ -37195,7 +37258,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37195
37258
  ...t
37196
37259
  }))
37197
37260
  ]);
37198
- add(`CREATE TRIGGER ${q$8(triggerName(name, labels.snapshot))} BEFORE INSERT OR UPDATE OR DELETE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(snapshot)}();`, owner);
37261
+ add(`CREATE TRIGGER ${q$9(triggerName(name, labels.snapshot))} BEFORE INSERT OR UPDATE OR DELETE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(snapshot)}();`, owner);
37199
37262
  }
37200
37263
  for (const config of catalogTables(contracts, physical, attributeCase)) {
37201
37264
  const table = tableName(config.table);
@@ -37220,7 +37283,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37220
37283
  "DELETE"
37221
37284
  ]) {
37222
37285
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37223
- add(`CREATE TRIGGER ${q$8(triggerName(table, `${labels.rights}_${operation.toLowerCase()}`))} AFTER ${operation} ON ${ref(table)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37286
+ add(`CREATE TRIGGER ${q$9(triggerName(table, `${labels.rights}_${operation.toLowerCase()}`))} AFTER ${operation} ON ${ref(table)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37224
37287
  }
37225
37288
  addTruncate(config.table);
37226
37289
  }
@@ -37237,7 +37300,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37237
37300
  const fn = functionName(name, label);
37238
37301
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37239
37302
  addFunction(fn, memberEventBody(member, contracts, physical, operation, provider, attributeCase), owner, [unitNode(COMMAND_FUNCTIONS.current), BUMP_NODE]);
37240
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37303
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37241
37304
  }
37242
37305
  addTruncate(table);
37243
37306
  }
@@ -37251,7 +37314,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37251
37314
  const fn = functionName(name, label);
37252
37315
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37253
37316
  addFunction(fn, usersEventBody(users, contracts, physical, operation, attributeCase, provider), owner, [unitNode(COMMAND_FUNCTIONS.current), ...operation === "UPDATE" ? [BUMP_NODE] : []]);
37254
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37317
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
37255
37318
  }
37256
37319
  addTruncate(table);
37257
37320
  }
@@ -37285,7 +37348,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37285
37348
  ]) {
37286
37349
  const label = `simetra_rights_relation_${operation.toLowerCase()}`;
37287
37350
  const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : operation === "DELETE" ? "REFERENCING OLD TABLE AS old_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
37288
- add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37351
+ add(`CREATE TRIGGER ${q$9(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
37289
37352
  }
37290
37353
  addTruncate(table);
37291
37354
  }
@@ -37319,17 +37382,17 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
37319
37382
  ...INVITATIONS_TABLE
37320
37383
  }]
37321
37384
  ]);
37322
- add(`CREATE CONSTRAINT TRIGGER ${q$8("rights_tx_pending_check")} AFTER INSERT ON ${ref(platform("rights_tx_pending"))} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(check)}();`);
37385
+ add(`CREATE CONSTRAINT TRIGGER ${q$9("rights_tx_pending_check")} AFTER INSERT ON ${ref(platform("rights_tx_pending"))} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(check)}();`);
37323
37386
  const markerCheck = platform("rights_tx_root_marker_check");
37324
37387
  addFunction(markerCheck, rootMarkerBody(), void 0, [{
37325
37388
  type: "table",
37326
37389
  ...ROOT_MARKER_TABLE
37327
37390
  }]);
37328
- add(`CREATE CONSTRAINT TRIGGER ${q$8(markerCheck.name)} AFTER INSERT ON ${ref(ROOT_MARKER_TABLE)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(markerCheck)}();`);
37391
+ add(`CREATE CONSTRAINT TRIGGER ${q$9(markerCheck.name)} AFTER INSERT ON ${ref(ROOT_MARKER_TABLE)} DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION ${ref(markerCheck)}();`);
37329
37392
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
37330
37393
  }
37331
37394
  // src/compiler/rights/invitation-put-units.ts
37332
- const q$7 = quoteIdent;
37395
+ const q$8 = quoteIdent;
37333
37396
  /** Функція запису запрошення (спека запрошень §4, крок 3) — одна на проєкт. */
37334
37397
  const INVITATION_PUT_FUNCTION = {
37335
37398
  schema: PLATFORM_SCHEMA,
@@ -37363,8 +37426,8 @@ function scopeOf(table) {
37363
37426
  * рівно ті рядки, які читає звірка.
37364
37427
  */
37365
37428
  function liveAssignments(assignments, style, member, scope) {
37366
- const a = (def) => `a.${q$7(standardColumn(assignments, def, style).name)}`;
37367
- return `${a(RIGHTS_COLUMNS.subject)} = ${member} AND a.${q$7(scopeOf(assignments))} = ${scope} AND NOT ${a(deletionMarkColumn())}`;
37429
+ const a = (def) => `a.${q$8(standardColumn(assignments, def, style).name)}`;
37430
+ return `${a(RIGHTS_COLUMNS.subject)} = ${member} AND a.${q$8(scopeOf(assignments))} = ${scope} AND NOT ${a(deletionMarkColumn())}`;
37368
37431
  }
37369
37432
  /**
37370
37433
  * Набір видачі (спека запрошень §4, крок 3): відсортований за id перелік
@@ -37379,23 +37442,23 @@ function issueSetSql(catalog, physical, style, member, scope) {
37379
37442
  const assignments = tableOf$1(physical, catalog.assignments.table);
37380
37443
  const roles = tableOf$1(physical, catalog.roles.table);
37381
37444
  const delta = tableOf$1(physical, catalog.roles.delta);
37382
- const col = (table, def) => q$7(standardColumn(table, def, style).name);
37445
+ const col = (table, def) => q$8(standardColumn(table, def, style).name);
37383
37446
  const a = (def) => `a.${col(assignments, def)}`;
37384
37447
  const c = (def) => `c.${col(roles, def)}`;
37385
37448
  const d = (def) => `d.${col(delta, def)}`;
37386
37449
  const R = RIGHTS_COLUMNS;
37387
37450
  const KEY = keyColumn(false);
37388
37451
  const VERSION = versionColumn();
37389
- const assignmentScope = `a.${q$7(scopeOf(assignments))}`;
37452
+ const assignmentScope = `a.${q$8(scopeOf(assignments))}`;
37390
37453
  const deltas = [
37391
37454
  `SELECT encode(sha256(convert_to(coalesce(jsonb_agg(to_jsonb(d) ORDER BY ${d(KEY)}), '[]'::jsonb)::text, 'UTF8')), 'hex')`,
37392
37455
  `FROM ${qualified(catalog.roles.delta)} d`,
37393
- `WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$7(scopeOf(delta))} = ${assignmentScope}`
37456
+ `WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$8(scopeOf(delta))} = ${assignmentScope}`
37394
37457
  ].join(" ");
37395
37458
  return [
37396
37459
  `SELECT coalesce(jsonb_agg(jsonb_build_object('id', ${a(KEY)}, 'version', ${a(VERSION)}) || CASE WHEN ${a(R.customRole)} IS NULL THEN '{}'::jsonb ELSE jsonb_build_object('customRole', jsonb_build_object('id', ${c(KEY)}, 'version', ${c(VERSION)}, 'deltas', (${deltas}))) END ORDER BY ${a(KEY)}), '[]'::jsonb)`,
37397
37460
  `FROM ${qualified(catalog.assignments.table)} a`,
37398
- `LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$7(scopeOf(roles))} = ${assignmentScope}`,
37461
+ `LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$8(scopeOf(roles))} = ${assignmentScope}`,
37399
37462
  `WHERE ${liveAssignments(assignments, style, member, scope)}`
37400
37463
  ].join("\n");
37401
37464
  }
@@ -37410,11 +37473,11 @@ function issueSetSql(catalog, physical, style, member, scope) {
37410
37473
  function issueSetLocks(catalog, physical, style, member, scope) {
37411
37474
  const assignments = tableOf$1(physical, catalog.assignments.table);
37412
37475
  const roles = tableOf$1(physical, catalog.roles.table);
37413
- const col = (table, def) => q$7(standardColumn(table, def, style).name);
37476
+ const col = (table, def) => q$8(standardColumn(table, def, style).name);
37414
37477
  const a = (def) => `a.${col(assignments, def)}`;
37415
37478
  const R = RIGHTS_COLUMNS;
37416
37479
  const live = liveAssignments(assignments, style, member, scope);
37417
- return [`PERFORM 1 FROM ${qualified(catalog.assignments.table)} a WHERE ${live} FOR SHARE;`, `PERFORM 1 FROM ${qualified(catalog.roles.table)} c WHERE c.${q$7(scopeOf(roles))} = ${scope} AND c.${col(roles, keyColumn(false))} IN (SELECT ${a(R.customRole)} FROM ${qualified(catalog.assignments.table)} a WHERE ${live}) FOR SHARE;`];
37480
+ return [`PERFORM 1 FROM ${qualified(catalog.assignments.table)} a WHERE ${live} FOR SHARE;`, `PERFORM 1 FROM ${qualified(catalog.roles.table)} c WHERE c.${q$8(scopeOf(roles))} = ${scope} AND c.${col(roles, keyColumn(false))} IN (SELECT ${a(R.customRole)} FROM ${qualified(catalog.assignments.table)} a WHERE ${live}) FOR SHARE;`];
37418
37481
  }
37419
37482
  /**
37420
37483
  * `simetra.invitation_put(p_member, p_hash)` (спека запрошень §4, кроки 2–4):
@@ -37446,14 +37509,14 @@ function invitationPutFunction(kinds, contracts, physical, style) {
37446
37509
  const m = kind.membership;
37447
37510
  const id = uuidLiteral(kind.kindId);
37448
37511
  const pending = [
37449
- `m.${q$7(m.key)} = p_member`,
37450
- `m.${q$7(m.user)} IS NULL`,
37451
- ...m.deletion === void 0 ? [] : [`NOT m.${q$7(m.deletion)}`]
37512
+ `m.${q$8(m.key)} = p_member`,
37513
+ `m.${q$8(m.user)} IS NULL`,
37514
+ ...m.deletion === void 0 ? [] : [`NOT m.${q$8(m.deletion)}`]
37452
37515
  ].join(" AND ");
37453
37516
  return [
37454
37517
  `IF v_object = ${sqlLiteral(kind.kindLabel)} THEN`,
37455
37518
  ...[
37456
- `SELECT m.${q$7(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
37519
+ `SELECT m.${q$8(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
37457
37520
  ...ifRefuse("NOT FOUND"),
37458
37521
  ...ifRefuse(`NOT ${scopeAdministerRights(kind.assignmentsLabel, kind.kindId, "v_scope")}`),
37459
37522
  ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = p_member AND i.scope_kind_id <> ${id})`),
@@ -37498,7 +37561,7 @@ function invitationPutFunction(kinds, contracts, physical, style) {
37498
37561
  return `CREATE OR REPLACE FUNCTION ${qualified(INVITATION_PUT_FUNCTION)}(p_member uuid, p_hash bytea)\nRETURNS timestamp with time zone\nLANGUAGE plpgsql VOLATILE SECURITY DEFINER\nSET search_path = ''\nAS ${tag}\n${body}\n${tag};`;
37499
37562
  }
37500
37563
  // src/compiler/rights/invitation-accept-units.ts
37501
- const q$6 = quoteIdent;
37564
+ const q$7 = quoteIdent;
37502
37565
  /** Функція прийняття запрошення (спека запрошень §5) — одна на проєкт. */
37503
37566
  const INVITATION_ACCEPT_FUNCTION = {
37504
37567
  schema: PLATFORM_SCHEMA,
@@ -37555,10 +37618,10 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37555
37618
  const m = kind.membership;
37556
37619
  const id = uuidLiteral(kind.kindId);
37557
37620
  const pending = [
37558
- `m.${q$6(m.key)} = v_member`,
37559
- `m.${q$6(m.scope)} = v_scope`,
37560
- `m.${q$6(m.user)} IS NULL`,
37561
- ...m.deletion === void 0 ? [] : [`NOT m.${q$6(m.deletion)}`]
37621
+ `m.${q$7(m.key)} = v_member`,
37622
+ `m.${q$7(m.scope)} = v_scope`,
37623
+ `m.${q$7(m.user)} IS NULL`,
37624
+ ...m.deletion === void 0 ? [] : [`NOT m.${q$7(m.deletion)}`]
37562
37625
  ].join(" AND ");
37563
37626
  const gone = `DELETE FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = v_member AND i.scope_kind_id = ${id};`;
37564
37627
  const changed = `(${issueSetSql(kind.catalog, physical, style, "v_member", "v_scope")}) IS DISTINCT FROM v_assignments`;
@@ -37580,14 +37643,14 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37580
37643
  ` ${gone}`,
37581
37644
  ...failed("changed", record).map((l) => ` ${l}`),
37582
37645
  "END IF;",
37583
- `IF EXISTS (SELECT 1 FROM ${qualified(m.table)} m WHERE m.${q$6(m.scope)} = v_scope AND m.${q$6(m.user)} = v_actor) THEN`,
37646
+ `IF EXISTS (SELECT 1 FROM ${qualified(m.table)} m WHERE m.${q$7(m.scope)} = v_scope AND m.${q$7(m.user)} = v_actor) THEN`,
37584
37647
  ...failed("already-member", record).map((l) => ` ${l}`),
37585
37648
  "END IF;",
37586
37649
  `v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
37587
37650
  "BEGIN",
37588
37651
  ...[
37589
37652
  `PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, jsonb_build_object('action', ${sqlLiteral(acceptInvitationAction.name)}, 'object', ${sqlLiteral(kind.kindLabel)}, 'root', v_member)::text, true);`,
37590
- `UPDATE ${qualified(m.table)} m SET ${q$6(m.user)} = v_actor WHERE m.${q$6(m.key)} = v_member;`,
37653
+ `UPDATE ${qualified(m.table)} m SET ${q$7(m.user)} = v_actor WHERE m.${q$7(m.key)} = v_member;`,
37591
37654
  ...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
37592
37655
  `IF ${changed} THEN`,
37593
37656
  ` RAISE EXCEPTION USING ERRCODE = '${CHANGED_STATE}';`,
@@ -37652,7 +37715,7 @@ function invitationAcceptFunction(kinds, contracts, physical, style) {
37652
37715
  return `CREATE OR REPLACE FUNCTION ${qualified(INVITATION_ACCEPT_FUNCTION)}(p_hash bytea)\nRETURNS jsonb\nLANGUAGE plpgsql VOLATILE SECURITY DEFINER\nSET search_path = ''\nSET row_security = off\nAS ${tag}\n${body}\n${tag};`;
37653
37716
  }
37654
37717
  // src/compiler/rights/root-creator-units.ts
37655
- const q$5 = quoteIdent;
37718
+ const q$6 = quoteIdent;
37656
37719
  /**
37657
37720
  * Функція гранту творцю кореня виду скоупу (спека П4 §6.13):
37658
37721
  * `simetra.<вид скоупу>_root_creator`. Ім'я — від фізичного імені виду: воно
@@ -37698,7 +37761,7 @@ function rootCreatorFunction(facts) {
37698
37761
  m.user,
37699
37762
  ...m.columns.map((c) => c.name)
37700
37763
  ])];
37701
- const memberValue = (column) => forced[column] ?? `CASE WHEN p_member ? ${sqlLiteral(column)} THEN v_in.${q$5(column)} ELSE ${m.columns.find((c) => c.name === column).default} END`;
37764
+ const memberValue = (column) => forced[column] ?? `CASE WHEN p_member ? ${sqlLiteral(column)} THEN v_in.${q$6(column)} ELSE ${m.columns.find((c) => c.name === column).default} END`;
37702
37765
  const typed = {
37703
37766
  storage: "'scope'",
37704
37767
  storage_id: kind,
@@ -37728,12 +37791,12 @@ function rootCreatorFunction(facts) {
37728
37791
  `DELETE FROM ${qualified(ROOT_MARKER_TABLE)} m WHERE m.xid = txid_current() AND m.scope_kind_id = ${kind} AND m.root = p_root AND m.actor = ${CURRENT_USER$1};`,
37729
37792
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
37730
37793
  ...ifRefuse("v_count = 0"),
37731
- ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(m.table)} r WHERE r.${q$5(m.scope)} = p_root) OR EXISTS (SELECT 1 FROM ${qualified(a.table)} r WHERE r.${q$5(a.scope)} = p_root)`),
37794
+ ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(m.table)} r WHERE r.${q$6(m.scope)} = p_root) OR EXISTS (SELECT 1 FROM ${qualified(a.table)} r WHERE r.${q$6(a.scope)} = p_root)`),
37732
37795
  ...ifRefuse(`${qualified(m.check)}(p_member - ARRAY[${Object.keys(forced).map(sqlLiteral).join(", ")}]::text[], p_root) IS NOT NULL`),
37733
37796
  `v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
37734
37797
  context(m.action, m.kindLabel, "p_member_id"),
37735
37798
  `v_in := jsonb_populate_record(NULL::${qualified(m.table)}, p_member);`,
37736
- `INSERT INTO ${qualified(m.table)} (${memberColumns.map(q$5).join(", ")}) VALUES (${memberColumns.map(memberValue).join(", ")});`,
37799
+ `INSERT INTO ${qualified(m.table)} (${memberColumns.map(q$6).join(", ")}) VALUES (${memberColumns.map(memberValue).join(", ")});`,
37737
37800
  ...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
37738
37801
  ...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(T.start)} s WHERE s.xid = txid_current())`),
37739
37802
  "v_assignment := gen_random_uuid();",
@@ -37746,7 +37809,7 @@ function rootCreatorFunction(facts) {
37746
37809
  a.scope,
37747
37810
  a.subject,
37748
37811
  a.archetype
37749
- ].map(q$5).join(", ")}) VALUES (v_assignment, p_root, p_member_id, ${archetype});`,
37812
+ ].map(q$6).join(", ")}) VALUES (v_assignment, p_root, p_member_id, ${archetype});`,
37750
37813
  `PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, v_context, true);`
37751
37814
  ].map((line) => ` ${line}`),
37752
37815
  "END"
@@ -37783,7 +37846,7 @@ function rightsCheck(contract, action, main, row, dml, rowless = false) {
37783
37846
  return predicates.map((p) => `(${p})`).join(" OR ");
37784
37847
  }
37785
37848
  // src/compiler/catalog-command/member-check.ts
37786
- const q$4 = quoteIdent;
37849
+ const q$5 = quoteIdent;
37787
37850
  /**
37788
37851
  * Перевірка рядка членства творця кореня (спека П4 §6.12, §6.13):
37789
37852
  * `<членство>_simetra_member_check(p_member jsonb, p_scope uuid) RETURNS text`
@@ -37807,7 +37870,7 @@ function memberCheckFunction(contract, membership) {
37807
37870
  ]);
37808
37871
  const keys = contract.createKeys.filter((c) => !forced.has(c));
37809
37872
  const fail = (detail) => `RETURN ${detail};`;
37810
- const scope = `v_new.${q$4(membership.scopeColumn)}`;
37873
+ const scope = `v_new.${q$5(membership.scopeColumn)}`;
37811
37874
  const references = contract.references.filter((reference) => (reference.form === "single" ? [reference.column] : [reference.typeColumn, reference.idColumn]).every((c) => !forced.has(c)));
37812
37875
  return coreFunction(memberCheckFunctionName(table), "p_member jsonb, p_scope uuid", [
37813
37876
  "v_in record;",
@@ -37823,8 +37886,8 @@ function memberCheckFunction(contract, membership) {
37823
37886
  tabular: false,
37824
37887
  fail
37825
37888
  }),
37826
- `v_new := jsonb_populate_record(NULL::${q$4(table.schema)}.${q$4(table.name)}, ${sqlLiteral("{}")});`,
37827
- ...keys.map((c) => `v_new.${q$4(c)} := CASE WHEN p_member ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${defaultOf(table, c)} END;`),
37889
+ `v_new := jsonb_populate_record(NULL::${q$5(table.schema)}.${q$5(table.name)}, ${sqlLiteral("{}")});`,
37890
+ ...keys.map((c) => `v_new.${q$5(c)} := CASE WHEN p_member ? ${sqlLiteral(c)} THEN v_in.${q$5(c)} ELSE ${defaultOf(table, c)} END;`),
37828
37891
  `${scope} := p_scope;`,
37829
37892
  ...referenceChecks(references, newRow({
37830
37893
  scope,
@@ -37866,8 +37929,8 @@ const SIGNAL_FUNCTIONS = {
37866
37929
  }
37867
37930
  };
37868
37931
  // src/compiler/catalog-command/units.ts
37869
- const q$3 = quoteIdent;
37870
- const relation$1 = (t) => `${q$3(t.schema)}.${q$3(t.name)}`;
37932
+ const q$4 = quoteIdent;
37933
+ const relation$2 = (t) => `${q$4(t.schema)}.${q$4(t.name)}`;
37871
37934
  const E = COMMAND_CORE_ERRORS;
37872
37935
  /** `DETAIL` — SQL-вираз: літерал ключа чи конкатенація з `v_key`. */
37873
37936
  const invalid = (detail) => `RAISE EXCEPTION USING ERRCODE = '${E.invalid.errcode}', MESSAGE = '${E.invalid.message}', DETAIL = ${detail};`;
@@ -37913,8 +37976,8 @@ function buildCatalogCommandUnits(input) {
37913
37976
  const { contracts, provider, parse } = input;
37914
37977
  if (!hasRightsFunctions(contracts, provider)) return [];
37915
37978
  const rightsById = new Map(contracts.rights.map((r) => [r.objectId, r]));
37916
- const accessByTable = new Map(contracts.access.map((a) => [relation$1(a.table), a]));
37917
- const authorLinks = new Set(authorCarrierLinks(input.physical, input.attributeCase).map((l) => `${relation$1(l.table)}\0${l.through}`));
37979
+ const accessByTable = new Map(contracts.access.map((a) => [relation$2(a.table), a]));
37980
+ const authorLinks = new Set(authorCarrierLinks(input.physical, input.attributeCase).map((l) => `${relation$2(l.table)}\0${l.through}`));
37918
37981
  const unitOf = (contract, schema = contract.table.schema) => (sql, requires) => ({
37919
37982
  ...generatedUnit(sql, schema, parse),
37920
37983
  ownerObjectId: contract.objectId,
@@ -37931,10 +37994,10 @@ function buildCatalogCommandUnits(input) {
37931
37994
  const units = contracts.membership.flatMap((membership) => {
37932
37995
  const contract = byObject.get(membership.objectId);
37933
37996
  if (contract === void 0) return [];
37934
- return withGrants(unitOf(contract), `${relation$1(memberCheckFunctionName(contract.table))}(jsonb, uuid)`, memberCheckFunction(contract, membership), input.units);
37997
+ return withGrants(unitOf(contract), `${relation$2(memberCheckFunctionName(contract.table))}(jsonb, uuid)`, memberCheckFunction(contract, membership), input.units);
37935
37998
  });
37936
37999
  const creators = rootCreators(input, byObject);
37937
- for (const { root, facts } of creators.values()) units.push(...withGrants(unitOf(root, PLATFORM_SCHEMA), `${relation$1(facts.fn)}(uuid, uuid, jsonb)`, rootCreatorFunction(facts), [...input.units, ...units]));
38000
+ for (const { root, facts } of creators.values()) units.push(...withGrants(unitOf(root, PLATFORM_SCHEMA), `${relation$2(facts.fn)}(uuid, uuid, jsonb)`, rootCreatorFunction(facts), [...input.units, ...units]));
37938
38001
  const invitations = invitationKinds(input, byObject);
37939
38002
  if (invitations.length > 0) {
37940
38003
  const put = (sql, requires) => ({
@@ -37948,10 +38011,10 @@ function buildCatalogCommandUnits(input) {
37948
38011
  units.push(put(sql, bodyRequires(sql, {
37949
38012
  ...input,
37950
38013
  units: input.units
37951
- })), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
38014
+ })), ...executeGrants(`${relation$2(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
37952
38015
  ...input,
37953
38016
  units: input.units
37954
- })), ...executeGrants(`${relation$1(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
38017
+ })), ...executeGrants(`${relation$2(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
37955
38018
  }
37956
38019
  const known = [...input.units, ...units];
37957
38020
  const signalModel = {
@@ -37961,12 +38024,12 @@ function buildCatalogCommandUnits(input) {
37961
38024
  };
37962
38025
  for (const contract of commands) {
37963
38026
  const rights = rightsById.get(contract.objectId);
37964
- const access = accessByTable.get(relation$1(contract.table));
38027
+ const access = accessByTable.get(relation$2(contract.table));
37965
38028
  const parts = coreParts(contract, {
37966
38029
  rights,
37967
38030
  access,
37968
38031
  attributeCase: input.attributeCase,
37969
- authorLink: (link) => authorLinks.has(`${relation$1(link.table)}\0${link.through}`),
38032
+ authorLink: (link) => authorLinks.has(`${relation$2(link.table)}\0${link.through}`),
37970
38033
  signal: access === void 0 || !isSignalObject(signalModel, contract.objectId) ? void 0 : {
37971
38034
  objectId: contract.objectId,
37972
38035
  scopeKindId: access.scope?.scopeKindId ?? ZERO_UUID,
@@ -38012,7 +38075,7 @@ function buildCatalogCommandUnits(input) {
38012
38075
  args: "uuid, bytea",
38013
38076
  sql: invitationIssueFunction(contract, invitation, parts)
38014
38077
  });
38015
- for (const { fn, args, sql } of functions) units.push(...withGrants(unitOf(contract), `${relation$1(fn)}(${args})`, sql, known));
38078
+ for (const { fn, args, sql } of functions) units.push(...withGrants(unitOf(contract), `${relation$2(fn)}(${args})`, sql, known));
38016
38079
  }
38017
38080
  return units.sort((a, b) => compareStrings(a.identity, b.identity));
38018
38081
  }
@@ -38149,7 +38212,7 @@ function defaultOf(table, column) {
38149
38212
  function textColumns(table, row) {
38150
38213
  const columns = table.columns.filter((c) => isTextEncodedType(c.type));
38151
38214
  if (columns.length === 0) return void 0;
38152
- return jsonbBuildObject(columns.map((c) => `${sqlLiteral(c.name)}, ${row}.${q$3(c.name)}::${c.type.endsWith("[]") ? "text[]" : "text"}`));
38215
+ return jsonbBuildObject(columns.map((c) => `${sqlLiteral(c.name)}, ${row}.${q$4(c.name)}::${c.type.endsWith("[]") ? "text[]" : "text"}`));
38153
38216
  }
38154
38217
  /**
38155
38218
  * Рядок результату ядра: `to_jsonb` без колонок, що не є полями сутності
@@ -38189,9 +38252,9 @@ function referenceViolations(reference, row) {
38189
38252
  const scoped = (target, alias) => {
38190
38253
  if (reference.crossScope === true || row.scope === void 0 || row.scopeKindId === void 0) return "";
38191
38254
  const column = target.columns.find((c) => c.origin.scopeKindId === row.scopeKindId);
38192
- return column === void 0 ? "" : ` AND ${alias}.${q$3(column.name)} = ${row.scope}`;
38255
+ return column === void 0 ? "" : ` AND ${alias}.${q$4(column.name)} = ${row.scope}`;
38193
38256
  };
38194
- const visible = (target, key, value, withScope) => `EXISTS (SELECT 1 FROM ${relation$1(target)} g WHERE g.${q$3(key)} = ${value}${withScope ? scoped(target, "g") : ""})`;
38257
+ const visible = (target, key, value, withScope) => `EXISTS (SELECT 1 FROM ${relation$2(target)} g WHERE g.${q$4(key)} = ${value}${withScope ? scoped(target, "g") : ""})`;
38195
38258
  if (reference.form === "single") {
38196
38259
  const value = row.value(reference.column);
38197
38260
  const old = row.old?.(reference.column);
@@ -38247,29 +38310,29 @@ function coreParts(contract, facts) {
38247
38310
  def,
38248
38311
  column: findStandardColumn(table, def, facts.attributeCase)?.name
38249
38312
  })).filter((a) => a.column !== void 0);
38250
- const copyRead = (link) => facts.authorLink(link) ? `SELECT ${link.copies.map((c) => `s.${q$3(c.column)}`).join(", ")} INTO ${link.copies.map((c) => `v_new.${q$3(c.name)}`).join(", ")} FROM ${relation$1(AUTHOR_CARRIER_SOURCES_FUNCTION)}() s;` : carrierCopyRead(link, "v_new", false);
38313
+ const copyRead = (link) => facts.authorLink(link) ? `SELECT ${link.copies.map((c) => `s.${q$4(c.column)}`).join(", ")} INTO ${link.copies.map((c) => `v_new.${q$4(c.name)}`).join(", ")} FROM ${relation$2(AUTHOR_CARRIER_SOURCES_FUNCTION)}() s;` : carrierCopyRead(link, "v_new", false);
38251
38314
  return {
38252
38315
  facts,
38253
38316
  label,
38254
- scope: contract.scopeColumn === void 0 ? void 0 : `v_new.${q$3(contract.scopeColumn)}`,
38317
+ scope: contract.scopeColumn === void 0 ? void 0 : `v_new.${q$4(contract.scopeColumn)}`,
38255
38318
  ownScopeKind,
38256
38319
  authors: authors.map((a) => a.column),
38257
38320
  updatedBy: authors.find((a) => a.def.logicalName === "updatedBy")?.column,
38258
- context: (action, root) => ifThen(`(SELECT ${relation$1(COMMAND_FUNCTIONS.action)}()) IS DISTINCT FROM ${sqlLiteral(action)} OR (SELECT ${relation$1(COMMAND_FUNCTIONS.root)}(${label})) IS DISTINCT FROM ${root}`, [contextRefused]),
38321
+ context: (action, root) => ifThen(`(SELECT ${relation$2(COMMAND_FUNCTIONS.action)}()) IS DISTINCT FROM ${sqlLiteral(action)} OR (SELECT ${relation$2(COMMAND_FUNCTIONS.root)}(${label})) IS DISTINCT FROM ${root}`, [contextRefused]),
38259
38322
  lock: `PERFORM ${hierarchyLockSql(table)};`,
38260
38323
  copyRead,
38261
- relink: (links) => links.flatMap((link) => ifThen(link.pairs.map((p) => `v_new.${q$3(p.local)} IS DISTINCT FROM v_old.${q$3(p.local)}`).join(" OR "), [copyRead(link)])),
38324
+ relink: (links) => links.flatMap((link) => ifThen(link.pairs.map((p) => `v_new.${q$4(p.local)} IS DISTINCT FROM v_old.${q$4(p.local)}`).join(" OR "), [copyRead(link)])),
38262
38325
  signal: (row, op, version) => {
38263
38326
  const target = facts.signal;
38264
38327
  if (target === void 0) return [];
38265
- const scope = target.carrier === void 0 ? uuidLiteral(ZERO_UUID) : `${row}.${q$3(target.carrier)}`;
38266
- return [`PERFORM ${relation$1(SIGNAL_FUNCTIONS.signal)}(${uuidLiteral(target.objectId)}, ${uuidLiteral(target.scopeKindId)}, ${scope}, jsonb_build_object(${sqlLiteral(key)}, ${row}.${q$3(key)}), ${version}, ${op});`];
38328
+ const scope = target.carrier === void 0 ? uuidLiteral(ZERO_UUID) : `${row}.${q$4(target.carrier)}`;
38329
+ return [`PERFORM ${relation$2(SIGNAL_FUNCTIONS.signal)}(${uuidLiteral(target.objectId)}, ${uuidLiteral(target.scopeKindId)}, ${scope}, jsonb_build_object(${sqlLiteral(key)}, ${row}.${q$4(key)}), ${version}, ${op});`];
38267
38330
  },
38268
38331
  rightsIf: (action, dml, row, reason) => ifThen(`(${rightsCheck(facts.rights, action, table, row, dml)}) IS NOT TRUE`, [forbidden(reason)]),
38269
38332
  lockedOld: (root, strength, byFields = false) => [
38270
- `SELECT * INTO v_old FROM ${relation$1(table)} r WHERE r.${q$3(key)} = ${root} FOR ${strength};`,
38333
+ `SELECT * INTO v_old FROM ${relation$2(table)} r WHERE r.${q$4(key)} = ${root} FOR ${strength};`,
38271
38334
  ...ifThen("NOT FOUND", [noRight]),
38272
- ...ifThen(`${byFields ? "p_expected_values IS NULL AND " : ""}v_old.${q$3(contract.versionColumn)} IS DISTINCT FROM p_expected_version`, [conflict(E.conflict.version, `v_old.${q$3(contract.versionColumn)}::text`)])
38335
+ ...ifThen(`${byFields ? "p_expected_values IS NULL AND " : ""}v_old.${q$4(contract.versionColumn)} IS DISTINCT FROM p_expected_version`, [conflict(E.conflict.version, `v_old.${q$4(contract.versionColumn)}::text`)])
38273
38336
  ]
38274
38337
  };
38275
38338
  }
@@ -38291,7 +38354,7 @@ function createParts(contract, parts, action, root) {
38291
38354
  /** Рядок «після» `v_new` для перевірки посилань: значення й скоуп рядка. */
38292
38355
  function newRow(parts) {
38293
38356
  return {
38294
- value: (c) => `v_new.${q$3(c)}`,
38357
+ value: (c) => `v_new.${q$4(c)}`,
38295
38358
  ...parts.scope === void 0 ? {} : { scope: parts.scope },
38296
38359
  ...parts.ownScopeKind === void 0 ? {} : { scopeKindId: parts.ownScopeKind }
38297
38360
  };
@@ -38300,11 +38363,11 @@ function newRow(parts) {
38300
38363
  function saveFunction(contract, parts) {
38301
38364
  const { key } = contract;
38302
38365
  const { scope, ownScopeKind, updatedBy, lock, rightsIf } = parts;
38303
- const root = `v_in.${q$3(key)}`;
38366
+ const root = `v_in.${q$4(key)}`;
38304
38367
  const context = (action) => parts.context(action, root);
38305
38368
  const references = (old) => referenceChecks(contract.references, {
38306
38369
  ...newRow(parts),
38307
- ...old ? { old: (c) => `v_old.${q$3(c)}` } : {}
38370
+ ...old ? { old: (c) => `v_old.${q$4(c)}` } : {}
38308
38371
  }, invalid);
38309
38372
  const createBranch = contract.actions.create === void 0 ? [invalid(sqlLiteral(E.invalid.create))] : createLines(contract, {
38310
38373
  ...createParts(contract, parts, contract.actions.create, root),
@@ -38318,8 +38381,8 @@ function saveFunction(contract, parts) {
38318
38381
  ...rightsIf(contract.actions.update, "update", "v_old", E.forbidden.noRight),
38319
38382
  ...fieldsCheck(contract),
38320
38383
  "v_new := v_old;",
38321
- ...contract.updateKeys.flatMap((c) => ifThen(`p_item ? ${sqlLiteral(c)}`, [`v_new.${q$3(c)} := v_in.${q$3(c)};`])),
38322
- ...updatedBy === void 0 ? [] : [`v_new.${q$3(updatedBy)} := ${CURRENT_USER$1};`],
38384
+ ...contract.updateKeys.flatMap((c) => ifThen(`p_item ? ${sqlLiteral(c)}`, [`v_new.${q$4(c)} := v_in.${q$4(c)};`])),
38385
+ ...updatedBy === void 0 ? [] : [`v_new.${q$4(updatedBy)} := ${CURRENT_USER$1};`],
38323
38386
  ...references(true),
38324
38387
  ...parts.relink(contract.carrierLinks),
38325
38388
  ...rightsIf(contract.actions.update, "update", "v_new", E.forbidden.newCarrier),
@@ -38352,12 +38415,12 @@ function saveFunction(contract, parts) {
38352
38415
  ...indent$1(updateBranch),
38353
38416
  "END IF;",
38354
38417
  ...tabularLines(contract, scope, ownScopeKind),
38355
- ...parts.signal("v_row", `CASE WHEN p_expected_version IS NULL THEN ${signalOp("create")} ELSE ${signalOp("update")} END`, `v_row.${q$3(contract.versionColumn)}`),
38418
+ ...parts.signal("v_row", `CASE WHEN p_expected_version IS NULL THEN ${signalOp("create")} ELSE ${signalOp("update")} END`, `v_row.${q$4(contract.versionColumn)}`),
38356
38419
  ...resultLines(contract, root, true)
38357
38420
  ]);
38358
38421
  }
38359
38422
  function inputLines(spec) {
38360
- const t = relation$1(spec.table);
38423
+ const t = relation$2(spec.table);
38361
38424
  const p = spec.param;
38362
38425
  const allowed = (keys) => textArray([.../* @__PURE__ */ new Set([...keys, ...spec.tabular ? ["tabular"] : []])]);
38363
38426
  const unknown = (keys) => `SELECT k.k INTO v_key FROM jsonb_object_keys(${p}) AS k(k) WHERE k.k <> ALL (${allowed(keys)}) ORDER BY k.k LIMIT 1;`;
@@ -38383,7 +38446,7 @@ function inputLines(spec) {
38383
38446
  ...indent$1([spec.fail("v_key")]),
38384
38447
  "END;",
38385
38448
  `${spec.target} := jsonb_populate_record(NULL::${t}, ${p});`,
38386
- ...spec.key === void 0 ? [] : ifThen(`${spec.target}.${q$3(spec.key)} IS NULL`, [spec.fail(sqlLiteral(spec.key))])
38449
+ ...spec.key === void 0 ? [] : ifThen(`${spec.target}.${q$4(spec.key)} IS NULL`, [spec.fail(sqlLiteral(spec.key))])
38387
38450
  ];
38388
38451
  }
38389
38452
  const isBranched = (keys) => !Array.isArray(keys);
@@ -38440,28 +38503,28 @@ function fieldsCheck(contract) {
38440
38503
  return ifThen("p_expected_values IS NOT NULL", [
38441
38504
  `v_expected := ${rowJson(table, "v_exp")};`,
38442
38505
  `v_current := ${rowJson(table, "v_old")};`,
38443
- ...ifThen(fieldsDiffer(table, contract.updateKeys), [conflict(E.conflict.fields, `v_old.${q$3(versionColumn)}::text`)])
38506
+ ...ifThen(fieldsDiffer(table, contract.updateKeys), [conflict(E.conflict.fields, `v_old.${q$4(versionColumn)}::text`)])
38444
38507
  ]);
38445
38508
  }
38446
38509
  /** Гілка створення (`p_expected_version IS NULL` у `save`, ядро кореня). */
38447
38510
  function createLines(contract, parts) {
38448
38511
  const { table, key } = contract;
38449
- const t = relation$1(table);
38450
- const exists = `PERFORM 1 FROM ${t} r WHERE r.${q$3(key)} = v_in.${q$3(key)};`;
38512
+ const t = relation$2(table);
38513
+ const exists = `PERFORM 1 FROM ${t} r WHERE r.${q$4(key)} = v_in.${q$4(key)};`;
38451
38514
  const constraints = keyConstraints(table, key);
38452
38515
  return [
38453
38516
  ...parts.context,
38454
38517
  exists,
38455
38518
  ...ifThen("FOUND", [conflict(E.conflict.exists)]),
38456
38519
  `v_new := jsonb_populate_record(NULL::${t}, '{}');`,
38457
- ...contract.createKeys.map((c) => `v_new.${q$3(c)} := CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$3(c)} ELSE ${defaultOf(table, c)} END;`),
38458
- ...parts.authors.map((c) => `v_new.${q$3(c)} := ${CURRENT_USER$1};`),
38520
+ ...contract.createKeys.map((c) => `v_new.${q$4(c)} := CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${defaultOf(table, c)} END;`),
38521
+ ...parts.authors.map((c) => `v_new.${q$4(c)} := ${CURRENT_USER$1};`),
38459
38522
  ...parts.references,
38460
38523
  ...parts.copies,
38461
38524
  ...parts.rights,
38462
- ...contract.hierarchy === void 0 ? [] : contract.hierarchy.lockAlways ? [parts.lock] : ifThen(`v_new.${q$3(contract.hierarchy.parent)} IS NOT NULL`, [parts.lock]),
38525
+ ...contract.hierarchy === void 0 ? [] : contract.hierarchy.lockAlways ? [parts.lock] : ifThen(`v_new.${q$4(contract.hierarchy.parent)} IS NOT NULL`, [parts.lock]),
38463
38526
  "BEGIN",
38464
- ...indent$1([`INSERT INTO ${t} (${contract.createKeys.map(q$3).join(", ")}) VALUES (${contract.createKeys.map((c) => `v_new.${q$3(c)}`).join(", ")})${parts.returning ? " RETURNING * INTO v_row" : ""};`]),
38527
+ ...indent$1([`INSERT INTO ${t} (${contract.createKeys.map(q$4).join(", ")}) VALUES (${contract.createKeys.map((c) => `v_new.${q$4(c)}`).join(", ")})${parts.returning ? " RETURNING * INTO v_row" : ""};`]),
38465
38528
  "EXCEPTION WHEN unique_violation THEN",
38466
38529
  ...indent$1([
38467
38530
  "GET STACKED DIAGNOSTICS v_constraint = CONSTRAINT_NAME;",
@@ -38496,14 +38559,14 @@ function keyColumns(table) {
38496
38559
  * `NO KEY UPDATE` (спека П4 §6.6), сумісний з `KEY SHARE` взаємних RI-перевірок.
38497
38560
  */
38498
38561
  function headerUpdate(contract) {
38499
- if (contract.updateKeys.length === 0) throw new Error(`internal: command core of ${relation$1(contract.table)} has no update keys`);
38562
+ if (contract.updateKeys.length === 0) throw new Error(`internal: command core of ${relation$2(contract.table)} has no update keys`);
38500
38563
  const keys = keyColumns(contract.table);
38501
- const form = (columns) => [`UPDATE ${relation$1(contract.table)} SET ${columns.map((c) => `${q$3(c)} = CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$3(c)} ELSE ${q$3(c)} END`).join(", ")} WHERE ${q$3(contract.key)} = v_in.${q$3(contract.key)} RETURNING * INTO v_row;`, "GET DIAGNOSTICS v_count = ROW_COUNT;"];
38564
+ const form = (columns) => [`UPDATE ${relation$2(contract.table)} SET ${columns.map((c) => `${q$4(c)} = CASE WHEN p_item ? ${sqlLiteral(c)} THEN v_in.${q$4(c)} ELSE ${q$4(c)} END`).join(", ")} WHERE ${q$4(contract.key)} = v_in.${q$4(contract.key)} RETURNING * INTO v_row;`, "GET DIAGNOSTICS v_count = ROW_COUNT;"];
38502
38565
  const changed = contract.updateKeys.filter((c) => keys.has(c));
38503
38566
  const rest = contract.updateKeys.filter((c) => !keys.has(c));
38504
38567
  if (changed.length === 0 || rest.length === 0) return form(contract.updateKeys);
38505
38568
  return [
38506
- `IF ${changed.map((c) => `(p_item ? ${sqlLiteral(c)} AND v_in.${q$3(c)} IS DISTINCT FROM v_old.${q$3(c)})`).join(" OR ")} THEN`,
38569
+ `IF ${changed.map((c) => `(p_item ? ${sqlLiteral(c)} AND v_in.${q$4(c)} IS DISTINCT FROM v_old.${q$4(c)})`).join(" OR ")} THEN`,
38507
38570
  ...indent$1(form(contract.updateKeys)),
38508
38571
  "ELSE",
38509
38572
  ...indent$1(form(rest)),
@@ -38522,28 +38585,28 @@ function tabularLines(contract, scope, scopeKindId) {
38522
38585
  ]);
38523
38586
  }
38524
38587
  function sectionLines(contract, section, scope, scopeKindId) {
38525
- const ts = relation$1(section.table);
38588
+ const ts = relation$2(section.table);
38526
38589
  const name = section.table.name;
38527
38590
  const items = `p_item -> 'tabular' -> ${sqlLiteral(name)}`;
38528
38591
  const detail = (suffix) => sqlLiteral(`${E.invalid.tabular}.${name}${suffix === void 0 ? "" : `.${suffix}`}`);
38529
- const root = `v_in.${q$3(contract.key)}`;
38530
- const key = q$3(section.key);
38531
- const parent = q$3(section.parent);
38592
+ const root = `v_in.${q$4(contract.key)}`;
38593
+ const key = q$4(section.key);
38594
+ const parent = q$4(section.parent);
38532
38595
  const elements = `jsonb_array_elements(${items}) WITH ORDINALITY AS x(e, ord) CROSS JOIN LATERAL jsonb_populate_record(NULL::${ts}, x.e) AS v`;
38533
38596
  const constraints = keyConstraints(section.table, section.key);
38534
38597
  const updatable = new Set(section.updateColumns);
38535
38598
  const afterColumns = [...new Set(section.references.flatMap((r) => r.form === "single" ? [r.column] : [r.typeColumn, r.idColumn]))];
38536
38599
  const afterValue = (c) => {
38537
- if (!updatable.has(c)) throw new Error(`internal: tabular reference ${relation$1(section.table)}.${c} is not an update column`);
38538
- return `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} WHEN o.${key} IS NOT NULL THEN o.${q$3(c)} ELSE ${defaultOf(section.table, c)} END AS ${q$3(c)}`;
38600
+ if (!updatable.has(c)) throw new Error(`internal: tabular reference ${relation$2(section.table)}.${c} is not an update column`);
38601
+ return `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} WHEN o.${key} IS NOT NULL THEN o.${q$4(c)} ELSE ${defaultOf(section.table, c)} END AS ${q$4(c)}`;
38539
38602
  };
38540
38603
  const owned = `${elements} LEFT JOIN ${ts} o ON o.${key} = v.${key} AND o.${parent} = ${root}`;
38541
38604
  const afterOf = `CROSS JOIN LATERAL jsonb_populate_record(NULL::${ts}, v_after -> (x.ord - 1)::int) AS n`;
38542
38605
  const materialize = afterColumns.length === 0 ? [] : [`v_after := (SELECT coalesce(jsonb_agg(to_jsonb(n) ORDER BY x.ord), '[]') FROM ${owned} CROSS JOIN LATERAL (SELECT ${afterColumns.map(afterValue).join(", ")}) AS n);`];
38543
38606
  const afterRows = `${owned} ${afterOf}`;
38544
38607
  const references = section.references.flatMap((reference) => referenceViolations(reference, {
38545
- value: (c) => `n.${q$3(c)}`,
38546
- old: (c) => `o.${q$3(c)}`,
38608
+ value: (c) => `n.${q$4(c)}`,
38609
+ old: (c) => `o.${q$4(c)}`,
38547
38610
  ...scope === void 0 ? {} : { scope },
38548
38611
  ...scopeKindId === void 0 ? {} : { scopeKindId }
38549
38612
  }).flatMap(({ column, condition }) => ifThen(`EXISTS (SELECT 1 FROM ${afterRows} WHERE ${condition})`, [invalid(detail(column))])));
@@ -38558,11 +38621,11 @@ function sectionLines(contract, section, scope, scopeKindId) {
38558
38621
  `v.${key}`,
38559
38622
  root,
38560
38623
  "x.ord",
38561
- ...section.scopeColumn === void 0 ? [] : [`v_new.${q$3(must$1(contract.scopeColumn))}`],
38562
- ...section.rowKeys.map((c) => afterColumns.includes(c) ? `n.${q$3(c)}` : `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} ELSE ${defaultOf(section.table, c)} END`)
38624
+ ...section.scopeColumn === void 0 ? [] : [`v_new.${q$4(must$1(contract.scopeColumn))}`],
38625
+ ...section.rowKeys.map((c) => afterColumns.includes(c) ? `n.${q$4(c)}` : `CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} ELSE ${defaultOf(section.table, c)} END`)
38563
38626
  ];
38564
38627
  const insertRows = afterColumns.length === 0 ? elements : `${elements} ${afterOf}`;
38565
- const set = [...section.updateColumns.map((c) => `${q$3(c)} = CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$3(c)} ELSE r.${q$3(c)} END`), `${q$3(section.lineNumber)} = x.ord`].join(", ");
38628
+ const set = [...section.updateColumns.map((c) => `${q$4(c)} = CASE WHEN x.e ? ${sqlLiteral(c)} THEN v.${q$4(c)} ELSE r.${q$4(c)} END`), `${q$4(section.lineNumber)} = x.ord`].join(", ");
38566
38629
  return ifThen(`p_item -> 'tabular' ? ${sqlLiteral(name)}`, [
38567
38630
  ...ifThen(`jsonb_typeof(${items}) IS DISTINCT FROM 'array'`, [invalid(detail())]),
38568
38631
  ...ifThen(`EXISTS (SELECT 1 FROM jsonb_array_elements(${items}) AS x(e) WHERE jsonb_typeof(x.e) IS DISTINCT FROM 'object')`, [invalid(detail())]),
@@ -38591,7 +38654,7 @@ function sectionLines(contract, section, scope, scopeKindId) {
38591
38654
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38592
38655
  ...ifThen("v_count IS DISTINCT FROM v_ts_update", [noRight]),
38593
38656
  "BEGIN",
38594
- ...indent$1([`INSERT INTO ${ts} (${insertColumns.map(q$3).join(", ")}) SELECT ${insertValues.join(", ")} FROM ${insertRows} WHERE NOT EXISTS (SELECT 1 FROM ${ts} r WHERE r.${key} = v.${key} AND r.${parent} = ${root});`]),
38657
+ ...indent$1([`INSERT INTO ${ts} (${insertColumns.map(q$4).join(", ")}) SELECT ${insertValues.join(", ")} FROM ${insertRows} WHERE NOT EXISTS (SELECT 1 FROM ${ts} r WHERE r.${key} = v.${key} AND r.${parent} = ${root});`]),
38595
38658
  "EXCEPTION WHEN unique_violation THEN",
38596
38659
  ...indent$1([
38597
38660
  "GET STACKED DIAGNOSTICS v_constraint = CONSTRAINT_NAME;",
@@ -38614,7 +38677,7 @@ function resultLines(contract, root, tabular) {
38614
38677
  `v_result := ${rowJson(table, "v_row")};`,
38615
38678
  ...!tabular || contract.tabularSections.length === 0 ? [] : ifThen("p_item ? 'tabular'", [
38616
38679
  "v_tabular := '{}';",
38617
- ...contract.tabularSections.flatMap((section) => ifThen(`p_item -> 'tabular' ? ${sqlLiteral(section.table.name)}`, [`v_tabular := v_tabular || jsonb_build_object(${sqlLiteral(section.table.name)}, (SELECT coalesce(jsonb_agg(${rowJson(section.table, "r")} ORDER BY r.${q$3(section.lineNumber)}), '[]') FROM ${relation$1(section.table)} r WHERE r.${q$3(section.parent)} = ${root}));`])),
38680
+ ...contract.tabularSections.flatMap((section) => ifThen(`p_item -> 'tabular' ? ${sqlLiteral(section.table.name)}`, [`v_tabular := v_tabular || jsonb_build_object(${sqlLiteral(section.table.name)}, (SELECT coalesce(jsonb_agg(${rowJson(section.table, "r")} ORDER BY r.${q$4(section.lineNumber)}), '[]') FROM ${relation$2(section.table)} r WHERE r.${q$4(section.parent)} = ${root}));`])),
38618
38681
  "v_result := v_result || jsonb_build_object('tabular', v_tabular);"
38619
38682
  ]),
38620
38683
  "RETURN v_result::text;"
@@ -38638,7 +38701,7 @@ function coreFunction(fn, args, declarations, statements) {
38638
38701
  "END"
38639
38702
  ].join("\n");
38640
38703
  const tag = dollarTag$1(body);
38641
- return `CREATE OR REPLACE FUNCTION ${relation$1(fn)}(${args})\nRETURNS text\nLANGUAGE plpgsql VOLATILE SECURITY INVOKER\nSET search_path = ''\n${pinnedSettingsClause()}\nAS ${tag}\n${body}\n${tag};`;
38704
+ return `CREATE OR REPLACE FUNCTION ${relation$2(fn)}(${args})\nRETURNS text\nLANGUAGE plpgsql VOLATILE SECURITY INVOKER\nSET search_path = ''\n${pinnedSettingsClause()}\nAS ${tag}\n${body}\n${tag};`;
38642
38705
  }
38643
38706
  /**
38644
38707
  * `<корінь>_create_root(p_item jsonb, p_member jsonb, p_member_id uuid)` (спека
@@ -38654,10 +38717,10 @@ function coreFunction(fn, args, declarations, statements) {
38654
38717
  */
38655
38718
  function createRootFunction(contract, fn, action, parts, creator) {
38656
38719
  const { table, key } = contract;
38657
- const root = `v_in.${q$3(key)}`;
38658
- const insertedVersion = (target, into) => `${into} := current_setting(${sqlLiteral(ROW_VERSION_SETTING)} || '${relation$1(target.table)}'::regclass::oid::text, true);`;
38720
+ const root = `v_in.${q$4(key)}`;
38721
+ const insertedVersion = (target, into) => `${into} := current_setting(${sqlLiteral(ROW_VERSION_SETTING)} || '${relation$2(target.table)}'::regclass::oid::text, true);`;
38659
38722
  const visible = (target, row, id, into, version) => [
38660
- `SELECT * INTO ${row} FROM ${relation$1(target.table)} r WHERE r.${q$3(target.key)} = ${id};`,
38723
+ `SELECT * INTO ${row} FROM ${relation$2(target.table)} r WHERE r.${q$4(target.key)} = ${id};`,
38661
38724
  "IF FOUND THEN",
38662
38725
  ` ${into} := ${rowJson(target.table, row)};`,
38663
38726
  "ELSE",
@@ -38690,7 +38753,7 @@ function createRootFunction(contract, fn, action, parts, creator) {
38690
38753
  }),
38691
38754
  ...creator === void 0 ? ifThen("p_member IS NOT NULL OR p_member_id IS NOT NULL", [invalid(sqlLiteral(E.invalid.creatorMember))]) : [
38692
38755
  ...ifThen("p_member IS NULL OR p_member_id IS NULL OR jsonb_typeof(p_member) IS DISTINCT FROM 'object'", [invalid(sqlLiteral(E.invalid.creatorMember))]),
38693
- `v_column := ${relation$1(creator.facts.membership.check)}(p_member, ${root});`,
38756
+ `v_column := ${relation$2(creator.facts.membership.check)}(p_member, ${root});`,
38694
38757
  ...ifThen("v_column IS NOT NULL", [invalid(`${sqlLiteral(`${E.invalid.creatorMember}.`)} || v_column`)])
38695
38758
  ],
38696
38759
  ...createLines(contract, {
@@ -38699,7 +38762,7 @@ function createRootFunction(contract, fn, action, parts, creator) {
38699
38762
  returning: false
38700
38763
  }),
38701
38764
  insertedVersion(contract, "v_root_version"),
38702
- ...creator === void 0 ? [] : [`PERFORM ${relation$1(creator.facts.fn)}(${root}, p_member_id, p_member);`, insertedVersion(creator.member, "v_member_version")],
38765
+ ...creator === void 0 ? [] : [`PERFORM ${relation$2(creator.facts.fn)}(${root}, p_member_id, p_member);`, insertedVersion(creator.member, "v_member_version")],
38703
38766
  ...visible(contract, "v_row", root, "v_result", "v_root_version"),
38704
38767
  ...creator === void 0 ? ["v_member := NULL;"] : visible(creator.member, "v_member_row", "p_member_id", "v_member", "v_member_version"),
38705
38768
  ...creator === void 0 ? [] : parts.signal("v_in", signalOp("create"), "v_root_version::bigint"),
@@ -38715,16 +38778,16 @@ function createRootFunction(contract, fn, action, parts, creator) {
38715
38778
  function markDeletionFunction(contract, fn, action, parts) {
38716
38779
  const { table, key } = contract;
38717
38780
  const root = "p_id";
38718
- const mark = q$3(standardColumn(table, deletionMarkColumn(), parts.facts.attributeCase).name);
38781
+ const mark = q$4(standardColumn(table, deletionMarkColumn(), parts.facts.attributeCase).name);
38719
38782
  const coupled = must$1(parts.facts.rights.actions.find((a) => a.action === action)).coupled;
38720
38783
  const couple = coupled === void 0 ? void 0 : {
38721
- column: q$3(coupled.column),
38784
+ column: q$4(coupled.column),
38722
38785
  value: sqlLiteral(coupled.value)
38723
38786
  };
38724
38787
  const changed = /* @__PURE__ */ new Set([
38725
38788
  mark,
38726
38789
  ...couple === void 0 ? [] : [couple.column],
38727
- ...parts.updatedBy === void 0 ? [] : [q$3(parts.updatedBy)]
38790
+ ...parts.updatedBy === void 0 ? [] : [q$4(parts.updatedBy)]
38728
38791
  ]);
38729
38792
  return coreFunction(fn, "p_id uuid, p_expected_version bigint, p_mark boolean", [
38730
38793
  "v_old record;",
@@ -38742,14 +38805,14 @@ function markDeletionFunction(contract, fn, action, parts) {
38742
38805
  "v_new := v_old;",
38743
38806
  `v_new.${mark} := p_mark;`,
38744
38807
  ...couple === void 0 ? [] : [`v_new.${couple.column} := ${couple.value};`],
38745
- ...parts.updatedBy === void 0 ? [] : [`v_new.${q$3(parts.updatedBy)} := ${CURRENT_USER$1};`],
38746
- ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$3(p.local))))),
38808
+ ...parts.updatedBy === void 0 ? [] : [`v_new.${q$4(parts.updatedBy)} := ${CURRENT_USER$1};`],
38809
+ ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$4(p.local))))),
38747
38810
  ...parts.rightsIf(action, "update", "v_new", E.forbidden.newCarrier),
38748
- ...contract.predefinedColumn === void 0 ? [] : ifThen(`v_old.${q$3(contract.predefinedColumn)} IS NOT NULL`, [invalid(sqlLiteral(E.invalid.predefined))]),
38749
- `UPDATE ${relation$1(table)} SET ${mark} = p_mark${couple === void 0 ? "" : `, ${couple.column} = ${couple.value}`} WHERE ${q$3(key)} = ${root} RETURNING * INTO v_row;`,
38811
+ ...contract.predefinedColumn === void 0 ? [] : ifThen(`v_old.${q$4(contract.predefinedColumn)} IS NOT NULL`, [invalid(sqlLiteral(E.invalid.predefined))]),
38812
+ `UPDATE ${relation$2(table)} SET ${mark} = p_mark${couple === void 0 ? "" : `, ${couple.column} = ${couple.value}`} WHERE ${q$4(key)} = ${root} RETURNING * INTO v_row;`,
38750
38813
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38751
38814
  ...ifThen("v_count = 0", [noRight]),
38752
- ...parts.signal("v_row", signalOp("markDeletion"), `v_row.${q$3(contract.versionColumn)}`),
38815
+ ...parts.signal("v_row", signalOp("markDeletion"), `v_row.${q$4(contract.versionColumn)}`),
38753
38816
  ...resultLines(contract, root, false)
38754
38817
  ]);
38755
38818
  }
@@ -38766,13 +38829,13 @@ function publicationFunction(contract, fn, action, publish, parts) {
38766
38829
  const { table, key } = contract;
38767
38830
  const root = "p_id";
38768
38831
  const rights = must$1(parts.facts.rights.actions.find((a) => a.action === action));
38769
- const published = q$3(must$1(rights.transition).column);
38832
+ const published = q$4(must$1(rights.transition).column);
38770
38833
  const marked = rights.coupled === void 0 ? void 0 : {
38771
- column: q$3(rights.coupled.column),
38834
+ column: q$4(rights.coupled.column),
38772
38835
  allowed: sqlLiteral(rights.coupled.value)
38773
38836
  };
38774
38837
  const value = sqlLiteral(publish);
38775
- const changed = /* @__PURE__ */ new Set([published, ...parts.updatedBy === void 0 ? [] : [q$3(parts.updatedBy)]]);
38838
+ const changed = /* @__PURE__ */ new Set([published, ...parts.updatedBy === void 0 ? [] : [q$4(parts.updatedBy)]]);
38776
38839
  return coreFunction(fn, "p_id uuid, p_expected_version bigint", [
38777
38840
  "v_old record;",
38778
38841
  "v_new record;",
@@ -38788,13 +38851,13 @@ function publicationFunction(contract, fn, action, publish, parts) {
38788
38851
  ...marked === void 0 ? [] : ifThen(`v_old.${marked.column} IS DISTINCT FROM ${marked.allowed}`, [invalid(sqlLiteral(E.invalid.marked))]),
38789
38852
  "v_new := v_old;",
38790
38853
  `v_new.${published} := ${value};`,
38791
- ...parts.updatedBy === void 0 ? [] : [`v_new.${q$3(parts.updatedBy)} := ${CURRENT_USER$1};`],
38792
- ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$3(p.local))))),
38854
+ ...parts.updatedBy === void 0 ? [] : [`v_new.${q$4(parts.updatedBy)} := ${CURRENT_USER$1};`],
38855
+ ...parts.relink(contract.carrierLinks.filter((link) => link.pairs.some((p) => changed.has(q$4(p.local))))),
38793
38856
  ...parts.rightsIf(action, "update", "v_new", E.forbidden.newCarrier),
38794
- `UPDATE ${relation$1(table)} SET ${published} = ${value} WHERE ${q$3(key)} = ${root} RETURNING * INTO v_row;`,
38857
+ `UPDATE ${relation$2(table)} SET ${published} = ${value} WHERE ${q$4(key)} = ${root} RETURNING * INTO v_row;`,
38795
38858
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38796
38859
  ...ifThen("v_count = 0", [noRight]),
38797
- ...parts.signal("v_row", signalOp("update"), `v_row.${q$3(contract.versionColumn)}`),
38860
+ ...parts.signal("v_row", signalOp("update"), `v_row.${q$4(contract.versionColumn)}`),
38798
38861
  ...resultLines(contract, root, false)
38799
38862
  ]);
38800
38863
  }
@@ -38809,17 +38872,17 @@ function publicationFunction(contract, fn, action, publish, parts) {
38809
38872
  function deleteFunction(contract, fn, action, parts) {
38810
38873
  const { table, key, scopeColumn } = contract;
38811
38874
  const root = "p_id";
38812
- const scope = scopeColumn === void 0 || scopeColumn === key ? "" : `, ${sqlLiteral(scopeColumn)}, v_old.${q$3(scopeColumn)}`;
38875
+ const scope = scopeColumn === void 0 || scopeColumn === key ? "" : `, ${sqlLiteral(scopeColumn)}, v_old.${q$4(scopeColumn)}`;
38813
38876
  return coreFunction(fn, "p_id uuid, p_expected_version bigint", ["v_old record;", "v_count bigint;"], [
38814
38877
  ...ifThen("p_expected_version IS NULL", [invalid(sqlLiteral(E.invalid.expectedVersion))]),
38815
38878
  ...parts.context(action, root),
38816
38879
  ...parts.lockedOld(root, "UPDATE"),
38817
38880
  ...parts.rightsIf(action, "delete", "v_old", E.forbidden.noRight),
38818
- `DELETE FROM ${relation$1(table)} WHERE ${q$3(key)} = ${root};`,
38881
+ `DELETE FROM ${relation$2(table)} WHERE ${q$4(key)} = ${root};`,
38819
38882
  "GET DIAGNOSTICS v_count = ROW_COUNT;",
38820
38883
  ...ifThen("v_count = 0", [noRight]),
38821
- ...parts.signal("v_old", signalOp("delete"), `v_old.${q$3(contract.versionColumn)}`),
38822
- `RETURN jsonb_build_object(${sqlLiteral(key)}, ${root}, ${sqlLiteral(contract.versionColumn)}, v_old.${q$3(contract.versionColumn)}::text${scope})::text;`
38884
+ ...parts.signal("v_old", signalOp("delete"), `v_old.${q$4(contract.versionColumn)}`),
38885
+ `RETURN jsonb_build_object(${sqlLiteral(key)}, ${root}, ${sqlLiteral(contract.versionColumn)}, v_old.${q$4(contract.versionColumn)}::text${scope})::text;`
38823
38886
  ]);
38824
38887
  }
38825
38888
  /**
@@ -38840,12 +38903,12 @@ function invitationIssueFunction(contract, invitation, parts) {
38840
38903
  const m = invitation.facts.membership;
38841
38904
  const statements = [
38842
38905
  ...parts.context(action, root),
38843
- `SELECT * INTO v_old FROM ${relation$1(table)} r WHERE r.${q$3(key)} = ${root} FOR NO KEY UPDATE;`,
38906
+ `SELECT * INTO v_old FROM ${relation$2(table)} r WHERE r.${q$4(key)} = ${root} FOR NO KEY UPDATE;`,
38844
38907
  ...ifThen("NOT FOUND", [noRight]),
38845
38908
  ...parts.rightsIf(action, "update", "v_old", E.forbidden.noRight),
38846
- ...ifThen([`v_old.${q$3(m.user)} IS NOT NULL`, ...m.deletion === void 0 ? [] : [`v_old.${q$3(m.deletion)}`]].join(" OR "), [`RAISE EXCEPTION USING ERRCODE = '${E.invitationNotPending.errcode}', MESSAGE = '${E.invitationNotPending.message}';`]),
38847
- ...ifThen(`NOT ${scopeAdministerRights(invitation.facts.assignmentsLabel, invitation.facts.kindId, `v_old.${q$3(m.scope)}`)}`, [noRight]),
38848
- `RETURN jsonb_build_object('expiresAt', ${relation$1(INVITATION_PUT_FUNCTION)}(${root}, p_hash))::text;`
38909
+ ...ifThen([`v_old.${q$4(m.user)} IS NOT NULL`, ...m.deletion === void 0 ? [] : [`v_old.${q$4(m.deletion)}`]].join(" OR "), [`RAISE EXCEPTION USING ERRCODE = '${E.invitationNotPending.errcode}', MESSAGE = '${E.invitationNotPending.message}';`]),
38910
+ ...ifThen(`NOT ${scopeAdministerRights(invitation.facts.assignmentsLabel, invitation.facts.kindId, `v_old.${q$4(m.scope)}`)}`, [noRight]),
38911
+ `RETURN jsonb_build_object('expiresAt', ${relation$2(INVITATION_PUT_FUNCTION)}(${root}, p_hash))::text;`
38849
38912
  ];
38850
38913
  return coreFunction(invitationIssueFunctionName(table), "p_member uuid, p_hash bytea", ["v_old record;"], statements);
38851
38914
  }
@@ -39087,10 +39150,19 @@ function branchesOf(input) {
39087
39150
  };
39088
39151
  }
39089
39152
  /**
39153
+ * Відмова права: код, повідомлення й причина з переліку T0, а `hint` — мітка
39154
+ * виду, на якому бракує права (тригер переприв'язування, спека прав
39155
+ * контейнера §2). Один будівник для `rights_require` і тригера, тож форма
39156
+ * відмови не розійдеться. Мітка — не дані рядка (Рт4).
39157
+ */
39158
+ function rightsRefusal(error, detail, hint) {
39159
+ return `RAISE EXCEPTION USING ERRCODE = '${error.errcode}', MESSAGE = '${error.message}', DETAIL = '${detail}'` + (hint === void 0 ? "" : `, HINT = ${sqlLiteral(hint)}`) + ";";
39160
+ }
39161
+ /**
39090
39162
  * Відмова одна: невідома пара, немає права, немає рядка й `NULL` не
39091
39163
  * розрізняються (оракул наявності рядків не відкривається).
39092
39164
  */
39093
- const REFUSAL = `RAISE EXCEPTION USING ERRCODE = '${RIGHTS_REQUIRE_ERROR.errcode}', MESSAGE = '${RIGHTS_REQUIRE_ERROR.message}', DETAIL = '${RIGHTS_REQUIRE_ERROR.noRight}';`;
39165
+ const REFUSAL = rightsRefusal(RIGHTS_REQUIRE_ERROR, RIGHTS_REQUIRE_ERROR.noRight);
39094
39166
  function requireFunction(name, target, branches) {
39095
39167
  const body = [
39096
39168
  "BEGIN",
@@ -40635,7 +40707,7 @@ const ROWS = {
40635
40707
  UPDATE: ["o", "n"],
40636
40708
  DELETE: ["o"]
40637
40709
  };
40638
- const q$2 = quoteIdent;
40710
+ const q$3 = quoteIdent;
40639
40711
  const ZERO = uuidLiteral(ZERO_UUID);
40640
40712
  const KEY = keyColumn(false);
40641
40713
  const nameOf = (table) => ({
@@ -40668,7 +40740,7 @@ function memberUsers(contracts, scopeKindId, from, subject) {
40668
40740
  }))];
40669
40741
  if (members.length === 0) throw new Error(`internal: no members of scope kind ${scopeKindId}`);
40670
40742
  return {
40671
- selects: members.map((m) => `SELECT m.${q$2(m.user)} AS user_id FROM ${from} JOIN ${qualified(m.table)} m ON m.${q$2(m.key)} = ${subject}`),
40743
+ selects: members.map((m) => `SELECT m.${q$3(m.user)} AS user_id FROM ${from} JOIN ${qualified(m.table)} m ON m.${q$3(m.key)} = ${subject}`),
40672
40744
  reads: members.map((m) => m.table)
40673
40745
  };
40674
40746
  }
@@ -40679,7 +40751,7 @@ function definitionShape(table, level) {
40679
40751
  return {
40680
40752
  reads: [],
40681
40753
  channels: (operation) => ({
40682
- scopes: ROWS[operation].map((a) => level.level === "scope" ? `SELECT ${uuidLiteral(level.scopeKindId)} AS scope_kind, ${a}.${q$2(scope)} AS scope FROM ${FROM[a]}` : `SELECT ${ZERO} AS scope_kind, ${ZERO} AS scope FROM ${FROM[a]}`),
40754
+ scopes: ROWS[operation].map((a) => level.level === "scope" ? `SELECT ${uuidLiteral(level.scopeKindId)} AS scope_kind, ${a}.${q$3(scope)} AS scope FROM ${FROM[a]}` : `SELECT ${ZERO} AS scope_kind, ${ZERO} AS scope FROM ${FROM[a]}`),
40683
40755
  users: []
40684
40756
  })
40685
40757
  };
@@ -40706,7 +40778,7 @@ function shapesOf(table, input) {
40706
40778
  channels: (operation) => ({
40707
40779
  scopes: [],
40708
40780
  users: ROWS[operation].flatMap((a) => {
40709
- const found = assignmentUsers(contracts, catalog.level, FROM[a], `${a}.${q$2(subject)}`);
40781
+ const found = assignmentUsers(contracts, catalog.level, FROM[a], `${a}.${q$3(subject)}`);
40710
40782
  reads.push(...found.reads);
40711
40783
  return found.selects;
40712
40784
  })
@@ -40718,14 +40790,14 @@ function shapesOf(table, input) {
40718
40790
  reads: [],
40719
40791
  channels: (operation) => ({
40720
40792
  scopes: [],
40721
- users: ROWS[operation].map((a) => `SELECT ${a}.${q$2(member.userColumn)} AS user_id FROM ${FROM[a]}`)
40793
+ users: ROWS[operation].map((a) => `SELECT ${a}.${q$3(member.userColumn)} AS user_id FROM ${FROM[a]}`)
40722
40794
  })
40723
40795
  });
40724
40796
  const users = contracts.users;
40725
40797
  if (users !== void 0 && same(users.table)) {
40726
- const key = q$2(users.keyColumn);
40727
- const invalid = q$2(users.invalidColumn);
40728
- const kind = q$2(standardColumn(table, USER_PLATFORM_COLUMNS.userKind, attributeCase).name);
40798
+ const key = q$3(users.keyColumn);
40799
+ const invalid = q$3(users.invalidColumn);
40800
+ const kind = q$3(standardColumn(table, USER_PLATFORM_COLUMNS.userKind, attributeCase).name);
40729
40801
  shapes.push({
40730
40802
  reads: [],
40731
40803
  channels: (operation) => ({
@@ -40746,7 +40818,7 @@ function shapesOf(table, input) {
40746
40818
  channels: (operation) => ({
40747
40819
  scopes: [],
40748
40820
  users: ROWS[operation].flatMap((a) => {
40749
- const subject = `${a}.${q$2(relation.subject)}`;
40821
+ const subject = `${a}.${q$3(relation.subject)}`;
40750
40822
  if ("users" in target) return [`SELECT ${subject} AS user_id FROM ${FROM[a]}`];
40751
40823
  const users = memberUsers(contracts, target.membership, FROM[a], subject);
40752
40824
  reads.push(...users.reads);
@@ -40766,13 +40838,13 @@ function shapesOf(table, input) {
40766
40838
  */
40767
40839
  function containerShape(table, scopeKindId, input) {
40768
40840
  const { contracts, physical, attributeCase } = input;
40769
- const key = q$2(standardColumn(table, KEY, attributeCase).name);
40841
+ const key = q$3(standardColumn(table, KEY, attributeCase).name);
40770
40842
  const scope = scopeKindId === void 0 ? void 0 : scopeColumnOf(table);
40771
40843
  const changed = (operation) => {
40772
40844
  if (operation === "INSERT") return `SELECT n.${key} AS container FROM new_rows n`;
40773
40845
  if (operation === "DELETE") return `SELECT o.${key} AS container FROM old_rows o`;
40774
40846
  if (scope === void 0) return void 0;
40775
- return `SELECT n.${key} AS container FROM old_rows o JOIN new_rows n ON n.${key} = o.${key} WHERE o.${q$2(scope)} IS DISTINCT FROM n.${q$2(scope)}`;
40847
+ return `SELECT n.${key} AS container FROM old_rows o JOIN new_rows n ON n.${key} = o.${key} WHERE o.${q$3(scope)} IS DISTINCT FROM n.${q$3(scope)}`;
40776
40848
  };
40777
40849
  const reads = [];
40778
40850
  return {
@@ -40790,7 +40862,7 @@ function containerShape(table, scopeKindId, input) {
40790
40862
  const subject = standardColumn(assignments, RIGHTS_COLUMNS.subject, attributeCase).name;
40791
40863
  const container = standardColumn(assignments, RIGHTS_COLUMNS.container, attributeCase).name;
40792
40864
  reads.push(catalog.assignments.table);
40793
- const users = assignmentUsers(contracts, catalog.level, `(${containers}) c JOIN ${qualified(catalog.assignments.table)} a ON a.${q$2(container)} = c.container`, `a.${q$2(subject)}`);
40865
+ const users = assignmentUsers(contracts, catalog.level, `(${containers}) c JOIN ${qualified(catalog.assignments.table)} a ON a.${q$3(container)} = c.container`, `a.${q$3(subject)}`);
40794
40866
  reads.push(...users.reads);
40795
40867
  return users.selects;
40796
40868
  })
@@ -40886,7 +40958,7 @@ function buildRightsSignalUnits(input) {
40886
40958
  const names = rightsSignalTriggerNames(table);
40887
40959
  for (const { operation } of operations) {
40888
40960
  const trigger = names.find((n) => n.operation === operation).trigger;
40889
- add(`CREATE TRIGGER ${q$2(trigger)} AFTER ${operation} ON ${qualified(nameOf(table))} ${TRANSITION[operation]} FOR EACH STATEMENT EXECUTE FUNCTION ${qualified(fn)}();`, owner);
40961
+ add(`CREATE TRIGGER ${q$3(trigger)} AFTER ${operation} ON ${qualified(nameOf(table))} ${TRANSITION[operation]} FOR EACH STATEMENT EXECUTE FUNCTION ${qualified(fn)}();`, owner);
40890
40962
  }
40891
40963
  }
40892
40964
  return {
@@ -41004,6 +41076,90 @@ function keyFunction(fn) {
41004
41076
  const tag = dollarTag$1(text);
41005
41077
  return `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS trigger\nLANGUAGE plpgsql SECURITY INVOKER\nSET search_path = ''\nAS ${tag}\n${text}\n${tag};`;
41006
41078
  }
41079
+ // src/compiler/rights/rebind-units.ts
41080
+ const q$2 = quoteIdent;
41081
+ const relation$1 = (t) => `${q$2(t.schema)}.${q$2(t.name)}`;
41082
+ /** Дія, право на яку переприв'язування вимагає на кожен вид-нащадок. */
41083
+ const REBIND_ACTION = "update";
41084
+ /** Вузол `requires` платформної функції за ім'ям і типами аргументів. */
41085
+ const functionNode = (fn, types) => ({
41086
+ type: "unit",
41087
+ identity: keyIdentity("function", functionKey(fn.schema, fn.name, types))
41088
+ });
41089
+ /**
41090
+ * Генератор переприв'язування (спека прав контейнера §2, Р-К1-8): на
41091
+ * основній таблиці кожного виду з ланцюжковими нащадками — `AFTER UPDATE`
41092
+ * тригер, що вимагає права `update` в обсязі `any` на кожен вид-нащадок і в
41093
+ * контейнері «до», і в контейнері «після»: зміна прив'язки рядка переносить
41094
+ * усіх його нащадків. Лише з функціями прав, як і тригер ефектів. Тіло
41095
+ * plpgsql граф не читає, тож функції тіла — явні ребра `requires`.
41096
+ */
41097
+ function buildRebindUnits(input) {
41098
+ const { contracts, physical, provider, module, parse } = input;
41099
+ if (!hasRightsFunctions(contracts, provider)) return [];
41100
+ const rightsById = new Map(contracts.rights.map((c) => [c.objectId, c]));
41101
+ const F = RIGHTS_FUNCTIONS;
41102
+ const units = [];
41103
+ for (const [sourceId, ids] of bindingDescendants(input.bindings)) {
41104
+ const binding = must$9(must$9(rightsById.get(sourceId)).binding);
41105
+ const table = must$9(mainTableOf(physical, sourceId));
41106
+ const descendants = ids.map((id) => must$9(rightsById.get(id))).sort((a, b) => compareStrings(a.kindLabel, b.kindLabel));
41107
+ const unit = (sql, requires) => ({
41108
+ ...generatedUnit(sql, table.schema, parse),
41109
+ ownerObjectId: sourceId,
41110
+ module,
41111
+ generator: "carriers",
41112
+ ...requires === void 0 ? {} : { requires }
41113
+ });
41114
+ const fn = carrierFunctionNames(table).rebind;
41115
+ const requires = [
41116
+ functionNode(COMMAND_FUNCTIONS.current, []),
41117
+ functionNode(F.any, ["text", "text"]),
41118
+ functionNode(F.container, [
41119
+ "text",
41120
+ "text",
41121
+ "text",
41122
+ "uuid"
41123
+ ]),
41124
+ ...descendants.some((d) => d.scopeKindId === void 0) ? [functionNode(F.hasRight, [
41125
+ "text",
41126
+ "text",
41127
+ "text",
41128
+ "uuid"
41129
+ ])] : []
41130
+ ];
41131
+ const when = [.../* @__PURE__ */ new Set([binding.carrier.column, binding.carrier.value])].map((c) => `(OLD.${q$2(c)} IS DISTINCT FROM NEW.${q$2(c)})`).join(" AND ");
41132
+ units.push(unit(definerTrigger(fn, rebindBody(table, binding.carrier.value, descendants)), requires), ...executeGrants(`${relation$1(fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$2(carrierTriggerNames(table).rebind)} AFTER UPDATE ON ${relation$1(table)} FOR EACH ROW WHEN (${when}) EXECUTE FUNCTION ${relation$1(fn)}();`));
41133
+ }
41134
+ return units.sort((a, b) => compareStrings(a.identity, b.identity));
41135
+ }
41136
+ /**
41137
+ * Тіло переприв'язування. Поза контекстом команди (режим обслуговування,
41138
+ * крок даних плану) не судить — до жодного виклику функцій прав. Сторона —
41139
+ * контейнер рядка з правом чи скоуп рядка з правом рівня скоупу; порожня
41140
+ * прив'язка дає `NULL = ANY(…)`, тож лишається право рівня скоупу, а
41141
+ * `IS NOT TRUE` відмовляє й на `NULL`. Права — початку транзакції: функції
41142
+ * фактів під контекстом читають знімок актора.
41143
+ */
41144
+ function rebindBody(table, carrier, descendants) {
41145
+ const scopeOf = (d) => d.scopeKindId === void 0 ? void 0 : must$9(table.columns.find((c) => c.origin.scopeKindId === d.scopeKindId)).name;
41146
+ const body = [
41147
+ "DECLARE",
41148
+ " v_action text;",
41149
+ "BEGIN",
41150
+ ` SELECT c.action INTO v_action FROM ${relation$1(COMMAND_FUNCTIONS.current)}() AS c;`,
41151
+ " IF v_action IS NULL THEN",
41152
+ " RETURN NULL;",
41153
+ " END IF;"
41154
+ ];
41155
+ for (const descendant of descendants) {
41156
+ const grants = anyGrants(descendant, REBIND_ACTION, carrier, scopeOf(descendant));
41157
+ const side = (row) => `(${renderCondition(grants.container, row)} OR ${renderCondition(grants.scope, row)})`;
41158
+ body.push(` IF (${side("OLD")} AND ${side("NEW")}) IS NOT TRUE THEN`, ` ${rightsRefusal(COMMAND_CORE_ERRORS.forbidden, COMMAND_CORE_ERRORS.forbidden.noRight, descendant.kindLabel)}`, " END IF;");
41159
+ }
41160
+ body.push(" RETURN NULL;", "END");
41161
+ return body.join("\n");
41162
+ }
41007
41163
  // src/compiler/rights/effects-units.ts
41008
41164
  const q$1 = quoteIdent;
41009
41165
  const relation = (t) => `${q$1(t.schema)}.${q$1(t.name)}`;
@@ -42546,6 +42702,19 @@ async function runStages(stage1, options = {}) {
42546
42702
  ...buildLanguageStateUnits(physical, stage1.objects, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42547
42703
  ...buildSubscriptionUnits(eventSubscriptions, physical, stage1.project.naming.attributeCase, module, parse),
42548
42704
  ...buildCarrierUnits(physical, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42705
+ ...buildRebindUnits({
42706
+ contracts: {
42707
+ rights,
42708
+ roles,
42709
+ users,
42710
+ membershipSources: sources.membershipSources
42711
+ },
42712
+ bindings: stage3.bindings,
42713
+ physical,
42714
+ provider: stage1.project.database.provider,
42715
+ module,
42716
+ parse
42717
+ }),
42549
42718
  ...buildRightsUnits(rightsInputs, physical, stage1.project.naming.attributeCase, stage1.project.database.provider, module, parse),
42550
42719
  ...buildExplainUnits({
42551
42720
  ...rightsInputs,
@@ -43368,6 +43537,7 @@ function platformTriggers(table) {
43368
43537
  entry("carriers", "carriers", carrierFns.derive, carriers.derive),
43369
43538
  entry("carriers", "carriers", carrierFns.propagate, carriers.propagate),
43370
43539
  entry("carriers", "carriers", carrierFns.propagate, carriers.propagateInsert),
43540
+ entry("carriers", "carriers", carrierFns.rebind, carriers.rebind),
43371
43541
  entry("hierarchy", "mechanics", hierarchy.fn, hierarchy.insert),
43372
43542
  entry("hierarchy", "mechanics", hierarchy.fn, hierarchy.update),
43373
43543
  entry("languageState", "mechanics", language.fn, language.row),