# DROP TABLE page; DROP TABLE; USER 

CREATE TABLE user (
  `id`   CHAR(32) PRIMARY KEY,
  `role` CHAR(16),

  INDEX(role)
);

INSERT INTO user (id, role) VALUES("test:Test", "restricted");

CREATE TABLE page (
  `id`       CHAR(16) NOT NULL PRIMARY KEY,
  `name`     VARCHAR(255) NOT NULL,
  `author`   VARCHAR(64),
  `category` VARCHAR(16) NOT NULL,

  `fictional_date` DATETIME NOT NULL,
  `publish_date`   DATETIME NOT NULL,
  `edit_date`      DATETIME NOT NULL,

  `dated`     BOOLEAN NOT NULL,
  `published` BOOLEAN NOT NULL,
  `unlisted`  BOOLEAN NOT NULL,
  `specific`  BOOLEAN NOT NULL,
  `indexed`   BOOLEAN NOT NULL,

  `type`   VARCHAR(16) NOT NULL,
  `source` MEDIUMTEXT  NOT NULL,

  `background_url` VARCHAR(255),

  FOREIGN KEY (`author`) REFERENCES user(`id`) ON DELETE SET NULL
);

CREATE TABLE tag (
  `id`       CHAR(24) NOT NULL PRIMARY KEY,
  `type`     CHAR(16) NOT NULL,
  `disabled` BOOLEAN  NOT NULL,
  `name`     VARCHAR(64) NOT NULL,

  UNIQUE(name),
  INDEX(disabled)
);

CREATE TABLE page_tag (
  `page_id` CHAR(16) NOT NULL,
  `tag_id`  CHAR(24) NOT NULL,
  `primary` BOOLEAN NOT NULL,

  PRIMARY KEY (`page_id`, `tag_id`),
  FOREIGN KEY (`page_id`) REFERENCES page(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`tag_id`) REFERENCES tag(`id`) ON DELETE CASCADE
);

CREATE TABLE page_unread (
  `page_id` CHAR(16) NOT NULL,
  `user_id` CHAR(32) NOT NULL,

  PRIMARY KEY (`page_id`, `user_id`),
  FOREIGN KEY (`page_id`) REFERENCES page(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`user_id`) REFERENCES user(`id`) ON DELETE CASCADE
);