• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PowerDNS / pdns / 19031394433

03 Nov 2025 10:27AM UTC coverage: 72.82% (+0.08%) from 72.74%
19031394433

Pull #16405

github

web-flow
Merge d30eed73d into 22b7a74ae
Pull Request #16405: dnsdist: Fix the outgoing DoT YAML example

38181 of 63134 branches covered (60.48%)

Branch coverage included in aggregate %.

127131 of 163882 relevant lines covered (77.57%)

12637218.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.38
/modules/gpgsqlbackend/spgsql.cc
1
/*
2
 * This file is part of PowerDNS or dnsdist.
3
 * Copyright -- PowerDNS.COM B.V. and its contributors
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of version 2 of the GNU General Public License as
7
 * published by the Free Software Foundation.
8
 *
9
 * In addition, for the avoidance of any doubt, permission is granted to
10
 * link this program with OpenSSL and to (re)distribute the binaries
11
 * produced as the result of such linking.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
 */
22

23
#ifdef HAVE_CONFIG_H
24
#include "config.h"
25
#endif
26
#include <string>
27
#include "spgsql.hh"
28
#include <sys/time.h>
29
#include <iostream>
30
#include "pdns/logger.hh"
31
#include "pdns/dns.hh"
32
#include "pdns/namespaces.hh"
33
#include <algorithm>
34

35
class SPgSQLStatement : public SSqlStatement
36
{
37
public:
38
  SPgSQLStatement(const string& query, bool dolog, int nparams, SPgSQL* db, unsigned int nstatement)
39
  {
257,077✔
40
    d_query = query;
257,077✔
41
    d_dolog = dolog;
257,077✔
42
    d_parent = db;
257,077✔
43
    d_nparams = nparams;
257,077✔
44
    d_nstatement = nstatement;
257,077✔
45
  }
257,077✔
46

47
  SSqlStatement* bind(const string& name, bool value) override { return bind(name, string(value ? "t" : "f")); }
1,058,842✔
48
  SSqlStatement* bind(const string& name, int value) override { return bind(name, std::to_string(value)); }
1,095,324✔
49
  SSqlStatement* bind(const string& name, uint32_t value) override { return bind(name, std::to_string(value)); }
447,624✔
50
  SSqlStatement* bind(const string& name, long value) override { return bind(name, std::to_string(value)); }
162✔
51
  SSqlStatement* bind(const string& name, unsigned long value) override { return bind(name, std::to_string(value)); }
22✔
52
  SSqlStatement* bind(const string& name, long long value) override { return bind(name, std::to_string(value)); }
×
53
  SSqlStatement* bind(const string& name, unsigned long long value) override { return bind(name, std::to_string(value)); }
×
54
  SSqlStatement* bind(const string& /* name */, const std::string& value) override
55
  {
4,453,846✔
56
    prepareStatement();
4,453,846✔
57
    allocate();
4,453,846✔
58
    if (d_paridx >= d_nparams) {
4,453,846!
59
      releaseStatement();
×
60
      throw SSqlException("Attempt to bind more parameters than query has: " + d_query);
×
61
    }
×
62
    paramValues[d_paridx] = new char[value.size() + 1];
4,453,846✔
63
    memset(paramValues[d_paridx], 0, sizeof(char) * (value.size() + 1));
4,453,846✔
64
    value.copy(paramValues[d_paridx], value.size());
4,453,846✔
65
    paramLengths[d_paridx] = value.size();
4,453,846✔
66
    d_paridx++;
4,453,846✔
67
    return this;
4,453,846✔
68
  }
4,453,846✔
69
  SSqlStatement* bindNull(const string& /* name */) override
70
  {
325,796✔
71
    prepareStatement();
325,796✔
72
    d_paridx++;
325,796✔
73
    return this;
325,796✔
74
  } // these are set null in allocate()
325,796✔
75
  SSqlStatement* execute() override
76
  {
662,952✔
77
    prepareStatement();
662,952✔
78
    if (d_dolog) {
662,952!
79
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": Statement: " << d_query << endl;
×
80
      if (d_paridx) {
×
81
        // Log message is similar, but not exactly the same as the postgres server log.
82
        std::stringstream log_message;
×
83
        log_message << "Query " << ((long)(void*)this) << ": Parameters: ";
×
84
        for (int i = 0; i < d_paridx; i++) {
×
85
          if (i != 0) {
×
86
            log_message << ", ";
×
87
          }
×
88
          log_message << "$" << (i + 1) << " = ";
×
89
          if (paramValues[i] == nullptr) {
×
90
            log_message << "NULL";
×
91
          }
×
92
          else {
×
93
            log_message << "'" << paramValues[i] << "'";
×
94
          }
×
95
        }
×
96
        g_log << Logger::Warning << log_message.str() << endl;
×
97
      }
×
98
      d_dtime.set();
×
99
    }
×
100
    if (!d_stmt.empty()) {
662,952✔
101
      d_res_set = PQexecPrepared(d_db(), d_stmt.c_str(), d_nparams, paramValues, paramLengths, nullptr, 0);
662,951✔
102
    }
662,951✔
103
    else {
1✔
104
      d_res_set = PQexecParams(d_db(), d_query.c_str(), d_nparams, nullptr, paramValues, paramLengths, nullptr, 0);
1✔
105
    }
1✔
106
    ExecStatusType status = PQresultStatus(d_res_set);
662,952✔
107
    if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
662,952!
108
      string errmsg(PQresultErrorMessage(d_res_set));
×
109
      releaseStatement();
×
110
      throw SSqlException("Fatal error during query: " + d_query + string(": ") + errmsg);
×
111
    }
×
112
    d_cur_set = 0;
662,952✔
113
    if (d_dolog) {
662,952!
114
      auto diff = d_dtime.udiffNoReset();
×
115
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << diff << " us to execute" << endl;
×
116
    }
×
117

118
    nextResult();
662,952✔
119
    return this;
662,952✔
120
  }
