Skip to content

Commit 7dd1a2f

Browse files
fix(objectql): a system-door delete of a record with no organization keeps it in the recycle bin (#36097)
repo:objectstack#7 · os-tesla · session_01L9qibwJEh7hMPPvagWM1g7 Fixes #35667 Clause-②: no Metadata-protocol: none Clause-② basis: no (the seat's reading, from L1 O1 7063276615). Under a walled posture, a system-door delete of an org-less record is now refused with `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`. That is not a narrowed accept set. Every SQL store already refused that delete on the bin's NOT NULL. The memory store accepted it only by writing a bin entry no organization owns, which breaks the bin's own invariant (ADR-0148 D1, ADR-0131 D1): no organization's listing or cascade reaches it. The fix makes every store answer as D9 states, so it is a bug fix, not a `(narrowing)`. ## 维护者速读 - 用户能看到什么变化:流程、钩子或管理工具以系统身份删除一条不归属任何组织的记录时,记录会进入回收站并可恢复,不再报数据库错误;多组织隔离模式下则明确拒绝并说明原因。 - 为什么做:回收站功能的修复,替以系统身份删除全局记录的流程和管理工具解决删除失败的问题。 - 出错会怎样:最坏情况是系统身份删除被拒绝而记录原样保留,不会丢数据;撤回本次改动即恢复原状。 - 要你做什么:无。 ## What changes A delete under `{ isSystem: true }` of a record that names no organization (a record of a `tenancy: { enabled: false }` object) wrote its recycle-bin entry with no organization. On SQL the delete failed with `NOT NULL constraint failed: sys_recycle_bin.organization_id` and the record stayed. On a store that enforces no NOT NULL, the delete succeeded and left an entry that no organization owned. The entry is a row of a tenant-column object (ADR-0148 D1). It now takes the organization any system insert takes (ADR-0131 D9): the record's own, else the context's, else the engine's one system-insert resolver. Under `single` that resolver answers the Default Organization. Under a wall it refuses with `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` before the root row is removed. Route B of the seat's routing call (claim amendment 7062354282, analysis 7062338699): `packages/objectql/src/engine.ts` gains no line and `scripts/facade-delegation-registry.json` is untouched. - `packages/objectql/src/engine-delete-and-aggregate.ts`: the delete module already holds the engine and already reads a sibling facet's host through it (`securityResolversHost.of(this.facade)`). It hands the capture's `write()` a call to `MiddlewareAndContextFacet.resolveSystemInsertOrganization` through `middlewareAndContextHost.of(this.facade)`. That is the same body the engine's insert calls, not a second spelling of it. - `packages/objectql/src/recycle-bin/capture.ts`: `write(resolveSystemInsertOrganization)` stamps the resolver's answer when neither the record nor the context names an organization. A new exported type `RecycleBinSystemInsertOrganization` states the contract and why it arrives as an argument and not as a `RecycleBinCaptureHost` member. - Pins: - `packages/runtime/src/recycle-bin-orgless-system-delete.test.ts`: a real `ObjectQL` on a real `SqlDriver` (better-sqlite3), the bin as platform-objects declares it, and the Default Organization. - A top-level describe in `packages/objectql/src/recycle-bin/capture.test.ts`, the shared capture harness, for the store that enforces no NOT NULL. - A `patch` changeset for `@objectstack/objectql`. ### Files to read first 1. `packages/objectql/src/recycle-bin/capture.ts`, the `write()` hunk: the order is record, then context, then resolver, and a refusal throws before `driver.create`. 2. `packages/objectql/src/engine-delete-and-aggregate.ts`, the `bin?.write(...)` call: the cross-facet host read. 3. `packages/objectql/src/recycle-bin/capture.test.ts`, the `makeEngine` Default Organization seed: fixture triage, see Acceptance notes. ### Two-minute check Run `pnpm --filter @objectstack/runtime exec vitest run --project local src/recycle-bin-orgless-system-delete.test.ts` after building objectql. Expect 3 passed: under `single` the entry's `organization_id` is `org_default` and restore brings the record back; a context-named organization is kept; under `isolated` the delete is refused with `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` and the record stays. ## Tests All readings are on head 4bd70f0 unless noted. <details><summary>Measurement before the fix (main 8145424, scratch test, not committed)</summary> - sqlite: the system-door delete threw `SQLITE_CONSTRAINT_NOTNULL`, `NOT NULL constraint failed: sys_recycle_bin.organization_id`, and no entry was written. A beforeDelete hook saw session `{ isSystem: true }` and no `tenantId`. - memory store: the delete answered `true`, and the bin held `{ object_name: mz_global, organization_id: null }`. - Control on sqlite: a tenant-column record written by a system insert was stamped `org_default` (D9), and its delete kept the entry under `org_default`. </details> <details><summary>Gate before building (route B premises)</summary> - `pnpm check:facade-delegation-only` exited 0 and printed `packages/objectql/src/engine.ts: 6857 lines, ceiling 6857 (0 left; ruling 7051956587)`. `wc -l packages/objectql/src/engine.ts` reads 6857. - `pnpm --filter @objectstack/objectql typecheck` (`tsc --noEmit && pnpm check:test-typecheck`) passed under lock VERDICT command-exit 0 with the cross-facet call in place. </details> <details><summary>Pins, ablation and package suites</summary> - Runtime pin (sqlite): Tests 3 passed (3). - Capture harness: Tests 30 passed (30). The `src/recycle-bin/` directory: Test Files 5 passed, Tests 178 passed. - Ablation on head 4bd70f0: - The mutation went through `scripts/ablation-replace.mjs`, replacing the resolver call with `const derived: string | undefined = undefined;`. Anchor count went 1 to 0, and the blob went d124655 to 79309b11f005. - objectql was rebuilt, and `ablation-dist-preflight --absent` confirmed the marker was absent from all 14 built files. - Results with the mutation: the runtime pin had 2 failed and 1 passed (the context control). The capture harness had 2 failed and 28 passed. - Restore: `git checkout HEAD --`, then `git diff HEAD` was 0 bytes and the hash matched d124655. objectql was rebuilt, the preflight found the marker present in 2 built files, and the tree was clean. - After the restore the runtime pin had 3 passed and the capture harness 30 passed. - `pnpm --filter @objectstack/objectql test`: Test Files 624 passed (624), Tests 14217 passed (14217). `pnpm --filter @objectstack/objectql typecheck` passed. Lock VERDICT command-exit 0. - Consumers that compose the bin and delete without a booted auth (`mcp` stdio-data-bridge.recycle-bin, `cloud-connection` connection-credential-ledger, `metadata-protocol` seed-tenancy-backfill, `runtime` sandbox body-runner): 5, 11, 58 and 42 tests passed. Lock VERDICT command-exit 0. - Not run locally, left to CI: `pnpm --filter @objectstack/runtime typecheck`, which needs the runtime dependency closure built, and `test:repo`. </details> ## Verification <details><summary>Gate families</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 66 families on 4bd70f0, and all 66 exited 0. `--ran` reconciliation: 66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN. On the earlier head e95ae7d, `check:driver-memory-census` was red because the first runtime pin imported `@objectstack/driver-memory`. Head 4bd70f0 moved that leg into the capture harness, and the census is green there. `overlap-check` returned a clean verdict before each push: origin/main merges cleanly, and so does #36060, which shares `engine-delete-and-aggregate.ts`. </details> ## Acceptance notes - **Deviation from the dispatch: the memory leg is not on `@objectstack/driver-memory`.** A new test consumer of that driver is a ruled disposition. `check:driver-memory-census` printed: "LEDGERED: … binds @objectstack/driver-memory (import) and the ledger does not cover it … Rule it, migrate it, or file it". So the store that enforces no NOT NULL is pinned in the capture harness, which keeps rows the way `driver-memory` does. That harness is the shared harness file for this component. - **Fixture triage (adds a missing declaration).** The capture harness registered `sys_organization` but held no organization. Under `single` that is the broken boot invariant D9 refuses. Ten existing capture tests deleted org-less records with org-less contexts there and went red on `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`. The harness now seeds the Default Organization. The one test whose deletes all name their organization (the organization-delete cascade) opts out, so it still counts only its own two organizations. - **Walled posture.** A system-door delete with no `tenantId` of a tenancy-disabled record is refused with `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` (500) and the record stays. The seat accepted this as D9 as written. A caller that needs it threads `tenantId` on the context. - **MongoDB.** `MongoDBDriver` does not stamp the tenant column on insert, by its own docblock (`packages/drivers/driver-mongodb/src/mongodb-driver.ts`, the single-tenant note). A tenant-column row it writes therefore carries no `organization_id`. No test here reproduces that; this is a code read only, and on the seat's word it is noted here and not filed. The capture change covers the system-door delete of such a row under `single`. --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7)_ <!-- signed: repo:objectstack#7 · os-tesla · session_01L9qibwJEh7hMPPvagWM1g7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3ae62ac commit 7dd1a2f

5 files changed

Lines changed: 241 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a system-context delete of a record with no organization now keeps it in the recycle bin instead of failing on `sys_recycle_bin.organization_id`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A delete made under `{ isSystem: true }` (the context flows, hooks and admin tooling use) of a record that names no organization, such as a record of a `tenancy: { enabled: false }` object, wrote its recycle-bin entry with no organization. On a SQL store, where the bin's tenant column is NOT NULL, the delete failed with `NOT NULL constraint failed: sys_recycle_bin.organization_id` and the record stayed. On the memory store the delete succeeded but left an entry no organization owned.
11+
12+
The entry now takes the organization any system-context insert takes (ADR-0131 D9): the record's own, else the context's, else the organization the engine derives. Under the `single` posture that is the Default Organization, so the record lands in the bin and can be restored. Under a walled posture (`isolated`, `group`), where no owner can be derived, the delete is refused with `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` before the record is removed, as a system insert is. A caller that deletes there passes the organization on the context (`{ isSystem: true, tenantId: '...' }`).

‎packages/objectql/src/engine-delete-and-aggregate.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ import type { InternalFieldEvaluationOptions, InternalFieldEvaluationQuery } fro
4141
import { assertFilterIsMaterializable, assertListComparandShapes, collectComposableReadableIds, invalidFilterError } from './filter-comparand-shape.js';
4242
// [ADR-0155 D4] The fixed-read leaf seam reads the engine through the security
4343
// resolvers' host, built once per engine, which carries every member it reads.
44-
import { securityResolversHost } from './engine-facet-hosts.js';
44+
import { middlewareAndContextHost, securityResolversHost } from './engine-facet-hosts.js';
45+
import { MiddlewareAndContextFacet } from './engine-middleware-and-context.js';
4546
import { atFixedReadLeafDoor, passFixedReadLeaves } from './fixed-read-leaf-seam.js';
4647
import { assertHavingTemporalComparandsInterpretable, assertTemporalComparandsInterpretable } from './temporal-comparand-door.js';
4748
import { assertTextOperatorTargetsAreStringCapable } from './text-operator-declared-type-door.js';
@@ -687,7 +688,13 @@ export class DeleteAndAggregateFacet {
687688
const bin = this.openRecycleBinCapture(object, hookContext.input.id as string | number, writeContext, options?.multi === true || permanent);
688689
await this.cascadeDeleteRelations(object, [hookContext.input.id as string | number], writeContext, 0, bin?.onCollected)
689690
.catch((e: unknown) => { throw cascadeStoppedRefusal(e, object); });
690-
const entry = await bin?.write();
691+
// [ADR-0131 D9] The entry's organization, when neither the record
692+
// nor the context names one, is the engine's own system-insert
693+
// answer: the one resolver body, reached through the middleware
694+
// facet's host of this engine (`capture.ts`,
695+
// `RecycleBinSystemInsertOrganization`, says why it is handed in).
696+
const entry = await bin?.write((...a) =>
697+
MiddlewareAndContextFacet.resolveSystemInsertOrganization.call(middlewareAndContextHost.of(this.facade), ...a));
691698
let removed: Awaited<ReturnType<typeof driver.delete>>;
692699
try {
693700
removed = await driver.delete(

‎packages/objectql/src/recycle-bin/capture.test.ts‎

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,16 +217,28 @@ const ephemeral = {
217217
};
218218
/** Nothing references it: the plain, non-cascading delete. */
219219
const loner = { name: 'loner', label: 'Loner', fields: { id: text('id'), name: text('name') } };
220+
/** A platform-global business object: no tenant column, so its records name no organization (ADR-0066). */
221+
const globalNote = { name: 'global_note', label: 'Global note', tenancy: { enabled: false }, fields: { id: text('id'), title: text('title') } };
220222

221-
async function makeEngine(options: { withBin?: boolean; transactional?: boolean; failDeleteOf?: string; removesNothingOf?: { object: string; answer: boolean | number } } = {}) {
223+
/**
224+
* The Default Organization the `single` posture holds from boot (ADR-0131 D3).
225+
* A delete whose record and context name no organization stamps its entry with
226+
* it, as any system insert is stamped (ADR-0131 D9); a composition that
227+
* registers `sys_organization` and holds none is the broken boot invariant D9
228+
* refuses, never a shape an entry can land in.
229+
*/
230+
const DEFAULT_ORG = 'org_default';
231+
232+
async function makeEngine(options: { withBin?: boolean; transactional?: boolean; failDeleteOf?: string; removesNothingOf?: { object: string; answer: boolean | number }; defaultOrganization?: boolean } = {}) {
222233
const rec = recordingLogger();
223234
const engine = new ObjectQL({ logger: rec.logger } as any);
224235
const driver = makeDriver(options);
225236
engine.registerDriver(driver, true);
226237
await engine.init();
227-
const objects: any[] = [account, contact, note, task, sysThing, cloudThing, aiThing, organization, ephemeral, loner];
238+
const objects: any[] = [account, contact, note, task, sysThing, cloudThing, aiThing, organization, ephemeral, loner, globalNote];
228239
if (options.withBin !== false) objects.push(bin);
229240
for (const o of objects) engine.registry.registerObject(o as any, '__test__');
241+
if (options.defaultOrganization !== false) driver.seed('sys_organization', { id: DEFAULT_ORG, name: 'Default' });
230242
return { engine, driver, rec };
231243
}
232244

@@ -532,7 +544,8 @@ describe('the TTL sweep reaps an entry once its stamped deadline has passed (D3)
532544

533545
describe("an organization's delete takes its entries with it (ruling Q4)", () => {
534546
it('removes the entries of that organization, is not refused by them, and leaves other organizations\' entries', async () => {
535-
const { engine, driver } = await makeEngine();
547+
// Every delete here names its organization on the context.
548+
const { engine, driver } = await makeEngine({ defaultOrganization: false });
536549
driver.seed('sys_organization', { id: 'org_1', name: 'One' });
537550
driver.seed('sys_organization', { id: 'org_2', name: 'Two' });
538551
driver.seed('loner', { id: 'l1', name: 'one' });
@@ -599,3 +612,48 @@ describe('cascadeMembersInOrder', () => {
599612
.toEqual(['a/1', 'b/2', 'b/3', 'c/4', 'd/5']);
600613
});
601614
});
615+
616+
/**
617+
* [ADR-0131 D9, ADR-0148 D1] A system-door delete of a record that names no
618+
* organization, on a store that enforces no NOT NULL (this harness keeps rows
619+
* the way `driver-memory` does). Measured before the fix: the delete answered
620+
* true and wrote the entry with no organization at all. The entry is a row of
621+
* a tenant-column object, so it takes the organization any system insert
622+
* takes: the Default Organization under `single`, a refusal under a wall. The
623+
* SQL half, where the bin's NOT NULL column used to fail the delete, is pinned
624+
* in `packages/runtime/src/recycle-bin-orgless-system-delete.test.ts`.
625+
*/
626+
describe('a system-door delete of a record that names no organization (ADR-0131 D9)', () => {
627+
const SYSTEM = { context: { isSystem: true } } as any;
628+
629+
it('under single: answers true, the entry carries the Default Organization, and restore brings the record back', async () => {
630+
const { engine, driver } = await makeEngine();
631+
driver.seed('global_note', { id: 'g1', title: 'kept' });
632+
633+
expect(await engine.delete('global_note', { where: { id: 'g1' }, ...SYSTEM })).toBe(true);
634+
635+
expect(driver.rowsOf('global_note')).toHaveLength(0);
636+
const entries = entriesOf(driver);
637+
expect(entries).toHaveLength(1);
638+
expect(entries[0]).toMatchObject({ object_name: 'global_note', record_id: 'g1', organization_id: DEFAULT_ORG });
639+
640+
await engine.restore(String(entries[0].id), SYSTEM);
641+
expect(driver.rowsOf('global_note')).toMatchObject([{ id: 'g1', title: 'kept' }]);
642+
expect(entriesOf(driver)).toHaveLength(0);
643+
});
644+
645+
it('under a wall: refused with ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED before the record is removed, and no entry stays', async () => {
646+
const { engine, driver } = await makeEngine();
647+
engine.setTenancyPostureProvider(() => 'isolated');
648+
driver.seed('global_note', { id: 'g1', title: 'kept' });
649+
650+
const refusal = await engine.delete('global_note', { where: { id: 'g1' }, ...SYSTEM }).then(
651+
() => undefined,
652+
(e: unknown) => e as { code?: unknown; status?: unknown },
653+
);
654+
655+
expect(refusal).toMatchObject({ code: 'ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED', status: 500 });
656+
expect(driver.rowsOf('global_note')).toMatchObject([{ id: 'g1', title: 'kept' }]);
657+
expect(entriesOf(driver)).toHaveLength(0);
658+
});
659+
});

‎packages/objectql/src/recycle-bin/capture.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,29 @@ const MISSING_BIN_NOTICE = 'missing-bin';
9292
/** How many ids one snapshot read names: the cascade walk's own `$in` batch. */
9393
const SNAPSHOT_READ_BATCH = 500;
9494

95+
/**
96+
* The engine's system-insert organization resolver
97+
* (`MiddlewareAndContextFacet.resolveSystemInsertOrganization`, ADR-0131 D9):
98+
* the organization an insert on `object` that carries none is stamped with,
99+
* `undefined` when the context or every row already carries one (or the
100+
* object has no tenant column, or the composition registers no organization
101+
* object), and a thrown `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` where no
102+
* owner is derivable.
103+
*
104+
* Handed to {@link RecycleBinCapture.write} by the delete path, which holds
105+
* the engine and reaches the body through the middleware facet's host, rather
106+
* than read off {@link RecycleBinCaptureHost}: that host is built in
107+
* `engine.ts`, which is at its facade line ceiling
108+
* (`scripts/facade-delegation-registry.json`), and the ceiling's remedy is
109+
* new wiring in the module beside it. It is the same body the engine's own
110+
* insert calls, ⛔ never a second spelling of the D9 decision.
111+
*/
112+
export type RecycleBinSystemInsertOrganization = (
113+
object: string,
114+
execCtx: ExecutionContext | undefined,
115+
rows: readonly Record<string, unknown>[],
116+
) => Promise<string | undefined>;
117+
95118
/** The engine members the capture reads. */
96119
export interface RecycleBinCaptureHost {
97120
readonly _registry: { getObject(name: string): unknown };
@@ -238,8 +261,15 @@ export class RecycleBinCapture {
238261
* Write the entry, after the walk and before the root row is removed.
239262
* `undefined` when there is nothing to keep: the root row was not there to
240263
* read (the delete removes nothing), or the set was never handed over.
264+
*
265+
* `resolveSystemInsertOrganization` is the engine's one ADR-0131 D9
266+
* resolver, handed in by the delete path (see
267+
* {@link RecycleBinSystemInsertOrganization} for why it is an argument and
268+
* not a host member). It answers the entry's organization when neither the
269+
* record nor the context names one, and its refusal throws from here,
270+
* before the root row is removed, so the delete is refused with it.
241271
*/
242-
async write(): Promise<RecycleBinWrittenEntry | undefined> {
272+
async write(resolveSystemInsertOrganization: RecycleBinSystemInsertOrganization): Promise<RecycleBinWrittenEntry | undefined> {
243273
const rows = this.rows;
244274
if (!rows || rows.length === 0 || rows[0].object !== this.object || rows[0].id !== this.id) {
245275
if (!this.set) {
@@ -267,6 +297,21 @@ export class RecycleBinCapture {
267297
});
268298
const row: Record<string, unknown> = { ...entry };
269299
if (organizationId !== undefined) row.organization_id = organizationId;
300+
else {
301+
// [ADR-0131 D9, ADR-0148 D1] Neither the record nor the context names an
302+
// organization: a record of an object with no tenant column (a
303+
// `tenancy: { enabled: false }` object) deleted through the system door,
304+
// or a tenant-column row its driver left unstamped. The entry is a row of
305+
// a tenant-column object all the same, so it takes the organization any
306+
// system insert would: derived under `single`, refused under a wall or
307+
// with no derivable owner (`ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED`),
308+
// left unstamped only in a composition that registers no organization
309+
// object (the D9 lean-embedding note). ⛔ Never NULL by omission: that
310+
// wrote a NULL-organization entry on a store that enforces no NOT NULL,
311+
// and failed the delete on the bin's constraint on one that does.
312+
const derived = await resolveSystemInsertOrganization(RECYCLE_BIN_OBJECT, this.context, [row]);
313+
if (derived !== undefined) row.organization_id = derived;
314+
}
270315
const driver = this.host.getDriver(RECYCLE_BIN_OBJECT);
271316
const options = this.host.buildDriverOptions(RECYCLE_BIN_OBJECT, this.context);
272317
const written = (await driver.create(RECYCLE_BIN_OBJECT, row, options)) as { id?: unknown } | null;
@@ -324,7 +369,8 @@ export class RecycleBinCapture {
324369

325370
/**
326371
* The organization that owns the entry: the root row's own, read off its
327-
* tenant column, else the deleting context's. An entry belongs to the
372+
* tenant column, else the deleting context's; with neither, `write()`
373+
* asks the D9 resolver. An entry belongs to the
328374
* organization whose record it holds, so the organization's delete removes
329375
* it (the bin's tenant column cascades) and its listing is that
330376
* organization's.
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A system-door delete of a record that carries no organization keeps it in
5+
* the recycle bin under the organization ADR-0131 D9 answers, on a SQL store.
6+
* The store that enforces no NOT NULL is pinned in objectql's capture harness
7+
* (`packages/objectql/src/recycle-bin/capture.test.ts`), which keeps rows the
8+
* way `driver-memory` does; a new test consumer of `driver-memory` itself is
9+
* a ruled disposition (`check:driver-memory-census`), not one this pin takes.
10+
*
11+
* ## The reading this pins
12+
*
13+
* Measured before the fix (the same composition as below): a delete through
14+
* `{ isSystem: true }`, the context flows, hooks and admin tooling carry, of a
15+
* record of a `tenancy: { enabled: false }` object failed on SQLite with
16+
* `NOT NULL constraint failed: sys_recycle_bin.organization_id` and left the
17+
* record in place. The record names no organization and the context names
18+
* none, and the capture wrote its entry raw with neither.
19+
*
20+
* The entry is a row of a tenant-column object (ADR-0148 D1), so it takes the
21+
* organization any system insert takes (ADR-0131 D9): the Default
22+
* Organization under `single`, and a loud
23+
* `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` refusal under a wall, before the
24+
* record is removed.
25+
*
26+
* ## What is real here
27+
*
28+
* A real `ObjectQL` over a real `SqlDriver` on better-sqlite3 (which creates
29+
* the bin's tenant column NOT NULL), the bin as
30+
* `@objectstack/platform-objects` declares it, and the Default Organization
31+
* the `single` posture holds (`installDefaultOrganization`). Codes, statuses,
32+
* ids and organizations are asserted, never wording.
33+
*/
34+
35+
import { describe, it, expect } from 'vitest';
36+
import { ObjectQL } from '@objectstack/objectql';
37+
import { SqlDriver } from '@objectstack/driver-sql';
38+
import { SysRecycleBin } from '@objectstack/platform-objects/system';
39+
import { RECYCLE_BIN_OBJECT } from '@objectstack/spec/data';
40+
import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js';
41+
42+
const GLOBAL = 'rbo_global_note';
43+
const SYSTEM = { context: { isSystem: true } } as const;
44+
45+
async function boot(posture: 'single' | 'isolated') {
46+
const engine = new ObjectQL();
47+
engine.registerDriver(
48+
new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never,
49+
true,
50+
);
51+
engine.setTenancyPostureProvider(() => posture);
52+
await engine.init();
53+
engine.registry.registerObject(SysRecycleBin as never, '@objectstack/platform-objects');
54+
engine.registry.registerObject(
55+
{ name: GLOBAL, label: 'Global note', tenancy: { enabled: false }, fields: { title: { type: 'text', label: 'Title' } } } as never,
56+
'rbo',
57+
);
58+
await engine.syncSchemas();
59+
await installDefaultOrganization(engine as never);
60+
const created = (await engine.insert(GLOBAL, { title: 'kept' }, SYSTEM as never)) as { id: string };
61+
return { engine, id: String(created.id) };
62+
}
63+
64+
const entries = async (engine: ObjectQL) =>
65+
(await engine.find(RECYCLE_BIN_OBJECT, SYSTEM as never)) as Array<Record<string, unknown>>;
66+
const stillThere = async (engine: ObjectQL, id: string) =>
67+
(await engine.find(GLOBAL, { where: { id }, ...SYSTEM } as never)) as Array<Record<string, unknown>>;
68+
69+
describe('a system-door delete of a tenancy-disabled record on sqlite', () => {
70+
it('under single: answers true, the entry carries the Default Organization, and restore brings the record back', async () => {
71+
const { engine, id } = await boot('single');
72+
let entryId: string | undefined;
73+
74+
const answer = await engine.delete(GLOBAL, {
75+
where: { id },
76+
...SYSTEM,
77+
onRecycleBinEntry: (e: string) => { entryId = e; },
78+
} as never);
79+
80+
expect(answer).toBe(true);
81+
expect(await stillThere(engine, id)).toHaveLength(0);
82+
const [entry, ...rest] = await entries(engine);
83+
expect(rest).toHaveLength(0);
84+
expect(entry).toMatchObject({ object_name: GLOBAL, record_id: id, organization_id: DEFAULT_ORGANIZATION_ID });
85+
expect(entryId).toBe(String(entry.id));
86+
87+
const restored = await engine.restore(String(entry.id), SYSTEM as never);
88+
expect(restored).toMatchObject({ object: GLOBAL, recordId: id });
89+
expect(await stillThere(engine, id)).toMatchObject([{ id, title: 'kept' }]);
90+
expect(await entries(engine)).toHaveLength(0);
91+
});
92+
93+
it('CONTROL a context that names an organization: the entry carries the context\'s, as before', async () => {
94+
const { engine, id } = await boot('single');
95+
expect(await engine.delete(GLOBAL, { where: { id }, context: { isSystem: true, tenantId: 'org_named' } } as never)).toBe(true);
96+
expect(await entries(engine)).toMatchObject([{ record_id: id, organization_id: 'org_named' }]);
97+
});
98+
99+
it('under a wall: refused with ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED, and the record stays with no entry', async () => {
100+
const { engine, id } = await boot('isolated');
101+
102+
const refusal = await engine.delete(GLOBAL, { where: { id }, ...SYSTEM } as never).then(
103+
() => undefined,
104+
(e: unknown) => e as { code?: unknown; status?: unknown },
105+
);
106+
107+
expect(refusal).toMatchObject({ code: 'ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED', status: 500 });
108+
expect(await stillThere(engine, id)).toMatchObject([{ id, title: 'kept' }]);
109+
expect(await entries(engine)).toHaveLength(0);
110+
});
111+
});

0 commit comments

Comments
 (0)