Postgres.hpp 6.36 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * The CERN Tape Archive (CTA) project
 * Copyright (C) 2019  CERN
 *
 * This program 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 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

21
#include "common/exception/DatabaseCheckConstraintError.hpp"
22
#include "common/exception/DatabaseUniqueError.hpp"
23
24
#include "common/exception/Exception.hpp"
#include "common/exception/LostDatabaseConnection.hpp"
25
26
27

#include <algorithm>
#include <cstring>
28
#include <iostream>
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <libpq-fe.h>
#include <string>

namespace cta {
namespace rdbms {
namespace wrapper {

/**
 * A convenience class containing some utilities used by the postgres rdbms wrapper classes.
 */
class Postgres {
public:

  /**
   * A method to throw a DB related error with an informative string obtained from the connection and/or
   * request status. The exception will be a LostDatabaseConnection() if the postgres connection structure
   * indicates that the connection is no longer valid.
   */
  [[noreturn]] static void ThrowInfo(const PGconn *conn, const PGresult *res, const std::string &prefix) {
    const char *const pgcstr = PQerrorMessage(conn);
    std::string pgstr;
    if (nullptr != pgcstr) {
      pgstr = pgcstr;
      pgstr.erase(std::remove(pgstr.begin(), pgstr.end(), '\n'), pgstr.end());
    }
    std::string resstr;
55
    bool uniqueViolation = false;
56
    bool checkViolation = false;
57
58
59
60
    if (nullptr != res) {
      resstr = "DB Result Status:" + std::to_string(PQresultStatus(res));
      const char *const e = PQresultErrorField(res, PG_DIAG_SQLSTATE);
      if (nullptr != e && '\0' != *e) {
61
        uniqueViolation = 0 == std::strcmp("23505", e);
62
        checkViolation = 0 == std::strcmp("23514", e);
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
        resstr += " SQLState:" + std::string(e);
      }
    }
    std::string dbmsg;
    if (!pgstr.empty()) {
      dbmsg = pgstr;
      if (!resstr.empty()) {
        dbmsg += " ("+resstr+")";
      }
    } else {
      dbmsg = resstr;
    }

    if (!dbmsg.empty()) {
      dbmsg = "Database library reported: " + dbmsg;
    }
    if (!prefix.empty()) {
      if (!dbmsg.empty()) {
        dbmsg = prefix + ": " + dbmsg;
      } else {
        dbmsg = prefix;
      }
    }

    bool badconn = false;
    if (nullptr != conn) {
      if (CONNECTION_OK != PQstatus(conn)) {
        badconn = true;
      }
    }

    if (badconn) {
      throw exception::LostDatabaseConnection(dbmsg);
    }
97
98
99
    if (uniqueViolation) {
      throw exception::DatabaseUniqueError(dbmsg);
    }
100
    if (checkViolation) {
101
      throw exception::DatabaseCheckConstraintError(dbmsg);
102
    }
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    throw exception::Exception(dbmsg);
  }

  /**
   * A class to help managing the lifetime of a postgres result.
   */
  class Result {
  public:

    Result( const Result& ) = delete; // non construction-copyable
    Result& operator=( const Result& ) = delete; // non copyable

    /**
     * Constructor.
     * The Result object will manage a single result.
     * A single result may contain 0 or more rows.
     *
     * @param res A libpq result.
     */
    Result(PGresult *res) : m_res(res), m_rcode(PQresultStatus(res)) {
    }

   /**
    * Destructor.
    */
    ~Result() {
      clear();
    }

    /**
     * Relases the single result or ensures the conneciton has no pending results.
     */
    void clear() {
      PQclear(m_res);
      m_res = nullptr;
    }

    /**
     * Gets the current result.
     *
     * @return The libpq result.
     */
    PGresult *get() const {
      return m_res;
    }

    /**
     * Gets the current result code.
     *
     * @return The libpq result rcode.
     */
    ExecStatusType rcode() const {
      return m_rcode;
    }

  private:
    /**
     * The result as a libpq result.
     */
    PGresult *m_res;

    /**
     * rcode of current result.
     */
    ExecStatusType m_rcode;

  }; // class Result

  /**
   * A class to help managing a sequence of results from a postgres connection.
   * Each result in the sequence may in tern contain 0 or more rows.
   */
  class ResultItr {
  public:

    ResultItr( const ResultItr& ) = delete; // non construction-copyable
    ResultItr& operator=( const ResultItr& ) = delete; // non copyable

    /**
     * Constructor.
     * The ResultItr object will manage a sequence of results, the first of which
     * is only available after calling next().
     *
     * @param conn A libpq connection.
     */
    ResultItr(PGconn *conn) :
      m_conn(conn), m_res(nullptr), m_finished(false), m_rcode(PGRES_FATAL_ERROR) {
    }

   /**
    * Destructor.
    */
    ~ResultItr() {
      clear();
    }

    /**
     * Relases the single result or ensures the conneciton has no pending results.
     */
    void clear() {
      while(nullptr != next());
    }

    /**
     * Gets the current result.
     *
     * @return The libpq result.
     */
    PGresult *get() const {
      return m_res;
    }

    /**
     * Moves to the next result available.
     *
     * @return  The libpq result of the next result or nullptr if none is available.
     */
    PGresult *next() {
      if (m_finished) {
        return nullptr;
      }
      PQclear(m_res);
      m_res = PQgetResult(m_conn);
      m_rcode = PQresultStatus(m_res);
      if (nullptr == m_res) {
        m_finished = true;
      }
      return m_res;
    }

    /**
     * Gets the current result code.
     *
     * @return The libpq result rcode.
     */
    ExecStatusType rcode() const {
      return m_rcode;
    }

  private:
    /**
     * The libpq postgres connection from which to fetch results
     */
    PGconn *m_conn;

    /**
     * The current result as a libpq result.
     */
    PGresult *m_res;

    /**
     * Indicates that the end of result series has been detected on the connection.
     */
    bool m_finished;

    /**
     * rcode of	current	result.
     */
    ExecStatusType m_rcode;

  }; // class ResultItr

}; // class Postgres

} // namespace wrapper
} // namespace rdbms
} // namespace cta