IF NOT  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[LEADER_STATUS_TABLE]') AND TYPE IN (N'U'))
CREATE TABLE  LEADER_STATUS_TABLE (
  GROUP_ID VARCHAR (450) NOT NULL,
  NODE_ID VARCHAR (450) NOT NULL,
  LAST_HEARTBEAT BIGINT NOT NULL,
  PRIMARY KEY (GROUP_ID)
);

IF NOT  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[CLUSTER_NODE_STATUS_TABLE]') AND TYPE IN (N'U'))
CREATE TABLE CLUSTER_NODE_STATUS_TABLE (
  GROUP_ID VARCHAR (450) NOT NULL,
  NODE_ID VARCHAR (450) NOT NULL,
  IS_NEW_NODE INT NOT NULL,
  LAST_HEARTBEAT BIGINT NOT NULL,
  PRIMARY KEY (GROUP_ID, NODE_ID)
);

IF NOT  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[MEMBERSHIP_EVENT_TABLE]') AND TYPE IN (N'U'))
CREATE TABLE MEMBERSHIP_EVENT_TABLE (
  GROUP_ID VARCHAR (450) NOT NULL,
  NODE_ID VARCHAR (450) NOT NULL,
  CHANGE_TYPE INT NOT NULL,
  CHANGED_MEMBER_ID VARCHAR (450) NOT NULL
);

IF NOT  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[REMOVED_MEMBERS_TABLE]') AND TYPE IN (N'U'))
CREATE TABLE REMOVED_MEMBERS_TABLE (
  GROUP_ID VARCHAR (450) NOT NULL,
  NODE_ID VARCHAR (450) NOT NULL,
  REMOVED_MEMBER_ID VARCHAR (450) NOT NULL
);

IF NOT  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[COORDINATED_TASK_TABLE]') AND TYPE IN (N'U'))
CREATE TABLE COORDINATED_TASK_TABLE (
  TASK_NAME VARCHAR (512) NOT NULL,
  DESTINED_NODE_ID VARCHAR (450),
  TASK_STATE VARCHAR (32),
  PRIMARY KEY (TASK_NAME)
);

IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[TASK_DELETE_GUARD]') AND TYPE IN (N'U'))
CREATE TABLE TASK_DELETE_GUARD (
  TASK_NAME VARCHAR (512) NOT NULL,
  GUARD_UUID VARCHAR (36) NOT NULL,
  UPDATED_AT BIGINT NOT NULL,
  PRIMARY KEY (TASK_NAME)
);

IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[TASK_DELETE_BARRIER]') AND TYPE IN (N'U'))
CREATE TABLE TASK_DELETE_BARRIER (
  TASK_NAME VARCHAR (512) NOT NULL,
  GUARD_UUID VARCHAR (36) NOT NULL,
  OWNER_NODE_ID VARCHAR (512) NOT NULL,
  STATUS VARCHAR (16) NOT NULL,
  DEADLINE_AT BIGINT NOT NULL,
  UPDATED_AT BIGINT NOT NULL,
  PRIMARY KEY (TASK_NAME, GUARD_UUID)
);

IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[TASK_DELETE_BARRIER_EXPECTED]') AND TYPE IN (N'U'))
CREATE TABLE TASK_DELETE_BARRIER_EXPECTED (
  TASK_NAME VARCHAR (512) NOT NULL,
  GUARD_UUID VARCHAR (36) NOT NULL,
  NODE_ID VARCHAR (220) NOT NULL,
  PRIMARY KEY (TASK_NAME, GUARD_UUID, NODE_ID)
);

IF NOT EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[TASK_DELETE_BARRIER_ACK]') AND TYPE IN (N'U'))
CREATE TABLE TASK_DELETE_BARRIER_ACK (
  TASK_NAME VARCHAR (512) NOT NULL,
  GUARD_UUID VARCHAR (36) NOT NULL,
  NODE_ID VARCHAR (220) NOT NULL,
  ACKED_AT BIGINT NOT NULL,
  PRIMARY KEY (TASK_NAME, GUARD_UUID, NODE_ID)
);
