SET @valid_from_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'sys_user'
      AND COLUMN_NAME = 'valid_from'
);
SET @add_valid_from_sql = IF(
    @valid_from_exists = 0,
    'ALTER TABLE sys_user ADD COLUMN valid_from DATETIME NULL AFTER status',
    'SELECT 1'
);
PREPARE stmt_add_valid_from FROM @add_valid_from_sql;
EXECUTE stmt_add_valid_from;
DEALLOCATE PREPARE stmt_add_valid_from;

SET @valid_to_exists = (
    SELECT COUNT(1)
    FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'sys_user'
      AND COLUMN_NAME = 'valid_to'
);
SET @add_valid_to_sql = IF(
    @valid_to_exists = 0,
    'ALTER TABLE sys_user ADD COLUMN valid_to DATETIME NULL AFTER valid_from',
    'SELECT 1'
);
PREPARE stmt_add_valid_to FROM @add_valid_to_sql;
EXECUTE stmt_add_valid_to;
DEALLOCATE PREPARE stmt_add_valid_to;

UPDATE sys_user
SET valid_from = IFNULL(valid_from, created_at),
    valid_to = IFNULL(valid_to, '2099-12-31 23:59:59')
WHERE is_deleted = 0;
