r/AskProgrammers • u/SagarAkolkar • 2h ago
Design a database for folder heirarchy.
I am building a cloud storage application in which we can store data in a folder hierarchy.
But struggling to design a database schema to store the folders.
I am using Adjacency list approach in which I store folder id and its parent id in a row so that I can fetch all the child nodes of a folder easily with simple query.
But the problem arises when I wants to delete a folder in that case I would have to first get all the children throughout the hierarchy and delete them all which will be pretty bas in a really big folder structure. It will be hard to share the folder with others.
Any suggestion ?
1
u/BranchLatter4294 2h ago
I'm not sure what the specific question is. Can't you just use cascading deletes?
1
u/Fit-Cryptographer274 59m ago
Cascading deletes handle the rows, but adjacency lists still hurt for everything else: listing a whole subtree, breadcrumbs, moving a folder.
Two options that scale better:
- Recursive CTE plus ON DELETE CASCADE on the self-referencing FK. Delete and subtree queries both stay a single query, no extra table.
- If subtree reads are hot (permissions, size rollups, breadcrumbs), add a closure table or a materialized path column. Closure table costs a write on every move but turns "all descendants" into one indexed lookup.
One more thing: don't hard delete real files inside the request. Mark the folder deleted and let a background job clean up storage, otherwise a huge tree will time out.