|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * Cascade-on-delete behavior for parent→child foreign keys, with a REAL |
| 5 | + * {@link ObjectQL} engine + in-memory driver. |
| 6 | + * |
| 7 | + * Regression: deleting a parent whose child has a *required* lookup FK used to |
| 8 | + * default to `set_null`, issuing an UPDATE that cleared the required FK — which |
| 9 | + * the child's validator rejected with a misleading "<field> is required" 400 |
| 10 | + * naming a field that isn't even on the object being deleted (CRM e2e gap). |
| 11 | + * A required FK can't be nulled, so the defaulted `set_null` now escalates to |
| 12 | + * `restrict`: the delete is refused with a clear dependent-count message |
| 13 | + * (`DELETE_RESTRICTED`, 409). Explicit `cascade`/`restrict` and optional |
| 14 | + * (nullable) lookups are unaffected. |
| 15 | + */ |
| 16 | + |
| 17 | +import { describe, it, expect, beforeEach } from 'vitest'; |
| 18 | +import { ObjectQL } from './engine.js'; |
| 19 | + |
| 20 | +const acct = { |
| 21 | + name: 'acct', |
| 22 | + label: 'Account', |
| 23 | + fields: { |
| 24 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 25 | + name: { name: 'name', type: 'text' as const }, |
| 26 | + }, |
| 27 | +}; |
| 28 | +const oppRequired = { |
| 29 | + name: 'opp', |
| 30 | + label: 'Opportunity', |
| 31 | + fields: { |
| 32 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 33 | + name: { name: 'name', type: 'text' as const }, |
| 34 | + // required lookup → can't be nulled |
| 35 | + account: { name: 'account', type: 'lookup' as const, reference: 'acct', required: true }, |
| 36 | + }, |
| 37 | +}; |
| 38 | +const noteOptional = { |
| 39 | + name: 'note', |
| 40 | + label: 'Note', |
| 41 | + fields: { |
| 42 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 43 | + body: { name: 'body', type: 'text' as const }, |
| 44 | + // optional lookup → default set_null is valid |
| 45 | + account: { name: 'account', type: 'lookup' as const, reference: 'acct' }, |
| 46 | + }, |
| 47 | +}; |
| 48 | +const taskCascade = { |
| 49 | + name: 'task', |
| 50 | + label: 'Task', |
| 51 | + fields: { |
| 52 | + id: { name: 'id', type: 'text' as const, primaryKey: true }, |
| 53 | + title: { name: 'title', type: 'text' as const }, |
| 54 | + // required FK but author explicitly opted into cascade |
| 55 | + account: { name: 'account', type: 'lookup' as const, reference: 'acct', required: true, deleteBehavior: 'cascade' }, |
| 56 | + }, |
| 57 | +}; |
| 58 | + |
| 59 | +function makeMemoryDriver() { |
| 60 | + const stores = new Map<string, Map<string, Record<string, unknown>>>(); |
| 61 | + const storeFor = (o: string) => { let s = stores.get(o); if (!s) { s = new Map(); stores.set(o, s); } return s; }; |
| 62 | + let nextId = 0; |
| 63 | + const matches = (row: Record<string, unknown>, where: any): boolean => { |
| 64 | + if (!where || typeof where !== 'object') return true; |
| 65 | + for (const [k, v] of Object.entries(where)) { |
| 66 | + if (k.startsWith('$')) continue; |
| 67 | + const exp = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; |
| 68 | + if ((row[k] ?? null) !== (exp ?? null)) return false; |
| 69 | + } |
| 70 | + return true; |
| 71 | + }; |
| 72 | + const driver: any = { |
| 73 | + name: 'memory', version: '0.0.0', supports: {}, |
| 74 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 75 | + async find(o: string, ast: any) { return Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); }, |
| 76 | + findStream() { throw new Error('ns'); }, |
| 77 | + async findOne(o: string, ast: any) { for (const r of storeFor(o).values()) if (matches(r, ast?.where)) return r; return null; }, |
| 78 | + async create(o: string, data: Record<string, unknown>) { |
| 79 | + nextId += 1; const id = (data.id as string) ?? `r_${nextId}`; const row = { ...data, id }; storeFor(o).set(id, row); return row; |
| 80 | + }, |
| 81 | + async update(o: string, id: string, data: Record<string, unknown>) { |
| 82 | + const s = storeFor(o); const cur = s.get(id); if (!cur) throw new Error(`nf ${o}/${id}`); |
| 83 | + const up = { ...cur, ...data, id }; s.set(id, up); return up; |
| 84 | + }, |
| 85 | + async upsert(o: string, data: Record<string, unknown>) { const id = data.id as string | undefined; return id && storeFor(o).has(id) ? this.update(o, id, data) : this.create(o, data); }, |
| 86 | + async delete(o: string, id: string) { return storeFor(o).delete(id); }, |
| 87 | + async count(o: string, ast: any) { return (await this.find(o, ast)).length; }, |
| 88 | + async bulkCreate(o: string, rows: Record<string, unknown>[]) { return Promise.all(rows.map((r) => this.create(o, r))); }, |
| 89 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 90 | + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, async commit() {}, async rollback() {}, |
| 91 | + }; |
| 92 | + return { driver, stores }; |
| 93 | +} |
| 94 | + |
| 95 | +describe('cascadeDeleteRelations — required FK escalates set_null → restrict', () => { |
| 96 | + let engine: ObjectQL; |
| 97 | + |
| 98 | + beforeEach(async () => { |
| 99 | + engine = new ObjectQL(); |
| 100 | + const { driver } = makeMemoryDriver(); |
| 101 | + engine.registerDriver(driver, true); |
| 102 | + await engine.init(); |
| 103 | + for (const o of [acct, oppRequired, noteOptional, taskCascade]) engine.registry.registerObject(o as any); |
| 104 | + }); |
| 105 | + |
| 106 | + it('refuses to delete a parent with a REQUIRED-FK child (DELETE_RESTRICTED, 409) and leaves both rows', async () => { |
| 107 | + const a = await engine.insert('acct', { name: 'Acme' }); |
| 108 | + await engine.insert('opp', { name: 'Deal', account: a.id }); |
| 109 | + |
| 110 | + await expect(engine.delete('acct', { where: { id: a.id } } as any)) |
| 111 | + .rejects.toMatchObject({ code: 'DELETE_RESTRICTED', status: 409, dependentObject: 'opp', dependentCount: 1 }); |
| 112 | + |
| 113 | + // Nothing was deleted or mutated. |
| 114 | + expect(await engine.findOne('acct', { where: { id: a.id } })).toBeTruthy(); |
| 115 | + expect((await engine.find('opp', {})).length).toBe(1); |
| 116 | + }); |
| 117 | + |
| 118 | + it('deletes a parent that has no dependents', async () => { |
| 119 | + const a = await engine.insert('acct', { name: 'Empty' }); |
| 120 | + await engine.delete('acct', { where: { id: a.id } } as any); |
| 121 | + expect(await engine.findOne('acct', { where: { id: a.id } })).toBeNull(); |
| 122 | + }); |
| 123 | + |
| 124 | + it('nulls the FK for an OPTIONAL (nullable) lookup child and deletes the parent', async () => { |
| 125 | + const a = await engine.insert('acct', { name: 'Acme' }); |
| 126 | + const n = await engine.insert('note', { body: 'hi', account: a.id }); |
| 127 | + await engine.delete('acct', { where: { id: a.id } } as any); |
| 128 | + expect(await engine.findOne('acct', { where: { id: a.id } })).toBeNull(); |
| 129 | + const note = await engine.findOne('note', { where: { id: n.id } }); |
| 130 | + expect(note).toBeTruthy(); |
| 131 | + expect((note as any).account).toBeNull(); |
| 132 | + }); |
| 133 | + |
| 134 | + it('honors an explicit deleteBehavior:cascade on a required FK (children removed, no escalation)', async () => { |
| 135 | + const a = await engine.insert('acct', { name: 'Acme' }); |
| 136 | + const t = await engine.insert('task', { title: 'Follow up', account: a.id }); |
| 137 | + await engine.delete('acct', { where: { id: a.id } } as any); |
| 138 | + expect(await engine.findOne('acct', { where: { id: a.id } })).toBeNull(); |
| 139 | + expect(await engine.findOne('task', { where: { id: t.id } })).toBeNull(); |
| 140 | + }); |
| 141 | +}); |
0 commit comments