Advertisement
infogulch

Untitled

Jun 7th, 2012
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.72 KB | None | 0 0
  1. CREATE TABLE nodes (
  2.       id         INTEGER PRIMARY KEY
  3.     , isdir      INTEGER
  4.     , name       TEXT
  5. );
  6. CREATE INDEX index_name ON nodes (name);
  7.  
  8. CREATE TABLE closures (
  9.       ancestor   INTEGER NOT NULL
  10.     , descendant INTEGER NOT NULL
  11.     , pathlength INTEGER NOT NULL
  12.     , PRIMARY KEY (ancestor, descendant)
  13.     , FOREIGN KEY (ancestor)   REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE
  14.     , FOREIGN KEY (descendant) REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE
  15. );
  16. CREATE INDEX index_descendant_ancestor ON closures (descendant, ancestor);
  17.  
  18. CREATE VIEW parent_of
  19. AS
  20. SELECT id
  21.      , ancestor AS parent_id
  22.      , isdir
  23.      , name
  24. FROM nodes
  25. JOIN closures ON descendant = id AND pathlength = 1;
  26.  
  27. CREATE TABLE orphans (
  28.       id         INTEGER PRIMARY KEY
  29.     , parent_id  INTEGER
  30.     , isdir      INTEGER
  31.     , name       TEXT
  32. );
  33.  
  34. CREATE TRIGGER build_closures
  35. INSTEAD OF INSERT ON parent_of
  36. FOR EACH ROW
  37. BEGIN
  38.     CASE WHEN (SELECT id FROM nodes WHERE id = NEW.parent_id LIMIT 1) IS NULL
  39.     THEN
  40.         INSERT INTO orphans (id, parent_id, isdir, name) VALUES (NEW.id, NEW.parent_id, NEW.isdir, NEW.name);
  41.     ELSE
  42.         INSERT INTO nodes (id, isdir, name) VALUES (NEW.id, NEW.isdir, NEW.name);
  43.        
  44.         INSERT INTO closures (ancestor,descendant,pathlength)
  45.         SELECT ancestor, NEW.id, pathlength+1
  46.         FROM closures
  47.         WHERE descendant = NEW.parent_id
  48.        
  49.         UNION ALL
  50.        
  51.         SELECT NEW.id,NEW.id,0;
  52.        
  53.         DELETE FROM orphans WHERE id = NEW.id;
  54.     END
  55.     INSERT INTO parent_of
  56.     SELECT * FROM orphans
  57.     WHERE parent_id IN (SELECT id FROM nodes);
  58. END;
  59.  
  60. -- Just insert everything into `parent_of` !
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement