RENAME TABLE qs_Gallery TO qs_OldGallery;
RENAME TABLE qs_GalleryCategory TO qs_OldGalleryCategory;

CREATE TABLE IF NOT EXISTS `qs_Gallery` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `image` varchar(255) DEFAULT NULL,
  `description` text NOT NULL,
  `rawDescription` text NOT NULL,
  `show` enum('y','n') NOT NULL DEFAULT 'y',
  `sorter` int(11) NOT NULL,
  `added` datetime NOT NULL,
  `changed` datetime NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `sorter` (`sorter`),
  INDEX `show` (`show`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

CREATE TABLE IF NOT EXISTS `qs_GalleryImage` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `galleryId` int(11) unsigned NOT NULL,
  `title` varchar(255) NOT NULL,
  `image` varchar(255) DEFAULT NULL,
  `description` text NOT NULL,
  `show` enum('y','n') NOT NULL DEFAULT 'y',
  `sorter` int(11) NOT NULL,
  `added` datetime NOT NULL,
  `changed` datetime NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `galleryId_show_sorter` (`galleryId`, `show`, `sorter`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

ALTER TABLE `qs_GalleryImage`
  ADD CONSTRAINT `fk_galleryId` FOREIGN KEY (`galleryId`) REFERENCES `qs_Gallery` (`id`) ON DELETE RESTRICT ON UPDATE CASCADE;



INSERT INTO qs_Gallery (`id`, `title`, `image`, `description`, `rawDescription`, `show`, `sorter`, `added`, `changed`)
SELECT
  `id`,
  `title`,
  `image`,
  `description`,
  `rawDescription`,
  `show`,
  `sorter`,
  `added`,
  `changed`
FROM qs_OldGalleryCategory;

INSERT INTO qs_GalleryImage (`id`, `galleryId`, `title`, `image`, `description`, `show`, `sorter`, `added`, `changed`)
SELECT
  `g`.`id`,
  `g`.`idCategory` AS `galleryId`,
  `g`.`title`,
  `g`.`image`,
  `g`.`description`,
  `g`.`show`,
  `g`.`sorter`,
  `g`.`added`,
  `g`.`changed`
FROM qs_OldGallery g
INNER JOIN qs_OldGalleryCategory c ON c.id = g.idCategory;


UPDATE qs_DPageItemType SET `type` = "Gallery\\" WHERE `type` = "Gallery\\Category\\";
UPDATE qs_DraftPageItem SET `type` = "Gallery\\" WHERE `type` = "Gallery\\Category\\";
UPDATE qs_PageItem SET `type` = "Gallery\\" WHERE `type` = "Gallery\\Category\\";

-- SanityCheck fix
UPDATE `qs_SanityCheckFileRegistry` 
SET `tableAlias` =  'GalleryImage',
    `pageQuery` =  '<type=Gallery\\Image\\Admin\\>' 
WHERE  `tableAlias` =  'GalleryCategory' 
    AND `fieldName` =  'image';
