-- Align organization snapshot columns with AreaDO and AlarmRuleDO.

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'area' AND COLUMN_NAME = 'org_code') = 0,
  'ALTER TABLE `area` ADD COLUMN `org_code` varchar(64) DEFAULT NULL COMMENT ''所属组织编码'' AFTER `parent_code`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'area' AND COLUMN_NAME = 'org_name') = 0,
  'ALTER TABLE `area` ADD COLUMN `org_name` varchar(255) DEFAULT NULL COMMENT ''所属组织名称'' AFTER `org_code`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'area' AND INDEX_NAME = 'idx_org_code') = 0,
  'ALTER TABLE `area` ADD KEY `idx_org_code` (`org_code`)',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'alarm_rule' AND COLUMN_NAME = 'org_code') = 0,
  'ALTER TABLE `alarm_rule` ADD COLUMN `org_code` varchar(64) DEFAULT NULL COMMENT ''所属公司编码'' AFTER `corpinfo_name`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'alarm_rule' AND COLUMN_NAME = 'org_name') = 0,
  'ALTER TABLE `alarm_rule` ADD COLUMN `org_name` varchar(255) DEFAULT NULL COMMENT ''所属公司名称'' AFTER `org_code`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'alarm_rule' AND INDEX_NAME = 'idx_org_code') = 0,
  'ALTER TABLE `alarm_rule` ADD KEY `idx_org_code` (`org_code`)',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
