simetra 0.3.0-next.5 → 0.3.0-next.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compiler/index.js +303 -85
- package/dist/model/index.d.ts +3 -3
- package/dist/schema/index.d.ts +1 -1
- package/dist/schema/index.js +1 -1
- package/package.json +2 -2
package/dist/compiler/index.js
CHANGED
|
@@ -12581,8 +12581,8 @@ function carrierFunctions(physical) {
|
|
|
12581
12581
|
role: "propagate"
|
|
12582
12582
|
}))];
|
|
12583
12583
|
}
|
|
12584
|
-
const q$
|
|
12585
|
-
const relation$4 = (t) => `${q$
|
|
12584
|
+
const q$11 = quoteIdent;
|
|
12585
|
+
const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
|
|
12586
12586
|
/** Функція джерел копій від авторства (спека П4 §6.7). */
|
|
12587
12587
|
const AUTHOR_CARRIER_SOURCES_FUNCTION = {
|
|
12588
12588
|
schema: PLATFORM_SCHEMA,
|
|
@@ -12643,12 +12643,12 @@ function authorSourcesUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12643
12643
|
const users = authorSource(authorCarrierLinks(physical, attributeCase));
|
|
12644
12644
|
const fn = relation$4(sources.fn);
|
|
12645
12645
|
const body = [
|
|
12646
|
-
`SELECT ${sources.columns.map((c) => `s.${q$
|
|
12646
|
+
`SELECT ${sources.columns.map((c) => `s.${q$11(c.name)}`).join(", ")}`,
|
|
12647
12647
|
`FROM ${relation$4(users)} s`,
|
|
12648
|
-
`WHERE s.${q$
|
|
12648
|
+
`WHERE s.${q$11(users.key)} = ${CURRENT_USER$1}`
|
|
12649
12649
|
].join("\n");
|
|
12650
12650
|
const tag = dollarTag$1(body);
|
|
12651
|
-
const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$
|
|
12651
|
+
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};`;
|
|
12652
12652
|
const requires = [{
|
|
12653
12653
|
type: "table",
|
|
12654
12654
|
schema: users.schema,
|
|
@@ -12703,7 +12703,7 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12703
12703
|
const table = group[0].table;
|
|
12704
12704
|
const fn = carrierFunctionNames(table).derive;
|
|
12705
12705
|
const sources = uniqueTables(group.map((l) => l.source));
|
|
12706
|
-
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$
|
|
12706
|
+
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)}();`));
|
|
12707
12707
|
}
|
|
12708
12708
|
for (const group of byTable((l) => l.source)) {
|
|
12709
12709
|
const source = group[0].source;
|
|
@@ -12711,9 +12711,9 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12711
12711
|
const names = carrierTriggerNames(source);
|
|
12712
12712
|
const dependents = uniqueTables(group.map((l) => l.table));
|
|
12713
12713
|
const read = new Set(group.flatMap((l) => l.copies.map((c) => c.column)));
|
|
12714
|
-
const changed = source.columns.filter((c) => read.has(c.name)).map((c) => `(OLD.${q$
|
|
12714
|
+
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 ");
|
|
12715
12715
|
const execute = `EXECUTE FUNCTION ${relation$4(fn)}();`;
|
|
12716
|
-
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$
|
|
12716
|
+
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}`));
|
|
12717
12717
|
}
|
|
12718
12718
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
12719
12719
|
}
|
|
@@ -12722,7 +12722,7 @@ function uniqueTables(tables) {
|
|
|
12722
12722
|
}
|
|
12723
12723
|
/** `s.<джерело> = <row>.<локальна> AND …` за колонками FK зв'язку. */
|
|
12724
12724
|
function sourceRow(link, row) {
|
|
12725
|
-
return link.pairs.map((p) => `s.${q$
|
|
12725
|
+
return link.pairs.map((p) => `s.${q$11(p.source)} = ${row}.${q$11(p.local)}`).join(" AND ");
|
|
12726
12726
|
}
|
|
12727
12727
|
/**
|
|
12728
12728
|
* Читання всіх копій зв'язку з рядка джерела в `row` — один будівник для
|
|
@@ -12733,8 +12733,8 @@ function sourceRow(link, row) {
|
|
|
12733
12733
|
*/
|
|
12734
12734
|
function carrierCopyRead(link, row, lock) {
|
|
12735
12735
|
return [
|
|
12736
|
-
`SELECT ${link.copies.map((c) => `s.${q$
|
|
12737
|
-
` INTO ${link.copies.map((c) => `${row}.${q$
|
|
12736
|
+
`SELECT ${link.copies.map((c) => `s.${q$11(c.column)}`).join(", ")}`,
|
|
12737
|
+
` INTO ${link.copies.map((c) => `${row}.${q$11(c.name)}`).join(", ")}`,
|
|
12738
12738
|
` FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
|
|
12739
12739
|
...lock ? [" FOR SHARE;"] : []
|
|
12740
12740
|
].join("\n");
|
|
@@ -12751,9 +12751,9 @@ function deriveFunction(fn, links) {
|
|
|
12751
12751
|
const body = ["BEGIN"];
|
|
12752
12752
|
for (const link of links) {
|
|
12753
12753
|
const from = `FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
|
|
12754
|
-
const linkChanged = link.pairs.map((p) => `NEW.${q$
|
|
12754
|
+
const linkChanged = link.pairs.map((p) => `NEW.${q$11(p.local)} IS DISTINCT FROM OLD.${q$11(p.local)}`).join(" OR ");
|
|
12755
12755
|
body.push(` IF TG_OP = 'INSERT' OR ${linkChanged} THEN`, ` ${carrierCopyRead(link, "NEW", true)}`, " ELSE");
|
|
12756
|
-
for (const copy of link.copies) body.push(` IF NEW.${q$
|
|
12756
|
+
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;");
|
|
12757
12757
|
body.push(" END IF;");
|
|
12758
12758
|
}
|
|
12759
12759
|
body.push(" RETURN NEW;", "END");
|
|
@@ -12769,9 +12769,9 @@ function propagateFunction(fn, links) {
|
|
|
12769
12769
|
const ordered = [...links].sort((a, b) => compareStrings(tableKey$1(a.table), tableKey$1(b.table)) || compareStrings(a.through, b.through));
|
|
12770
12770
|
const body = ["BEGIN"];
|
|
12771
12771
|
for (const link of ordered) {
|
|
12772
|
-
const set = link.copies.map((c) => `${q$
|
|
12773
|
-
const row = link.pairs.map((p) => `d.${q$
|
|
12774
|
-
const differs = link.copies.map((c) => `d.${q$
|
|
12772
|
+
const set = link.copies.map((c) => `${q$11(c.name)} = NEW.${q$11(c.column)}`).join(", ");
|
|
12773
|
+
const row = link.pairs.map((p) => `d.${q$11(p.local)} = NEW.${q$11(p.source)}`).join(" AND ");
|
|
12774
|
+
const differs = link.copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM NEW.${q$11(c.column)}`).join(" OR ");
|
|
12775
12775
|
body.push(` UPDATE ${relation$4(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
|
|
12776
12776
|
}
|
|
12777
12777
|
body.push(" RETURN NULL;", "END");
|
|
@@ -12836,8 +12836,8 @@ function carrierBackfillStatements(physical, pending) {
|
|
|
12836
12836
|
};
|
|
12837
12837
|
for (const b of backfills) visit(b);
|
|
12838
12838
|
return ordered.map(({ link, copies }) => {
|
|
12839
|
-
const from = `FROM ${relation$4(link.source)} AS s WHERE ` + link.pairs.map((p) => `s.${q$
|
|
12840
|
-
const differs = copies.map((c) => `d.${q$
|
|
12839
|
+
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 ");
|
|
12840
|
+
const differs = copies.map((c) => `d.${q$11(c.name)} IS DISTINCT FROM (SELECT s.${q$11(c.column)} ${from})`).join(" OR ");
|
|
12841
12841
|
return {
|
|
12842
12842
|
table: {
|
|
12843
12843
|
schema: link.table.schema,
|
|
@@ -12848,7 +12848,7 @@ function carrierBackfillStatements(physical, pending) {
|
|
|
12848
12848
|
name: link.source.name
|
|
12849
12849
|
},
|
|
12850
12850
|
columns: copies.map((c) => c.name),
|
|
12851
|
-
sql: `UPDATE ${relation$4(link.table)} AS d SET (${copies.map((c) => q$
|
|
12851
|
+
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};`
|
|
12852
12852
|
};
|
|
12853
12853
|
});
|
|
12854
12854
|
}
|
|
@@ -23791,6 +23791,34 @@ function liveInputs(contracts, physical, style, user) {
|
|
|
23791
23791
|
deltas: deltasCte(contracts.rightsCatalogs, physical, style)
|
|
23792
23792
|
};
|
|
23793
23793
|
}
|
|
23794
|
+
/**
|
|
23795
|
+
* Входи набору видачі запрошення (Р-З1-1): ті самі генератори й фільтри
|
|
23796
|
+
* дієвості, що `liveInputs`, але за переліком id призначень довідника рівня
|
|
23797
|
+
* `catalog` (`ids` — SQL-вираз `uuid[]`), а не за користувачем: учасник, що
|
|
23798
|
+
* очікує, ще ні в чиїх «моїх скоупах». Носії `fullAccess` — за архетипом
|
|
23799
|
+
* прямого призначення набору, без актора: користувача в учасника ще немає.
|
|
23800
|
+
* Дельти — лише довідника набору: кастомна роль призначення — того самого
|
|
23801
|
+
* рівня й тенанта. Рядок `typed` несе ще й id призначення (`assignment`):
|
|
23802
|
+
* функція прийняття пише його в `rights_tx_typed.assignment`, а живий шлях
|
|
23803
|
+
* цієї колонки не має, тож його SQL не змінюється.
|
|
23804
|
+
*/
|
|
23805
|
+
function issueInputs(contracts, catalog, physical, style, ids) {
|
|
23806
|
+
const typed = withCtes([["assignments", catalogAssignments(catalog, physical, style, { ids })]], typedCte(false, true));
|
|
23807
|
+
const storage = storageSql(catalog.level);
|
|
23808
|
+
return {
|
|
23809
|
+
typed,
|
|
23810
|
+
containers: containersCte(contracts.rights, physical, style),
|
|
23811
|
+
deltas: deltasCte([catalog], physical, style),
|
|
23812
|
+
holders: [
|
|
23813
|
+
`SELECT DISTINCT ${sqlLiteral(catalog.level.level)}::text AS level, ${storage.storageId} AS level_id, t.scope`,
|
|
23814
|
+
`FROM (\n${indent$2(typed)}\n) t`,
|
|
23815
|
+
`JOIN ${call$1(RIGHTS_FUNCTIONS.fullAccessRoles)} f`,
|
|
23816
|
+
` ON f.role_id = t.archetype`,
|
|
23817
|
+
` AND f.storage_id IS NOT DISTINCT FROM ${storage.storageId}`,
|
|
23818
|
+
`WHERE t.custom_role IS NULL`
|
|
23819
|
+
].join("\n")
|
|
23820
|
+
};
|
|
23821
|
+
}
|
|
23794
23822
|
/** `WITH` з CTE `[ім'я, тіло, матеріалізація?]` перед запитом `tail`. */
|
|
23795
23823
|
function withCtes(ctes, tail) {
|
|
23796
23824
|
return [`WITH ${ctes.map(([name, sql, materialized = ""]) => `${name} AS ${materialized}(\n${indent$2(sql)}\n)`).join(",\n")}`, tail].join("\n");
|
|
@@ -24099,7 +24127,7 @@ function catalogAssignments(catalog, physical, style, of) {
|
|
|
24099
24127
|
return [
|
|
24100
24128
|
`SELECT ${storage.storage} AS storage, ${storage.storageId} AS storage_id, ${scope} AS scope, ${a(R.container)} AS container, ${a(R.customRole)} AS custom_role,`,
|
|
24101
24129
|
` CASE WHEN ${a(R.customRole)} IS NULL THEN ${a(R.archetype)} ELSE ${c(R.archetype)} END AS archetype,`,
|
|
24102
|
-
` ${storage.storageId} AS scope_kind_id, NULL::text AS source_level, NULL::uuid AS source_level_id`,
|
|
24130
|
+
` ${storage.storageId} AS scope_kind_id, NULL::text AS source_level, NULL::uuid AS source_level_id${"ids" in of ? `, ${a(KEY)} AS assignment` : ""}`,
|
|
24103
24131
|
`FROM ${qualified(catalog.assignments.table)} a`,
|
|
24104
24132
|
...mine,
|
|
24105
24133
|
`LEFT JOIN ${qualified(catalog.roles.table)} c`,
|
|
@@ -24168,10 +24196,11 @@ function sourceScopeKind(level, rights) {
|
|
|
24168
24196
|
* зберігання ролей, покритих джерелом, — `NULL`, тож рядок джерела
|
|
24169
24197
|
* типізується інакше (спека прав §4.7): рівень ролі мусить дорівнювати рівню джерела —
|
|
24170
24198
|
* сталій генератора, а не даним; ключ глобальної ролі в контейнерному джерелі
|
|
24171
|
-
* її не вмикає.
|
|
24199
|
+
* її не вмикає. `withAssignment` — колонка id призначення лише для входів
|
|
24200
|
+
* набору видачі (`issueInputs`).
|
|
24172
24201
|
*/
|
|
24173
|
-
function typedCte(withSources) {
|
|
24174
|
-
const columns = `SELECT x.storage, x.storage_id, x.scope, x.container, x.custom_role, x.archetype, x.scope_kind_id, r.level, r.level_id`;
|
|
24202
|
+
function typedCte(withSources, withAssignment = false) {
|
|
24203
|
+
const columns = `SELECT x.storage, x.storage_id, x.scope, x.container, x.custom_role, x.archetype, x.scope_kind_id, r.level, r.level_id${withAssignment ? ", x.assignment" : ""}`;
|
|
24175
24204
|
const roles = `JOIN ${call$1(RIGHTS_FUNCTIONS.roles)} r`;
|
|
24176
24205
|
return [
|
|
24177
24206
|
columns,
|
|
@@ -31316,8 +31345,8 @@ function hierarchyNames(table) {
|
|
|
31316
31345
|
}
|
|
31317
31346
|
};
|
|
31318
31347
|
}
|
|
31319
|
-
const q$
|
|
31320
|
-
const relation$3 = (t) => `${q$
|
|
31348
|
+
const q$10 = quoteIdent;
|
|
31349
|
+
const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
|
|
31321
31350
|
/**
|
|
31322
31351
|
* Виклик advisory-замка ієрархії таблиці — одне джерело ключа для тригера й
|
|
31323
31352
|
* ядра команд (спека П4 §6.6): інший вираз ключа в ядрі не серіалізував би його з
|
|
@@ -31383,7 +31412,7 @@ function buildHierarchyUnits(physical, objects, attributeCase, provider, module,
|
|
|
31383
31412
|
}] } : {}
|
|
31384
31413
|
});
|
|
31385
31414
|
const execute = `EXECUTE FUNCTION ${relation$3(names.fn)}();`;
|
|
31386
|
-
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$
|
|
31415
|
+
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}`));
|
|
31387
31416
|
}
|
|
31388
31417
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
31389
31418
|
}
|
|
@@ -31400,11 +31429,11 @@ function hierarchyBody({ table, parent, key }) {
|
|
|
31400
31429
|
" IF current_setting('transaction_isolation') <> 'read committed' THEN",
|
|
31401
31430
|
` RAISE EXCEPTION USING ERRCODE = '${HIERARCHY_ISOLATION_ERROR.errcode}', MESSAGE = '${HIERARCHY_ISOLATION_ERROR.message}';`,
|
|
31402
31431
|
" END IF;",
|
|
31403
|
-
` IF NEW.${q$
|
|
31432
|
+
` IF NEW.${q$10(parent)} = NEW.${q$10(key)} THEN`,
|
|
31404
31433
|
` ${invalid}`,
|
|
31405
31434
|
" END IF;",
|
|
31406
31435
|
` PERFORM ${hierarchyLockSql(table)};`,
|
|
31407
|
-
` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$
|
|
31436
|
+
` 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`,
|
|
31408
31437
|
` ${invalid}`,
|
|
31409
31438
|
" END IF;",
|
|
31410
31439
|
" RETURN NULL;",
|
|
@@ -31476,8 +31505,8 @@ function languageStateTables(physical, objects, attributeCase) {
|
|
|
31476
31505
|
}
|
|
31477
31506
|
return result.sort((a, b) => compareStrings(a.table.schema, b.table.schema) || compareStrings(a.table.name, b.table.name));
|
|
31478
31507
|
}
|
|
31479
|
-
const q$
|
|
31480
|
-
const relation$2 = (t) => `${q$
|
|
31508
|
+
const q$9 = quoteIdent;
|
|
31509
|
+
const relation$2 = (t) => `${q$9(t.schema)}.${q$9(t.name)}`;
|
|
31481
31510
|
/**
|
|
31482
31511
|
* Тригер стану мови (Р-B2-4, спека багатомовності §5.2): незмінність основної
|
|
31483
31512
|
* й коду, переходи стану за матрицею факту ролі, заборона позначки видалення,
|
|
@@ -31500,7 +31529,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
|
|
|
31500
31529
|
generator: "mechanics"
|
|
31501
31530
|
});
|
|
31502
31531
|
const execute = `EXECUTE FUNCTION ${relation$2(names.fn)}();`;
|
|
31503
|
-
units.push(unit(definerTrigger(names.fn, languageStateBody(entry), { rowSecurity: "off" })), ...executeGrants(`${relation$2(names.fn)}()`, [], provider).map((sql) => unit(sql)), unit(`CREATE TRIGGER ${q$
|
|
31532
|
+
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}`));
|
|
31504
31533
|
}
|
|
31505
31534
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
31506
31535
|
}
|
|
@@ -31513,7 +31542,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
|
|
|
31513
31542
|
function languageStateBody({ state, columns }) {
|
|
31514
31543
|
const E = COMMAND_CORE_ERRORS.invalid;
|
|
31515
31544
|
const refuse = `RAISE EXCEPTION USING ERRCODE = '${E.errcode}', MESSAGE = '${E.message}', DETAIL = ${sqlLiteral(E.languageState)};`;
|
|
31516
|
-
const col = (row, name) => `${row}.${q$
|
|
31545
|
+
const col = (row, name) => `${row}.${q$9(name)}`;
|
|
31517
31546
|
const branch = (condition, body, indent = " ") => [
|
|
31518
31547
|
`${indent}IF ${condition} THEN`,
|
|
31519
31548
|
...body.map((line) => `${indent} ${line}`),
|
|
@@ -36197,7 +36226,7 @@ function effectiveHolderRows(catalog, contracts, physical, attributeCase) {
|
|
|
36197
36226
|
].filter(Boolean).join("\n");
|
|
36198
36227
|
}
|
|
36199
36228
|
// src/compiler/rights/guard-units.ts
|
|
36200
|
-
const q$
|
|
36229
|
+
const q$8 = quoteIdent;
|
|
36201
36230
|
const platform = (name) => ({
|
|
36202
36231
|
schema: PLATFORM_SCHEMA,
|
|
36203
36232
|
name
|
|
@@ -36319,17 +36348,17 @@ function journalRelation(table) {
|
|
|
36319
36348
|
return `${table.schema}.${table.name}`;
|
|
36320
36349
|
}
|
|
36321
36350
|
function scopeSql(config, alias) {
|
|
36322
|
-
return [sqlLiteral(config.catalog.level.level === "scope" ? config.catalog.level.scopeKindId : ZERO_UUID) + "::uuid", config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `${alias}.${q$
|
|
36351
|
+
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)}`];
|
|
36323
36352
|
}
|
|
36324
36353
|
function transitionSql(config, operation) {
|
|
36325
36354
|
const old = operation !== "INSERT";
|
|
36326
36355
|
const next = operation !== "DELETE";
|
|
36327
|
-
const source = operation === "INSERT" ? "new_rows n" : operation === "DELETE" ? "old_rows o" : `old_rows o FULL JOIN new_rows n ON n.${q$
|
|
36328
|
-
const key = next && old ? `coalesce(n.${q$
|
|
36356
|
+
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)}`;
|
|
36357
|
+
const key = next && old ? `coalesce(n.${q$8(config.key)}, o.${q$8(config.key)})` : `${next ? "n" : "o"}.${q$8(config.key)}`;
|
|
36329
36358
|
const [scopeKind, oldScope] = scopeSql(config, "o");
|
|
36330
36359
|
const [, newScope] = scopeSql(config, "n");
|
|
36331
36360
|
const scope = next && old ? `coalesce(${newScope}, ${oldScope})` : next ? newScope : oldScope;
|
|
36332
|
-
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$
|
|
36361
|
+
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}`;
|
|
36333
36362
|
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}`;
|
|
36334
36363
|
const relation = journalRelation(config.table);
|
|
36335
36364
|
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)}` : "";
|
|
@@ -36551,12 +36580,12 @@ function pendingSql(config, operation) {
|
|
|
36551
36580
|
const after = operation !== "DELETE";
|
|
36552
36581
|
const [kind] = scopeSql(config, "r");
|
|
36553
36582
|
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 ");
|
|
36554
|
-
const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$
|
|
36555
|
-
const roleKey = config.kind === "delta" ? `r.${q$
|
|
36583
|
+
const scope = config.scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(config.scope)}`;
|
|
36584
|
+
const roleKey = config.kind === "delta" ? `r.${q$8(config.parent)}` : `r.${q$8(config.key)}`;
|
|
36556
36585
|
return pendingInsert([
|
|
36557
|
-
`SELECT ${sqlLiteral(config.kind === "assignment" ? "assignment" : "role")}::text AS kind, ${config.kind === "assignment" ? `r.${q$
|
|
36558
|
-
...config.kind === "assignment" ? [`SELECT 'role'::text, r.${q$
|
|
36559
|
-
...config.kind === "assignment" && before ? [`SELECT 'holders'::text, ${scope}, ${kind}, ${scope}, 1 FROM old_rows r WHERE r.${q$
|
|
36586
|
+
`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`,
|
|
36587
|
+
...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`] : [],
|
|
36588
|
+
...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"})`] : [],
|
|
36560
36589
|
actorPending()
|
|
36561
36590
|
], "v_maintenance");
|
|
36562
36591
|
}
|
|
@@ -36572,7 +36601,7 @@ function pendingSql(config, operation) {
|
|
|
36572
36601
|
function stateRows(table, state, match, style) {
|
|
36573
36602
|
const name = ref(tableName(table));
|
|
36574
36603
|
const equals = match.any === true ? `= ANY (${match.value})` : `= ${match.value}`;
|
|
36575
|
-
const live = `l.${q$
|
|
36604
|
+
const live = `l.${q$8(match.column)} ${equals}`;
|
|
36576
36605
|
if (state === "after") return `SELECT to_jsonb(l) AS doc FROM ${name} l WHERE ${live}`;
|
|
36577
36606
|
const key = column(table, KEY$1, style);
|
|
36578
36607
|
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(" ");
|
|
@@ -36580,7 +36609,7 @@ function stateRows(table, state, match, style) {
|
|
|
36580
36609
|
`(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)`,
|
|
36581
36610
|
"UNION ALL",
|
|
36582
36611
|
`SELECT to_jsonb(l) FROM ${name} l WHERE ${live}`,
|
|
36583
|
-
` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$
|
|
36612
|
+
` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$8(key)})`
|
|
36584
36613
|
].join("\n");
|
|
36585
36614
|
}
|
|
36586
36615
|
/** Звуження за ключем рядка: перевірка судить один рядок черги. */
|
|
@@ -36662,7 +36691,7 @@ function rootExists(catalog, physical) {
|
|
|
36662
36691
|
return `EXISTS (SELECT 1 FROM ${ref({
|
|
36663
36692
|
schema: fk.references.schema,
|
|
36664
36693
|
name: fk.references.table
|
|
36665
|
-
})} root WHERE root.${q$
|
|
36694
|
+
})} root WHERE root.${q$8(fk.references.columns[index])} = v_pending.scope)`;
|
|
36666
36695
|
}
|
|
36667
36696
|
function assignmentBeforeSet(catalog, physical, style) {
|
|
36668
36697
|
const table = tableOf$2(physical, catalog.assignments.table);
|
|
@@ -36734,15 +36763,15 @@ function escalationSql(after, before, storageKind) {
|
|
|
36734
36763
|
function deltaDomainSql(catalog, physical, style) {
|
|
36735
36764
|
const roles = tableOf$2(physical, catalog.roles.table);
|
|
36736
36765
|
const delta = tableOf$2(physical, catalog.roles.delta);
|
|
36737
|
-
const r = (def) => `r.${q$
|
|
36738
|
-
const l = (def) => `l.${q$
|
|
36766
|
+
const r = (def) => `r.${q$8(column(roles, def, style))}`;
|
|
36767
|
+
const l = (def) => `l.${q$8(column(delta, def, style))}`;
|
|
36739
36768
|
const roleScope = scopeColumn(roles);
|
|
36740
36769
|
const deltaScope = scopeColumn(delta);
|
|
36741
36770
|
const journal = (table) => `${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.relation = ${sqlLiteral(journalRelation(table))}`;
|
|
36742
36771
|
const storage = catalog.level.level === "scope" ? `m.storage = 'scope' AND m.storage_id = ${sqlLiteral(catalog.level.scopeKindId)}::uuid` : "m.storage = 'global'";
|
|
36743
36772
|
return [
|
|
36744
|
-
`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$
|
|
36745
|
-
` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$
|
|
36773
|
+
`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`}`,
|
|
36774
|
+
` WHERE ${r(KEY$1)} = v_pending.key${roleScope === void 0 ? "" : ` AND r.${q$8(roleScope)} = v_pending.scope`}`,
|
|
36746
36775
|
` AND (EXISTS (SELECT 1 FROM ${journal(delta)} AND j.row_id = ${l(KEY$1)} AND j.after IS NOT NULL)`,
|
|
36747
36776
|
` 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)}))`,
|
|
36748
36777
|
` 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`,
|
|
@@ -36754,17 +36783,17 @@ function catalogCheck(catalog, contracts, physical, style) {
|
|
|
36754
36783
|
const roles = tableOf$2(physical, catalog.roles.table);
|
|
36755
36784
|
const assignments = tableOf$2(physical, catalog.assignments.table);
|
|
36756
36785
|
const scope = catalog.level.level === "scope" ? `${sqlLiteral(catalog.level.scopeKindId)}::uuid` : `${sqlLiteral(ZERO_UUID)}::uuid`;
|
|
36757
|
-
const roleId = `r.${q$
|
|
36786
|
+
const roleId = `r.${q$8(column(roles, KEY$1, style))}`;
|
|
36758
36787
|
const assignmentScope = scopeColumn(assignments);
|
|
36759
36788
|
const roleScope = scopeColumn(roles);
|
|
36760
|
-
const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$
|
|
36761
|
-
const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$
|
|
36789
|
+
const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$8(roleScope)} = v_pending.scope`;
|
|
36790
|
+
const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$8(assignmentScope)} = v_pending.scope`;
|
|
36762
36791
|
const root = rootExists(catalog, physical);
|
|
36763
36792
|
return [
|
|
36764
36793
|
`IF v_pending.scope_kind_id = ${scope} THEN`,
|
|
36765
36794
|
" IF v_pending.kind = 'role' THEN",
|
|
36766
|
-
` IF EXISTS (SELECT 1 FROM ${ref(catalog.roles.table)} r WHERE ${roleId} = v_pending.key AND ${sameRole} AND r.${q$
|
|
36767
|
-
` AND EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$
|
|
36795
|
+
` 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))})`,
|
|
36796
|
+
` 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))})`,
|
|
36768
36797
|
` THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.roleInUse)} END IF;`,
|
|
36769
36798
|
` ${deltaDomainSql(catalog, physical, style)}`,
|
|
36770
36799
|
` ${escalationSql(roleGrantSet(catalog, physical, "after", style), roleGrantSet(catalog, physical, "before", style), catalogStorageKind(catalog))}`,
|
|
@@ -36886,7 +36915,7 @@ function eventRows(operation, alias, source) {
|
|
|
36886
36915
|
}
|
|
36887
36916
|
function bumpRows(operation, scopeKindId, scope) {
|
|
36888
36917
|
const rows = [...eventRows(operation, "r", "old"), ...eventRows(operation, "r", "new")].join(" UNION ALL ");
|
|
36889
|
-
const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$
|
|
36918
|
+
const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(scope)}`;
|
|
36890
36919
|
return `PERFORM ${ref(RIGHTS_FUNCTIONS.bump)}(${sqlLiteral(scopeKindId)}::uuid, s.scope) FROM (SELECT DISTINCT ${value} AS scope FROM (${rows}) r) s;`;
|
|
36891
36920
|
}
|
|
36892
36921
|
/**
|
|
@@ -36900,13 +36929,13 @@ function bumpRows(operation, scopeKindId, scope) {
|
|
|
36900
36929
|
* ключем рядка: зміну самого ключа тримає row-level тригер `_id`.
|
|
36901
36930
|
*/
|
|
36902
36931
|
function memberEventBody(member, contracts, physical, operation, provider, style) {
|
|
36903
|
-
const key = q$
|
|
36904
|
-
const scope = q$
|
|
36905
|
-
const user = q$
|
|
36932
|
+
const key = q$8(member.keyColumn);
|
|
36933
|
+
const scope = q$8(member.scopeColumn);
|
|
36934
|
+
const user = q$8(member.userColumn);
|
|
36906
36935
|
const assignments = contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "scope" && catalog.level.scopeKindId === member.scopeKindId).map((catalog) => {
|
|
36907
36936
|
const table = catalog.assignments.table;
|
|
36908
36937
|
const actual = tableOf$2(physical, table);
|
|
36909
|
-
return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$
|
|
36938
|
+
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})`;
|
|
36910
36939
|
});
|
|
36911
36940
|
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;` : "";
|
|
36912
36941
|
const changed = operation === "UPDATE" ? [
|
|
@@ -36935,13 +36964,13 @@ function memberEventBody(member, contracts, physical, operation, provider, style
|
|
|
36935
36964
|
* видалення облікового запису) і режим обслуговування.
|
|
36936
36965
|
*/
|
|
36937
36966
|
function usersEventBody(users, contracts, physical, operation, attributeCase, provider) {
|
|
36938
|
-
const key = q$
|
|
36939
|
-
const invalid = q$
|
|
36967
|
+
const key = q$8(users.keyColumn);
|
|
36968
|
+
const invalid = q$8(users.invalidColumn);
|
|
36940
36969
|
const table = tableOf$2(physical, users.table);
|
|
36941
|
-
const kind = q$
|
|
36942
|
-
const repeated = operation === "INSERT" ? [...contracts.membership.map((member) => `EXISTS (SELECT 1 FROM ${ref(member.table)} m WHERE m.${q$
|
|
36970
|
+
const kind = q$8(column(table, USER_PLATFORM_COLUMNS.userKind, attributeCase));
|
|
36971
|
+
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) => {
|
|
36943
36972
|
const assignment = tableOf$2(physical, catalog.assignments.table);
|
|
36944
|
-
return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$
|
|
36973
|
+
return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignment, R.subject, attributeCase))} = n.${key})`;
|
|
36945
36974
|
})] : [];
|
|
36946
36975
|
const update = operation === "UPDATE" ? [
|
|
36947
36976
|
`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}`,
|
|
@@ -36992,7 +37021,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
36992
37021
|
const name = tableName(table);
|
|
36993
37022
|
const fn = functionName(name, labels.truncate);
|
|
36994
37023
|
addFunction(fn, truncateBody(table), table.origin.objectId);
|
|
36995
|
-
add(`CREATE TRIGGER ${q$
|
|
37024
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, labels.truncate))} BEFORE TRUNCATE ON ${ref(name)} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
|
|
36996
37025
|
};
|
|
36997
37026
|
for (const { table, facts } of sources.sources) {
|
|
36998
37027
|
const name = tableName(table);
|
|
@@ -37009,7 +37038,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37009
37038
|
...t
|
|
37010
37039
|
}))
|
|
37011
37040
|
]);
|
|
37012
|
-
add(`CREATE TRIGGER ${q$
|
|
37041
|
+
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);
|
|
37013
37042
|
}
|
|
37014
37043
|
for (const config of catalogTables(contracts, physical, attributeCase)) {
|
|
37015
37044
|
const table = tableName(config.table);
|
|
@@ -37034,7 +37063,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37034
37063
|
"DELETE"
|
|
37035
37064
|
]) {
|
|
37036
37065
|
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";
|
|
37037
|
-
add(`CREATE TRIGGER ${q$
|
|
37066
|
+
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);
|
|
37038
37067
|
}
|
|
37039
37068
|
addTruncate(config.table);
|
|
37040
37069
|
}
|
|
@@ -37051,7 +37080,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37051
37080
|
const fn = functionName(name, label);
|
|
37052
37081
|
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";
|
|
37053
37082
|
addFunction(fn, memberEventBody(member, contracts, physical, operation, provider, attributeCase), owner, [unitNode(COMMAND_FUNCTIONS.current), BUMP_NODE]);
|
|
37054
|
-
add(`CREATE TRIGGER ${q$
|
|
37083
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
|
|
37055
37084
|
}
|
|
37056
37085
|
addTruncate(table);
|
|
37057
37086
|
}
|
|
@@ -37065,7 +37094,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37065
37094
|
const fn = functionName(name, label);
|
|
37066
37095
|
const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
|
|
37067
37096
|
addFunction(fn, usersEventBody(users, contracts, physical, operation, attributeCase, provider), owner, [unitNode(COMMAND_FUNCTIONS.current), ...operation === "UPDATE" ? [BUMP_NODE] : []]);
|
|
37068
|
-
add(`CREATE TRIGGER ${q$
|
|
37097
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
|
|
37069
37098
|
}
|
|
37070
37099
|
addTruncate(table);
|
|
37071
37100
|
}
|
|
@@ -37099,7 +37128,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37099
37128
|
]) {
|
|
37100
37129
|
const label = `simetra_rights_relation_${operation.toLowerCase()}`;
|
|
37101
37130
|
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";
|
|
37102
|
-
add(`CREATE TRIGGER ${q$
|
|
37131
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, table.origin.objectId);
|
|
37103
37132
|
}
|
|
37104
37133
|
addTruncate(table);
|
|
37105
37134
|
}
|
|
@@ -37133,17 +37162,17 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37133
37162
|
...INVITATIONS_TABLE
|
|
37134
37163
|
}]
|
|
37135
37164
|
]);
|
|
37136
|
-
add(`CREATE CONSTRAINT TRIGGER ${q$
|
|
37165
|
+
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)}();`);
|
|
37137
37166
|
const markerCheck = platform("rights_tx_root_marker_check");
|
|
37138
37167
|
addFunction(markerCheck, rootMarkerBody(), void 0, [{
|
|
37139
37168
|
type: "table",
|
|
37140
37169
|
...ROOT_MARKER_TABLE
|
|
37141
37170
|
}]);
|
|
37142
|
-
add(`CREATE CONSTRAINT TRIGGER ${q$
|
|
37171
|
+
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)}();`);
|
|
37143
37172
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
37144
37173
|
}
|
|
37145
37174
|
// src/compiler/rights/invitation-put-units.ts
|
|
37146
|
-
const q$
|
|
37175
|
+
const q$7 = quoteIdent;
|
|
37147
37176
|
/** Функція запису запрошення (спека запрошень §4, крок 3) — одна на проєкт. */
|
|
37148
37177
|
const INVITATION_PUT_FUNCTION = {
|
|
37149
37178
|
schema: PLATFORM_SCHEMA,
|
|
@@ -37154,6 +37183,11 @@ const PENDING_TABLE = {
|
|
|
37154
37183
|
schema: PLATFORM_SCHEMA,
|
|
37155
37184
|
name: "rights_tx_pending"
|
|
37156
37185
|
};
|
|
37186
|
+
/**
|
|
37187
|
+
* Сесія з claim `act` — агент від імені користувача (спека запрошень §4,
|
|
37188
|
+
* §5): одна умова для видачі й прийняття.
|
|
37189
|
+
*/
|
|
37190
|
+
const ACT_CLAIM_SQL = `coalesce(nullif(current_setting(${sqlLiteral(SESSION_CLAIMS_SETTING)}, true), '')::jsonb ? 'act', false)`;
|
|
37157
37191
|
/** Вид ключа черги перевірок прав видачі (спека запрошень §4, крок 4). */
|
|
37158
37192
|
const INVITATION_PENDING_KIND = "invitation";
|
|
37159
37193
|
function tableOf$1(physical, name) {
|
|
@@ -37167,6 +37201,15 @@ function scopeOf(table) {
|
|
|
37167
37201
|
return found.name;
|
|
37168
37202
|
}
|
|
37169
37203
|
/**
|
|
37204
|
+
* Живі призначення учасника `member` у скоупі `scope` (псевдонім `a`): одна
|
|
37205
|
+
* умова для набору видачі й замків кроку 5 прийняття — замок мусить тримати
|
|
37206
|
+
* рівно ті рядки, які читає звірка.
|
|
37207
|
+
*/
|
|
37208
|
+
function liveAssignments(assignments, style, member, scope) {
|
|
37209
|
+
const a = (def) => `a.${q$7(standardColumn(assignments, def, style).name)}`;
|
|
37210
|
+
return `${a(RIGHTS_COLUMNS.subject)} = ${member} AND a.${q$7(scopeOf(assignments))} = ${scope} AND NOT ${a(deletionMarkColumn())}`;
|
|
37211
|
+
}
|
|
37212
|
+
/**
|
|
37170
37213
|
* Набір видачі (спека запрошень §4, крок 3): відсортований за id перелік
|
|
37171
37214
|
* живих призначень учасника `member` у скоупі `scope` — `{ id, version,
|
|
37172
37215
|
* customRole?: { id, version, deltas } }`. `deltas` — `sha256` канонічної
|
|
@@ -37179,27 +37222,44 @@ function issueSetSql(catalog, physical, style, member, scope) {
|
|
|
37179
37222
|
const assignments = tableOf$1(physical, catalog.assignments.table);
|
|
37180
37223
|
const roles = tableOf$1(physical, catalog.roles.table);
|
|
37181
37224
|
const delta = tableOf$1(physical, catalog.roles.delta);
|
|
37182
|
-
const col = (table, def) => q$
|
|
37225
|
+
const col = (table, def) => q$7(standardColumn(table, def, style).name);
|
|
37183
37226
|
const a = (def) => `a.${col(assignments, def)}`;
|
|
37184
37227
|
const c = (def) => `c.${col(roles, def)}`;
|
|
37185
37228
|
const d = (def) => `d.${col(delta, def)}`;
|
|
37186
37229
|
const R = RIGHTS_COLUMNS;
|
|
37187
37230
|
const KEY = keyColumn(false);
|
|
37188
37231
|
const VERSION = versionColumn();
|
|
37189
|
-
const assignmentScope = `a.${q$
|
|
37232
|
+
const assignmentScope = `a.${q$7(scopeOf(assignments))}`;
|
|
37190
37233
|
const deltas = [
|
|
37191
37234
|
`SELECT encode(sha256(convert_to(coalesce(jsonb_agg(to_jsonb(d) ORDER BY ${d(KEY)}), '[]'::jsonb)::text, 'UTF8')), 'hex')`,
|
|
37192
37235
|
`FROM ${qualified(catalog.roles.delta)} d`,
|
|
37193
|
-
`WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$
|
|
37236
|
+
`WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$7(scopeOf(delta))} = ${assignmentScope}`
|
|
37194
37237
|
].join(" ");
|
|
37195
37238
|
return [
|
|
37196
37239
|
`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)`,
|
|
37197
37240
|
`FROM ${qualified(catalog.assignments.table)} a`,
|
|
37198
|
-
`LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$
|
|
37199
|
-
`WHERE ${
|
|
37241
|
+
`LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$7(scopeOf(roles))} = ${assignmentScope}`,
|
|
37242
|
+
`WHERE ${liveAssignments(assignments, style, member, scope)}`
|
|
37200
37243
|
].join("\n");
|
|
37201
37244
|
}
|
|
37202
37245
|
/**
|
|
37246
|
+
* Замки кроку 5 прийняття (спека запрошень §5): живі призначення учасника
|
|
37247
|
+
* `member` у скоупі `scope` і рядки їхніх кастомних ролей `FOR SHARE` — та
|
|
37248
|
+
* сама множина, що в `issueSetSql`. Зміна призначення чи ролі командою (вона
|
|
37249
|
+
* бере рядок ролі `FOR NO KEY UPDATE`) чекає на COMMIT прийняття, тож набір,
|
|
37250
|
+
* звірений після замків, не зміниться до перевірки ⊆. Окремими операторами
|
|
37251
|
+
* до звірки: у `READ COMMITTED` новий оператор бачить рядок, на який чекав.
|
|
37252
|
+
*/
|
|
37253
|
+
function issueSetLocks(catalog, physical, style, member, scope) {
|
|
37254
|
+
const assignments = tableOf$1(physical, catalog.assignments.table);
|
|
37255
|
+
const roles = tableOf$1(physical, catalog.roles.table);
|
|
37256
|
+
const col = (table, def) => q$7(standardColumn(table, def, style).name);
|
|
37257
|
+
const a = (def) => `a.${col(assignments, def)}`;
|
|
37258
|
+
const R = RIGHTS_COLUMNS;
|
|
37259
|
+
const live = liveAssignments(assignments, style, member, scope);
|
|
37260
|
+
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;`];
|
|
37261
|
+
}
|
|
37262
|
+
/**
|
|
37203
37263
|
* `simetra.invitation_put(p_member, p_hash)` (спека запрошень §4, кроки 2–4):
|
|
37204
37264
|
* єдиний писар записів запрошень на шляху видачі. `SECURITY DEFINER`, бо
|
|
37205
37265
|
* таблиці запрошень закриті для ролей застосунку; гілка на кожен вид — за
|
|
@@ -37229,14 +37289,14 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37229
37289
|
const m = kind.membership;
|
|
37230
37290
|
const id = uuidLiteral(kind.kindId);
|
|
37231
37291
|
const pending = [
|
|
37232
|
-
`m.${q$
|
|
37233
|
-
`m.${q$
|
|
37234
|
-
...m.deletion === void 0 ? [] : [`NOT m.${q$
|
|
37292
|
+
`m.${q$7(m.key)} = p_member`,
|
|
37293
|
+
`m.${q$7(m.user)} IS NULL`,
|
|
37294
|
+
...m.deletion === void 0 ? [] : [`NOT m.${q$7(m.deletion)}`]
|
|
37235
37295
|
].join(" AND ");
|
|
37236
37296
|
return [
|
|
37237
37297
|
`IF v_object = ${sqlLiteral(kind.kindLabel)} THEN`,
|
|
37238
37298
|
...[
|
|
37239
|
-
`SELECT m.${q$
|
|
37299
|
+
`SELECT m.${q$7(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
|
|
37240
37300
|
...ifRefuse("NOT FOUND"),
|
|
37241
37301
|
...ifRefuse(`NOT ${scopeAdministerRights(kind.assignmentsLabel, kind.kindId, "v_scope")}`),
|
|
37242
37302
|
...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = p_member AND i.scope_kind_id <> ${id})`),
|
|
@@ -37267,7 +37327,7 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37267
37327
|
" v_expires timestamp with time zone;",
|
|
37268
37328
|
"BEGIN",
|
|
37269
37329
|
...[
|
|
37270
|
-
...ifRefuse(
|
|
37330
|
+
...ifRefuse(ACT_CLAIM_SQL, refusal(E.noRight)),
|
|
37271
37331
|
`SELECT c.action, c.object, c.root INTO v_action, v_object, v_root FROM ${qualified(COMMAND_FUNCTIONS.current)}() c;`,
|
|
37272
37332
|
`v_actor := ${CURRENT_USER$1};`,
|
|
37273
37333
|
...ifRefuse(`v_actor IS NULL OR v_action IS DISTINCT FROM 'update' OR v_root IS DISTINCT FROM p_member`),
|
|
@@ -37280,6 +37340,160 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37280
37340
|
const tag = dollarTag$1(body);
|
|
37281
37341
|
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};`;
|
|
37282
37342
|
}
|
|
37343
|
+
// src/compiler/rights/invitation-accept-units.ts
|
|
37344
|
+
const q$6 = quoteIdent;
|
|
37345
|
+
/** Функція прийняття запрошення (спека запрошень §5) — одна на проєкт. */
|
|
37346
|
+
const INVITATION_ACCEPT_FUNCTION = {
|
|
37347
|
+
schema: PLATFORM_SCHEMA,
|
|
37348
|
+
name: "invitation_accept"
|
|
37349
|
+
};
|
|
37350
|
+
/**
|
|
37351
|
+
* Простір ключів advisory-замка спроб прийняття (`SIMI`): поруч із простором
|
|
37352
|
+
* ієрархії (`SIMH`) і замка застосування схеми (`SIME`), не перетинаючись
|
|
37353
|
+
* із ними, — інакше спроба прийняття чекала б на чуже.
|
|
37354
|
+
*/
|
|
37355
|
+
const INVITATION_LOCK_SPACE = 1397312841;
|
|
37356
|
+
/**
|
|
37357
|
+
* Внутрішній SQLSTATE повторної звірки після кроку 8: лише ним точка
|
|
37358
|
+
* збереження відкочує заповнення учасника; будь-яка інша помилка (зокрема
|
|
37359
|
+
* `rights-context`) виходить далі. Клас `SI` Postgres не вживає.
|
|
37360
|
+
*/
|
|
37361
|
+
const CHANGED_STATE = "SIACH";
|
|
37362
|
+
/** Походження рядка входу знімка, дописаного прийняттям (крок 9). */
|
|
37363
|
+
const INVITATION_PROVENANCE = "invitation";
|
|
37364
|
+
/**
|
|
37365
|
+
* `simetra.invitation_accept(p_hash bytea) RETURNS jsonb` (спека запрошень §5,
|
|
37366
|
+
* кроки 1–10) — названий виняток із ⊆ за зразком функції гранту творцю
|
|
37367
|
+
* (`root-creator-units.ts`). `SECURITY DEFINER`: таблиці запрошень закриті
|
|
37368
|
+
* для ролей застосунку, а запрошений ще не має прав у скоупі. `row_security =
|
|
37369
|
+
* off`: власник RLS обходить, а якби ні — пошук і звірка мовчки не побачили б
|
|
37370
|
+
* рядків; так вони падають гучно (fail-closed). Гілка на кожен вид — за видом
|
|
37371
|
+
* запису, без динамічного SQL.
|
|
37372
|
+
*
|
|
37373
|
+
* Відмови кроків 1–6 — значення, а не виняток: T3 фіксує транзакцію, і рядок
|
|
37374
|
+
* `failed` лишається (ліміт спроб рахує саме їх); `rate-limited` рядка не
|
|
37375
|
+
* пише, тож запити понад ліміт журнал не ростять. Виняток — лише
|
|
37376
|
+
* `rights-context`: транзакція з чужим чи наявним знімком не може дописати
|
|
37377
|
+
* входи знімка, і її треба відкотити.
|
|
37378
|
+
*/
|
|
37379
|
+
function invitationAcceptFunction(kinds, contracts, physical, style) {
|
|
37380
|
+
const context = refusal(COMMAND_CORE_ERRORS.forbidden.rightsContext);
|
|
37381
|
+
const ifRefuse = (condition) => [
|
|
37382
|
+
`IF ${condition} THEN`,
|
|
37383
|
+
` ${context}`,
|
|
37384
|
+
"END IF;"
|
|
37385
|
+
];
|
|
37386
|
+
const T = SNAPSHOT_TABLES;
|
|
37387
|
+
const journal = (event, reason, where) => `INSERT INTO ${qualified(INVITATION_JOURNAL_TABLE)} (event, reason, scope_kind_id, scope, member, actor) VALUES (${sqlLiteral(event)}, ${reason === null ? "NULL" : sqlLiteral(reason)}, ${where === null ? "NULL, NULL, NULL" : `${where.kind}, ${where.scope}, ${where.member}`}, v_actor);`;
|
|
37388
|
+
const answer = (outcome, reason) => `RETURN jsonb_build_object('outcome', ${sqlLiteral(outcome)}, 'reason', ${sqlLiteral(reason)});`;
|
|
37389
|
+
const failed = (reason, where) => [journal("failed", reason, where), answer("failed", reason)];
|
|
37390
|
+
const record = {
|
|
37391
|
+
kind: "v_kind",
|
|
37392
|
+
scope: "v_scope",
|
|
37393
|
+
member: "v_member"
|
|
37394
|
+
};
|
|
37395
|
+
const header = (fact) => `NOT EXISTS (SELECT 1 FROM ${qualified(T.header)} h WHERE h.xid = txid_current() AND h.fact = ${sqlLiteral(fact)} AND h.actor = v_actor)`;
|
|
37396
|
+
const provenance = `t.xid = txid_current() AND t.provenance = ${sqlLiteral(INVITATION_PROVENANCE)}`;
|
|
37397
|
+
const branches = kinds.flatMap((kind) => {
|
|
37398
|
+
const m = kind.membership;
|
|
37399
|
+
const id = uuidLiteral(kind.kindId);
|
|
37400
|
+
const pending = [
|
|
37401
|
+
`m.${q$6(m.key)} = v_member`,
|
|
37402
|
+
`m.${q$6(m.scope)} = v_scope`,
|
|
37403
|
+
`m.${q$6(m.user)} IS NULL`,
|
|
37404
|
+
...m.deletion === void 0 ? [] : [`NOT m.${q$6(m.deletion)}`]
|
|
37405
|
+
].join(" AND ");
|
|
37406
|
+
const gone = `DELETE FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = v_member AND i.scope_kind_id = ${id};`;
|
|
37407
|
+
const changed = `(${issueSetSql(kind.catalog, physical, style, "v_member", "v_scope")}) IS DISTINCT FROM v_assignments`;
|
|
37408
|
+
const inputs = issueInputs(contracts, kind.catalog, physical, style, "ARRAY(SELECT (e.value ->> 'id')::uuid FROM jsonb_array_elements(v_assignments) e)");
|
|
37409
|
+
return [
|
|
37410
|
+
`IF v_kind = ${id} THEN`,
|
|
37411
|
+
...[
|
|
37412
|
+
`PERFORM 1 FROM ${qualified(m.table)} m WHERE ${pending} FOR UPDATE;`,
|
|
37413
|
+
"IF NOT FOUND THEN",
|
|
37414
|
+
` ${gone}`,
|
|
37415
|
+
...failed("member-gone", record).map((l) => ` ${l}`),
|
|
37416
|
+
"END IF;",
|
|
37417
|
+
`PERFORM 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.secret_hash = p_hash FOR UPDATE;`,
|
|
37418
|
+
"IF NOT FOUND THEN",
|
|
37419
|
+
...failed("unknown", null).map((l) => ` ${l}`),
|
|
37420
|
+
"END IF;",
|
|
37421
|
+
...issueSetLocks(kind.catalog, physical, style, "v_member", "v_scope"),
|
|
37422
|
+
`IF ${changed} THEN`,
|
|
37423
|
+
` ${gone}`,
|
|
37424
|
+
...failed("changed", record).map((l) => ` ${l}`),
|
|
37425
|
+
"END IF;",
|
|
37426
|
+
`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`,
|
|
37427
|
+
...failed("already-member", record).map((l) => ` ${l}`),
|
|
37428
|
+
"END IF;",
|
|
37429
|
+
`v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
|
|
37430
|
+
"BEGIN",
|
|
37431
|
+
...[
|
|
37432
|
+
`PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, jsonb_build_object('action', ${sqlLiteral(acceptInvitationAction.name)}, 'object', ${sqlLiteral(kind.kindLabel)}, 'root', v_member)::text, true);`,
|
|
37433
|
+
`UPDATE ${qualified(m.table)} m SET ${q$6(m.user)} = v_actor WHERE m.${q$6(m.key)} = v_member;`,
|
|
37434
|
+
...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
|
|
37435
|
+
`IF ${changed} THEN`,
|
|
37436
|
+
` RAISE EXCEPTION USING ERRCODE = '${CHANGED_STATE}';`,
|
|
37437
|
+
"END IF;"
|
|
37438
|
+
].map((line) => ` ${line}`),
|
|
37439
|
+
`EXCEPTION WHEN SQLSTATE '${CHANGED_STATE}' THEN`,
|
|
37440
|
+
` ${gone}`,
|
|
37441
|
+
...failed("changed", record).map((l) => ` ${l}`),
|
|
37442
|
+
"END;",
|
|
37443
|
+
`INSERT INTO ${qualified(T.typed)} (xid, ${inputColumns("typed")}, provenance, assignment)`,
|
|
37444
|
+
`SELECT txid_current(), ${inputColumns("typed", "t")}, ${sqlLiteral(INVITATION_PROVENANCE)}, t.assignment FROM (${inputs.typed}) t;`,
|
|
37445
|
+
`INSERT INTO ${qualified(T.containers)} (xid, ${inputColumns("containers")})`,
|
|
37446
|
+
`SELECT txid_current(), ${inputColumns("containers", "k")} FROM (${inputs.containers}) k`,
|
|
37447
|
+
`WHERE EXISTS (SELECT 1 FROM ${qualified(T.typed)} t WHERE ${provenance} AND t.level = 'container' AND t.level_id = k.level_id AND t.container = k.container);`,
|
|
37448
|
+
`INSERT INTO ${qualified(T.deltas)} (xid, ${inputColumns("deltas")})`,
|
|
37449
|
+
`SELECT txid_current(), ${inputColumns("deltas", "d")} FROM (${inputs.deltas}) d`,
|
|
37450
|
+
`WHERE EXISTS (SELECT 1 FROM ${qualified(T.typed)} t WHERE ${provenance} AND t.storage = d.storage AND t.storage_id IS NOT DISTINCT FROM d.storage_id AND t.custom_role = d.custom_role);`,
|
|
37451
|
+
`INSERT INTO ${qualified(T.holders)} (xid, level, level_id, scope)`,
|
|
37452
|
+
`SELECT txid_current(), h.level, h.level_id, h.scope FROM (${inputs.holders}) h;`,
|
|
37453
|
+
`INSERT INTO ${qualified(T.scopes)} (xid, scope_kind_id, scope, member, catalog) VALUES (txid_current(), ${id}, v_scope, v_member, true);`,
|
|
37454
|
+
gone,
|
|
37455
|
+
journal("accepted", null, record),
|
|
37456
|
+
`PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, v_context, true);`,
|
|
37457
|
+
"RETURN jsonb_build_object('outcome', 'accepted', 'scopeKind', v_kind, 'scope', v_scope, 'member', v_member);"
|
|
37458
|
+
].map((line) => ` ${line}`),
|
|
37459
|
+
"END IF;"
|
|
37460
|
+
];
|
|
37461
|
+
});
|
|
37462
|
+
const body = [
|
|
37463
|
+
"DECLARE",
|
|
37464
|
+
" v_actor uuid;",
|
|
37465
|
+
" v_member uuid;",
|
|
37466
|
+
" v_kind uuid;",
|
|
37467
|
+
" v_scope uuid;",
|
|
37468
|
+
" v_assignments jsonb;",
|
|
37469
|
+
" v_expires timestamp with time zone;",
|
|
37470
|
+
" v_context text;",
|
|
37471
|
+
"BEGIN",
|
|
37472
|
+
...[
|
|
37473
|
+
`v_actor := ${CURRENT_USER$1};`,
|
|
37474
|
+
`IF v_actor IS NULL OR ${ACT_CLAIM_SQL} THEN`,
|
|
37475
|
+
...failed("actor", null).map((l) => ` ${l}`),
|
|
37476
|
+
"END IF;",
|
|
37477
|
+
...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(T.header)} h WHERE h.xid = txid_current()) OR EXISTS (SELECT 1 FROM ${qualified(T.start)} s WHERE s.xid = txid_current())`),
|
|
37478
|
+
`PERFORM pg_advisory_xact_lock(${INVITATION_LOCK_SPACE}, hashtext(v_actor::text));`,
|
|
37479
|
+
`IF (SELECT count(*) FROM ${qualified(INVITATION_JOURNAL_TABLE)} j WHERE j.actor = v_actor AND j.event = 'failed' AND j.at > now() - interval '1 hour') >= 10 THEN`,
|
|
37480
|
+
` ${answer("rate-limited", "rate-limited")}`,
|
|
37481
|
+
"END IF;",
|
|
37482
|
+
`SELECT i.member, i.scope_kind_id, i.scope, i.assignments, i.expires_at INTO v_member, v_kind, v_scope, v_assignments, v_expires FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.secret_hash = p_hash;`,
|
|
37483
|
+
"IF NOT FOUND THEN",
|
|
37484
|
+
...failed("unknown", null).map((l) => ` ${l}`),
|
|
37485
|
+
"END IF;",
|
|
37486
|
+
"IF v_expires <= now() THEN",
|
|
37487
|
+
...failed("expired", record).map((l) => ` ${l}`),
|
|
37488
|
+
"END IF;",
|
|
37489
|
+
...branches,
|
|
37490
|
+
context
|
|
37491
|
+
].map((line) => ` ${line}`),
|
|
37492
|
+
"END"
|
|
37493
|
+
].join("\n");
|
|
37494
|
+
const tag = dollarTag$1(body);
|
|
37495
|
+
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};`;
|
|
37496
|
+
}
|
|
37283
37497
|
// src/compiler/rights/root-creator-units.ts
|
|
37284
37498
|
const q$5 = quoteIdent;
|
|
37285
37499
|
/**
|
|
@@ -37573,10 +37787,14 @@ function buildCatalogCommandUnits(input) {
|
|
|
37573
37787
|
...requires === void 0 ? {} : { requires }
|
|
37574
37788
|
});
|
|
37575
37789
|
const sql = invitationPutFunction(invitations.map((i) => i.facts), contracts, input.physical, input.attributeCase);
|
|
37790
|
+
const accept = invitationAcceptFunction(invitations.map((i) => i.facts), contracts, input.physical, input.attributeCase);
|
|
37576
37791
|
units.push(put(sql, bodyRequires(sql, {
|
|
37577
37792
|
...input,
|
|
37578
37793
|
units: input.units
|
|
37579
|
-
})), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant))
|
|
37794
|
+
})), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
|
|
37795
|
+
...input,
|
|
37796
|
+
units: input.units
|
|
37797
|
+
})), ...executeGrants(`${relation$1(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
|
|
37580
37798
|
}
|
|
37581
37799
|
const known = [...input.units, ...units];
|
|
37582
37800
|
const signalModel = {
|
|
@@ -42389,7 +42607,7 @@ async function runStages(stage1, options = {}) {
|
|
|
42389
42607
|
carriers: (unit) => `the carrier copies of ${name(unit.ownerObjectId)}`,
|
|
42390
42608
|
command: (unit) => `the command context function ${unit.name}`,
|
|
42391
42609
|
effects: (unit) => `the action effects check of ${name(unit.ownerObjectId)}`,
|
|
42392
|
-
catalogCommand: (unit) => unit.ownerObjectId === void 0 ?
|
|
42610
|
+
catalogCommand: (unit) => unit.ownerObjectId === void 0 ? `the invitation function ${unit.name}` : `the command core of ${name(unit.ownerObjectId)}`,
|
|
42393
42611
|
schemaUsage: (unit) => `the USAGE grant on schema ${unit.name}`,
|
|
42394
42612
|
signalOutbox: () => "the signal outbox of the platform",
|
|
42395
42613
|
storage: (unit) => unit.ownerObjectId === void 0 ? `the file storage object ${unit.name}` : `the file storage of ${name(unit.ownerObjectId)}`,
|
package/dist/model/index.d.ts
CHANGED
|
@@ -3623,8 +3623,8 @@ export declare const projectSchema: z.ZodObject<{
|
|
|
3623
3623
|
en: z.ZodOptional<z.ZodString>;
|
|
3624
3624
|
}, z.core.$strict>>;
|
|
3625
3625
|
defaultLocale: z.ZodDefault<z.ZodEnum<{
|
|
3626
|
-
uk: "uk";
|
|
3627
3626
|
en: "en";
|
|
3627
|
+
uk: "uk";
|
|
3628
3628
|
}>>;
|
|
3629
3629
|
primaryDataLanguage: z.ZodOptional<z.ZodString>;
|
|
3630
3630
|
defaultSchema: z.ZodDefault<z.ZodString>;
|
|
@@ -3969,11 +3969,11 @@ export declare const pgEnumSchema: z.ZodObject<{
|
|
|
3969
3969
|
en: z.ZodOptional<z.ZodString>;
|
|
3970
3970
|
}, z.core.$strict>>;
|
|
3971
3971
|
id: z.ZodOptional<z.ZodUUID>;
|
|
3972
|
+
name: z.ZodString;
|
|
3972
3973
|
description: z.ZodOptional<z.ZodObject<{
|
|
3973
3974
|
uk: z.ZodOptional<z.ZodString>;
|
|
3974
3975
|
en: z.ZodOptional<z.ZodString>;
|
|
3975
3976
|
}, z.core.$strict>>;
|
|
3976
|
-
name: z.ZodString;
|
|
3977
3977
|
schema: z.ZodOptional<z.ZodString>;
|
|
3978
3978
|
$schema: z.ZodOptional<z.ZodString>;
|
|
3979
3979
|
physicalName: z.ZodOptional<z.ZodString>;
|
|
@@ -4029,11 +4029,11 @@ export declare const eventSubscriptionSchema: z.ZodObject<{
|
|
|
4029
4029
|
en: z.ZodOptional<z.ZodString>;
|
|
4030
4030
|
}, z.core.$strict>>;
|
|
4031
4031
|
id: z.ZodOptional<z.ZodUUID>;
|
|
4032
|
+
name: z.ZodString;
|
|
4032
4033
|
description: z.ZodOptional<z.ZodObject<{
|
|
4033
4034
|
uk: z.ZodOptional<z.ZodString>;
|
|
4034
4035
|
en: z.ZodOptional<z.ZodString>;
|
|
4035
4036
|
}, z.core.$strict>>;
|
|
4036
|
-
name: z.ZodString;
|
|
4037
4037
|
$schema: z.ZodOptional<z.ZodString>;
|
|
4038
4038
|
physicalName: z.ZodOptional<z.ZodString>;
|
|
4039
4039
|
}, z.core.$strict>;
|
package/dist/schema/index.d.ts
CHANGED
|
@@ -1021,7 +1021,7 @@ export declare function checkOwnerAttributes(tx: ApplyTransaction, provider: Dat
|
|
|
1021
1021
|
* тримає тест, а не читання маніфесту під час виконання: ярус не звертається
|
|
1022
1022
|
* до файлової системи.
|
|
1023
1023
|
*/
|
|
1024
|
-
export declare const PLATFORM_VERSION = "0.3.0-next.
|
|
1024
|
+
export declare const PLATFORM_VERSION = "0.3.0-next.6";
|
|
1025
1025
|
/**
|
|
1026
1026
|
* Структурний ключ таблиці для множин і мап: ім'я з крапкою не злипається зі
|
|
1027
1027
|
* схемою, як злиплося б у `schema.name`. Складені ключі підоб'єктів — так
|
package/dist/schema/index.js
CHANGED
|
@@ -3893,7 +3893,7 @@ async function readSessionSearchPath(tx) {
|
|
|
3893
3893
|
* тримає тест, а не читання маніфесту під час виконання: ярус не звертається
|
|
3894
3894
|
* до файлової системи.
|
|
3895
3895
|
*/
|
|
3896
|
-
const PLATFORM_VERSION = "0.3.0-next.
|
|
3896
|
+
const PLATFORM_VERSION = "0.3.0-next.6";
|
|
3897
3897
|
// src/schema/apply/state.ts
|
|
3898
3898
|
/**
|
|
3899
3899
|
* Форма стану застосування (платформна спека §6.1). Читач приймає лише її:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "simetra",
|
|
3
|
-
"version": "0.3.0-next.
|
|
3
|
+
"version": "0.3.0-next.6",
|
|
4
4
|
"description": "Metadata-driven platform for business applications on Postgres: metamodel, compiler and schema engine",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"metadata",
|
|
@@ -135,7 +135,7 @@
|
|
|
135
135
|
"publishConfig": {
|
|
136
136
|
"access": "public"
|
|
137
137
|
},
|
|
138
|
-
"gitHead": "
|
|
138
|
+
"gitHead": "f4b281b5a9cce3b0a52185a0dd435f0717e273c8",
|
|
139
139
|
"scripts": {
|
|
140
140
|
"build": "tsc --noEmit",
|
|
141
141
|
"build:package": "tsdown",
|