-- Add guarded writeback tokens without changing public API contracts.

SET @ddl = IF(
  (SELECT COUNT(1) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'fence' AND COLUMN_NAME = 'sync_token') = 0,
  'ALTER TABLE `fence` ADD COLUMN `sync_token` varchar(64) DEFAULT NULL COMMENT ''本地同步版本令牌'' AFTER `sync_status`',
  '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 = 'sync_token') = 0,
  'ALTER TABLE `alarm_rule` ADD COLUMN `sync_token` varchar(64) DEFAULT NULL COMMENT ''本地同步版本令牌'' AFTER `sync_status`',
  '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 = 'terminal' AND COLUMN_NAME = 'sync_token') = 0,
  'ALTER TABLE `terminal` ADD COLUMN `sync_token` varchar(64) DEFAULT NULL COMMENT ''本地同步版本令牌'' AFTER `sync_status`',
  '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 = 'terminal_bind' AND COLUMN_NAME = 'sync_token') = 0,
  'ALTER TABLE `terminal_bind` ADD COLUMN `sync_token` varchar(64) DEFAULT NULL COMMENT ''本地同步版本令牌'' AFTER `sync_status`',
  'DO 0'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
