USE iot;

-- DROP TABLE IF EXISTS `device_healthbeat`;

--  ///  device_healthbeat BEGIN 

CREATE TABLE IF NOT EXISTS `device_healthbeat` (
	`id` VARCHAR(36) NOT NULL DEFAULT '-',
	`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`features` JSON NOT NULL,
	`device_id` INT(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

ALTER TABLE `device_healthbeat` ADD PRIMARY KEY pk_device_healthbeat_id(`id`);
ALTER TABLE `device_healthbeat` ADD KEY idx_device_healthbeat_create_time (`create_time`);
ALTER TABLE `device_healthbeat` ADD KEY idx_device_healthbeat_update_time (`update_time`);
ALTER TABLE `device_healthbeat` ADD UNIQUE KEY uk_device_healthbeat (`device_id`);
ALTER TABLE `device_healthbeat` ADD CONSTRAINT fk_device_healthbeat_device_id
	FOREIGN KEY (`device_id`) 
 		REFERENCES device_stock(`id`) 
 		ON DELETE CASCADE 
 		ON UPDATE CASCADE;

DROP TRIGGER IF EXISTS `device_healthbeat_uuid`;
DELIMITER $
CREATE TRIGGER `device_healthbeat_uuid`
BEFORE INSERT
ON `device_healthbeat`
FOR EACH ROW
BEGIN
	IF new.id = '-'
    THEN 
		SET new.id = (SELECT uuid());
	END IF;
END$
DELIMITER ;

DROP TRIGGER IF EXISTS `device_healthbeat_update_time`;
DELIMITER $
CREATE TRIGGER `device_healthbeat_update_time`
BEFORE UPDATE
ON `device_healthbeat`
FOR EACH ROW
BEGIN
	SET new.update_time = (SELECT now());
END$
DELIMITER ;

--  ///  device_healthbeat END 

--  ///  device_stock_view BEGIN

DROP VIEW IF EXISTS `device_stock_view`;
CREATE VIEW `device_stock_view` AS 
SELECT 
	a.*, 
	b.update_time AS healthbeat_time 
FROM 
	device_stock a 
LEFT JOIN 
	device_healthbeat b 
ON 
	a.id = b.device_id;

--  ///  device_stock_view END 