
-- add new tables for faceted search
CREATE TABLE IF NOT EXISTS ControlledNameFacetCache (
    ResourceId  INT,
    Names       TEXT,
    INDEX       (ResourceId)
);
CREATE TABLE IF NOT EXISTS ClassificationFacetCache (
    ResourceId  INT,
    Classes     TEXT,
    INDEX       (ResourceId)
);

ALTER TABLE MetadataFields
        ADD COLUMN IncludeInFacetedSearch INT DEFAULT 0 AFTER IncludeInAdvancedSearch;

UPDATE MetadataFields SET IncludeInFacetedSearch = IncludeInAdvancedSearch ;

-- add configuration option for faceted search
ALTER TABLE SystemConfiguration
        ADD COLUMN NumResourcesForSearchFacets INT DEFAULT 5000;

ALTER TABLE SystemConfiguration
        ADD COLUMN MaxFacetsPerField INT DEFAULT 75;

-- change image IDs to auto-increment so new IDs are always unique
ALTER TABLE Images CHANGE COLUMN ImageId ImageId INT NOT NULL AUTO_INCREMENT;

-- add intersection table between Resources and Images
CREATE TABLE IF NOT EXISTS ResourceImageInts (
    ResourceId              INT NOT NULL,
    FieldId                 INT NOT NULL,
    ImageId                 INT NOT NULL,
    INDEX                   (ResourceId, FieldId),
    INDEX                   (ImageId)
);

-- increase template location cache column size to avoid overflow
ALTER TABLE ApplicationFrameworkSettings
        CHANGE COLUMN TemplateLocationCache TemplateLocationCache MEDIUMTEXT;

-- add column to record full resource count for classifications
ALTER TABLE Classifications
        ADD COLUMN FullResourceCount INT DEFAULT 0;

-- copy the released-only resource count over for now. the counts are updated
-- in a background task to be fully accurate
UPDATE Classifications SET FullResourceCount = ResourceCount;

-- add column for the name of resources within each metadata schema
ALTER TABLE MetadataSchemas
        ADD COLUMN ResourceName TEXT;

-- set the resource names for the built-in metadata schemas
UPDATE MetadataSchemas SET ResourceName = 'Resource' WHERE SchemaId = 0;
UPDATE MetadataSchemas SET ResourceName = 'User' WHERE SchemaId = 1;
