simetra 0.3.0-next.5 → 0.3.0-next.7
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.d.ts +7 -4
- package/dist/compiler/index.js +686 -311
- package/dist/data/index.js +257 -66
- package/dist/model/index.d.ts +16 -10
- package/dist/model/index.js +9 -3
- package/dist/schema/index.d.ts +1 -1
- package/dist/schema/index.js +1 -1
- package/package.json +2 -2
- package/schemas/catalogs.schema.json +3 -26
- package/schemas/documents.schema.json +3 -26
package/dist/compiler/index.js
CHANGED
|
@@ -2416,11 +2416,11 @@ const MESSAGES = {
|
|
|
2416
2416
|
}
|
|
2417
2417
|
},
|
|
2418
2418
|
"rights.container-target": {
|
|
2419
|
-
en: (p) => p.role !== void 0 ? `Role "${p.role}" is assigned on "${p.name}", which is not a rights container` : p.source === void 0 ? `Container binding "${p.attribute}" references "${p.name}", which is
|
|
2420
|
-
uk: (p) => p.role !== void 0 ? `Роль "${p.role}" має рівень "${p.name}", який не є контейнером прав` : p.source === void 0 ? `Прив'язка до контейнера "${p.attribute}" посилається на "${p.name}", який не є контейнером
|
|
2419
|
+
en: (p) => p.role !== void 0 ? `Role "${p.role}" is assigned on "${p.name}", which is not a rights container` : p.source === void 0 ? `Container binding "${p.attribute}" references "${p.name}", which is neither a rights container nor bound to one` : `Assignment source "${p.source}" is assigned on "${p.name}", which is not a rights container`,
|
|
2420
|
+
uk: (p) => p.role !== void 0 ? `Роль "${p.role}" має рівень "${p.name}", який не є контейнером прав` : p.source === void 0 ? `Прив'язка до контейнера "${p.attribute}" посилається на "${p.name}", який не є контейнером прав і не прив'язаний до нього` : `Джерело призначень "${p.source}" має рівень "${p.name}", який не є контейнером прав`,
|
|
2421
2421
|
hint: {
|
|
2422
|
-
en: "Set rightsContainer: true on the target catalog or name another attribute.",
|
|
2423
|
-
uk: "Задайте rightsContainer: true на
|
|
2422
|
+
en: (p) => p.attribute !== void 0 ? "Set rightsContainer: true on the target catalog, give the target its own containerBinding, or name another attribute." : "Set rightsContainer: true on the target catalog or name another catalog.",
|
|
2423
|
+
uk: (p) => p.attribute !== void 0 ? "Задайте rightsContainer: true на довіднику-цілі, дайте цілі власний containerBinding або назвіть інший реквізит." : "Задайте rightsContainer: true на довіднику-цілі або назвіть інший довідник."
|
|
2424
2424
|
}
|
|
2425
2425
|
},
|
|
2426
2426
|
"rights.container-self": {
|
|
@@ -2431,6 +2431,14 @@ const MESSAGES = {
|
|
|
2431
2431
|
uk: "Контейнер — вершина власного рівня: не прив'язуйте його або прив'яжіть до іншого контейнера."
|
|
2432
2432
|
}
|
|
2433
2433
|
},
|
|
2434
|
+
"rights.container-binding-cycle": {
|
|
2435
|
+
en: (p) => `The binding chain of "${p.name}" through container binding "${p.attribute}" returns to "${p.name}" itself`,
|
|
2436
|
+
uk: (p) => `Ланцюжок прив'язок об'єкта "${p.name}" через прив'язку до контейнера "${p.attribute}" повертається до самого "${p.name}"`,
|
|
2437
|
+
hint: {
|
|
2438
|
+
en: "Break the cycle: remove or redirect one binding of the chain, including a binding of a rights container, so that no object is bound back into it. A hierarchy parent is not a binding.",
|
|
2439
|
+
uk: "Розірвіть цикл: приберіть чи змініть одну прив'язку ланцюжка, зокрема прив'язку контейнера прав, щоб жоден об'єкт не був прив'язаний назад у нього. Батько ієрархії — не прив'язка."
|
|
2440
|
+
}
|
|
2441
|
+
},
|
|
2434
2442
|
"rights.dimension-unknown": {
|
|
2435
2443
|
en: (p) => `Access dimension "${p.dimension}" is not declared in the project`,
|
|
2436
2444
|
uk: (p) => `Вимір доступу "${p.dimension}" не оголошено в проєкті`,
|
|
@@ -5048,6 +5056,7 @@ const COMPILER_RULES = [
|
|
|
5048
5056
|
"rights.ownership-target",
|
|
5049
5057
|
"rights.container-target",
|
|
5050
5058
|
"rights.container-self",
|
|
5059
|
+
"rights.container-binding-cycle",
|
|
5051
5060
|
"rights.dimension-unknown",
|
|
5052
5061
|
"rights.dimension-target",
|
|
5053
5062
|
"rights.dimension-relation",
|
|
@@ -6729,7 +6738,7 @@ function headerReference(object, index, at, references) {
|
|
|
6729
6738
|
function ownershipOf(object) {
|
|
6730
6739
|
return object.data.ownership ?? [];
|
|
6731
6740
|
}
|
|
6732
|
-
/**
|
|
6741
|
+
/** Ім'я реквізиту `containerBinding` об'єкта виду з фактом `rightsBinding`. */
|
|
6733
6742
|
function bindingOf(object) {
|
|
6734
6743
|
return object.data.containerBinding;
|
|
6735
6744
|
}
|
|
@@ -10051,6 +10060,267 @@ function storageTables(objects) {
|
|
|
10051
10060
|
})
|
|
10052
10061
|
].sort((a, b) => compareStrings(a.name, b.name));
|
|
10053
10062
|
}
|
|
10063
|
+
// src/compiler/rights/carriers.ts
|
|
10064
|
+
/**
|
|
10065
|
+
* Чи носій прав «в межах скоупу» (спека прав §4.2): фізичний FK поля є складеним, тобто
|
|
10066
|
+
* несе скоуп-колонку першою парою, а в проєкті без видів скоупу межі немає й
|
|
10067
|
+
* підходить будь-який одиночний `Ref`.
|
|
10068
|
+
*
|
|
10069
|
+
* `foreignKey` — FK поля виду в знімку (`undefined`, коли поле FK не має), як
|
|
10070
|
+
* його знаходить `fieldForeignKey`. Лише для полів виду: поле виду дає
|
|
10071
|
+
* одноколонковий FK лише простим посиланням, тож більше однієї колонки
|
|
10072
|
+
* однозначно означає складений; FK прийнятої таблиці описує файл, і там цей
|
|
10073
|
+
* висновок не тримається. Для прийнятої таблиці (`declared`) правило
|
|
10074
|
+
* закрите за побудовою: її колонки не мають `origin.scopeKindId`, тож
|
|
10075
|
+
* `fieldForeignKey` знаходить лише одноколонковий FK (у проєкті з видами
|
|
10076
|
+
* скоупу — не в межах), а складений не знаходить зовсім (не `Ref`).
|
|
10077
|
+
*/
|
|
10078
|
+
function inScopeTarget(foreignKey, project) {
|
|
10079
|
+
if (project.scopeKinds.length === 0) return true;
|
|
10080
|
+
return foreignKey !== void 0 && foreignKey.columns.length > 1;
|
|
10081
|
+
}
|
|
10082
|
+
/** Об'єкт, на який вказує кінцеве поле носія: сам власник ключа чи ціль `Ref`. */
|
|
10083
|
+
function carrierTarget(terminal) {
|
|
10084
|
+
return terminal.field.key ? terminal.object : terminal.field.target;
|
|
10085
|
+
}
|
|
10086
|
+
/**
|
|
10087
|
+
* Резолв носія прав (спека прав §4.2, Рх21) у колонку таблиці об'єкта: рядок — власне
|
|
10088
|
+
* поле; шлях — перший крок мусить бути одиночним неполіморфним `Ref` у межах
|
|
10089
|
+
* скоупу, бо інакше з'єднання в політиці вийшло б за тенант, а другий —
|
|
10090
|
+
* реквізит його цілі. Кінцеве поле — `Ref` або ключ; що саме воно має
|
|
10091
|
+
* означати, вирішує правило поля (власність, прив'язка, вимір).
|
|
10092
|
+
*
|
|
10093
|
+
* `at.pointer` — вказівник носія у файлі, `at.field` — ім'я поля для
|
|
10094
|
+
* діагностики невідомого реквізиту, `at.role` — роль першого кроку в індексі
|
|
10095
|
+
* (типово `rights.carrier`; мапінг `access` має власну).
|
|
10096
|
+
*/
|
|
10097
|
+
function resolveCarrier(object, carrier, at, ctx) {
|
|
10098
|
+
const headRole = at.role ?? "rights.carrier";
|
|
10099
|
+
if (typeof carrier === "string") {
|
|
10100
|
+
const step = resolveStep(object, object, carrier, at, headRole, ctx);
|
|
10101
|
+
if (!step.ok) return step;
|
|
10102
|
+
return {
|
|
10103
|
+
ok: true,
|
|
10104
|
+
terminal: {
|
|
10105
|
+
object,
|
|
10106
|
+
field: step.field
|
|
10107
|
+
},
|
|
10108
|
+
contract: {
|
|
10109
|
+
column: step.field.column,
|
|
10110
|
+
value: step.field.column
|
|
10111
|
+
}
|
|
10112
|
+
};
|
|
10113
|
+
}
|
|
10114
|
+
const [first, second] = carrier;
|
|
10115
|
+
const head = resolveStep(object, object, first, {
|
|
10116
|
+
pointer: `${at.pointer}/0`,
|
|
10117
|
+
field: at.field
|
|
10118
|
+
}, headRole, ctx);
|
|
10119
|
+
if (!head.ok) return head;
|
|
10120
|
+
const firstPointer = `${at.pointer}/0`;
|
|
10121
|
+
if (head.field.target === void 0) return fail("rights.carrier-not-ref", object, firstPointer, first);
|
|
10122
|
+
if (KIND_REGISTRY[head.field.target.kind].declared) return fail("rights.carrier-path-adopted", object, firstPointer, first);
|
|
10123
|
+
if (!head.field.inScope) return {
|
|
10124
|
+
ok: false,
|
|
10125
|
+
diagnostic: crossTenant(object, firstPointer, first, ctx.references)
|
|
10126
|
+
};
|
|
10127
|
+
const target = head.field.target;
|
|
10128
|
+
const tail = resolveStep(object, target, second, {
|
|
10129
|
+
pointer: `${at.pointer}/1`,
|
|
10130
|
+
field: at.field
|
|
10131
|
+
}, "rights.carrierPath", ctx);
|
|
10132
|
+
if (!tail.ok) return tail;
|
|
10133
|
+
const table = must$9(mainTableOf(ctx.physical, must$9(target.id)));
|
|
10134
|
+
return {
|
|
10135
|
+
ok: true,
|
|
10136
|
+
terminal: {
|
|
10137
|
+
object: target,
|
|
10138
|
+
field: tail.field
|
|
10139
|
+
},
|
|
10140
|
+
contract: {
|
|
10141
|
+
column: head.field.column,
|
|
10142
|
+
value: carrierCopyName(head.field.column, tail.field.column),
|
|
10143
|
+
via: {
|
|
10144
|
+
objectId: must$9(target.id),
|
|
10145
|
+
table: {
|
|
10146
|
+
schema: table.schema,
|
|
10147
|
+
name: table.name
|
|
10148
|
+
},
|
|
10149
|
+
column: tail.field.column
|
|
10150
|
+
}
|
|
10151
|
+
}
|
|
10152
|
+
};
|
|
10153
|
+
}
|
|
10154
|
+
/**
|
|
10155
|
+
* Один крок: ім'я резолвить індекс посилань (роль кроку на його вказівнику),
|
|
10156
|
+
* а що це за поле — каже фізичний знімок: одна колонка з FK — одиночний
|
|
10157
|
+
* `Ref` (і реквізит, і стандартний, як `createdBy`), ключ — колонка
|
|
10158
|
+
* первинного ключа без FK. Поліморфна пара FK не має й двох колонок.
|
|
10159
|
+
*/
|
|
10160
|
+
function resolveStep(owner, object, name, at, role, ctx) {
|
|
10161
|
+
const reference = ctx.references.find((r) => r.from.file === owner.file && r.from.pointer === at.pointer && r.role === role);
|
|
10162
|
+
if (reference === void 0 || object.id === void 0) return {
|
|
10163
|
+
ok: false,
|
|
10164
|
+
diagnostic: diagnostic("rights.attribute-unknown", owner.file, at.pointer, {
|
|
10165
|
+
attribute: name,
|
|
10166
|
+
field: at.field,
|
|
10167
|
+
...object === owner ? {} : { target: object.name }
|
|
10168
|
+
})
|
|
10169
|
+
};
|
|
10170
|
+
const field = at.field === "publication" ? publicationField(object, reference.to.id, name, ctx) : elementField(object, reference.to.id, name, ctx);
|
|
10171
|
+
return field === void 0 ? fail("rights.carrier-not-ref", owner, at.pointer, name) : {
|
|
10172
|
+
ok: true,
|
|
10173
|
+
field
|
|
10174
|
+
};
|
|
10175
|
+
}
|
|
10176
|
+
/**
|
|
10177
|
+
* Що за поле — елемент `elementId` в основній таблиці об'єкта, за фізичним
|
|
10178
|
+
* знімком: одна колонка з FK — одиночний `Ref` (і реквізит, і стандартний, як
|
|
10179
|
+
* `createdBy`), ключ — колонка первинного ключа без FK. Поліморфна пара FK не
|
|
10180
|
+
* має й двох колонок, тож, як і не-посилання, дає `undefined`.
|
|
10181
|
+
*
|
|
10182
|
+
* `inScope` виводиться лише для полів виду (`inScopeTarget`): на прийнятій
|
|
10183
|
+
* таблиці складений FK з файлу не розпізнається, і поле лишається поза
|
|
10184
|
+
* межею скоупу чи не-`Ref` — відмова, а не хибний дозвіл.
|
|
10185
|
+
*/
|
|
10186
|
+
function elementField(object, elementId, name, ctx) {
|
|
10187
|
+
const table = must$9(mainTableOf(ctx.physical, must$9(object.id)));
|
|
10188
|
+
const columns = elementColumns(object, table, ctx.project.naming.attributeCase).get(elementId) ?? [];
|
|
10189
|
+
if (columns.length !== 1) return void 0;
|
|
10190
|
+
const column = columns[0];
|
|
10191
|
+
if (table.primaryKey?.columns.length === 1 && table.primaryKey.columns[0] === column) return {
|
|
10192
|
+
name,
|
|
10193
|
+
column,
|
|
10194
|
+
key: true,
|
|
10195
|
+
inScope: true
|
|
10196
|
+
};
|
|
10197
|
+
const foreignKey = fieldForeignKey(table, column);
|
|
10198
|
+
const target = foreignKey === void 0 ? void 0 : objectOfTable(foreignKey.references, ctx);
|
|
10199
|
+
if (target === void 0) return void 0;
|
|
10200
|
+
return {
|
|
10201
|
+
name,
|
|
10202
|
+
column,
|
|
10203
|
+
key: false,
|
|
10204
|
+
target,
|
|
10205
|
+
inScope: inScopeTarget(foreignKey, ctx.project)
|
|
10206
|
+
};
|
|
10207
|
+
}
|
|
10208
|
+
/**
|
|
10209
|
+
* Колонка V шапки як носій публікації: елемент мусить бути стандартною
|
|
10210
|
+
* колонкою умови публікації самого об'єкта. Ні ключем, ні `Ref` вона не є, а
|
|
10211
|
+
* межа скоупу її не стосується: значення — ознака рядка, не посилання.
|
|
10212
|
+
*/
|
|
10213
|
+
function publicationField(object, elementId, name, ctx) {
|
|
10214
|
+
const objectId = must$9(object.id);
|
|
10215
|
+
if (!publicationCarriers().some(({ column }) => standardElementId(objectId, column) === elementId)) return void 0;
|
|
10216
|
+
const columns = elementColumns(object, must$9(mainTableOf(ctx.physical, objectId)), ctx.project.naming.attributeCase).get(elementId) ?? [];
|
|
10217
|
+
if (columns.length !== 1) return void 0;
|
|
10218
|
+
return {
|
|
10219
|
+
name,
|
|
10220
|
+
column: columns[0],
|
|
10221
|
+
key: false,
|
|
10222
|
+
inScope: true
|
|
10223
|
+
};
|
|
10224
|
+
}
|
|
10225
|
+
/** Об'єкт, чия основна таблиця — ціль FK. */
|
|
10226
|
+
function objectOfTable(references, ctx) {
|
|
10227
|
+
const table = ctx.physical.tables.find((t) => t.schema === references.schema && t.name === references.table && isObjectTable(t) && t.origin.tabularSectionId === void 0 && t.origin.part === void 0);
|
|
10228
|
+
return table === void 0 ? void 0 : ctx.byId.get(table.origin.objectId);
|
|
10229
|
+
}
|
|
10230
|
+
/**
|
|
10231
|
+
* Обхід графа прив'язок (Р-К1-7). Цикл судиться в графі видів, крізь
|
|
10232
|
+
* контейнери теж: два контейнери, прив'язані один до одного, — коло, хоч
|
|
10233
|
+
* ланцюжок кожного й кінчається на першому контейнері. Сам ланцюжок
|
|
10234
|
+
* зупиняється на першому контейнері: роль зовнішнього контейнера не сягає
|
|
10235
|
+
* об'єктів, прив'язаних до внутрішнього (§3).
|
|
10236
|
+
*/
|
|
10237
|
+
function bindingChain(start, hopOf, isContainer) {
|
|
10238
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
10239
|
+
for (let hop = hopOf(start); hop !== void 0; hop = hopOf(hop.target)) {
|
|
10240
|
+
if (hop.target === start) return {
|
|
10241
|
+
ok: false,
|
|
10242
|
+
cycle: true
|
|
10243
|
+
};
|
|
10244
|
+
if (seen.has(hop.target)) break;
|
|
10245
|
+
seen.add(hop.target);
|
|
10246
|
+
}
|
|
10247
|
+
const hops = [];
|
|
10248
|
+
for (let current = start;;) {
|
|
10249
|
+
const hop = hopOf(current);
|
|
10250
|
+
if (hop === void 0) return {
|
|
10251
|
+
ok: false,
|
|
10252
|
+
cycle: false
|
|
10253
|
+
};
|
|
10254
|
+
hops.push(hop);
|
|
10255
|
+
const { target } = hop;
|
|
10256
|
+
if (isContainer(target)) return {
|
|
10257
|
+
ok: true,
|
|
10258
|
+
hops,
|
|
10259
|
+
container: target
|
|
10260
|
+
};
|
|
10261
|
+
if (hops.some((h) => h.object === target)) return {
|
|
10262
|
+
ok: false,
|
|
10263
|
+
cycle: false
|
|
10264
|
+
};
|
|
10265
|
+
current = target;
|
|
10266
|
+
}
|
|
10267
|
+
}
|
|
10268
|
+
/**
|
|
10269
|
+
* Колонка зі значенням прив'язки об'єкта кроку `index` (Р-К1-3): у прямо
|
|
10270
|
+
* прив'язаного — колонка реквізиту, вище — копія, названа колонкою реквізиту
|
|
10271
|
+
* й кінцевою колонкою прямої прив'язки, тож ім'я не залежить від глибини.
|
|
10272
|
+
*/
|
|
10273
|
+
function bindingValue(hops, index) {
|
|
10274
|
+
const direct = hops[hops.length - 1];
|
|
10275
|
+
return index === hops.length - 1 ? direct.column : carrierCopyName(hops[index].column, direct.column);
|
|
10276
|
+
}
|
|
10277
|
+
/**
|
|
10278
|
+
* Прив'язка об'єкта в контракті: контейнер — кінцевий, носій — колонка
|
|
10279
|
+
* реквізиту, а в ланцюжку — копія зі значенням прив'язки цілі (`via`); з
|
|
10280
|
+
* фізичного знімка — лише ім'я основної таблиці цілі. `undefined` — ланцюжок
|
|
10281
|
+
* не дійшов до контейнера; це звітує стадія 4.
|
|
10282
|
+
*/
|
|
10283
|
+
function bindingContract(binding, physical) {
|
|
10284
|
+
if (binding === void 0 || !binding.ok) return void 0;
|
|
10285
|
+
const { hops } = binding;
|
|
10286
|
+
const [first] = hops;
|
|
10287
|
+
const carrier = {
|
|
10288
|
+
column: first.column,
|
|
10289
|
+
value: bindingValue(hops, 0)
|
|
10290
|
+
};
|
|
10291
|
+
if (hops.length > 1) {
|
|
10292
|
+
const table = must$9(mainTableOf(physical, first.target));
|
|
10293
|
+
carrier.via = {
|
|
10294
|
+
objectId: first.target,
|
|
10295
|
+
table: {
|
|
10296
|
+
schema: table.schema,
|
|
10297
|
+
name: table.name
|
|
10298
|
+
},
|
|
10299
|
+
column: bindingValue(hops, 1)
|
|
10300
|
+
};
|
|
10301
|
+
}
|
|
10302
|
+
return {
|
|
10303
|
+
containerId: binding.container,
|
|
10304
|
+
carrier
|
|
10305
|
+
};
|
|
10306
|
+
}
|
|
10307
|
+
/**
|
|
10308
|
+
* Носій виходить за межі скоупу. Нескоуплений об'єкт тенанта не має, тож
|
|
10309
|
+
* текст тоді називає не «вихід за тенант», а те, що посилання не тримається
|
|
10310
|
+
* межі скоупу: виправлення інше — скоупити об'єкт.
|
|
10311
|
+
*/
|
|
10312
|
+
function crossTenant(object, pointer, attribute, references) {
|
|
10313
|
+
return diagnostic("rights.carrier-cross-tenant", object.file, pointer, {
|
|
10314
|
+
attribute,
|
|
10315
|
+
...scopeKindOf(object, references) === void 0 ? { host: "unscoped" } : {}
|
|
10316
|
+
});
|
|
10317
|
+
}
|
|
10318
|
+
function fail(code, object, pointer, attribute) {
|
|
10319
|
+
return {
|
|
10320
|
+
ok: false,
|
|
10321
|
+
diagnostic: diagnostic(code, object.file, pointer, { attribute })
|
|
10322
|
+
};
|
|
10323
|
+
}
|
|
10054
10324
|
// src/compiler/stages/model.ts
|
|
10055
10325
|
/**
|
|
10056
10326
|
* Мітки похідних таблиць регістра (`<регістр>_totals`,
|
|
@@ -10103,7 +10373,9 @@ function carrierRefKey(file, pointer, role) {
|
|
|
10103
10373
|
* й колонка цілі — копії двох шляхів через ту саму колонку не збігаються.
|
|
10104
10374
|
*/
|
|
10105
10375
|
function carrierCopyName(through, column) {
|
|
10106
|
-
|
|
10376
|
+
const plain = makeObjectName(through, void 0, column);
|
|
10377
|
+
if (new TextEncoder().encode(plain).length <= 63) return plain;
|
|
10378
|
+
return makeObjectName(through, column, sha256HexSync(`${through}\0${column}`).slice(0, 8));
|
|
10107
10379
|
}
|
|
10108
10380
|
/** Ключі з усіх колонок за зростанням — вид похідних індексів без порядку. */
|
|
10109
10381
|
function ascending(columns) {
|
|
@@ -10188,6 +10460,7 @@ var SnapshotBuilder = class {
|
|
|
10188
10460
|
carrierRefs;
|
|
10189
10461
|
/** Об'єкти з носіями прав, чиї таблиці отримують копії носіїв у `finish`. */
|
|
10190
10462
|
carrierHosts = [];
|
|
10463
|
+
bindings = /* @__PURE__ */ new Map();
|
|
10191
10464
|
/** Основні таблиці об'єктів, чиї поля пошуку отримують колонки в `finish`. */
|
|
10192
10465
|
searchHosts = [];
|
|
10193
10466
|
/**
|
|
@@ -10561,7 +10834,8 @@ var SnapshotBuilder = class {
|
|
|
10561
10834
|
sources: this.sources,
|
|
10562
10835
|
declaredNames: this.declaredNames,
|
|
10563
10836
|
elementChecks,
|
|
10564
|
-
checkColumns
|
|
10837
|
+
checkColumns,
|
|
10838
|
+
bindings: this.bindings
|
|
10565
10839
|
};
|
|
10566
10840
|
}
|
|
10567
10841
|
/**
|
|
@@ -10589,7 +10863,12 @@ var SnapshotBuilder = class {
|
|
|
10589
10863
|
addCarrierCopies(host) {
|
|
10590
10864
|
const { object, main } = host;
|
|
10591
10865
|
const values = [];
|
|
10592
|
-
for (const { carrier, pointer, role } of carrierDeclarations(object)) {
|
|
10866
|
+
for (const { carrier, pointer, field, role } of carrierDeclarations(object)) {
|
|
10867
|
+
if (field === "containerBinding") {
|
|
10868
|
+
const value = this.bindingCopy(object, main, host.scope);
|
|
10869
|
+
if (value !== void 0) values.push(value);
|
|
10870
|
+
continue;
|
|
10871
|
+
}
|
|
10593
10872
|
const headPointer = typeof carrier === "string" ? pointer : `${pointer}/0`;
|
|
10594
10873
|
const head = this.carrierColumn(object, main, headPointer, role);
|
|
10595
10874
|
if (head === void 0) continue;
|
|
@@ -10597,10 +10876,9 @@ var SnapshotBuilder = class {
|
|
|
10597
10876
|
if (!(main.primaryKey?.columns.length === 1 && main.primaryKey.columns[0] === head.name)) values.push(head);
|
|
10598
10877
|
continue;
|
|
10599
10878
|
}
|
|
10600
|
-
const
|
|
10601
|
-
|
|
10602
|
-
const
|
|
10603
|
-
if (targetObject === void 0 || isDeclaredTable(targetObject)) continue;
|
|
10879
|
+
const found = this.refTarget(main, head.name);
|
|
10880
|
+
if (found === void 0) continue;
|
|
10881
|
+
const { table: target, object: targetObject } = found;
|
|
10604
10882
|
const tail = this.carrierColumn(targetObject, target, `${pointer}/1`, "rights.carrierPath", object.file);
|
|
10605
10883
|
if (tail === void 0) continue;
|
|
10606
10884
|
const copy = {
|
|
@@ -10631,6 +10909,70 @@ var SnapshotBuilder = class {
|
|
|
10631
10909
|
}
|
|
10632
10910
|
}
|
|
10633
10911
|
/**
|
|
10912
|
+
* Носій прив'язки в основній таблиці (спека прав контейнера §2, Р-К1-7):
|
|
10913
|
+
* пряма прив'язка — сама колонка реквізиту (ключ — без копії), ланцюжок —
|
|
10914
|
+
* копія прив'язки цілі. Граф обходить кроки за індексом посилань стадії 2
|
|
10915
|
+
* й FK вже побудованих таблиць — єдине виведення ланцюжка (`bindings`); на
|
|
10916
|
+
* циклі, нижче за ним чи без контейнера носія немає — це звітує стадія 4.
|
|
10917
|
+
*/
|
|
10918
|
+
bindingCopy(object, main, scope) {
|
|
10919
|
+
const hopOf = (o) => {
|
|
10920
|
+
const table = o === object ? main : mainTableIn(this.tables, o.id);
|
|
10921
|
+
if (table === void 0) return void 0;
|
|
10922
|
+
const column = this.carrierColumn(o, table, "/containerBinding", "rights.carrier");
|
|
10923
|
+
if (column === void 0) return void 0;
|
|
10924
|
+
const target = table.primaryKey?.columns.length === 1 && table.primaryKey.columns[0] === column.name ? o : this.refTarget(table, column.name)?.object;
|
|
10925
|
+
return target === void 0 ? void 0 : {
|
|
10926
|
+
object: o,
|
|
10927
|
+
column: column.name,
|
|
10928
|
+
target
|
|
10929
|
+
};
|
|
10930
|
+
};
|
|
10931
|
+
const chain = bindingChain(object, hopOf, isRightsContainer);
|
|
10932
|
+
this.bindings.set(object.id, chain.ok ? {
|
|
10933
|
+
ok: true,
|
|
10934
|
+
hops: chain.hops.map((h) => ({
|
|
10935
|
+
object: h.object.id,
|
|
10936
|
+
column: h.column,
|
|
10937
|
+
target: h.target.id
|
|
10938
|
+
})),
|
|
10939
|
+
container: chain.container.id
|
|
10940
|
+
} : chain);
|
|
10941
|
+
if (!chain.ok) return void 0;
|
|
10942
|
+
const { hops } = chain;
|
|
10943
|
+
const direct = hops[hops.length - 1];
|
|
10944
|
+
const column = mainTableIn(this.tables, direct.object.id).columns.find((c) => c.name === direct.column);
|
|
10945
|
+
if (hops.length === 1) return column;
|
|
10946
|
+
const target = mainTableIn(this.tables, hops[0].target.id);
|
|
10947
|
+
const copy = {
|
|
10948
|
+
name: bindingValue(hops, 0),
|
|
10949
|
+
type: column.type
|
|
10950
|
+
};
|
|
10951
|
+
this.addCopy(main, scope, copy, {
|
|
10952
|
+
table: {
|
|
10953
|
+
schema: target.schema,
|
|
10954
|
+
name: target.name
|
|
10955
|
+
},
|
|
10956
|
+
column: bindingValue(hops, 1),
|
|
10957
|
+
through: hops[0].column
|
|
10958
|
+
});
|
|
10959
|
+
return copy;
|
|
10960
|
+
}
|
|
10961
|
+
/**
|
|
10962
|
+
* Ціль FK колонки на основну таблицю об'єкта виду. Прийнята таблиця цілі
|
|
10963
|
+
* не дає: тригер поширення лежав би на ній (спека прав Рх21).
|
|
10964
|
+
*/
|
|
10965
|
+
refTarget(table, column) {
|
|
10966
|
+
const fk = fieldForeignKey(table, column);
|
|
10967
|
+
const target = fk === void 0 ? void 0 : this.tables.find((t) => t.schema === fk.references.schema && t.name === fk.references.table && t.origin.tabularSectionId === void 0 && t.origin.part === void 0);
|
|
10968
|
+
const object = target === void 0 ? void 0 : this.byId.get(target.origin.objectId);
|
|
10969
|
+
if (object === void 0 || isDeclaredTable(object)) return void 0;
|
|
10970
|
+
return {
|
|
10971
|
+
table: target,
|
|
10972
|
+
object
|
|
10973
|
+
};
|
|
10974
|
+
}
|
|
10975
|
+
/**
|
|
10634
10976
|
* Колонка кроку носія: елемент, який резолвила стадія 2 за вказівником у
|
|
10635
10977
|
* файлі `file` (у шляху — у файлі власника носія), у таблиці `table` його
|
|
10636
10978
|
* об'єкта. Поліморфна пара чи невідомий крок колонки не дають.
|
|
@@ -12581,8 +12923,8 @@ function carrierFunctions(physical) {
|
|
|
12581
12923
|
role: "propagate"
|
|
12582
12924
|
}))];
|
|
12583
12925
|
}
|
|
12584
|
-
const q$
|
|
12585
|
-
const relation$4 = (t) => `${q$
|
|
12926
|
+
const q$11 = quoteIdent;
|
|
12927
|
+
const relation$4 = (t) => `${q$11(t.schema)}.${q$11(t.name)}`;
|
|
12586
12928
|
/** Функція джерел копій від авторства (спека П4 §6.7). */
|
|
12587
12929
|
const AUTHOR_CARRIER_SOURCES_FUNCTION = {
|
|
12588
12930
|
schema: PLATFORM_SCHEMA,
|
|
@@ -12643,12 +12985,12 @@ function authorSourcesUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12643
12985
|
const users = authorSource(authorCarrierLinks(physical, attributeCase));
|
|
12644
12986
|
const fn = relation$4(sources.fn);
|
|
12645
12987
|
const body = [
|
|
12646
|
-
`SELECT ${sources.columns.map((c) => `s.${q$
|
|
12988
|
+
`SELECT ${sources.columns.map((c) => `s.${q$11(c.name)}`).join(", ")}`,
|
|
12647
12989
|
`FROM ${relation$4(users)} s`,
|
|
12648
|
-
`WHERE s.${q$
|
|
12990
|
+
`WHERE s.${q$11(users.key)} = ${CURRENT_USER$1}`
|
|
12649
12991
|
].join("\n");
|
|
12650
12992
|
const tag = dollarTag$1(body);
|
|
12651
|
-
const create = `CREATE OR REPLACE FUNCTION ${fn}()\nRETURNS TABLE (${sources.columns.map((c) => `${q$
|
|
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};`;
|
|
12652
12994
|
const requires = [{
|
|
12653
12995
|
type: "table",
|
|
12654
12996
|
schema: users.schema,
|
|
@@ -12703,7 +13045,7 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12703
13045
|
const table = group[0].table;
|
|
12704
13046
|
const fn = carrierFunctionNames(table).derive;
|
|
12705
13047
|
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$
|
|
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)}();`));
|
|
12707
13049
|
}
|
|
12708
13050
|
for (const group of byTable((l) => l.source)) {
|
|
12709
13051
|
const source = group[0].source;
|
|
@@ -12711,9 +13053,9 @@ function buildCarrierUnits(physical, attributeCase, provider, module, parse) {
|
|
|
12711
13053
|
const names = carrierTriggerNames(source);
|
|
12712
13054
|
const dependents = uniqueTables(group.map((l) => l.table));
|
|
12713
13055
|
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$
|
|
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 ");
|
|
12715
13057
|
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$
|
|
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}`));
|
|
12717
13059
|
}
|
|
12718
13060
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
12719
13061
|
}
|
|
@@ -12722,7 +13064,7 @@ function uniqueTables(tables) {
|
|
|
12722
13064
|
}
|
|
12723
13065
|
/** `s.<джерело> = <row>.<локальна> AND …` за колонками FK зв'язку. */
|
|
12724
13066
|
function sourceRow(link, row) {
|
|
12725
|
-
return link.pairs.map((p) => `s.${q$
|
|
13067
|
+
return link.pairs.map((p) => `s.${q$11(p.source)} = ${row}.${q$11(p.local)}`).join(" AND ");
|
|
12726
13068
|
}
|
|
12727
13069
|
/**
|
|
12728
13070
|
* Читання всіх копій зв'язку з рядка джерела в `row` — один будівник для
|
|
@@ -12733,8 +13075,8 @@ function sourceRow(link, row) {
|
|
|
12733
13075
|
*/
|
|
12734
13076
|
function carrierCopyRead(link, row, lock) {
|
|
12735
13077
|
return [
|
|
12736
|
-
`SELECT ${link.copies.map((c) => `s.${q$
|
|
12737
|
-
` INTO ${link.copies.map((c) => `${row}.${q$
|
|
13078
|
+
`SELECT ${link.copies.map((c) => `s.${q$11(c.column)}`).join(", ")}`,
|
|
13079
|
+
` INTO ${link.copies.map((c) => `${row}.${q$11(c.name)}`).join(", ")}`,
|
|
12738
13080
|
` FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, row)}${lock ? "" : ";"}`,
|
|
12739
13081
|
...lock ? [" FOR SHARE;"] : []
|
|
12740
13082
|
].join("\n");
|
|
@@ -12751,9 +13093,9 @@ function deriveFunction(fn, links) {
|
|
|
12751
13093
|
const body = ["BEGIN"];
|
|
12752
13094
|
for (const link of links) {
|
|
12753
13095
|
const from = `FROM ${relation$4(link.source)} s WHERE ${sourceRow(link, "NEW")}`;
|
|
12754
|
-
const linkChanged = link.pairs.map((p) => `NEW.${q$
|
|
13096
|
+
const linkChanged = link.pairs.map((p) => `NEW.${q$11(p.local)} IS DISTINCT FROM OLD.${q$11(p.local)}`).join(" OR ");
|
|
12755
13097
|
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$
|
|
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;");
|
|
12757
13099
|
body.push(" END IF;");
|
|
12758
13100
|
}
|
|
12759
13101
|
body.push(" RETURN NEW;", "END");
|
|
@@ -12769,9 +13111,9 @@ function propagateFunction(fn, links) {
|
|
|
12769
13111
|
const ordered = [...links].sort((a, b) => compareStrings(tableKey$1(a.table), tableKey$1(b.table)) || compareStrings(a.through, b.through));
|
|
12770
13112
|
const body = ["BEGIN"];
|
|
12771
13113
|
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$
|
|
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 ");
|
|
12775
13117
|
body.push(` UPDATE ${relation$4(link.table)} d SET ${set}`, ` WHERE ${row} AND (${differs});`);
|
|
12776
13118
|
}
|
|
12777
13119
|
body.push(" RETURN NULL;", "END");
|
|
@@ -12836,8 +13178,8 @@ function carrierBackfillStatements(physical, pending) {
|
|
|
12836
13178
|
};
|
|
12837
13179
|
for (const b of backfills) visit(b);
|
|
12838
13180
|
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$
|
|
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 ");
|
|
12841
13183
|
return {
|
|
12842
13184
|
table: {
|
|
12843
13185
|
schema: link.table.schema,
|
|
@@ -12848,7 +13190,7 @@ function carrierBackfillStatements(physical, pending) {
|
|
|
12848
13190
|
name: link.source.name
|
|
12849
13191
|
},
|
|
12850
13192
|
columns: copies.map((c) => c.name),
|
|
12851
|
-
sql: `UPDATE ${relation$4(link.table)} AS d SET (${copies.map((c) => q$
|
|
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};`
|
|
12852
13194
|
};
|
|
12853
13195
|
});
|
|
12854
13196
|
}
|
|
@@ -21817,190 +22159,6 @@ function hasRootForeignKey(table, column, kind, byKey) {
|
|
|
21817
22159
|
return "columns" in references && references.columns.length === 1 && primaryKey?.length === 1 && references.columns[0] === primaryKey[0];
|
|
21818
22160
|
});
|
|
21819
22161
|
}
|
|
21820
|
-
// src/compiler/rights/carriers.ts
|
|
21821
|
-
/**
|
|
21822
|
-
* Чи носій прав «в межах скоупу» (спека прав §4.2): фізичний FK поля є складеним, тобто
|
|
21823
|
-
* несе скоуп-колонку першою парою, а в проєкті без видів скоупу межі немає й
|
|
21824
|
-
* підходить будь-який одиночний `Ref`.
|
|
21825
|
-
*
|
|
21826
|
-
* `foreignKey` — FK поля виду в знімку (`undefined`, коли поле FK не має), як
|
|
21827
|
-
* його знаходить `fieldForeignKey`. Лише для полів виду: поле виду дає
|
|
21828
|
-
* одноколонковий FK лише простим посиланням, тож більше однієї колонки
|
|
21829
|
-
* однозначно означає складений; FK прийнятої таблиці описує файл, і там цей
|
|
21830
|
-
* висновок не тримається. Для прийнятої таблиці (`declared`) правило
|
|
21831
|
-
* закрите за побудовою: її колонки не мають `origin.scopeKindId`, тож
|
|
21832
|
-
* `fieldForeignKey` знаходить лише одноколонковий FK (у проєкті з видами
|
|
21833
|
-
* скоупу — не в межах), а складений не знаходить зовсім (не `Ref`).
|
|
21834
|
-
*/
|
|
21835
|
-
function inScopeTarget(foreignKey, project) {
|
|
21836
|
-
if (project.scopeKinds.length === 0) return true;
|
|
21837
|
-
return foreignKey !== void 0 && foreignKey.columns.length > 1;
|
|
21838
|
-
}
|
|
21839
|
-
/** Об'єкт, на який вказує кінцеве поле носія: сам власник ключа чи ціль `Ref`. */
|
|
21840
|
-
function carrierTarget(terminal) {
|
|
21841
|
-
return terminal.field.key ? terminal.object : terminal.field.target;
|
|
21842
|
-
}
|
|
21843
|
-
/**
|
|
21844
|
-
* Резолв носія прав (спека прав §4.2, Рх21) у колонку таблиці об'єкта: рядок — власне
|
|
21845
|
-
* поле; шлях — перший крок мусить бути одиночним неполіморфним `Ref` у межах
|
|
21846
|
-
* скоупу, бо інакше з'єднання в політиці вийшло б за тенант, а другий —
|
|
21847
|
-
* реквізит його цілі. Кінцеве поле — `Ref` або ключ; що саме воно має
|
|
21848
|
-
* означати, вирішує правило поля (власність, прив'язка, вимір).
|
|
21849
|
-
*
|
|
21850
|
-
* `at.pointer` — вказівник носія у файлі, `at.field` — ім'я поля для
|
|
21851
|
-
* діагностики невідомого реквізиту, `at.role` — роль першого кроку в індексі
|
|
21852
|
-
* (типово `rights.carrier`; мапінг `access` має власну).
|
|
21853
|
-
*/
|
|
21854
|
-
function resolveCarrier(object, carrier, at, ctx) {
|
|
21855
|
-
const headRole = at.role ?? "rights.carrier";
|
|
21856
|
-
if (typeof carrier === "string") {
|
|
21857
|
-
const step = resolveStep(object, object, carrier, at, headRole, ctx);
|
|
21858
|
-
if (!step.ok) return step;
|
|
21859
|
-
return {
|
|
21860
|
-
ok: true,
|
|
21861
|
-
terminal: {
|
|
21862
|
-
object,
|
|
21863
|
-
field: step.field
|
|
21864
|
-
},
|
|
21865
|
-
contract: {
|
|
21866
|
-
column: step.field.column,
|
|
21867
|
-
value: step.field.column
|
|
21868
|
-
}
|
|
21869
|
-
};
|
|
21870
|
-
}
|
|
21871
|
-
const [first, second] = carrier;
|
|
21872
|
-
const head = resolveStep(object, object, first, {
|
|
21873
|
-
pointer: `${at.pointer}/0`,
|
|
21874
|
-
field: at.field
|
|
21875
|
-
}, headRole, ctx);
|
|
21876
|
-
if (!head.ok) return head;
|
|
21877
|
-
const firstPointer = `${at.pointer}/0`;
|
|
21878
|
-
if (head.field.target === void 0) return fail("rights.carrier-not-ref", object, firstPointer, first);
|
|
21879
|
-
if (KIND_REGISTRY[head.field.target.kind].declared) return fail("rights.carrier-path-adopted", object, firstPointer, first);
|
|
21880
|
-
if (!head.field.inScope) return {
|
|
21881
|
-
ok: false,
|
|
21882
|
-
diagnostic: crossTenant(object, firstPointer, first, ctx.references)
|
|
21883
|
-
};
|
|
21884
|
-
const target = head.field.target;
|
|
21885
|
-
const tail = resolveStep(object, target, second, {
|
|
21886
|
-
pointer: `${at.pointer}/1`,
|
|
21887
|
-
field: at.field
|
|
21888
|
-
}, "rights.carrierPath", ctx);
|
|
21889
|
-
if (!tail.ok) return tail;
|
|
21890
|
-
const table = must$9(mainTableOf(ctx.physical, must$9(target.id)));
|
|
21891
|
-
return {
|
|
21892
|
-
ok: true,
|
|
21893
|
-
terminal: {
|
|
21894
|
-
object: target,
|
|
21895
|
-
field: tail.field
|
|
21896
|
-
},
|
|
21897
|
-
contract: {
|
|
21898
|
-
column: head.field.column,
|
|
21899
|
-
value: carrierCopyName(head.field.column, tail.field.column),
|
|
21900
|
-
via: {
|
|
21901
|
-
objectId: must$9(target.id),
|
|
21902
|
-
table: {
|
|
21903
|
-
schema: table.schema,
|
|
21904
|
-
name: table.name
|
|
21905
|
-
},
|
|
21906
|
-
column: tail.field.column
|
|
21907
|
-
}
|
|
21908
|
-
}
|
|
21909
|
-
};
|
|
21910
|
-
}
|
|
21911
|
-
/**
|
|
21912
|
-
* Один крок: ім'я резолвить індекс посилань (роль кроку на його вказівнику),
|
|
21913
|
-
* а що це за поле — каже фізичний знімок: одна колонка з FK — одиночний
|
|
21914
|
-
* `Ref` (і реквізит, і стандартний, як `createdBy`), ключ — колонка
|
|
21915
|
-
* первинного ключа без FK. Поліморфна пара FK не має й двох колонок.
|
|
21916
|
-
*/
|
|
21917
|
-
function resolveStep(owner, object, name, at, role, ctx) {
|
|
21918
|
-
const reference = ctx.references.find((r) => r.from.file === owner.file && r.from.pointer === at.pointer && r.role === role);
|
|
21919
|
-
if (reference === void 0 || object.id === void 0) return {
|
|
21920
|
-
ok: false,
|
|
21921
|
-
diagnostic: diagnostic("rights.attribute-unknown", owner.file, at.pointer, {
|
|
21922
|
-
attribute: name,
|
|
21923
|
-
field: at.field,
|
|
21924
|
-
...object === owner ? {} : { target: object.name }
|
|
21925
|
-
})
|
|
21926
|
-
};
|
|
21927
|
-
const field = at.field === "publication" ? publicationField(object, reference.to.id, name, ctx) : elementField(object, reference.to.id, name, ctx);
|
|
21928
|
-
return field === void 0 ? fail("rights.carrier-not-ref", owner, at.pointer, name) : {
|
|
21929
|
-
ok: true,
|
|
21930
|
-
field
|
|
21931
|
-
};
|
|
21932
|
-
}
|
|
21933
|
-
/**
|
|
21934
|
-
* Що за поле — елемент `elementId` в основній таблиці об'єкта, за фізичним
|
|
21935
|
-
* знімком: одна колонка з FK — одиночний `Ref` (і реквізит, і стандартний, як
|
|
21936
|
-
* `createdBy`), ключ — колонка первинного ключа без FK. Поліморфна пара FK не
|
|
21937
|
-
* має й двох колонок, тож, як і не-посилання, дає `undefined`.
|
|
21938
|
-
*
|
|
21939
|
-
* `inScope` виводиться лише для полів виду (`inScopeTarget`): на прийнятій
|
|
21940
|
-
* таблиці складений FK з файлу не розпізнається, і поле лишається поза
|
|
21941
|
-
* межею скоупу чи не-`Ref` — відмова, а не хибний дозвіл.
|
|
21942
|
-
*/
|
|
21943
|
-
function elementField(object, elementId, name, ctx) {
|
|
21944
|
-
const table = must$9(mainTableOf(ctx.physical, must$9(object.id)));
|
|
21945
|
-
const columns = elementColumns(object, table, ctx.project.naming.attributeCase).get(elementId) ?? [];
|
|
21946
|
-
if (columns.length !== 1) return void 0;
|
|
21947
|
-
const column = columns[0];
|
|
21948
|
-
if (table.primaryKey?.columns.length === 1 && table.primaryKey.columns[0] === column) return {
|
|
21949
|
-
name,
|
|
21950
|
-
column,
|
|
21951
|
-
key: true,
|
|
21952
|
-
inScope: true
|
|
21953
|
-
};
|
|
21954
|
-
const foreignKey = fieldForeignKey(table, column);
|
|
21955
|
-
const target = foreignKey === void 0 ? void 0 : objectOfTable(foreignKey.references, ctx);
|
|
21956
|
-
if (target === void 0) return void 0;
|
|
21957
|
-
return {
|
|
21958
|
-
name,
|
|
21959
|
-
column,
|
|
21960
|
-
key: false,
|
|
21961
|
-
target,
|
|
21962
|
-
inScope: inScopeTarget(foreignKey, ctx.project)
|
|
21963
|
-
};
|
|
21964
|
-
}
|
|
21965
|
-
/**
|
|
21966
|
-
* Колонка V шапки як носій публікації: елемент мусить бути стандартною
|
|
21967
|
-
* колонкою умови публікації самого об'єкта. Ні ключем, ні `Ref` вона не є, а
|
|
21968
|
-
* межа скоупу її не стосується: значення — ознака рядка, не посилання.
|
|
21969
|
-
*/
|
|
21970
|
-
function publicationField(object, elementId, name, ctx) {
|
|
21971
|
-
const objectId = must$9(object.id);
|
|
21972
|
-
if (!publicationCarriers().some(({ column }) => standardElementId(objectId, column) === elementId)) return void 0;
|
|
21973
|
-
const columns = elementColumns(object, must$9(mainTableOf(ctx.physical, objectId)), ctx.project.naming.attributeCase).get(elementId) ?? [];
|
|
21974
|
-
if (columns.length !== 1) return void 0;
|
|
21975
|
-
return {
|
|
21976
|
-
name,
|
|
21977
|
-
column: columns[0],
|
|
21978
|
-
key: false,
|
|
21979
|
-
inScope: true
|
|
21980
|
-
};
|
|
21981
|
-
}
|
|
21982
|
-
/** Об'єкт, чия основна таблиця — ціль FK. */
|
|
21983
|
-
function objectOfTable(references, ctx) {
|
|
21984
|
-
const table = ctx.physical.tables.find((t) => t.schema === references.schema && t.name === references.table && isObjectTable(t) && t.origin.tabularSectionId === void 0 && t.origin.part === void 0);
|
|
21985
|
-
return table === void 0 ? void 0 : ctx.byId.get(table.origin.objectId);
|
|
21986
|
-
}
|
|
21987
|
-
/**
|
|
21988
|
-
* Носій виходить за межі скоупу. Нескоуплений об'єкт тенанта не має, тож
|
|
21989
|
-
* текст тоді називає не «вихід за тенант», а те, що посилання не тримається
|
|
21990
|
-
* межі скоупу: виправлення інше — скоупити об'єкт.
|
|
21991
|
-
*/
|
|
21992
|
-
function crossTenant(object, pointer, attribute, references) {
|
|
21993
|
-
return diagnostic("rights.carrier-cross-tenant", object.file, pointer, {
|
|
21994
|
-
attribute,
|
|
21995
|
-
...scopeKindOf(object, references) === void 0 ? { host: "unscoped" } : {}
|
|
21996
|
-
});
|
|
21997
|
-
}
|
|
21998
|
-
function fail(code, object, pointer, attribute) {
|
|
21999
|
-
return {
|
|
22000
|
-
ok: false,
|
|
22001
|
-
diagnostic: diagnostic(code, object.file, pointer, { attribute })
|
|
22002
|
-
};
|
|
22003
|
-
}
|
|
22004
22162
|
// src/compiler/rights/command-columns.ts
|
|
22005
22163
|
/**
|
|
22006
22164
|
* Факт ролі довідника `fixedColumns` (логічні імена) як визначення його
|
|
@@ -22123,9 +22281,9 @@ function checkRights(ctx) {
|
|
|
22123
22281
|
});
|
|
22124
22282
|
diagnostics.push(...requiresCycles(object, actions, standard));
|
|
22125
22283
|
if (def.rightsExtents.includes("own")) diagnostics.push(...checkOwnership(object, ctx, carriers));
|
|
22126
|
-
if (def.rightsBinding) diagnostics.push(...checkBinding(object, carriers));
|
|
22284
|
+
if (def.rightsBinding) diagnostics.push(...checkBinding(object, carriers, ctx.model.bindings));
|
|
22127
22285
|
if (def.rightsExtents.includes("dimension")) diagnostics.push(...checkAccess(object, ctx, carriers));
|
|
22128
|
-
diagnostics.push(...checkCarrierCopies(object, carriers));
|
|
22286
|
+
diagnostics.push(...checkCarrierCopies(object, carriers, ctx.model.bindings));
|
|
22129
22287
|
diagnostics.push(...checkLazyCarriers(object, ctx.references));
|
|
22130
22288
|
}
|
|
22131
22289
|
diagnostics.push(...checkDimensions(ctx, carriers));
|
|
@@ -22215,27 +22373,33 @@ function checkOwnership(object, ctx, carriers) {
|
|
|
22215
22373
|
});
|
|
22216
22374
|
}
|
|
22217
22375
|
/**
|
|
22218
|
-
* Правило прив'язки до контейнера (спека прав §4.3
|
|
22219
|
-
*
|
|
22220
|
-
*
|
|
22376
|
+
* Правило прив'язки до контейнера (спека прав §4.3, спека прав контейнера
|
|
22377
|
+
* §2): ціль реквізиту — об'єкт із `rightsContainer` (не сам об'єкт) чи об'єкт
|
|
22378
|
+
* із власною прив'язкою, тоді ланцюжок мусить дійти до контейнера без циклу;
|
|
22379
|
+
* і в межах скоупу (інакше чужий контейнер відкрив би рядок). Кожен об'єкт
|
|
22380
|
+
* звітує лише свій крок: ланцюжок, що впирається в помилку нижче, звітує та
|
|
22381
|
+
* ціль.
|
|
22221
22382
|
*/
|
|
22222
|
-
function checkBinding(object, carriers) {
|
|
22383
|
+
function checkBinding(object, carriers, bindings) {
|
|
22223
22384
|
const carrier = bindingOf(object);
|
|
22224
22385
|
if (carrier === void 0) return [];
|
|
22225
|
-
const
|
|
22386
|
+
const at = "/containerBinding";
|
|
22226
22387
|
const resolved = resolveCarrier(object, carrier, {
|
|
22227
|
-
pointer,
|
|
22388
|
+
pointer: at,
|
|
22228
22389
|
field: "containerBinding"
|
|
22229
22390
|
}, carriers);
|
|
22230
22391
|
if (!resolved.ok) return [resolved.diagnostic];
|
|
22231
|
-
const at = typeof carrier === "string" ? pointer : `${pointer}/1`;
|
|
22232
22392
|
const { field } = resolved.terminal;
|
|
22233
22393
|
const target = carrierTarget(resolved.terminal);
|
|
22234
|
-
|
|
22394
|
+
const params = {
|
|
22235
22395
|
attribute: field.name,
|
|
22236
22396
|
name: target.name
|
|
22237
|
-
}
|
|
22238
|
-
if (target
|
|
22397
|
+
};
|
|
22398
|
+
if (isRightsContainer(target)) {
|
|
22399
|
+
if (target === object) return [diagnostic("rights.container-self", object.file, at, params)];
|
|
22400
|
+
} else if (bindingOf(target) === void 0) return [diagnostic("rights.container-target", object.file, at, params)];
|
|
22401
|
+
const chain = bindings.get(must$9(object.id));
|
|
22402
|
+
if (chain?.ok === false && chain.cycle) return [diagnostic("rights.container-binding-cycle", object.file, at, {
|
|
22239
22403
|
attribute: field.name,
|
|
22240
22404
|
name: object.name
|
|
22241
22405
|
})];
|
|
@@ -22334,7 +22498,7 @@ function checkAccess(object, ctx, carriers) {
|
|
|
22334
22498
|
* ім'я зайняте колонкою опису, і стадія 3 копії не поклала — права читали б
|
|
22335
22499
|
* чуже значення.
|
|
22336
22500
|
*/
|
|
22337
|
-
function checkCarrierCopies(object, carriers) {
|
|
22501
|
+
function checkCarrierCopies(object, carriers, bindings) {
|
|
22338
22502
|
if (KIND_REGISTRY[object.kind].registerKeys !== void 0) return [];
|
|
22339
22503
|
const objectId = must$9(object.id);
|
|
22340
22504
|
const main = must$9(mainTableOf(carriers.physical, objectId));
|
|
@@ -22352,7 +22516,8 @@ function checkCarrierCopies(object, carriers) {
|
|
|
22352
22516
|
role
|
|
22353
22517
|
}, carriers);
|
|
22354
22518
|
if (!resolved.ok) continue;
|
|
22355
|
-
const
|
|
22519
|
+
const contract = field === "containerBinding" ? bindingContract(bindings.get(objectId), carriers.physical)?.carrier : resolved.contract;
|
|
22520
|
+
if (contract === void 0) continue;
|
|
22356
22521
|
const expected = [];
|
|
22357
22522
|
if (contract.via !== void 0) expected.push([main, {
|
|
22358
22523
|
table: contract.via.table,
|
|
@@ -23791,6 +23956,34 @@ function liveInputs(contracts, physical, style, user) {
|
|
|
23791
23956
|
deltas: deltasCte(contracts.rightsCatalogs, physical, style)
|
|
23792
23957
|
};
|
|
23793
23958
|
}
|
|
23959
|
+
/**
|
|
23960
|
+
* Входи набору видачі запрошення (Р-З1-1): ті самі генератори й фільтри
|
|
23961
|
+
* дієвості, що `liveInputs`, але за переліком id призначень довідника рівня
|
|
23962
|
+
* `catalog` (`ids` — SQL-вираз `uuid[]`), а не за користувачем: учасник, що
|
|
23963
|
+
* очікує, ще ні в чиїх «моїх скоупах». Носії `fullAccess` — за архетипом
|
|
23964
|
+
* прямого призначення набору, без актора: користувача в учасника ще немає.
|
|
23965
|
+
* Дельти — лише довідника набору: кастомна роль призначення — того самого
|
|
23966
|
+
* рівня й тенанта. Рядок `typed` несе ще й id призначення (`assignment`):
|
|
23967
|
+
* функція прийняття пише його в `rights_tx_typed.assignment`, а живий шлях
|
|
23968
|
+
* цієї колонки не має, тож його SQL не змінюється.
|
|
23969
|
+
*/
|
|
23970
|
+
function issueInputs(contracts, catalog, physical, style, ids) {
|
|
23971
|
+
const typed = withCtes([["assignments", catalogAssignments(catalog, physical, style, { ids })]], typedCte(false, true));
|
|
23972
|
+
const storage = storageSql(catalog.level);
|
|
23973
|
+
return {
|
|
23974
|
+
typed,
|
|
23975
|
+
containers: containersCte(contracts.rights, physical, style),
|
|
23976
|
+
deltas: deltasCte([catalog], physical, style),
|
|
23977
|
+
holders: [
|
|
23978
|
+
`SELECT DISTINCT ${sqlLiteral(catalog.level.level)}::text AS level, ${storage.storageId} AS level_id, t.scope`,
|
|
23979
|
+
`FROM (\n${indent$2(typed)}\n) t`,
|
|
23980
|
+
`JOIN ${call$1(RIGHTS_FUNCTIONS.fullAccessRoles)} f`,
|
|
23981
|
+
` ON f.role_id = t.archetype`,
|
|
23982
|
+
` AND f.storage_id IS NOT DISTINCT FROM ${storage.storageId}`,
|
|
23983
|
+
`WHERE t.custom_role IS NULL`
|
|
23984
|
+
].join("\n")
|
|
23985
|
+
};
|
|
23986
|
+
}
|
|
23794
23987
|
/** `WITH` з CTE `[ім'я, тіло, матеріалізація?]` перед запитом `tail`. */
|
|
23795
23988
|
function withCtes(ctes, tail) {
|
|
23796
23989
|
return [`WITH ${ctes.map(([name, sql, materialized = ""]) => `${name} AS ${materialized}(\n${indent$2(sql)}\n)`).join(",\n")}`, tail].join("\n");
|
|
@@ -24099,7 +24292,7 @@ function catalogAssignments(catalog, physical, style, of) {
|
|
|
24099
24292
|
return [
|
|
24100
24293
|
`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
24294
|
` 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`,
|
|
24295
|
+
` ${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
24296
|
`FROM ${qualified(catalog.assignments.table)} a`,
|
|
24104
24297
|
...mine,
|
|
24105
24298
|
`LEFT JOIN ${qualified(catalog.roles.table)} c`,
|
|
@@ -24168,10 +24361,11 @@ function sourceScopeKind(level, rights) {
|
|
|
24168
24361
|
* зберігання ролей, покритих джерелом, — `NULL`, тож рядок джерела
|
|
24169
24362
|
* типізується інакше (спека прав §4.7): рівень ролі мусить дорівнювати рівню джерела —
|
|
24170
24363
|
* сталій генератора, а не даним; ключ глобальної ролі в контейнерному джерелі
|
|
24171
|
-
* її не вмикає.
|
|
24364
|
+
* її не вмикає. `withAssignment` — колонка id призначення лише для входів
|
|
24365
|
+
* набору видачі (`issueInputs`).
|
|
24172
24366
|
*/
|
|
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`;
|
|
24367
|
+
function typedCte(withSources, withAssignment = false) {
|
|
24368
|
+
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
24369
|
const roles = `JOIN ${call$1(RIGHTS_FUNCTIONS.roles)} r`;
|
|
24176
24370
|
return [
|
|
24177
24371
|
columns,
|
|
@@ -31316,8 +31510,8 @@ function hierarchyNames(table) {
|
|
|
31316
31510
|
}
|
|
31317
31511
|
};
|
|
31318
31512
|
}
|
|
31319
|
-
const q$
|
|
31320
|
-
const relation$3 = (t) => `${q$
|
|
31513
|
+
const q$10 = quoteIdent;
|
|
31514
|
+
const relation$3 = (t) => `${q$10(t.schema)}.${q$10(t.name)}`;
|
|
31321
31515
|
/**
|
|
31322
31516
|
* Виклик advisory-замка ієрархії таблиці — одне джерело ключа для тригера й
|
|
31323
31517
|
* ядра команд (спека П4 §6.6): інший вираз ключа в ядрі не серіалізував би його з
|
|
@@ -31383,7 +31577,7 @@ function buildHierarchyUnits(physical, objects, attributeCase, provider, module,
|
|
|
31383
31577
|
}] } : {}
|
|
31384
31578
|
});
|
|
31385
31579
|
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$
|
|
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}`));
|
|
31387
31581
|
}
|
|
31388
31582
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
31389
31583
|
}
|
|
@@ -31400,11 +31594,11 @@ function hierarchyBody({ table, parent, key }) {
|
|
|
31400
31594
|
" IF current_setting('transaction_isolation') <> 'read committed' THEN",
|
|
31401
31595
|
` RAISE EXCEPTION USING ERRCODE = '${HIERARCHY_ISOLATION_ERROR.errcode}', MESSAGE = '${HIERARCHY_ISOLATION_ERROR.message}';`,
|
|
31402
31596
|
" END IF;",
|
|
31403
|
-
` IF NEW.${q$
|
|
31597
|
+
` IF NEW.${q$10(parent)} = NEW.${q$10(key)} THEN`,
|
|
31404
31598
|
` ${invalid}`,
|
|
31405
31599
|
" END IF;",
|
|
31406
31600
|
` PERFORM ${hierarchyLockSql(table)};`,
|
|
31407
|
-
` IF EXISTS (WITH RECURSIVE up(node) AS (SELECT p.${q$
|
|
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`,
|
|
31408
31602
|
` ${invalid}`,
|
|
31409
31603
|
" END IF;",
|
|
31410
31604
|
" RETURN NULL;",
|
|
@@ -31476,8 +31670,8 @@ function languageStateTables(physical, objects, attributeCase) {
|
|
|
31476
31670
|
}
|
|
31477
31671
|
return result.sort((a, b) => compareStrings(a.table.schema, b.table.schema) || compareStrings(a.table.name, b.table.name));
|
|
31478
31672
|
}
|
|
31479
|
-
const q$
|
|
31480
|
-
const relation$2 = (t) => `${q$
|
|
31673
|
+
const q$9 = quoteIdent;
|
|
31674
|
+
const relation$2 = (t) => `${q$9(t.schema)}.${q$9(t.name)}`;
|
|
31481
31675
|
/**
|
|
31482
31676
|
* Тригер стану мови (Р-B2-4, спека багатомовності §5.2): незмінність основної
|
|
31483
31677
|
* й коду, переходи стану за матрицею факту ролі, заборона позначки видалення,
|
|
@@ -31500,7 +31694,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
|
|
|
31500
31694
|
generator: "mechanics"
|
|
31501
31695
|
});
|
|
31502
31696
|
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$
|
|
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}`));
|
|
31504
31698
|
}
|
|
31505
31699
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
31506
31700
|
}
|
|
@@ -31513,7 +31707,7 @@ function buildLanguageStateUnits(physical, objects, attributeCase, provider, mod
|
|
|
31513
31707
|
function languageStateBody({ state, columns }) {
|
|
31514
31708
|
const E = COMMAND_CORE_ERRORS.invalid;
|
|
31515
31709
|
const refuse = `RAISE EXCEPTION USING ERRCODE = '${E.errcode}', MESSAGE = '${E.message}', DETAIL = ${sqlLiteral(E.languageState)};`;
|
|
31516
|
-
const col = (row, name) => `${row}.${q$
|
|
31710
|
+
const col = (row, name) => `${row}.${q$9(name)}`;
|
|
31517
31711
|
const branch = (condition, body, indent = " ") => [
|
|
31518
31712
|
`${indent}IF ${condition} THEN`,
|
|
31519
31713
|
...body.map((line) => `${indent} ${line}`),
|
|
@@ -32526,7 +32720,7 @@ function uniformExtents(actions, label) {
|
|
|
32526
32720
|
* `rightsExtents`. Викликається лише на моделі без помилок: цикли вимог і
|
|
32527
32721
|
* невідомі дії вже відхилила стадія 4, тож замикання не кидає.
|
|
32528
32722
|
*/
|
|
32529
|
-
function rightsContracts(objects, references, physical, project) {
|
|
32723
|
+
function rightsContracts(objects, references, physical, project, bindings) {
|
|
32530
32724
|
const ctx = carrierContext({
|
|
32531
32725
|
objects,
|
|
32532
32726
|
references,
|
|
@@ -32534,9 +32728,9 @@ function rightsContracts(objects, references, physical, project) {
|
|
|
32534
32728
|
project
|
|
32535
32729
|
});
|
|
32536
32730
|
const memberships = invitationMemberships(objects, references, project);
|
|
32537
|
-
return objects.filter((object) => KIND_REGISTRY[object.kind].rightsExtents.length > 0).map((object) => rightsContract(object, ctx, memberships)).sort((a, b) => compareStrings(a.objectId, b.objectId));
|
|
32731
|
+
return objects.filter((object) => KIND_REGISTRY[object.kind].rightsExtents.length > 0).map((object) => rightsContract(object, ctx, bindings, memberships)).sort((a, b) => compareStrings(a.objectId, b.objectId));
|
|
32538
32732
|
}
|
|
32539
|
-
function rightsContract(object, ctx, memberships) {
|
|
32733
|
+
function rightsContract(object, ctx, bindings, memberships) {
|
|
32540
32734
|
const { references, physical } = ctx;
|
|
32541
32735
|
const def = KIND_REGISTRY[object.kind];
|
|
32542
32736
|
const objectId = must$9(object.id);
|
|
@@ -32579,18 +32773,10 @@ function rightsContract(object, ctx, memberships) {
|
|
|
32579
32773
|
});
|
|
32580
32774
|
const authorColumn = findStandardColumn(table, must$9(authorColumns().find((c) => c.logicalName === "createdBy")), ctx.project.naming.attributeCase)?.name;
|
|
32581
32775
|
const rootAuthor = root && authorColumn !== void 0 ? ownership.find((carrier) => carrier.via === void 0 && carrier.value === authorColumn)?.value : void 0;
|
|
32582
|
-
const bindingCarrier = bindingOf(object);
|
|
32583
32776
|
let binding;
|
|
32584
|
-
if (
|
|
32585
|
-
|
|
32586
|
-
|
|
32587
|
-
field: "containerBinding"
|
|
32588
|
-
}, ctx);
|
|
32589
|
-
if (!resolved.ok) throw new Error("internal: unchecked rights carrier");
|
|
32590
|
-
binding = {
|
|
32591
|
-
containerId: must$9(carrierTarget(resolved.terminal).id),
|
|
32592
|
-
carrier: resolved.contract
|
|
32593
|
-
};
|
|
32777
|
+
if (bindingOf(object) !== void 0) {
|
|
32778
|
+
binding = bindingContract(bindings.get(objectId), ctx.physical);
|
|
32779
|
+
if (binding === void 0) throw new Error("internal: unchecked container binding");
|
|
32594
32780
|
}
|
|
32595
32781
|
const access = accessOf(object).map((mapping, index) => {
|
|
32596
32782
|
const { carrier, pointer } = accessCarrier(mapping, index);
|
|
@@ -36197,7 +36383,7 @@ function effectiveHolderRows(catalog, contracts, physical, attributeCase) {
|
|
|
36197
36383
|
].filter(Boolean).join("\n");
|
|
36198
36384
|
}
|
|
36199
36385
|
// src/compiler/rights/guard-units.ts
|
|
36200
|
-
const q$
|
|
36386
|
+
const q$8 = quoteIdent;
|
|
36201
36387
|
const platform = (name) => ({
|
|
36202
36388
|
schema: PLATFORM_SCHEMA,
|
|
36203
36389
|
name
|
|
@@ -36319,17 +36505,17 @@ function journalRelation(table) {
|
|
|
36319
36505
|
return `${table.schema}.${table.name}`;
|
|
36320
36506
|
}
|
|
36321
36507
|
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$
|
|
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)}`];
|
|
36323
36509
|
}
|
|
36324
36510
|
function transitionSql(config, operation) {
|
|
36325
36511
|
const old = operation !== "INSERT";
|
|
36326
36512
|
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$
|
|
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)}`;
|
|
36329
36515
|
const [scopeKind, oldScope] = scopeSql(config, "o");
|
|
36330
36516
|
const [, newScope] = scopeSql(config, "n");
|
|
36331
36517
|
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$
|
|
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}`;
|
|
36333
36519
|
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
36520
|
const relation = journalRelation(config.table);
|
|
36335
36521
|
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 +36737,12 @@ function pendingSql(config, operation) {
|
|
|
36551
36737
|
const after = operation !== "DELETE";
|
|
36552
36738
|
const [kind] = scopeSql(config, "r");
|
|
36553
36739
|
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$
|
|
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)}`;
|
|
36556
36742
|
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$
|
|
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"})`] : [],
|
|
36560
36746
|
actorPending()
|
|
36561
36747
|
], "v_maintenance");
|
|
36562
36748
|
}
|
|
@@ -36572,7 +36758,7 @@ function pendingSql(config, operation) {
|
|
|
36572
36758
|
function stateRows(table, state, match, style) {
|
|
36573
36759
|
const name = ref(tableName(table));
|
|
36574
36760
|
const equals = match.any === true ? `= ANY (${match.value})` : `= ${match.value}`;
|
|
36575
|
-
const live = `l.${q$
|
|
36761
|
+
const live = `l.${q$8(match.column)} ${equals}`;
|
|
36576
36762
|
if (state === "after") return `SELECT to_jsonb(l) AS doc FROM ${name} l WHERE ${live}`;
|
|
36577
36763
|
const key = column(table, KEY$1, style);
|
|
36578
36764
|
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 +36766,7 @@ function stateRows(table, state, match, style) {
|
|
|
36580
36766
|
`(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
36767
|
"UNION ALL",
|
|
36582
36768
|
`SELECT to_jsonb(l) FROM ${name} l WHERE ${live}`,
|
|
36583
|
-
` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$
|
|
36769
|
+
` AND NOT EXISTS (SELECT 1 FROM ${journal} AND j.row_id = l.${q$8(key)})`
|
|
36584
36770
|
].join("\n");
|
|
36585
36771
|
}
|
|
36586
36772
|
/** Звуження за ключем рядка: перевірка судить один рядок черги. */
|
|
@@ -36662,7 +36848,7 @@ function rootExists(catalog, physical) {
|
|
|
36662
36848
|
return `EXISTS (SELECT 1 FROM ${ref({
|
|
36663
36849
|
schema: fk.references.schema,
|
|
36664
36850
|
name: fk.references.table
|
|
36665
|
-
})} root WHERE root.${q$
|
|
36851
|
+
})} root WHERE root.${q$8(fk.references.columns[index])} = v_pending.scope)`;
|
|
36666
36852
|
}
|
|
36667
36853
|
function assignmentBeforeSet(catalog, physical, style) {
|
|
36668
36854
|
const table = tableOf$2(physical, catalog.assignments.table);
|
|
@@ -36734,15 +36920,15 @@ function escalationSql(after, before, storageKind) {
|
|
|
36734
36920
|
function deltaDomainSql(catalog, physical, style) {
|
|
36735
36921
|
const roles = tableOf$2(physical, catalog.roles.table);
|
|
36736
36922
|
const delta = tableOf$2(physical, catalog.roles.delta);
|
|
36737
|
-
const r = (def) => `r.${q$
|
|
36738
|
-
const l = (def) => `l.${q$
|
|
36923
|
+
const r = (def) => `r.${q$8(column(roles, def, style))}`;
|
|
36924
|
+
const l = (def) => `l.${q$8(column(delta, def, style))}`;
|
|
36739
36925
|
const roleScope = scopeColumn(roles);
|
|
36740
36926
|
const deltaScope = scopeColumn(delta);
|
|
36741
36927
|
const journal = (table) => `${ref(platform("rights_journal"))} j WHERE j.xid = v_pending.xid AND j.relation = ${sqlLiteral(journalRelation(table))}`;
|
|
36742
36928
|
const storage = catalog.level.level === "scope" ? `m.storage = 'scope' AND m.storage_id = ${sqlLiteral(catalog.level.scopeKindId)}::uuid` : "m.storage = 'global'";
|
|
36743
36929
|
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$
|
|
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`}`,
|
|
36746
36932
|
` AND (EXISTS (SELECT 1 FROM ${journal(delta)} AND j.row_id = ${l(KEY$1)} AND j.after IS NOT NULL)`,
|
|
36747
36933
|
` 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
36934
|
` 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 +36940,17 @@ function catalogCheck(catalog, contracts, physical, style) {
|
|
|
36754
36940
|
const roles = tableOf$2(physical, catalog.roles.table);
|
|
36755
36941
|
const assignments = tableOf$2(physical, catalog.assignments.table);
|
|
36756
36942
|
const scope = catalog.level.level === "scope" ? `${sqlLiteral(catalog.level.scopeKindId)}::uuid` : `${sqlLiteral(ZERO_UUID)}::uuid`;
|
|
36757
|
-
const roleId = `r.${q$
|
|
36943
|
+
const roleId = `r.${q$8(column(roles, KEY$1, style))}`;
|
|
36758
36944
|
const assignmentScope = scopeColumn(assignments);
|
|
36759
36945
|
const roleScope = scopeColumn(roles);
|
|
36760
|
-
const sameRole = roleScope === void 0 ? "TRUE" : `r.${q$
|
|
36761
|
-
const sameAssignment = assignmentScope === void 0 ? "TRUE" : `a.${q$
|
|
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`;
|
|
36762
36948
|
const root = rootExists(catalog, physical);
|
|
36763
36949
|
return [
|
|
36764
36950
|
`IF v_pending.scope_kind_id = ${scope} THEN`,
|
|
36765
36951
|
" 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$
|
|
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))})`,
|
|
36768
36954
|
` THEN ${refusal(COMMAND_CORE_ERRORS.forbidden.roleInUse)} END IF;`,
|
|
36769
36955
|
` ${deltaDomainSql(catalog, physical, style)}`,
|
|
36770
36956
|
` ${escalationSql(roleGrantSet(catalog, physical, "after", style), roleGrantSet(catalog, physical, "before", style), catalogStorageKind(catalog))}`,
|
|
@@ -36886,7 +37072,7 @@ function eventRows(operation, alias, source) {
|
|
|
36886
37072
|
}
|
|
36887
37073
|
function bumpRows(operation, scopeKindId, scope) {
|
|
36888
37074
|
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$
|
|
37075
|
+
const value = scope === void 0 ? `${sqlLiteral(ZERO_UUID)}::uuid` : `r.${q$8(scope)}`;
|
|
36890
37076
|
return `PERFORM ${ref(RIGHTS_FUNCTIONS.bump)}(${sqlLiteral(scopeKindId)}::uuid, s.scope) FROM (SELECT DISTINCT ${value} AS scope FROM (${rows}) r) s;`;
|
|
36891
37077
|
}
|
|
36892
37078
|
/**
|
|
@@ -36900,13 +37086,13 @@ function bumpRows(operation, scopeKindId, scope) {
|
|
|
36900
37086
|
* ключем рядка: зміну самого ключа тримає row-level тригер `_id`.
|
|
36901
37087
|
*/
|
|
36902
37088
|
function memberEventBody(member, contracts, physical, operation, provider, style) {
|
|
36903
|
-
const key = q$
|
|
36904
|
-
const scope = q$
|
|
36905
|
-
const user = q$
|
|
37089
|
+
const key = q$8(member.keyColumn);
|
|
37090
|
+
const scope = q$8(member.scopeColumn);
|
|
37091
|
+
const user = q$8(member.userColumn);
|
|
36906
37092
|
const assignments = contracts.rightsCatalogs.filter((catalog) => catalog.level.level === "scope" && catalog.level.scopeKindId === member.scopeKindId).map((catalog) => {
|
|
36907
37093
|
const table = catalog.assignments.table;
|
|
36908
37094
|
const actual = tableOf$2(physical, table);
|
|
36909
|
-
return `EXISTS (SELECT 1 FROM ${ref(table)} a WHERE a.${q$
|
|
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})`;
|
|
36910
37096
|
});
|
|
36911
37097
|
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
37098
|
const changed = operation === "UPDATE" ? [
|
|
@@ -36935,13 +37121,13 @@ function memberEventBody(member, contracts, physical, operation, provider, style
|
|
|
36935
37121
|
* видалення облікового запису) і режим обслуговування.
|
|
36936
37122
|
*/
|
|
36937
37123
|
function usersEventBody(users, contracts, physical, operation, attributeCase, provider) {
|
|
36938
|
-
const key = q$
|
|
36939
|
-
const invalid = q$
|
|
37124
|
+
const key = q$8(users.keyColumn);
|
|
37125
|
+
const invalid = q$8(users.invalidColumn);
|
|
36940
37126
|
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$
|
|
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) => {
|
|
36943
37129
|
const assignment = tableOf$2(physical, catalog.assignments.table);
|
|
36944
|
-
return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$
|
|
37130
|
+
return `EXISTS (SELECT 1 FROM ${ref(catalog.assignments.table)} a WHERE a.${q$8(column(assignment, R.subject, attributeCase))} = n.${key})`;
|
|
36945
37131
|
})] : [];
|
|
36946
37132
|
const update = operation === "UPDATE" ? [
|
|
36947
37133
|
`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 +37178,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
36992
37178
|
const name = tableName(table);
|
|
36993
37179
|
const fn = functionName(name, labels.truncate);
|
|
36994
37180
|
addFunction(fn, truncateBody(table), table.origin.objectId);
|
|
36995
|
-
add(`CREATE TRIGGER ${q$
|
|
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);
|
|
36996
37182
|
};
|
|
36997
37183
|
for (const { table, facts } of sources.sources) {
|
|
36998
37184
|
const name = tableName(table);
|
|
@@ -37009,7 +37195,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37009
37195
|
...t
|
|
37010
37196
|
}))
|
|
37011
37197
|
]);
|
|
37012
|
-
add(`CREATE TRIGGER ${q$
|
|
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);
|
|
37013
37199
|
}
|
|
37014
37200
|
for (const config of catalogTables(contracts, physical, attributeCase)) {
|
|
37015
37201
|
const table = tableName(config.table);
|
|
@@ -37034,7 +37220,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37034
37220
|
"DELETE"
|
|
37035
37221
|
]) {
|
|
37036
37222
|
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$
|
|
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);
|
|
37038
37224
|
}
|
|
37039
37225
|
addTruncate(config.table);
|
|
37040
37226
|
}
|
|
@@ -37051,7 +37237,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37051
37237
|
const fn = functionName(name, label);
|
|
37052
37238
|
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
37239
|
addFunction(fn, memberEventBody(member, contracts, physical, operation, provider, attributeCase), owner, [unitNode(COMMAND_FUNCTIONS.current), BUMP_NODE]);
|
|
37054
|
-
add(`CREATE TRIGGER ${q$
|
|
37240
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
|
|
37055
37241
|
}
|
|
37056
37242
|
addTruncate(table);
|
|
37057
37243
|
}
|
|
@@ -37065,7 +37251,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37065
37251
|
const fn = functionName(name, label);
|
|
37066
37252
|
const transition = operation === "INSERT" ? "REFERENCING NEW TABLE AS new_rows" : "REFERENCING OLD TABLE AS old_rows NEW TABLE AS new_rows";
|
|
37067
37253
|
addFunction(fn, usersEventBody(users, contracts, physical, operation, attributeCase, provider), owner, [unitNode(COMMAND_FUNCTIONS.current), ...operation === "UPDATE" ? [BUMP_NODE] : []]);
|
|
37068
|
-
add(`CREATE TRIGGER ${q$
|
|
37254
|
+
add(`CREATE TRIGGER ${q$8(triggerName(name, label))} AFTER ${operation} ON ${ref(name)} ${transition} FOR EACH STATEMENT EXECUTE FUNCTION ${ref(fn)}();`, owner);
|
|
37069
37255
|
}
|
|
37070
37256
|
addTruncate(table);
|
|
37071
37257
|
}
|
|
@@ -37099,7 +37285,7 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37099
37285
|
]) {
|
|
37100
37286
|
const label = `simetra_rights_relation_${operation.toLowerCase()}`;
|
|
37101
37287
|
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$
|
|
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);
|
|
37103
37289
|
}
|
|
37104
37290
|
addTruncate(table);
|
|
37105
37291
|
}
|
|
@@ -37133,17 +37319,17 @@ function buildRightsGuardUnits(contracts, physical, objects, attributeCase, prov
|
|
|
37133
37319
|
...INVITATIONS_TABLE
|
|
37134
37320
|
}]
|
|
37135
37321
|
]);
|
|
37136
|
-
add(`CREATE CONSTRAINT TRIGGER ${q$
|
|
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)}();`);
|
|
37137
37323
|
const markerCheck = platform("rights_tx_root_marker_check");
|
|
37138
37324
|
addFunction(markerCheck, rootMarkerBody(), void 0, [{
|
|
37139
37325
|
type: "table",
|
|
37140
37326
|
...ROOT_MARKER_TABLE
|
|
37141
37327
|
}]);
|
|
37142
|
-
add(`CREATE CONSTRAINT TRIGGER ${q$
|
|
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)}();`);
|
|
37143
37329
|
return units.sort((a, b) => compareStrings(a.identity, b.identity));
|
|
37144
37330
|
}
|
|
37145
37331
|
// src/compiler/rights/invitation-put-units.ts
|
|
37146
|
-
const q$
|
|
37332
|
+
const q$7 = quoteIdent;
|
|
37147
37333
|
/** Функція запису запрошення (спека запрошень §4, крок 3) — одна на проєкт. */
|
|
37148
37334
|
const INVITATION_PUT_FUNCTION = {
|
|
37149
37335
|
schema: PLATFORM_SCHEMA,
|
|
@@ -37154,6 +37340,11 @@ const PENDING_TABLE = {
|
|
|
37154
37340
|
schema: PLATFORM_SCHEMA,
|
|
37155
37341
|
name: "rights_tx_pending"
|
|
37156
37342
|
};
|
|
37343
|
+
/**
|
|
37344
|
+
* Сесія з claim `act` — агент від імені користувача (спека запрошень §4,
|
|
37345
|
+
* §5): одна умова для видачі й прийняття.
|
|
37346
|
+
*/
|
|
37347
|
+
const ACT_CLAIM_SQL = `coalesce(nullif(current_setting(${sqlLiteral(SESSION_CLAIMS_SETTING)}, true), '')::jsonb ? 'act', false)`;
|
|
37157
37348
|
/** Вид ключа черги перевірок прав видачі (спека запрошень §4, крок 4). */
|
|
37158
37349
|
const INVITATION_PENDING_KIND = "invitation";
|
|
37159
37350
|
function tableOf$1(physical, name) {
|
|
@@ -37167,6 +37358,15 @@ function scopeOf(table) {
|
|
|
37167
37358
|
return found.name;
|
|
37168
37359
|
}
|
|
37169
37360
|
/**
|
|
37361
|
+
* Живі призначення учасника `member` у скоупі `scope` (псевдонім `a`): одна
|
|
37362
|
+
* умова для набору видачі й замків кроку 5 прийняття — замок мусить тримати
|
|
37363
|
+
* рівно ті рядки, які читає звірка.
|
|
37364
|
+
*/
|
|
37365
|
+
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())}`;
|
|
37368
|
+
}
|
|
37369
|
+
/**
|
|
37170
37370
|
* Набір видачі (спека запрошень §4, крок 3): відсортований за id перелік
|
|
37171
37371
|
* живих призначень учасника `member` у скоупі `scope` — `{ id, version,
|
|
37172
37372
|
* customRole?: { id, version, deltas } }`. `deltas` — `sha256` канонічної
|
|
@@ -37179,27 +37379,44 @@ function issueSetSql(catalog, physical, style, member, scope) {
|
|
|
37179
37379
|
const assignments = tableOf$1(physical, catalog.assignments.table);
|
|
37180
37380
|
const roles = tableOf$1(physical, catalog.roles.table);
|
|
37181
37381
|
const delta = tableOf$1(physical, catalog.roles.delta);
|
|
37182
|
-
const col = (table, def) => q$
|
|
37382
|
+
const col = (table, def) => q$7(standardColumn(table, def, style).name);
|
|
37183
37383
|
const a = (def) => `a.${col(assignments, def)}`;
|
|
37184
37384
|
const c = (def) => `c.${col(roles, def)}`;
|
|
37185
37385
|
const d = (def) => `d.${col(delta, def)}`;
|
|
37186
37386
|
const R = RIGHTS_COLUMNS;
|
|
37187
37387
|
const KEY = keyColumn(false);
|
|
37188
37388
|
const VERSION = versionColumn();
|
|
37189
|
-
const assignmentScope = `a.${q$
|
|
37389
|
+
const assignmentScope = `a.${q$7(scopeOf(assignments))}`;
|
|
37190
37390
|
const deltas = [
|
|
37191
37391
|
`SELECT encode(sha256(convert_to(coalesce(jsonb_agg(to_jsonb(d) ORDER BY ${d(KEY)}), '[]'::jsonb)::text, 'UTF8')), 'hex')`,
|
|
37192
37392
|
`FROM ${qualified(catalog.roles.delta)} d`,
|
|
37193
|
-
`WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$
|
|
37393
|
+
`WHERE ${d(tabularParentColumn())} = ${a(R.customRole)} AND d.${q$7(scopeOf(delta))} = ${assignmentScope}`
|
|
37194
37394
|
].join(" ");
|
|
37195
37395
|
return [
|
|
37196
37396
|
`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
37397
|
`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 ${
|
|
37398
|
+
`LEFT JOIN ${qualified(catalog.roles.table)} c ON ${c(KEY)} = ${a(R.customRole)} AND c.${q$7(scopeOf(roles))} = ${assignmentScope}`,
|
|
37399
|
+
`WHERE ${liveAssignments(assignments, style, member, scope)}`
|
|
37200
37400
|
].join("\n");
|
|
37201
37401
|
}
|
|
37202
37402
|
/**
|
|
37403
|
+
* Замки кроку 5 прийняття (спека запрошень §5): живі призначення учасника
|
|
37404
|
+
* `member` у скоупі `scope` і рядки їхніх кастомних ролей `FOR SHARE` — та
|
|
37405
|
+
* сама множина, що в `issueSetSql`. Зміна призначення чи ролі командою (вона
|
|
37406
|
+
* бере рядок ролі `FOR NO KEY UPDATE`) чекає на COMMIT прийняття, тож набір,
|
|
37407
|
+
* звірений після замків, не зміниться до перевірки ⊆. Окремими операторами
|
|
37408
|
+
* до звірки: у `READ COMMITTED` новий оператор бачить рядок, на який чекав.
|
|
37409
|
+
*/
|
|
37410
|
+
function issueSetLocks(catalog, physical, style, member, scope) {
|
|
37411
|
+
const assignments = tableOf$1(physical, catalog.assignments.table);
|
|
37412
|
+
const roles = tableOf$1(physical, catalog.roles.table);
|
|
37413
|
+
const col = (table, def) => q$7(standardColumn(table, def, style).name);
|
|
37414
|
+
const a = (def) => `a.${col(assignments, def)}`;
|
|
37415
|
+
const R = RIGHTS_COLUMNS;
|
|
37416
|
+
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;`];
|
|
37418
|
+
}
|
|
37419
|
+
/**
|
|
37203
37420
|
* `simetra.invitation_put(p_member, p_hash)` (спека запрошень §4, кроки 2–4):
|
|
37204
37421
|
* єдиний писар записів запрошень на шляху видачі. `SECURITY DEFINER`, бо
|
|
37205
37422
|
* таблиці запрошень закриті для ролей застосунку; гілка на кожен вид — за
|
|
@@ -37229,14 +37446,14 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37229
37446
|
const m = kind.membership;
|
|
37230
37447
|
const id = uuidLiteral(kind.kindId);
|
|
37231
37448
|
const pending = [
|
|
37232
|
-
`m.${q$
|
|
37233
|
-
`m.${q$
|
|
37234
|
-
...m.deletion === void 0 ? [] : [`NOT m.${q$
|
|
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)}`]
|
|
37235
37452
|
].join(" AND ");
|
|
37236
37453
|
return [
|
|
37237
37454
|
`IF v_object = ${sqlLiteral(kind.kindLabel)} THEN`,
|
|
37238
37455
|
...[
|
|
37239
|
-
`SELECT m.${q$
|
|
37456
|
+
`SELECT m.${q$7(m.scope)} INTO v_scope FROM ${qualified(m.table)} m WHERE ${pending};`,
|
|
37240
37457
|
...ifRefuse("NOT FOUND"),
|
|
37241
37458
|
...ifRefuse(`NOT ${scopeAdministerRights(kind.assignmentsLabel, kind.kindId, "v_scope")}`),
|
|
37242
37459
|
...ifRefuse(`EXISTS (SELECT 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = p_member AND i.scope_kind_id <> ${id})`),
|
|
@@ -37267,7 +37484,7 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37267
37484
|
" v_expires timestamp with time zone;",
|
|
37268
37485
|
"BEGIN",
|
|
37269
37486
|
...[
|
|
37270
|
-
...ifRefuse(
|
|
37487
|
+
...ifRefuse(ACT_CLAIM_SQL, refusal(E.noRight)),
|
|
37271
37488
|
`SELECT c.action, c.object, c.root INTO v_action, v_object, v_root FROM ${qualified(COMMAND_FUNCTIONS.current)}() c;`,
|
|
37272
37489
|
`v_actor := ${CURRENT_USER$1};`,
|
|
37273
37490
|
...ifRefuse(`v_actor IS NULL OR v_action IS DISTINCT FROM 'update' OR v_root IS DISTINCT FROM p_member`),
|
|
@@ -37280,6 +37497,160 @@ function invitationPutFunction(kinds, contracts, physical, style) {
|
|
|
37280
37497
|
const tag = dollarTag$1(body);
|
|
37281
37498
|
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
37499
|
}
|
|
37500
|
+
// src/compiler/rights/invitation-accept-units.ts
|
|
37501
|
+
const q$6 = quoteIdent;
|
|
37502
|
+
/** Функція прийняття запрошення (спека запрошень §5) — одна на проєкт. */
|
|
37503
|
+
const INVITATION_ACCEPT_FUNCTION = {
|
|
37504
|
+
schema: PLATFORM_SCHEMA,
|
|
37505
|
+
name: "invitation_accept"
|
|
37506
|
+
};
|
|
37507
|
+
/**
|
|
37508
|
+
* Простір ключів advisory-замка спроб прийняття (`SIMI`): поруч із простором
|
|
37509
|
+
* ієрархії (`SIMH`) і замка застосування схеми (`SIME`), не перетинаючись
|
|
37510
|
+
* із ними, — інакше спроба прийняття чекала б на чуже.
|
|
37511
|
+
*/
|
|
37512
|
+
const INVITATION_LOCK_SPACE = 1397312841;
|
|
37513
|
+
/**
|
|
37514
|
+
* Внутрішній SQLSTATE повторної звірки після кроку 8: лише ним точка
|
|
37515
|
+
* збереження відкочує заповнення учасника; будь-яка інша помилка (зокрема
|
|
37516
|
+
* `rights-context`) виходить далі. Клас `SI` Postgres не вживає.
|
|
37517
|
+
*/
|
|
37518
|
+
const CHANGED_STATE = "SIACH";
|
|
37519
|
+
/** Походження рядка входу знімка, дописаного прийняттям (крок 9). */
|
|
37520
|
+
const INVITATION_PROVENANCE = "invitation";
|
|
37521
|
+
/**
|
|
37522
|
+
* `simetra.invitation_accept(p_hash bytea) RETURNS jsonb` (спека запрошень §5,
|
|
37523
|
+
* кроки 1–10) — названий виняток із ⊆ за зразком функції гранту творцю
|
|
37524
|
+
* (`root-creator-units.ts`). `SECURITY DEFINER`: таблиці запрошень закриті
|
|
37525
|
+
* для ролей застосунку, а запрошений ще не має прав у скоупі. `row_security =
|
|
37526
|
+
* off`: власник RLS обходить, а якби ні — пошук і звірка мовчки не побачили б
|
|
37527
|
+
* рядків; так вони падають гучно (fail-closed). Гілка на кожен вид — за видом
|
|
37528
|
+
* запису, без динамічного SQL.
|
|
37529
|
+
*
|
|
37530
|
+
* Відмови кроків 1–6 — значення, а не виняток: T3 фіксує транзакцію, і рядок
|
|
37531
|
+
* `failed` лишається (ліміт спроб рахує саме їх); `rate-limited` рядка не
|
|
37532
|
+
* пише, тож запити понад ліміт журнал не ростять. Виняток — лише
|
|
37533
|
+
* `rights-context`: транзакція з чужим чи наявним знімком не може дописати
|
|
37534
|
+
* входи знімка, і її треба відкотити.
|
|
37535
|
+
*/
|
|
37536
|
+
function invitationAcceptFunction(kinds, contracts, physical, style) {
|
|
37537
|
+
const context = refusal(COMMAND_CORE_ERRORS.forbidden.rightsContext);
|
|
37538
|
+
const ifRefuse = (condition) => [
|
|
37539
|
+
`IF ${condition} THEN`,
|
|
37540
|
+
` ${context}`,
|
|
37541
|
+
"END IF;"
|
|
37542
|
+
];
|
|
37543
|
+
const T = SNAPSHOT_TABLES;
|
|
37544
|
+
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);`;
|
|
37545
|
+
const answer = (outcome, reason) => `RETURN jsonb_build_object('outcome', ${sqlLiteral(outcome)}, 'reason', ${sqlLiteral(reason)});`;
|
|
37546
|
+
const failed = (reason, where) => [journal("failed", reason, where), answer("failed", reason)];
|
|
37547
|
+
const record = {
|
|
37548
|
+
kind: "v_kind",
|
|
37549
|
+
scope: "v_scope",
|
|
37550
|
+
member: "v_member"
|
|
37551
|
+
};
|
|
37552
|
+
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)`;
|
|
37553
|
+
const provenance = `t.xid = txid_current() AND t.provenance = ${sqlLiteral(INVITATION_PROVENANCE)}`;
|
|
37554
|
+
const branches = kinds.flatMap((kind) => {
|
|
37555
|
+
const m = kind.membership;
|
|
37556
|
+
const id = uuidLiteral(kind.kindId);
|
|
37557
|
+
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)}`]
|
|
37562
|
+
].join(" AND ");
|
|
37563
|
+
const gone = `DELETE FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.member = v_member AND i.scope_kind_id = ${id};`;
|
|
37564
|
+
const changed = `(${issueSetSql(kind.catalog, physical, style, "v_member", "v_scope")}) IS DISTINCT FROM v_assignments`;
|
|
37565
|
+
const inputs = issueInputs(contracts, kind.catalog, physical, style, "ARRAY(SELECT (e.value ->> 'id')::uuid FROM jsonb_array_elements(v_assignments) e)");
|
|
37566
|
+
return [
|
|
37567
|
+
`IF v_kind = ${id} THEN`,
|
|
37568
|
+
...[
|
|
37569
|
+
`PERFORM 1 FROM ${qualified(m.table)} m WHERE ${pending} FOR UPDATE;`,
|
|
37570
|
+
"IF NOT FOUND THEN",
|
|
37571
|
+
` ${gone}`,
|
|
37572
|
+
...failed("member-gone", record).map((l) => ` ${l}`),
|
|
37573
|
+
"END IF;",
|
|
37574
|
+
`PERFORM 1 FROM ${qualified(INVITATIONS_TABLE)} i WHERE i.secret_hash = p_hash FOR UPDATE;`,
|
|
37575
|
+
"IF NOT FOUND THEN",
|
|
37576
|
+
...failed("unknown", null).map((l) => ` ${l}`),
|
|
37577
|
+
"END IF;",
|
|
37578
|
+
...issueSetLocks(kind.catalog, physical, style, "v_member", "v_scope"),
|
|
37579
|
+
`IF ${changed} THEN`,
|
|
37580
|
+
` ${gone}`,
|
|
37581
|
+
...failed("changed", record).map((l) => ` ${l}`),
|
|
37582
|
+
"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`,
|
|
37584
|
+
...failed("already-member", record).map((l) => ` ${l}`),
|
|
37585
|
+
"END IF;",
|
|
37586
|
+
`v_context := current_setting(${sqlLiteral(COMMAND_SETTING)}, true);`,
|
|
37587
|
+
"BEGIN",
|
|
37588
|
+
...[
|
|
37589
|
+
`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;`,
|
|
37591
|
+
...ifRefuse(`${header("rights")} OR ${header("scopes")}`),
|
|
37592
|
+
`IF ${changed} THEN`,
|
|
37593
|
+
` RAISE EXCEPTION USING ERRCODE = '${CHANGED_STATE}';`,
|
|
37594
|
+
"END IF;"
|
|
37595
|
+
].map((line) => ` ${line}`),
|
|
37596
|
+
`EXCEPTION WHEN SQLSTATE '${CHANGED_STATE}' THEN`,
|
|
37597
|
+
` ${gone}`,
|
|
37598
|
+
...failed("changed", record).map((l) => ` ${l}`),
|
|
37599
|
+
"END;",
|
|
37600
|
+
`INSERT INTO ${qualified(T.typed)} (xid, ${inputColumns("typed")}, provenance, assignment)`,
|
|
37601
|
+
`SELECT txid_current(), ${inputColumns("typed", "t")}, ${sqlLiteral(INVITATION_PROVENANCE)}, t.assignment FROM (${inputs.typed}) t;`,
|
|
37602
|
+
`INSERT INTO ${qualified(T.containers)} (xid, ${inputColumns("containers")})`,
|
|
37603
|
+
`SELECT txid_current(), ${inputColumns("containers", "k")} FROM (${inputs.containers}) k`,
|
|
37604
|
+
`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);`,
|
|
37605
|
+
`INSERT INTO ${qualified(T.deltas)} (xid, ${inputColumns("deltas")})`,
|
|
37606
|
+
`SELECT txid_current(), ${inputColumns("deltas", "d")} FROM (${inputs.deltas}) d`,
|
|
37607
|
+
`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);`,
|
|
37608
|
+
`INSERT INTO ${qualified(T.holders)} (xid, level, level_id, scope)`,
|
|
37609
|
+
`SELECT txid_current(), h.level, h.level_id, h.scope FROM (${inputs.holders}) h;`,
|
|
37610
|
+
`INSERT INTO ${qualified(T.scopes)} (xid, scope_kind_id, scope, member, catalog) VALUES (txid_current(), ${id}, v_scope, v_member, true);`,
|
|
37611
|
+
gone,
|
|
37612
|
+
journal("accepted", null, record),
|
|
37613
|
+
`PERFORM set_config(${sqlLiteral(COMMAND_SETTING)}, v_context, true);`,
|
|
37614
|
+
"RETURN jsonb_build_object('outcome', 'accepted', 'scopeKind', v_kind, 'scope', v_scope, 'member', v_member);"
|
|
37615
|
+
].map((line) => ` ${line}`),
|
|
37616
|
+
"END IF;"
|
|
37617
|
+
];
|
|
37618
|
+
});
|
|
37619
|
+
const body = [
|
|
37620
|
+
"DECLARE",
|
|
37621
|
+
" v_actor uuid;",
|
|
37622
|
+
" v_member uuid;",
|
|
37623
|
+
" v_kind uuid;",
|
|
37624
|
+
" v_scope uuid;",
|
|
37625
|
+
" v_assignments jsonb;",
|
|
37626
|
+
" v_expires timestamp with time zone;",
|
|
37627
|
+
" v_context text;",
|
|
37628
|
+
"BEGIN",
|
|
37629
|
+
...[
|
|
37630
|
+
`v_actor := ${CURRENT_USER$1};`,
|
|
37631
|
+
`IF v_actor IS NULL OR ${ACT_CLAIM_SQL} THEN`,
|
|
37632
|
+
...failed("actor", null).map((l) => ` ${l}`),
|
|
37633
|
+
"END IF;",
|
|
37634
|
+
...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())`),
|
|
37635
|
+
`PERFORM pg_advisory_xact_lock(${INVITATION_LOCK_SPACE}, hashtext(v_actor::text));`,
|
|
37636
|
+
`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`,
|
|
37637
|
+
` ${answer("rate-limited", "rate-limited")}`,
|
|
37638
|
+
"END IF;",
|
|
37639
|
+
`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;`,
|
|
37640
|
+
"IF NOT FOUND THEN",
|
|
37641
|
+
...failed("unknown", null).map((l) => ` ${l}`),
|
|
37642
|
+
"END IF;",
|
|
37643
|
+
"IF v_expires <= now() THEN",
|
|
37644
|
+
...failed("expired", record).map((l) => ` ${l}`),
|
|
37645
|
+
"END IF;",
|
|
37646
|
+
...branches,
|
|
37647
|
+
context
|
|
37648
|
+
].map((line) => ` ${line}`),
|
|
37649
|
+
"END"
|
|
37650
|
+
].join("\n");
|
|
37651
|
+
const tag = dollarTag$1(body);
|
|
37652
|
+
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
|
+
}
|
|
37283
37654
|
// src/compiler/rights/root-creator-units.ts
|
|
37284
37655
|
const q$5 = quoteIdent;
|
|
37285
37656
|
/**
|
|
@@ -37573,10 +37944,14 @@ function buildCatalogCommandUnits(input) {
|
|
|
37573
37944
|
...requires === void 0 ? {} : { requires }
|
|
37574
37945
|
});
|
|
37575
37946
|
const sql = invitationPutFunction(invitations.map((i) => i.facts), contracts, input.physical, input.attributeCase);
|
|
37947
|
+
const accept = invitationAcceptFunction(invitations.map((i) => i.facts), contracts, input.physical, input.attributeCase);
|
|
37576
37948
|
units.push(put(sql, bodyRequires(sql, {
|
|
37577
37949
|
...input,
|
|
37578
37950
|
units: input.units
|
|
37579
|
-
})), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant))
|
|
37951
|
+
})), ...executeGrants(`${relation$1(INVITATION_PUT_FUNCTION)}(uuid, bytea)`, ["command"], provider).map((grant) => put(grant)), put(accept, bodyRequires(accept, {
|
|
37952
|
+
...input,
|
|
37953
|
+
units: input.units
|
|
37954
|
+
})), ...executeGrants(`${relation$1(INVITATION_ACCEPT_FUNCTION)}(bytea)`, ["command"], provider).map((grant) => put(grant)));
|
|
37580
37955
|
}
|
|
37581
37956
|
const known = [...input.units, ...units];
|
|
37582
37957
|
const signalModel = {
|
|
@@ -42004,7 +42379,7 @@ async function runStages(stage1, options = {}) {
|
|
|
42004
42379
|
ok: !hasErrors(staged),
|
|
42005
42380
|
diagnostics: staged
|
|
42006
42381
|
};
|
|
42007
|
-
const rights = rightsContracts(stage1.objects, stage2.references, physical, stage1.project);
|
|
42382
|
+
const rights = rightsContracts(stage1.objects, stage2.references, physical, stage1.project, stage3.bindings);
|
|
42008
42383
|
const roles = roleContracts(stage1.objects, stage2.references);
|
|
42009
42384
|
const projection = rightsProjection(stage1.objects, stage2.references, rights, roles, stage1.project);
|
|
42010
42385
|
if (projection.diagnostics.length > 0) return {
|
|
@@ -42389,7 +42764,7 @@ async function runStages(stage1, options = {}) {
|
|
|
42389
42764
|
carriers: (unit) => `the carrier copies of ${name(unit.ownerObjectId)}`,
|
|
42390
42765
|
command: (unit) => `the command context function ${unit.name}`,
|
|
42391
42766
|
effects: (unit) => `the action effects check of ${name(unit.ownerObjectId)}`,
|
|
42392
|
-
catalogCommand: (unit) => unit.ownerObjectId === void 0 ?
|
|
42767
|
+
catalogCommand: (unit) => unit.ownerObjectId === void 0 ? `the invitation function ${unit.name}` : `the command core of ${name(unit.ownerObjectId)}`,
|
|
42393
42768
|
schemaUsage: (unit) => `the USAGE grant on schema ${unit.name}`,
|
|
42394
42769
|
signalOutbox: () => "the signal outbox of the platform",
|
|
42395
42770
|
storage: (unit) => unit.ownerObjectId === void 0 ? `the file storage object ${unit.name}` : `the file storage of ${name(unit.ownerObjectId)}`,
|
|
@@ -42480,7 +42855,7 @@ function metadataRights(files) {
|
|
|
42480
42855
|
if (stage1.project === void 0 || hasErrors([...stage1.diagnostics, ...stage2.diagnostics])) return void 0;
|
|
42481
42856
|
try {
|
|
42482
42857
|
const stage3 = buildModel(stage1.objects, stage1.project, stage2.references);
|
|
42483
|
-
const rights = rightsContracts(stage1.objects, stage2.references, stage3.physical, stage1.project);
|
|
42858
|
+
const rights = rightsContracts(stage1.objects, stage2.references, stage3.physical, stage1.project, stage3.bindings);
|
|
42484
42859
|
return {
|
|
42485
42860
|
objects: stage1.objects.flatMap((o) => o.id === void 0 ? [] : [{
|
|
42486
42861
|
id: o.id,
|