/*
   This file is part of TALER
   Copyright (C) 2022, 2026 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/>
 */
/**
 * @file exchangedb/update_shard_progress.c
 * @brief Implementation of the update_shard_progress function for Postgres
 * @author Christian Grothoff
 */
#include "taler/taler_pq_lib.h"
#include "exchange-database/update_shard_progress.h"
#include "helper.h"


enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_update_shard_progress (
  struct TALER_EXCHANGEDB_PostgresContext *pg,
  const char *job_name,
  uint64_t start_row,
  uint64_t end_row,
  uint64_t progress_row,
  struct GNUNET_TIME_Relative lease)
{
  struct GNUNET_TIME_Absolute lease_until
    = GNUNET_TIME_relative_to_absolute (lease);
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_string (job_name),
    GNUNET_PQ_query_param_uint64 (&start_row),
    GNUNET_PQ_query_param_uint64 (&end_row),
    GNUNET_PQ_query_param_uint64 (&progress_row),
    GNUNET_PQ_query_param_absolute_time (&lease_until),
    GNUNET_PQ_query_param_end
  };

  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "Shard %s (%llu,%llu] progressed to %llu\n",
              job_name,
              (unsigned long long) start_row,
              (unsigned long long) end_row,
              (unsigned long long) progress_row);
  /* GREATEST() keeps this monotonic: a worker that lost the shard to a second
     one and only notices later must not push the marker back. Both the
     'completed' flag and the lease renewal ride along on this one statement,
     so a caller never needs a second round-trip (let alone a second
     transaction) to say "and that was the last of it". */
  PREPARE (pg,
           "update_shard_progress",
           "UPDATE work_shards"
           "   SET progress_row=GREATEST(progress_row,$4)"
           "      ,completed=(GREATEST(progress_row,$4) >= end_row)"
           "      ,last_attempt=$5"
           " WHERE job_name=$1"
           "   AND start_row=$2"
           "   AND end_row=$3;");
  return GNUNET_PQ_eval_prepared_non_select (pg->conn,
                                             "update_shard_progress",
                                             params);
}
