Skip to content

Instantly share code, notes, and snippets.

@maxcelos
Created October 19, 2024 23:47
Show Gist options
  • Save maxcelos/fb2bc3a808dd249be19090f924695ec7 to your computer and use it in GitHub Desktop.
Save maxcelos/fb2bc3a808dd249be19090f924695ec7 to your computer and use it in GitHub Desktop.
An example of database table and use case with entity recursive relationship.
drop table if exists folder;

create table folder (
	id INTEGER primary key AUTOINCREMENT, -- Primary key for the folder, automatically incremented
	name TEXT not null, -- Name of the folder
	parent_id INTEGER, -- Foreign key referencing the parent folder
	foreign key (parent_id) references folder (id) -- Self-referencing foreign key
);

-- Insert a root folder
insert into folder (name, parent_id) values ('Root_Folder', null);

-- Insert random folders (run it as mutch as needed)
with recursive generate_series as (
	select
		1 as n
	union all
	select
		n + 1
	from
		generate_series
	where
		n < 5
) insert into folder (name, parent_id)
select
	'Folder_' || n || '_' || (ABS(RANDOM()) % 100), (
		select
			id
		from
			folder
		order by
			RANDOM()
		limit 1) -- Select a random existing folder as the parent
from
	generate_series;

-- Query folder with its subfolders recursivelly 
with recursive FolderHierarchy as (
	-- Anchor member: select the folder with the given ID
	select
		id,
		name,
		parent_id
	from
		folder
	where
		id = ? -- Replace ? with the given folder ID
	union all
	-- Recursive member: select all subfolders
	select
		f.id,
		f.name,
		f.parent_id
	from
		folder f
		inner join FolderHierarchy fh on f.parent_id = fh.id
)
select
	id,
	name,
	parent_id
from
	FolderHierarchy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment