CREATE TABLE page(id INTEGER PRIMARY KEY, name varchar(256), lastrevision integer, visible integer DEFAULT 1);
CREATE TABLE user(id INTEGER PRIMARY KEY,username varchar(64), 
password blob, salt blob, permissions integer);
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 TRIGGER search_ai AFTER INSERT ON revision BEGIN
  DELETE FROM search WHERE page = new.page;
  INSERT INTO search(rowid, content, page) VALUES (new.id, new.content, new.page);
END;
CREATE TRIGGER search_au AFTER UPDATE ON revision BEGIN
  DELETE FROM search WHERE page = old.page;
  INSERT INTO search(rowid, content, page) VALUES (new.id, new.content, new.page);
END;
CREATE VIRTUAL TABLE search USING fts5(content, page UNINDEXED, content=revision,content_rowid=id)
/* search(content,page) */;
CREATE TABLE IF NOT EXISTS 'search_data'(id INTEGER PRIMARY KEY, block BLOB);
CREATE TABLE IF NOT EXISTS 'search_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS 'search_docsize'(id INTEGER PRIMARY KEY, sz BLOB);
CREATE TABLE IF NOT EXISTS 'search_config'(k PRIMARY KEY, v) WITHOUT ROWID;
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;
