https://supabase.com/ logo
#sql
Title
# sql
a

acpatrice

08/18/2021, 8:04 PM
hi folks — a general question about schema design or structure — let's say I wanted files and folders — like a tree with nested folders (however many deep) — where would I start? a file would be an arbitrary table with its columns. also, a folder would need to be a column too since it may have its own metadata.
s

silentworks

08/18/2021, 8:12 PM
Do a google search on nested sets
a

acpatrice

08/18/2021, 8:13 PM
I think what I need is just a category table with a
parent_id
where
null
would be the highest up
s

silentworks

08/18/2021, 8:13 PM
Yes thats one option or depending on how complex it is then nested sets might be better
a

acpatrice

08/18/2021, 8:16 PM
thanks! I'll look into both. FWIW it's a fairly lightweight list represented in the left-nav and specific to the user.
f

florian-lefebvre

08/18/2021, 9:20 PM
That's exactly what I have done recently: I made a function to get all the parents from a directory
Copy code
pgsql
drop function if exists public.category_hierarchy;

create function public.category_hierarchy(id_param int)
returns table (
  id bigint,
  title varchar,
  parent_id bigint
)
as $$
begin
  return query with recursive parents
  as (
    select
      c1.id,
      c1.title,
      c1.parent_id
    from categories c1
    where c1.id = id_param
    union
      select
        c2.id,
        c2.title,
        c2.parent_id
      from categories c2
      inner join parents p on p.parent_id = c2.id
  ) select * from parents;
end;
$$ language plpgsql security definer;
a

acpatrice

08/18/2021, 9:41 PM
thanks for sharing.
in what scenario would you need this, for example? and can you give me an idea of what the data it returns looks like?
f

florian-lefebvre

08/19/2021, 7:44 AM
I needed to build a breadcrumb so it returns a list of the hierachy of a specific category
For example
select * from category_hierarchy(5)
Returns
Copy code
[
{Id: 5, title: "Category 5", parent_id: 4},
{Id: 4, title: "Category 4", parent_id: 3},
...
{Id: 1, title: "Category 1", parent_id: null}
]