SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE DATABASE IF NOT EXISTS hyapp_cron DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_cron;

CREATE TABLE IF NOT EXISTS cron_task_leases (
  task_name VARCHAR(96) NOT NULL,
  app_code VARCHAR(32) NOT NULL,
  owner_node_id VARCHAR(128) NOT NULL,
  lease_until_ms BIGINT NOT NULL,
  updated_at_ms BIGINT NOT NULL,
  PRIMARY KEY (task_name, app_code),
  KEY idx_cron_task_leases_expire (lease_until_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS cron_task_runs (
  run_id VARCHAR(96) NOT NULL,
  task_name VARCHAR(96) NOT NULL,
  app_code VARCHAR(32) NOT NULL,
  owner_node_id VARCHAR(128) NOT NULL,
  status VARCHAR(32) NOT NULL,
  claimed_count INT NOT NULL DEFAULT 0,
  processed_count INT NOT NULL DEFAULT 0,
  success_count INT NOT NULL DEFAULT 0,
  failure_count INT NOT NULL DEFAULT 0,
  started_at_ms BIGINT NOT NULL,
  finished_at_ms BIGINT NULL,
  duration_ms BIGINT NOT NULL DEFAULT 0,
  error_message VARCHAR(512) NOT NULL DEFAULT '',
  PRIMARY KEY (run_id),
  KEY idx_cron_task_runs_task_time (task_name, app_code, started_at_ms),
  KEY idx_cron_task_runs_status (status, started_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

