CREATE TABLE page(id INTEGER PRIMARY KEY, name varchar(256), title varchar(1024), lastrevision integer, visible integer DEFAULT 1, parent integer REFERENCES page(id));
CREATE TABLE user(id INTEGER PRIMARY KEY,username varchar(64), 
password blob, salt blob, permissions integer, enabled integer DEFAULT 1);
CREATE TABLE session(id INTEGER PRIMARY KEY, csrf_token varchar(32), 
creationtime date, userid integer , token varchar(32));
CREATE TABLE permissions(id INTEGER PRIMARY KEY, permissions integer, 
userid integer REFERENCES user(id), page integer REFERENCES page(id ) );
CREATE TABLE revision
(

id INTEGER PRIMARY KEY, 
author integer REFERENCES user(id), 
comment text, 
content text, 
creationtime date, 
page integer REFERENCES page(id ),
revisionid integer
);
CREATE TABLE loginattempt
(
id INTEGER PRIMARY KEY,
ip varchar(16),
count integer
);
CREATE TABLE category(id INTEGER PRIMARY KEY, name varchar(255));
CREATE TABLE categorymember(id INTEGER PRIMARY KEY, category REFERENCES category(id), page REFERENCES page (id));
CREATE INDEX revisionid ON revision (revisionid DESC);
CREATE INDEX pagename ON page (name);
CREATE INDEX token ON session (token);
CREATE VIRTUAL TABLE search USING fts5(content, page UNINDEXED, content=revision,content_rowid=id);
CREATE TRIGGER search_ad AFTER DELETE ON revision BEGIN
  INSERT INTO search(search, rowid, content, page) VALUES('delete', old.id, old.content, old.page);
END;
CREATE TRIGGER search_ai AFTER INSERT ON revision BEGIN
  INSERT INTO search(search, rowid, content, page) SELECT 'delete', id, content, page FROM revision WHERE page = new.page AND revisionid = new.revisionid - 1; 
  INSERT INTO search(rowid, content, page) VALUES (new.id, new.content, new.page);
END;
