SHARE
    TWEET
    ferrybig

    Postgres with example

    Oct 6th, 2025
    7,750
    0
    Never
    2
    Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
    1. -- drop table file, folder;
    2. CREATE TABLE "folder" (
    3. "id" INT PRIMARY key GENERATED ALWAYS AS IDENTITY,
    4. "name" VARCHAR NOT NULL,
    5. "parent_id" INTEGER REFERENCES "folder"("id")--,
    6. --constraint folder_name UNIQUE NULLS NOT DISTINCT (name, parent_id)
    7. );
    8. CREATE TABLE "file" (
    9. "id" INT PRIMARY key GENERATED ALWAYS AS IDENTITY,
    10. "name" VARCHAR NOT NULL,
    11. "parent_id" INTEGER REFERENCES "folder"("id"),
    12. "contents" TEXT--,
    13. --constraint folder_name UNIQUE NULLS NOT DISTINCT (name, parent_id)
    14. );
    15. insert into folder (name, parent_id) values
    16. ('dir1', null),
    17. ('dir2', null),
    18. ('dir3', null),
    19. ('dir4', null);
    20. insert into folder (name, parent_id)
    21. select t.name, folder.id
    22. from (values
    23. ('subdir1'),
    24. ('subdir2'),
    25. ('subdir3'),
    26. ('subdir4')
    27. ) AS t (name)
    28. inner join folder on true;
    29. insert into folder (name, parent_id)
    30. select t.name, folder.parent_id
    31. from (values
    32. ('subsubdir1'),
    33. ('subsubdir2'),
    34. ('subsubdir3'),
    35. ('subsubdir4')
    36. ) AS t (name)
    37. inner join folder on folder.parent_id is not null;
    38. insert into file(name, parent_id, contents)
    39. select t.name, folder.id, ''
    40. from (values
    41. ('file1.txt'),
    42. ('t.test')
    43. ) AS t (name)
    44. inner join folder on true;
    45. insert into file(name, parent_id, contents)
    46. values ('root.txt', null, '');
    47. update file
    48. set name = id || '-' || name;
    49. WITH RECURSIVE tree(id, parent_id, name) AS (
    50. select id, parent_id, array[name] from folder
    51. UNION ALL
    52. SELECT tree.id, folder.parent_id, folder.name || tree.name
    53. from tree
    54. inner join folder on folder.id = tree.parent_id
    55. )
    56. select
    57. file.id,
    58. coalesce(array_to_string(tree.name || file.name, '/'), file.name) as path
    59. from file
    60. left join tree on tree.parent_id is null and tree.id = file.parent_id
    61. order by 2
    Advertisement
    Comments
    • User was banned
    • User was banned
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /