Advertisement
infogulch

closures

Jun 2nd, 2012
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.55 KB | None | 0 0
  1. -- CREATE TABLE nodes_u AS SELECT * FROM diskdb.nodes; -- initial table. _u == unsorted
  2. CREATE TABLE nodes_s ( -- _s == sorted
  3.       id         INTEGER PRIMARY KEY
  4.     , parent_id  INTEGER
  5.     , isdir      INTEGER
  6.     , name       TEXT
  7.     , pathlength INTEGER DEFAULT NULL
  8. );
  9.  
  10. CREATE TABLE nodes (
  11.       id         INTEGER PRIMARY KEY
  12.     , parent_id  INTEGER
  13.     , isdir      INTEGER
  14.     , name       TEXT
  15. );
  16. CREATE INDEX index_name ON nodes (name);
  17.  
  18. CREATE TABLE closures (
  19.       ancestor   INTEGER NOT NULL
  20.     , descendant INTEGER NOT NULL
  21.     , pathlength INTEGER NOT NULL
  22.     , PRIMARY KEY (ancestor, descendant)
  23.     , FOREIGN KEY (ancestor)   REFERENCES nodes(id)
  24.     , FOREIGN KEY (descendant) REFERENCES nodes(id)
  25. );
  26. CREATE INDEX index_descendant_ancestor ON closures (descendant, ancestor);
  27.  
  28. CREATE TRIGGER build_closures
  29. AFTER INSERT ON nodes
  30. FOR EACH ROW
  31. BEGIN
  32.     INSERT INTO closures (ancestor,descendant,pathlength)
  33.     SELECT ancestor, NEW.id, pathlength+1
  34.     FROM Closures
  35.     WHERE descendant = NEW.parent_id
  36.    
  37.     UNION ALL
  38.    
  39.     SELECT NEW.id,NEW.id,0;
  40. END;
  41.  
  42. -- REPEAT until COUNT nodes_u doesn't change
  43.     INSERT INTO nodes_s
  44.     SELECT nodes_u.*, (SELECT COALESCE(MAX(pathlength)+1, 0) FROM nodes_s)
  45.     FROM nodes_u
  46.     WHERE parent_id IN (SELECT id FROM nodes_s) OR parent_id IS NULL;
  47.  
  48.     DELETE FROM nodes_u
  49.     WHERE id IN (SELECT id FROM nodes_s);
  50.     -- SELECT COUNT(*) FROM nodes_u;
  51.  
  52.  
  53. -- BUILD CLOSURES
  54. INSERT INTO nodes
  55. SELECT id, parent_id, isdir, name
  56. FROM nodes_s
  57. ORDER BY pathlength;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement