File: spgsql.cc

package info (click to toggle)
pdns 5.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,824 kB
  • sloc: cpp: 101,240; sh: 5,616; makefile: 2,318; sql: 860; ansic: 675; python: 635; yacc: 245; perl: 161; lex: 131
file content (435 lines) | stat: -rw-r--r-- 11,932 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
55
56
57
58
59
60
61
62
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
97
98
99
100
101
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <string>
#include "spgsql.hh"
#include <sys/time.h>
#include <iostream>
#include "pdns/logger.hh"
#include "pdns/dns.hh"
#include "pdns/namespaces.hh"
#include <algorithm>

class SPgSQLStatement : public SSqlStatement
{
public:
  SPgSQLStatement(const string& query, bool dolog, int nparams, SPgSQL* db, unsigned int nstatement)
  {
    d_query = query;
    d_dolog = dolog;
    d_parent = db;
    d_nparams = nparams;
    d_nstatement = nstatement;
  }

  SSqlStatement* bind(const string& name, bool value) override { return bind(name, string(value ? "t" : "f")); }
  SSqlStatement* bind(const string& name, int value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& name, uint32_t value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& name, long value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& name, unsigned long value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& name, long long value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& name, unsigned long long value) override { return bind(name, std::to_string(value)); }
  SSqlStatement* bind(const string& /* name */, const std::string& value) override
  {
    prepareStatement();
    allocate();
    if (d_paridx >= d_nparams) {
      releaseStatement();
      throw SSqlException("Attempt to bind more parameters than query has: " + d_query);
    }
    paramValues[d_paridx] = new char[value.size() + 1];
    memset(paramValues[d_paridx], 0, sizeof(char) * (value.size() + 1));
    value.copy(paramValues[d_paridx], value.size());
    paramLengths[d_paridx] = value.size();
    d_paridx++;
    return this;
  }
  SSqlStatement* bindNull(const string& /* name */) override
  {
    prepareStatement();
    d_paridx++;
    return this;
  } // these are set null in allocate()
  SSqlStatement* execute() override
  {
    prepareStatement();
    if (d_dolog) {
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": Statement: " << d_query << endl;
      if (d_paridx) {
        // Log message is similar, but not exactly the same as the postgres server log.
        std::stringstream log_message;
        log_message << "Query " << ((long)(void*)this) << ": Parameters: ";
        for (int i = 0; i < d_paridx; i++) {
          if (i != 0) {
            log_message << ", ";
          }
          log_message << "$" << (i + 1) << " = ";
          if (paramValues[i] == nullptr) {
            log_message << "NULL";
          }
          else {
            log_message << "'" << paramValues[i] << "'";
          }
        }
        g_log << Logger::Warning << log_message.str() << endl;
      }
      d_dtime.set();
    }
    if (!d_stmt.empty()) {
      d_res_set = PQexecPrepared(d_db(), d_stmt.c_str(), d_nparams, paramValues, paramLengths, nullptr, 0);
    }
    else {
      d_res_set = PQexecParams(d_db(), d_query.c_str(), d_nparams, nullptr, paramValues, paramLengths, nullptr, 0);
    }
    ExecStatusType status = PQresultStatus(d_res_set);
    if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
      string errmsg(PQresultErrorMessage(d_res_set));
      releaseStatement();
      throw SSqlException("Fatal error during query: " + d_query + string(": ") + errmsg);
    }
    d_cur_set = 0;
    if (d_dolog) {
      auto diff = d_dtime.udiffNoReset();
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << diff << " us to execute" << endl;
    }

    nextResult();
    return this;
  }

  void nextResult()
  {
    if (d_res_set == nullptr)
      return;
    if (d_cur_set >= PQntuples(d_res_set)) {
      PQclear(d_res_set);
      d_res_set = nullptr;
      return;
    }
    if (PQftype(d_res_set, 0) == 1790) { // REFCURSOR
      g_log << Logger::Error << "Postgres query returned a REFCURSOR and we do not support those - see https://github.com/PowerDNS/pdns/pull/10259" << endl;
      PQclear(d_res_set);
      d_res_set = nullptr;
    }
    else {
      d_res = d_res_set;
      d_res_set = nullptr;
      d_resnum = PQntuples(d_res);
    }
  }

  bool hasNextRow() override
  {
    if (d_dolog && d_residx == d_resnum) {
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << d_dtime.udiff() << " us total to last row" << endl;
    }

    return d_residx < d_resnum;
  }

  SSqlStatement* nextRow(row_t& row) override
  {
    int i;
    row.clear();
    if (d_residx >= d_resnum || !d_res)
      return this;
    row.reserve(PQnfields(d_res));
    for (i = 0; i < PQnfields(d_res); i++) {
      if (PQgetisnull(d_res, d_residx, i)) {
        row.emplace_back("");
      }
      else if (PQftype(d_res, i) == 16) { // BOOLEAN
        char* val = PQgetvalue(d_res, d_residx, i);
        row.emplace_back(val[0] == 't' ? "1" : "0");
      }
      else {
        row.emplace_back(PQgetvalue(d_res, d_residx, i));
      }
    }
    d_residx++;
    if (d_residx >= d_resnum) {
      PQclear(d_res);
      d_res = nullptr;
      nextResult();
    }
    return this;
  }

  SSqlStatement* getResult(result_t& result) override
  {
    result.clear();
    if (d_res == nullptr)
      return this;
    result.reserve(d_resnum);
    row_t row;
    while (hasNextRow()) {
      nextRow(row);
      result.push_back(std::move(row));
    }
    return this;
  }

  SSqlStatement* reset() override
  {
    int i;
    if (d_res) {
      PQclear(d_res);
    }
    if (d_res_set) {
      PQclear(d_res_set);
    }
    d_res_set = nullptr;
    d_res = nullptr;
    d_paridx = d_residx = d_resnum = 0;
    if (paramValues) {
      for (i = 0; i < d_nparams; i++) {
        if (paramValues[i]) {
          delete[] paramValues[i];
        }
      }
    }
    delete[] paramValues;
    paramValues = nullptr;
    delete[] paramLengths;
    paramLengths = nullptr;
    return this;
  }

  const std::string& getQuery() override { return d_query; }

  ~SPgSQLStatement() override
  {
    releaseStatement();
  }

private:
  PGconn* d_db()
  {
    return d_parent->db();
  }

  void releaseStatement()
  {
    d_prepared = false;
    reset();
    if (!d_stmt.empty()) {
      string cmd = string("DEALLOCATE " + d_stmt);
      PGresult* res = PQexec(d_db(), cmd.c_str());
      PQclear(res);
      d_stmt.clear();
    }
  }

  void prepareStatement()
  {
    if (d_prepared)
      return;
    if (d_parent->usePrepared()) {
      // prepare a statement; name must be unique per session (using d_nstatement to ensure this).
      this->d_stmt = string("stmt") + std::to_string(d_nstatement);
      PGresult* res = PQprepare(d_db(), d_stmt.c_str(), d_query.c_str(), d_nparams, nullptr);
      ExecStatusType status = PQresultStatus(res);
      string errmsg(PQresultErrorMessage(res));
      PQclear(res);
      if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
        releaseStatement();
        throw SSqlException("Fatal error during prePQpreparepare: " + d_query + string(": ") + errmsg);
      }
    }
    paramValues = nullptr;
    paramLengths = nullptr;
    d_cur_set = d_paridx = d_residx = d_resnum = 0;
    d_res = nullptr;
    d_res_set = nullptr;
    d_prepared = true;
  }

  void allocate()
  {
    if (paramValues != nullptr)
      return;
    paramValues = new char*[d_nparams];
    paramLengths = new int[d_nparams];
    memset(paramValues, 0, sizeof(char*) * d_nparams);
    memset(paramLengths, 0, sizeof(int) * d_nparams);
  }

  string d_query;
  string d_stmt;
  SPgSQL* d_parent;
  PGresult* d_res_set{nullptr};
  PGresult* d_res{nullptr};
  bool d_dolog;
  DTime d_dtime; // only used if d_dolog is set
  bool d_prepared{false};
  int d_nparams;
  int d_paridx{0};
  char** paramValues{nullptr};
  int* paramLengths{nullptr};
  int d_residx{0};
  int d_resnum{0};
  int d_cur_set{0};
  unsigned int d_nstatement;
};

