--
-- This file is part of TALER
-- Copyright (C) 2014--2022 Taler Systems SA
--
-- TALER is free software; you can redistribute it and/or modify it under the
-- terms of the GNU General Public License as published by the Free Software
-- Foundation; either version 3, or (at your option) any later version.
--
-- TALER is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-- A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along with
-- TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
--

CREATE TABLE work_shards
  (shard_serial_id BIGINT GENERATED BY DEFAULT AS IDENTITY UNIQUE
  ,last_attempt INT8 NOT NULL
  ,start_row INT8 NOT NULL
  ,end_row INT8 NOT NULL
  ,completed BOOLEAN NOT NULL DEFAULT FALSE
  ,job_name TEXT NOT NULL
  ,PRIMARY KEY (job_name, start_row)
  );
COMMENT ON TABLE work_shards
  IS 'coordinates work between multiple processes working on the same job';
COMMENT ON COLUMN work_shards.shard_serial_id
  IS 'unique serial number identifying the shard';
COMMENT ON COLUMN work_shards.last_attempt
  IS 'last time a worker attempted to work on the shard';
COMMENT ON COLUMN work_shards.completed
  IS 'set to TRUE once the shard is finished by a worker';
COMMENT ON COLUMN work_shards.start_row
  IS 'row at which the shard scope starts, inclusive';
COMMENT ON COLUMN work_shards.end_row
  IS 'row at which the shard scope ends, exclusive';
COMMENT ON COLUMN work_shards.job_name
  IS 'unique name of the job the workers on this shard are performing';

CREATE INDEX work_shards_by_job_name_completed_last_attempt_index
  ON work_shards
  (job_name
  ,completed
  ,last_attempt ASC
  );

CREATE INDEX work_shards_by_end_row_index
  ON work_shards
  (end_row DESC);

CREATE INDEX work_shards_by_rows
  ON work_shards
  (job_name
  ,start_row
  ,end_row);