662,952✔
121

122
  void nextResult()
123
  {
699,419✔
124
    if (d_res_set == nullptr)
699,419✔
125
      return;
36,466✔
126
    if (d_cur_set >= PQntuples(d_res_set)) {
662,953✔
127
      PQclear(d_res_set);
626,484✔
128
      d_res_set = nullptr;
626,484✔
129
      return;
626,484✔
130
    }
626,484✔
131
    if (PQftype(d_res_set, 0) == 1790) { // REFCURSOR
36,469!
132
      g_log << Logger::Error << "Postgres query returned a REFCURSOR and we do not support those - see https://github.com/PowerDNS/pdns/pull/10259" << endl;
×
133
      PQclear(d_res_set);
×
134
      d_res_set = nullptr;
×
135
    }
×
136
    else {
36,469✔
137
      d_res = d_res_set;
36,469✔
138
      d_res_set = nullptr;
36,469✔
139
      d_resnum = PQntuples(d_res);
36,469✔
140
    }
36,469✔
141
  }
36,469✔
142

143
  bool hasNextRow() override
144
  {
591,171✔
145
    if (d_dolog && d_residx == d_resnum) {
591,171!
146
      g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << d_dtime.udiff() << " us total to last row" << endl;
×
147
    }
×
148

149
    return d_residx < d_resnum;
591,171✔
150
  }
591,171✔
151

152
  SSqlStatement* nextRow(row_t& row) override
153
  {
543,561✔
154
    int i;
543,561✔
155
    row.clear();
543,561✔
156
    if (d_residx >= d_resnum || !d_res)
543,562!
157
      return this;
×
158
    row.reserve(PQnfields(d_res));
543,561✔
159
    for (i = 0; i < PQnfields(d_res); i++) {
5,223,611✔
160
      if (PQgetisnull(d_res, d_residx, i)) {
4,680,050✔
161
        row.emplace_back("");
396,702✔
162
      }
396,702✔
163
      else if (PQftype(d_res, i) == 16) { // BOOLEAN
4,283,348✔
164
        char* val = PQgetvalue(d_res, d_residx, i);
332✔
165
        row.emplace_back(val[0] == 't' ? "1" : "0");
332✔
166
      }
332✔
167
      else {
4,283,016✔
168
        row.emplace_back(PQgetvalue(d_res, d_residx, i));
4,283,016✔
169
      }
4,283,016✔
170
    }
4,680,050✔
171
    d_residx++;
543,561✔
172
    if (d_residx >= d_resnum) {
543,561✔
173
      PQclear(d_res);
36,466✔
174
      d_res = nullptr;
36,466✔
175
      nextResult();
36,466✔
176
    }
36,466✔
177
    return this;
543,561✔
178
  }
543,561✔
179

180
  SSqlStatement* getResult(result_t& result) override
181
  {
2,412✔
182
    result.clear();
2,412✔
183
    if (d_res == nullptr)
2,412✔
184
      return this;
330✔
185
    result.reserve(d_resnum);
2,082✔
186
    row_t row;
2,082✔
187
    while (hasNextRow()) {
4,294✔
188
      nextRow(row);
2,212✔
189
      result.push_back(std::move(row));
2,212✔
190
    }
2,212✔
191
    return this;
2,082✔
192
  }
2,412✔
193

194
  SSqlStatement* reset() override
