Advertisement
infogulch

Untitled

Jun 2nd, 2012
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.00 KB | None | 0 0
  1. CREATE TABLE nodes (
  2.       id        INTEGER PRIMARY KEY
  3.     , parent_id INTEGER
  4.     , isdir     INTEGER
  5.     , name      TEXT
  6. );
  7. CREATE INDEX index_name ON nodes (name);
  8.  
  9. CREATE TABLE closures (
  10.       ancestor   INTEGER -- NULL allowed
  11.     , descendant INTEGER NOT NULL
  12.     , pathlength INTEGER NOT NULL
  13.     , PRIMARY KEY (ancestor, descendant)
  14.     , FOREIGN KEY (ancestor)   REFERENCES nodes(id)
  15.     , FOREIGN KEY (descendant) REFERENCES nodes(id)
  16. );
  17. CREATE INDEX index_descendant_ancestor ON closures (descendant, ancestor);
  18.  
  19. -- insert all root nodes into closures table
  20. INSERT INTO closures (ancestor, descendant, pathlength)
  21. SELECT id, id, 0
  22. FROM nodes WHERE parent_id IS NULL
  23. UNION ALL
  24. SELECT NULL, id, -1
  25. FROM nodes WHERE parent_id IS NULL;
  26.  
  27. -- run this query repeatedly to incrementally insert one more level at a time
  28. INSERT OR REPLACE INTO closures (ancestor, descendant, pathlength)
  29. SELECT COALESCE(ancestor, id), id, pathlength+1
  30. FROM closures
  31. JOIN nodes ON parent_id = descendant;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement