Skip to content

Commit 6403982

Browse files
authored
fix: cascade record deletion when clearing the collection (#333)
1 parent c384a04 commit 6403982

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/collection.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,10 @@ export class Collection<Schema extends StandardSchemaV1> {
473473
* Deletes all the records in this collection.
474474
*/
475475
public clear(): void {
476+
for (const record of this.#records) {
477+
this.#deleteRecord(record)
478+
}
479+
476480
this.#records.length = 0
477481
}
478482

tests/relations/one-to-many.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,30 @@ it('cascades foreign record deletion when the owner record is deleted', async ()
339339
expect(users.all()).toEqual([])
340340
})
341341

342+
it('cascades foreign record deletion when clearing the entire collection', async () => {
343+
const users = new Collection({ schema: userSchema })
344+
const posts = new Collection({ schema: postSchema })
345+
346+
users.defineRelations(({ many }) => ({
347+
posts: many(posts),
348+
}))
349+
posts.defineRelations(({ one }) => ({
350+
// When the referenced author is deleted, delete all their posts.
351+
author: one(users, { onDelete: 'cascade' }),
352+
}))
353+
354+
const post = await posts.create({ title: 'First' })
355+
const user = await users.create({
356+
id: 1,
357+
posts: [post],
358+
})
359+
360+
users.clear()
361+
362+
expect(posts.all()).toEqual([])
363+
expect(users.all()).toEqual([])
364+
})
365+
342366
it('supports unique one-to-many relations', async () => {
343367
const users = new Collection({ schema: userSchema })
344368
const posts = new Collection({ schema: postSchema })

0 commit comments

Comments
 (0)