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


/**
 * Commit the current transaction of a database connection.
 *
 * @param pg the database context
 * @return final transaction status
 */
enum GNUNET_DB_QueryStatus
TALER_EXCHANGEDB_commit (struct TALER_EXCHANGEDB_PostgresContext *pg)
{
  struct GNUNET_PQ_QueryParam params[] = {
    GNUNET_PQ_query_param_end
  };
  enum GNUNET_DB_QueryStatus qs;

  GNUNET_break (NULL != pg->transaction_name);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Committing transaction `%s'\n",
              pg->transaction_name);
  PREPARE (pg,
           "commit",
           "COMMIT");
  {
    PGresult *result;

    result = GNUNET_PQ_exec_prepared (pg->conn,
                                      "commit",
                                      params);
    qs = GNUNET_PQ_eval_result (pg->conn,
                                "commit",
                                result);
    if ( (0 <= qs) &&
         (NULL != result) &&
         (0 == strcmp ("ROLLBACK",
                       PQcmdStatus (result))) )
    {
      /* PostgreSQL accepts COMMIT on a transaction it has already aborted:
         it silently rolls back and answers PGRES_COMMAND_OK with the command
         tag ROLLBACK.  That is indistinguishable from a successful commit to
         GNUNET_PQ_eval_result(), so every caller would take the success path
         for a transaction whose writes are gone.  Report it as a soft error:
         the transaction is almost always aborted by a serialization failure
         (we run SERIALIZABLE), so retrying is the right answer, and callers
         with a retry loop will give up and fail visibly after
         MAX_RETRIES. */
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Transaction `%s' was rolled back by the database instead of committed; a previous statement must have failed without being handled\n",
                  pg->transaction_name);
      qs = GNUNET_DB_STATUS_SOFT_ERROR;
    }
    PQclear (result);
  }
  pg->transaction_name = NULL;
  return qs;
}
