/*
  This file is part of TALER
  (C) 2014--2025 Taler Systems SA

  TALER is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser 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 src/backenddb/start.c
 * @brief implementation of the start, rollback and commit functions
 * @author Christian Grothoff
 */
#include <gnunet/gnunet_util_lib.h>
#include "merchantdb_lib.h"
#include "merchant-database/start.h"
#include "merchant-database/preflight.h"
#include "helper.h"


enum GNUNET_GenericReturnValue
TALER_MERCHANTDB_start (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *name)
{
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("START TRANSACTION ISOLATION LEVEL SERIALIZABLE"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  GNUNET_assert (NULL != name);
  TALER_MERCHANTDB_preflight (pg);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Starting merchant DB transaction `%s'\n",
              name);
  if (GNUNET_OK !=
      GNUNET_PQ_exec_statements (pg->conn,
                                 es))
  {
    TALER_LOG_ERROR ("Failed to start transaction\n");
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  pg->transaction_name = name;
  return GNUNET_OK;
}


enum GNUNET_GenericReturnValue
TALER_MERCHANTDB_start_read_committed (
  struct TALER_MERCHANTDB_PostgresContext *pg,
  const char *name)
{
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("START TRANSACTION ISOLATION LEVEL READ COMMITTED"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  GNUNET_assert (NULL != name);
  TALER_MERCHANTDB_preflight (pg);
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Starting merchant DB transaction %s (READ COMMITTED)\n",
              name);
  if (GNUNET_OK !=
      GNUNET_PQ_exec_statements (pg->conn,
                                 es))
  {
    TALER_LOG_ERROR ("Failed to start transaction\n");
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  pg->transaction_name = name;
  return GNUNET_OK;
}


void
TALER_MERCHANTDB_rollback (
  struct TALER_MERCHANTDB_PostgresContext *pg)
{
  struct GNUNET_PQ_ExecuteStatement es[] = {
    GNUNET_PQ_make_execute ("ROLLBACK"),
    GNUNET_PQ_EXECUTE_STATEMENT_END
  };

  if (NULL == pg->transaction_name)
    return;
  GNUNET_log (GNUNET_ERROR_TYPE_INFO,
              "Rolling back merchant DB transaction `%s'\n",
              pg->transaction_name);
  GNUNET_break (GNUNET_OK ==
                GNUNET_PQ_exec_statements (pg->conn,
                                           es));
  pg->transaction_name = NULL;
}


enum GNUNET_DB_QueryStatus
TALER_MERCHANTDB_commit (
  struct TALER_MERCHANTDB_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);
    /* PostgreSQL accepts COMMIT on a transaction it has already aborted: it
       silently rolls the transaction back and answers PGRES_COMMAND_OK with the
       command tag ROLLBACK.  GNUNET_PQ_eval_result() cannot tell that apart from
       a real commit, so every caller took the success path for a transaction
       whose writes are gone.  Report it as a soft error instead: sessions run
       SERIALIZABLE, so the overwhelmingly likely cause is an unhandled
       40001/40P01 for which retrying is right; a caller with a retry loop gives
       up after MAX_RETRIES and fails visibly, one without fails immediately.

       The *success* path deliberately keeps returning exactly what
       GNUNET_PQ_eval_prepared_non_select() returned before.  That function is
       GNUNET_PQ_exec_prepared() + GNUNET_PQ_eval_result() plus a
       strtol(PQcmdTuples()) step that only runs when the status is already
       GNUNET_DB_STATUS_SUCCESS_NO_RESULTS, and PQcmdTuples() on a COMMIT command
       tag is the empty string -- so that step yields 0, which is
       GNUNET_DB_STATUS_SUCCESS_NO_RESULTS again. */
    if ( (0 <= qs) &&
         (NULL != result) &&
         (0 == strcmp ("ROLLBACK",
                       PQcmdStatus (result))) )
    {
      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;
}