bool SPgSQL::s_dolog;

static string escapeForPQparam(const string& v)
{
  string ret = v;
  boost::replace_all(ret, "\\", "\\\\");
  boost::replace_all(ret, "'", "\\'");

  return string("'") + ret + string("'");
}

SPgSQL::SPgSQL(const string& database, const string& host, const string& port, const string& user,
               const string& password, const string& extra_connection_parameters, const bool use_prepared)
{
  d_db = nullptr;
  d_in_trx = false;
  d_connectstr = "";
  d_nstatements = 0;

  if (!database.empty())
    d_connectstr += "dbname=" + escapeForPQparam(database);

  if (!user.empty())
    d_connectstr += " user=" + escapeForPQparam(user);

  if (!host.empty())
    d_connectstr += " host=" + escapeForPQparam(host);

  if (!port.empty())
    d_connectstr += " port=" + escapeForPQparam(port);

  if (!extra_connection_parameters.empty())
    d_connectstr += " " + extra_connection_parameters;

  d_connectlogstr = d_connectstr;

  if (!password.empty()) {
    d_connectlogstr += " password=<HIDDEN>";
    d_connectstr += " password=" + escapeForPQparam(password);
  }

  d_use_prepared = use_prepared;

  d_db = PQconnectdb(d_connectstr.c_str());

  if (!d_db || PQstatus(d_db) == CONNECTION_BAD) {
    try {
      throw sPerrorException("Unable to connect to database, connect string: " + d_connectlogstr);
    }
    catch (...) {
      if (d_db)
        PQfinish(d_db);
      d_db = 0;
      throw;
    }
  }
}

void SPgSQL::setLog(bool state)
{
  s_dolog = state;
}

SPgSQL::~SPgSQL()
{
  PQfinish(d_db);
}

SSqlException SPgSQL::sPerrorException(const string& reason)
{
  return SSqlException(reason + string(": ") + (d_db ? PQerrorMessage(d_db) : "no connection"));
}

void SPgSQL::execute(const string& query)
{
  PGresult* res = PQexec(d_db, query.c_str());
  ExecStatusType status = PQresultStatus(res);
  string errmsg(PQresultErrorMessage(res));
  PQclear(res);
  if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
    throw sPerrorException("Fatal error during query: " + errmsg);
  }
}

std::unique_ptr<SSqlStatement> SPgSQL::prepare(const string& query, int nparams)
{
  d_nstatements++;
  return std::make_unique<SPgSQLStatement>(query, s_dolog, nparams, this, d_nstatements);
}

void SPgSQL::startTransaction()
{
  execute("begin");
  d_in_trx = true;
}

void SPgSQL::commit()
{
  execute("commit");
  d_in_trx = false;
}

void SPgSQL::rollback()
{
  execute("rollback");
  d_in_trx = false;
}

bool SPgSQL::isConnectionUsable()
{
  if (PQstatus(d_db) != CONNECTION_OK) {
    return false;
  }

  bool usable = false;
  int sd = PQsocket(d_db);
  bool wasNonBlocking = isNonBlocking(sd);

  if (!wasNonBlocking) {
    if (!setNonBlocking(sd)) {
      return usable;
    }
  }

  usable = isTCPSocketUsable(sd);

  if (!wasNonBlocking) {
    if (!setBlocking(sd)) {
      usable = false;
    }
  }

  return usable;
}

void SPgSQL::reconnect()
{
  PQreset(d_db);
}