PRAGMA foreign_keys==off;
----
-- Table structure plugins
----
CREATE TABLE 'plugins' (
    'id'      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    'libelle' TEXT NOT NULL
);
INSERT INTO 'plugins' VALUES (0, 'List');
INSERT INTO 'plugins' VALUES (1, 'Hierarchy');

----
-- Table structure for items
----
CREATE TABLE 'items' (
    'id'      INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    'plugin'  INTEGER DEFAULT 1,
    'code'    TEXT NOT NULL,
    'libelle' TEXT NOT NULL,
    CONSTRAINT fk_items
      FOREIGN KEY('plugin') REFERENCES 'plugins'('id')
      ON DELETE CASCADE
);

----
-- Table structure for links
----
CREATE TABLE 'links' (
    'id'    INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    'link'  INTEGER DEFAULT 0,
    'item' INTEGER,
    CONSTRAINT fk_links
      FOREIGN KEY('item') REFERENCES 'items'('id')
      ON DELETE CASCADE
);

----
-- Table structure for nodes
----
CREATE TABLE 'nodes' (
    'child'   INTEGER, 
    'parent' INTEGER, 
    'rank'   INTEGER DEFAULT 0,
    CONSTRAINT fk_nodes_1
      FOREIGN KEY('child') REFERENCES 'links'('id')
      ON DELETE CASCADE,
    CONSTRAINT fk_nodes_2
      FOREIGN KEY('parent') REFERENCES 'links'('id')
      ON DELETE CASCADE
);

----
-- View structure for v_items
----
CREATE VIEW v_items AS 
SELECT 
    items.plugin, items.code, items.libelle ,
    links.*
FROM links 
INNER JOIN items ON items.id = links.item;

----
-- View structure for v_items_tree
----
CREATE VIEW v_items_tree AS
SELECT
    nodes.parent, nodes.rank,
    v_items.*
FROM v_items
LEFT JOIN nodes ON nodes.child = v_items.id;

PRAGMA foreign_keys=on;
