From 40d71240ffd42b3d362210f1814a345e09db8bac Mon Sep 17 00:00:00 2001 From: Artem Zakharchenko Date: Sun, 5 Oct 2025 13:58:11 +0200 Subject: [PATCH] fix: cascade record deletion when clearing the collection --- src/collection.ts | 4 ++++ tests/relations/one-to-many.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/src/collection.ts b/src/collection.ts index e1251f4..9bceeb5 100644 --- a/src/collection.ts +++ b/src/collection.ts @@ -473,6 +473,10 @@ export class Collection { * Deletes all the records in this collection. */ public clear(): void { + for (const record of this.#records) { + this.#deleteRecord(record) + } + this.#records.length = 0 } diff --git a/tests/relations/one-to-many.test.ts b/tests/relations/one-to-many.test.ts index b3586ba..85b8077 100644 --- a/tests/relations/one-to-many.test.ts +++ b/tests/relations/one-to-many.test.ts @@ -339,6 +339,30 @@ it('cascades foreign record deletion when the owner record is deleted', async () expect(users.all()).toEqual([]) }) +it('cascades foreign record deletion when clearing the entire collection', async () => { + const users = new Collection({ schema: userSchema }) + const posts = new Collection({ schema: postSchema }) + + users.defineRelations(({ many }) => ({ + posts: many(posts), + })) + posts.defineRelations(({ one }) => ({ + // When the referenced author is deleted, delete all their posts. + author: one(users, { onDelete: 'cascade' }), + })) + + const post = await posts.create({ title: 'First' }) + const user = await users.create({ + id: 1, + posts: [post], + }) + + users.clear() + + expect(posts.all()).toEqual([]) + expect(users.all()).toEqual([]) +}) + it('supports unique one-to-many relations', async () => { const users = new Collection({ schema: userSchema }) const posts = new Collection({ schema: postSchema })