195
  {
905,069✔
196
    int i;
905,069✔
197
    if (d_res) {
905,069!
198
      PQclear(d_res);
×
199
    }
×
200
    if (d_res_set) {
905,069!
201
      PQclear(d_res_set);
×
202
    }
×
203
    d_res_set = nullptr;
905,069✔
204
    d_res = nullptr;
905,069✔
205
    d_paridx = d_residx = d_resnum = 0;
905,069✔
206
    if (paramValues) {
905,069✔
207
      for (i = 0; i < d_nparams; i++) {
5,442,533✔
208
        if (paramValues[i]) {
4,779,634✔
209
          delete[] paramValues[i];
4,453,837✔
210
        }
4,453,837✔
211
      }
4,779,634✔
212
    }
662,899✔
213
    delete[] paramValues;
905,069✔
214
    paramValues = nullptr;
905,069✔
215
    delete[] paramLengths;
905,069✔
216
    paramLengths = nullptr;
905,069✔
217
    return this;
905,069✔
218
  }
905,069✔
219

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

222
  ~SPgSQLStatement() override
223
  {
241,432✔
224
    releaseStatement();
241,432✔
225
  }
241,432✔
226

227
private:
228
  PGconn* d_db()
229
  {
690,729✔
230
    return d_parent->db();
690,729✔
231
  }
690,729✔
232

233
  void releaseStatement()
234
  {
241,759✔
235
    d_prepared = false;
241,759✔
236
    reset();
241,759✔
237
    if (!d_stmt.empty()) {
241,759✔
238
      string cmd = string("DEALLOCATE " + d_stmt);
13,484✔
239
      PGresult* res = PQexec(d_db(), cmd.c_str());
13,484✔
240
      PQclear(res);
13,484✔
241
      d_stmt.clear();
13,484✔
242
    }
13,484✔
243
  }
241,759✔
244

245
  void prepareStatement()
246
  {
5,442,592✔
247
    if (d_prepared)
5,442,592✔
248
      return;
5,428,291✔
249
    if (d_parent->usePrepared()) {
14,301✔
250
      // prepare a statement; name must be unique per session (using d_nstatement to ensure this).
251
      this->d_stmt = string("stmt") + std::to_string(d_nstatement);
14,293✔
252
      PGresult* res = PQprepare(d_db(), d_stmt.c_str(), d_query.c_str(), d_nparams, nullptr);
14,293✔
253
      ExecStatusType status = PQresultStatus(res);
14,293✔
254
      string errmsg(PQresultErrorMessage(res));
14,293✔
255
      PQclear(res);
14,293✔
256
      if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
14,293!
257
        releaseStatement();
×
258
        throw SSqlException("Fatal error during prePQpreparepare: " + d_query + string(": ") + errmsg);
×
259
      }
×
260
    }
14,293✔
261
    paramValues = nullptr;
14,301✔
262
    paramLengths = nullptr;
14,301✔
263
    d_cur_set = d_paridx = d_residx = d_resnum = 0;
14,301✔
264
    d_res = nullptr;
14,301✔
265
    d_res_set = nullptr;
14,301✔
266
    d_prepared = true;
14,301✔
267
  }
14,301✔
268

269
  void allocate()
270
  {
4,453,843✔
271
    if (paramValues != nullptr)
4,453,843✔
272
      return;
3,790,941✔
273
    paramValues = new char*[d_nparams];
662,902✔
274
    paramLengths = new int[d_nparams];
662,902✔
275
    memset(paramValues, 0, sizeof(char*) * d_nparams);
662,902✔
276
    memset(paramLengths, 0, sizeof(int) * d_nparams);
662,902✔
277
  }
662,902✔
278

279
  string d_query;
280
  string d_stmt;
281
  SPgSQL* d_parent;
282
  PGresult* d_res_set{nullptr};
283
  PGresult* d_res{nullptr};
284
  bool d_dolog;
285
  DTime d_dtime; // only used if d_dolog is set
286
  bool d_prepared{false};
287
  int d_nparams;
288
  int d_paridx{0};
289
  char** paramValues{nullptr};
290
  int* paramLengths{nullptr};
291
  int d_residx{0};
292
  int d_resnum{0};
293
  int d_cur_set{0};
294
  unsigned int d_nstatement;
295
};
296

297
bool SPgSQL::s_dolog;
298

299
static string escapeForPQparam(const string& v)
300
{
6,609✔
301
  string ret = v;
6,609✔
302
  boost::replace_all(ret, "\\", "\\\\");
6,609✔
303
  boost::replace_all(ret, "'", "\\'");
6,609✔
304

305
  return string("'") + ret + string("'");
6,609✔
306
}
6,609✔
307

308
SPgSQL::SPgSQL(const string& database, const string& host, const string& port, const string& user,
309
               const string& password, const string& extra_connection_parameters, const bool use_prepared)
