ALTER TABLE "command_records"
  ADD COLUMN IF NOT EXISTS "claim_generation" bigint NOT NULL DEFAULT 1;

ALTER TABLE "command_records"
  ADD COLUMN IF NOT EXISTS "lease_expires_at" timestamp with time zone;

UPDATE "command_records"
SET "lease_expires_at" = "claimed_at" + INTERVAL '10 minutes'
WHERE "lease_expires_at" IS NULL;

ALTER TABLE "command_records"
  ALTER COLUMN "lease_expires_at" SET DEFAULT (CURRENT_TIMESTAMP + INTERVAL '10 minutes'),
  ALTER COLUMN "lease_expires_at" SET NOT NULL;

DROP INDEX IF EXISTS "command_records_status_claimed_at_idx";
CREATE INDEX IF NOT EXISTS "command_records_status_lease_expires_at_idx"
  ON "command_records" ("status", "lease_expires_at");
