SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;


CREATE TABLE `blobs` (
  `id` char(36) NOT NULL,
  `mime_type` varchar(255) NOT NULL DEFAULT 'application/octet-stream',
  `modify_token` char(255) NOT NULL,
  `ref_branch_blob` char(36) DEFAULT NULL,
  `is_removed` tinyint(1) NOT NULL DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `collections` (
  `id` char(36) NOT NULL,
  `modify_token` char(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `rel_collections_blobs` (
  `ref_collection_id` char(36) NOT NULL,
  `ref_blob_id` char(36) NOT NULL,
  `label` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE `rel_collections_collections` (
  `ref_collection_id` char(36) NOT NULL,
  `ref_child_collection_id` char(36) NOT NULL,
  `label` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;


ALTER TABLE `blobs`
  ADD PRIMARY KEY (`id`),
  ADD KEY `ref_replaces_blob` (`ref_branch_blob`);

ALTER TABLE `collections`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `rel_collections_blobs`
  ADD KEY `ref_collection_id` (`ref_collection_id`),
  ADD KEY `ref_blob_id` (`ref_blob_id`);

ALTER TABLE `rel_collections_collections`
  ADD KEY `ref_collection_id` (`ref_collection_id`,`ref_child_collection_id`),
  ADD KEY `ref_child_collection_id` (`ref_child_collection_id`);


ALTER TABLE `blobs`
  ADD CONSTRAINT `blobs_ibfk_1` FOREIGN KEY (`ref_branch_blob`) REFERENCES `blobs` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE `rel_collections_blobs`
  ADD CONSTRAINT `rel_collections_blobs_ibfk_1` FOREIGN KEY (`ref_blob_id`) REFERENCES `blobs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `rel_collections_blobs_ibfk_2` FOREIGN KEY (`ref_collection_id`) REFERENCES `collections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `rel_collections_collections`
  ADD CONSTRAINT `rel_collections_collections_ibfk_1` FOREIGN KEY (`ref_collection_id`) REFERENCES `collections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `rel_collections_collections_ibfk_2` FOREIGN KEY (`ref_child_collection_id`) REFERENCES `collections` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