310
{
3,782✔
311
  d_db = nullptr;
3,782✔
312
  d_in_trx = false;
3,782✔
313
  d_connectstr = "";
3,782✔
314
  d_nstatements = 0;
3,782✔
315

316
  if (!database.empty())
3,782✔
317
    d_connectstr += "dbname=" + escapeForPQparam(database);
3,777✔
318

319
  if (!user.empty())
3,782✔
320
    d_connectstr += " user=" + escapeForPQparam(user);
2,826✔
321

322
  if (!host.empty())
3,782!
323
    d_connectstr += " host=" + escapeForPQparam(host);
×
324

325
  if (!port.empty())
3,782!
326
    d_connectstr += " port=" + escapeForPQparam(port);
×
327

328
  if (!extra_connection_parameters.empty())
3,782!
329
    d_connectstr += " " + extra_connection_parameters;
×
330

331
  d_connectlogstr = d_connectstr;
3,782✔
332

333
  if (!password.empty()) {
3,782!
334
    d_connectlogstr += " password=<HIDDEN>";
×
335
    d_connectstr += " password=" + escapeForPQparam(password);
×
336
  }
×
337

338
  d_use_prepared = use_prepared;
3,782✔
339

340
  d_db = PQconnectdb(d_connectstr.c_str());
3,782✔
341

342
  if (!d_db || PQstatus(d_db) == CONNECTION_BAD) {
3,782!
343
    try {
×
344
      throw sPerrorException("Unable to connect to database, connect string: " + d_connectlogstr);
×
345
    }
×
346
    catch (...) {
×
347
      if (d_db)
×
348
        PQfinish(d_db);
×
349
      d_db = 0;
×
350
      throw;
×
351
    }
×
352
  }
×
353
}
3,782✔
354

355
void SPgSQL::setLog(bool state)
356
{
3,781✔
357
  s_dolog = state;
3,781✔
358
}
3,781✔
359

360
SPgSQL::~SPgSQL()
361
{
3,569✔
362
  PQfinish(d_db);
3,569✔
363
}
3,569✔
364

365
SSqlException SPgSQL::sPerrorException(const string& reason)
366
{
×
367
  return SSqlException(reason + string(": ") + (d_db ? PQerrorMessage(d_db) : "no connection"));
×
368
}
×
369

370
void SPgSQL::execute(const string& query)
371
{
2,168✔
372
  PGresult* res = PQexec(d_db, query.c_str());
2,168✔
373
  ExecStatusType status = PQresultStatus(res);
2,168✔
374
  string errmsg(PQresultErrorMessage(res));
2,168✔
375
  PQclear(res);
2,168✔
376
  if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
2,168!
377
    throw sPerrorException("Fatal error during query: " + errmsg);
×
378
  }
×
379
}
2,168✔
380

381
std::unique_ptr<SSqlStatement> SPgSQL::prepare(const string& query, int nparams)
382
{
257,163✔
383
  d_nstatements++;
257,163✔
384
  return std::make_unique<SPgSQLStatement>(query, s_dolog, nparams, this, d_nstatements);
257,163✔
385
}
257,163✔
386

387
void SPgSQL::startTransaction()
388
{
1,106✔
389
  execute("begin");
1,106✔
390
  d_in_trx = true;
1,106✔
391
}
1,106✔
392

393
void SPgSQL::commit()
394
{
1,042✔
395
  execute("commit");
1,042✔
396
  d_in_trx = false;
1,042✔
397
}
1,042✔
398

399
void SPgSQL::rollback()
400
{
20✔
401
  execute("rollback");
20✔
402
  d_in_trx = false;
20✔
403
}
20✔
404

405
bool SPgSQL::isConnectionUsable()
406
{
46,108✔
407
  if (PQstatus(d_db) != CONNECTION_OK) {
46,108!
408
    return false;
×
409
  }
×
410

411
  bool usable = false;
46,108✔
412
  int sd = PQsocket(d_db);
46,108✔
413
  bool wasNonBlocking = isNonBlocking(sd);
46,108✔
414

415
  if (!wasNonBlocking) {
46,108!
416
    if (!setNonBlocking(sd)) {
×
417
      return usable;
×
418
    }
×
419
  }
×
420

421
  usable = isTCPSocketUsable(sd);
46,108✔
422

423
  if (!wasNonBlocking) {
46,108!
424
    if (!setBlocking(sd)) {
×
425
      usable = false;
×
426
    }
×
427
  }
×
428

429
  return usable;
46,108✔
430
}
46,108✔
431

432
void SPgSQL::reconnect()
433
{
×
434
  PQreset(d_db);
×
435
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc