Clean up sensors and related tables and add constraints

Remove sensors for non existent devices and delete unused sensors_to_state_indexes, state_indexes, and state_translations
Change sensors.device_id to unsigned to match devices.device_id
Add foreign keys to sensors and sensors_to_state_indexes for cascading deletes
This commit is contained in:
Tony Murray
2016-06-28 21:09:25 -05:00
parent 5f5db66eaa
commit efadac68d4

8
sql-schema/120.sql Normal file
View File

@ -0,0 +1,8 @@
DELETE FROM `sensors_to_state_indexes` WHERE `sensors_to_state_indexes`.`sensor_id` NOT IN (SELECT DISTINCT `sensors`.`sensor_id` FROM `sensors` INNER JOIN `devices` ON `sensors`.`device_id` = `devices`.`device_id`);
DELETE FROM `sensors` WHERE `sensors`.`device_id` NOT IN (SELECT `device_id` FROM `devices`);
DELETE FROM `state_indexes` WHERE `state_indexes`.`state_index_id` NOT IN (SELECT `sensors_to_state_indexes`.`state_index_id` FROM `sensors_to_state_indexes`);
DELETE FROM `state_translations` WHERE `state_translations`.`state_index_id` NOT IN (SELECT `state_indexes`.`state_index_id` FROM `state_indexes`);
ALTER TABLE `sensors` CHANGE `device_id` `device_id` INT(11) UNSIGNED NOT NULL DEFAULT '0';
ALTER TABLE `sensors` ADD CONSTRAINT `sensors_device_id_foreign` FOREIGN KEY (`device_id`) REFERENCES `devices` (`device_id`) ON DELETE CASCADE;
ALTER TABLE `sensors_to_state_indexes` ADD CONSTRAINT `sensors_to_state_indexes_sensor_id_foreign` FOREIGN KEY (`sensor_id`) REFERENCES `sensors` (`sensor_id`) ON DELETE CASCADE;