#!/bin/bash
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2018 Research Group Biomedical Physics,
# Max-Planck-Institute for Dynamics and Self-Organization Göttingen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#
# adds a property_id column to data_type.
# Update mysql schema to version v2.0.5
NEW_VERSION="v2.0.6"
OLD_VERSION="v2.0.5"

if [ -z "$UTILSPATH" ]; then
 UTILSPATH="../utils"
fi

. $UTILSPATH/helpers.sh 
. $UTILSPATH/patch_header.sh $*

check_version $OLD_VERSION

function create_new_table {
	mysql_execute 'CREATE TABLE data_type2 (
		domain_id INT UNSIGNED,
		entity_id INT UNSIGNED,
		property_id INT UNSIGNED,
		datatype INT UNSIGNED,
		INDEX `name_ov_dom_ent_idx` (domain_id,entity_id),
		FOREIGN KEY `datatype_forkey_dom` (`domain_id`) REFERENCES `entities` (`id`),
		FOREIGN KEY `datatype_forkey_ent` (`entity_id`) REFERENCES `entities` (`id`),
		FOREIGN KEY `datatype_forkey_pro` (`property_id`) REFERENCES `entities` (`id`),
		FOREIGN KEY `datatype_forkey_type` (`datatype`) REFERENCES `entities` (`id`)
	) ENGINE=InnoDB;
	'
}

function copy_old {
	mysql_execute 'INSERT INTO data_type2 (domain_id, entity_id, property_id, datatype) SELECT 0, domain_id, entity_id, datatype FROM data_type;'
	mysql_execute 'UPDATE data_type2,reference_data SET data_type2.domain_id=reference_data.domain_id WHERE data_type2.entity_id=reference_data.entity_id and data_type2.property_id=reference_data.value and status="REPLACEMENT" and reference_data.domain_id!=0;'
}

function delete_rename {
	mysql_execute 'DROP TABLE data_type;'
	mysql_execute 'ALTER TABLE data_type2 RENAME data_type;'
}

function set_idx {
	mysql_execute 'ALTER TABLE data_type ADD UNIQUE KEY `datatype_ukey` (domain_id,entity_id,property_id);'
}

create_new_table
copy_old
delete_rename
set_idx
update_version $NEW_VERSION

success
