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

PowerDNS / pdns / 26289710241

22 May 2026 01:09PM UTC coverage: 71.073% (+0.05%) from 71.028%
26289710241

Pull #17460

github

web-flow
Merge 2fbf90ffa into 407e72ccc
Pull Request #17460: iputils: Return early when the tree is empty

46300 of 81390 branches covered (56.89%)

Branch coverage included in aggregate %.

6 of 6 new or added lines in 1 file covered. (100.0%)

37 existing lines in 10 files now uncovered.

132730 of 170507 relevant lines covered (77.84%)

6620571.39 hits per line

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

63.78
/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(Logr::log_t log, const string& query, bool dolog, int nparams, SPgSQL* db, unsigned int nstatement)
39
  {
131,493✔
40
    d_slog = log;
131,493✔
41
    d_query = query;
131,493✔
42
    d_dolog = dolog;
131,493✔
43
    d_parent = db;
131,493✔
44
    d_nparams = nparams;
131,493✔
45
    d_nstatement = nstatement;
131,493✔
46
  }
131,493✔
47

48
  SSqlStatement* bind(const string& name, bool value) override { return bind(name, string(value ? "t" : "f")); }
529,658✔
49
  SSqlStatement* bind(const string& name, int value) override { return bind(name, std::to_string(value)); }
548,172✔
50
  SSqlStatement* bind(const string& name, uint32_t value) override { return bind(name, std::to_string(value)); }
223,907✔
51
  SSqlStatement* bind(const string& name, long value) override { return bind(name, std::to_string(value)); }
82✔
52
  SSqlStatement* bind(const string& name, unsigned long value) override { return bind(name, std::to_string(value)); }
11✔
53
  SSqlStatement* bind(const string& name, long long value) override { return bind(name, std::to_string(value)); }
×
54
  SSqlStatement* bind(const string& name, unsigned long long value) override { return bind(name, std::to_string(value)); }
×
55
  SSqlStatement* bind(const string& /* name */, const std::string& value) override
56
  {
2,229,392✔
57
    prepareStatement();
2,229,392✔
58
    allocate();
2,229,392✔
59
    if (d_paridx >= d_nparams) {
2,229,392!
60
      releaseStatement();
×
61
      throw SSqlException("Attempt to bind more parameters than query has: " + d_query);
×
62
    }
×
63
    paramValues[d_paridx] = new char[value.size() + 1];
2,229,392✔
64
    memset(paramValues[d_paridx], 0, sizeof(char) * (value.size() + 1));
2,229,392✔
65
    value.copy(paramValues[d_paridx], value.size());
2,229,392✔
66
    paramLengths[d_paridx] = value.size();
2,229,392✔
67
    d_paridx++;
2,229,392✔
68
    return this;
2,229,392✔
69
  }
2,229,392✔
70
  SSqlStatement* bindNull(const string& /* name */) override
71
  {
162,999✔
72
    prepareStatement();
162,999✔
73
    d_paridx++;
162,999✔
74
    return this;
162,999✔
75
  } // these are set null in allocate()
162,999✔
76
  SSqlStatement* execute() override
77
  {
332,400✔
78
    prepareStatement();
332,400✔
79
    if (d_dolog) {
332,400!
80
      if (g_slogStructured) {
×
81
        if (d_paridx) {
×
82
          // This is ugly, but will do until paramValues is converted to a
83
          // std::array.
84
          std::vector<char*> vecparam;
×
85
          vecparam.reserve(d_paridx);
×
86
          for (auto i = 0; i < d_paridx; ++i) {
×
87
            vecparam[i] = paramValues[i];
×
88
          }
×
89
          d_slog->info(Logr::Warning, "execute SQL query", "query", Logging::Loggable(d_query), "arguments", Logging::IterLoggable(vecparam.cbegin(), vecparam.cend()));
×
90
        }
×
91
        else {
×
92
          d_slog->info(Logr::Warning, "execute SQL query", "query", Logging::Loggable(d_query));
×
93
        }
×
94
      }
×
95
      else {
×
96
        g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": Statement: " << d_query << endl;
×
97
        if (d_paridx) {
×
98
          std::stringstream log_message;
×
99
          // Log message is similar, but not exactly the same as the postgres server log.
100
          log_message << "Query " << ((long)(void*)this) << ": Parameters: ";
×
101
          for (int i = 0; i < d_paridx; i++) {
×
102
            if (i != 0) {
×
103
              log_message << ", ";
×
104
            }
×
105
            log_message << "$" << (i + 1) << " = ";
×
106
            if (paramValues[i] == nullptr) {
×
107
              log_message << "NULL";
×
108
            }
×
109
            else {
×
110
              log_message << "'" << paramValues[i] << "'";
×
111
            }
×
112
          }
×
113
          g_log << Logger::Warning << log_message.str() << endl;
×
114
        }
×
115
      }
×
116
      d_dtime.set();
×
117
    }
×
118
    if (!d_stmt.empty()) {
332,400!
119
      d_res_set = PQexecPrepared(d_db(), d_stmt.c_str(), d_nparams, paramValues, paramLengths, nullptr, 0);
332,400✔
120
    }
332,400✔
UNCOV
121
    else {
×
UNCOV
122
      d_res_set = PQexecParams(d_db(), d_query.c_str(), d_nparams, nullptr, paramValues, paramLengths, nullptr, 0);
×
UNCOV
123
    }
×
124
    ExecStatusType status = PQresultStatus(d_res_set);
332,400✔
125
    if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
332,400!
126
      string errmsg(PQresultErrorMessage(d_res_set));
×
127
      releaseStatement();
×
128
      throw SSqlException("Fatal error during query: " + d_query + string(": ") + errmsg);
×
129
    }
×
130
    d_cur_set = 0;
332,400✔
131
    if (d_dolog) {
332,400!
132
      auto diff = d_dtime.udiffNoReset();
×
133
      SLOG(g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << diff << " us to execute" << endl,
×
134
           d_slog->info(Logr::Warning, "query completed", "microseconds", Logging::Loggable(diff)));
×
135
    }
×
136

137
    nextResult();
332,400✔
138
    return this;
332,400✔
139
  }
332,400✔
140

141
  void nextResult()
142
  {
350,939✔
143
    if (d_res_set == nullptr)
350,939✔
144
      return;
18,540✔
145
    if (d_cur_set >= PQntuples(d_res_set)) {
332,399✔
146
      PQclear(d_res_set);
313,859✔
147
      d_res_set = nullptr;
313,859✔
148
      return;
313,859✔
149
    }
313,859✔
150
    if (PQftype(d_res_set, 0) == 1790) { // REFCURSOR
18,540!
151
      SLOG(g_log << Logger::Error << "Postgres query returned a REFCURSOR and we do not support those - see https://github.com/PowerDNS/pdns/pull/10259" << endl,
×
152
           d_slog->info(Logr::Error, "query returned a REFCURSOR which is not supported by PowerDNS", "more information", Logging::Loggable("https://github.com/PowerDNS/pdns/pull/10259")));
×
153
      PQclear(d_res_set);
×
154
      d_res_set = nullptr;
×
155
    }
×
156
    else {
18,540✔
157
      d_res = d_res_set;
18,540✔
158
      d_res_set = nullptr;
18,540✔
159
      d_resnum = PQntuples(d_res);
18,540✔
160
    }
18,540✔
161
  }
18,540✔
162

163
  bool hasNextRow() override
164
  {
296,747✔
165
    if (d_dolog && d_residx == d_resnum) {
296,747!
166
      SLOG(g_log << Logger::Warning << "Query " << ((long)(void*)this) << ": " << d_dtime.udiff() << " us total to last row" << endl,
×
167
           d_slog->info(Logr::Warning, "all query results procesed", "microseconds", Logging::Loggable(d_dtime.udiff())));
×
168
    }
×
169

170
    return d_residx < d_resnum;
296,747✔
171
  }
296,747✔
172

173
  SSqlStatement* nextRow(row_t& row) override
174
  {
272,289✔
175
    int i;
272,289✔
176
    row.clear();
272,289✔
177
    if (d_residx >= d_resnum || !d_res)
272,289!
178
      return this;
×
179
    row.reserve(PQnfields(d_res));
272,289✔
180
    for (i = 0; i < PQnfields(d_res); i++) {
2,616,216✔
181
      if (PQgetisnull(d_res, d_residx, i)) {
2,343,927✔
182
        row.emplace_back("");
199,020✔
183
      }
199,020✔
184
      else if (PQftype(d_res, i) == 16) { // BOOLEAN
2,144,907✔
185
        char* val = PQgetvalue(d_res, d_residx, i);
165✔
186
        row.emplace_back(val[0] == 't' ? "1" : "0");
165✔
187
      }
165✔
188
      else {
2,144,742✔
189
        row.emplace_back(PQgetvalue(d_res, d_residx, i));
2,144,742✔
190
      }
2,144,742✔
191
    }
2,343,927✔
192
    d_residx++;
272,289✔
193
    if (d_residx >= d_resnum) {
272,289✔
194
      PQclear(d_res);
18,541✔
195
      d_res = nullptr;
18,541✔
196
      nextResult();
18,541✔
197
    }
18,541✔
198
    return this;
272,289✔
199
  }
272,289✔
200

201
  SSqlStatement* getResult(result_t& result) override
202
  {
1,288✔
203
    result.clear();
1,288✔
204
    if (d_res == nullptr)
1,288✔
205
      return this;
179✔
206
    result.reserve(d_resnum);
1,109✔
207
    row_t row;
1,109✔
208
    while (hasNextRow()) {
2,283✔
209
      nextRow(row);
1,174✔
210
      result.push_back(std::move(row));
1,174✔
211
    }
1,174✔
212
    return this;
1,109✔
213
  }
1,288✔
214

215
  SSqlStatement* reset() override
216
  {
456,344✔
217
    int i;
456,344✔
218
    if (d_res) {
456,344!
219
      PQclear(d_res);
×
220
    }
×
221
    if (d_res_set) {
456,344!
222
      PQclear(d_res_set);
×
223
    }
×
224
    d_res_set = nullptr;
456,344✔
225
    d_res = nullptr;
456,344✔
226
    d_paridx = d_residx = d_resnum = 0;
456,344✔
227
    if (paramValues) {
456,344✔
228
      for (i = 0; i < d_nparams; i++) {
2,724,764✔
229
        if (paramValues[i]) {
2,392,390✔
230
          delete[] paramValues[i];
2,229,391✔
231
        }
2,229,391✔
232
      }
2,392,390✔
233
    }
332,374✔
234
    delete[] paramValues;
456,344✔
235
    paramValues = nullptr;
456,344✔
236
    delete[] paramLengths;
456,344✔
237
    paramLengths = nullptr;
456,344✔
238
    return this;
456,344✔
239
  }
456,344✔
240

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

243
  ~SPgSQLStatement() override
244
  {
124,271✔
245
    releaseStatement();
124,271✔
246
  }
124,271✔
247

248
private:
249
  PGconn* d_db()
250
  {
347,069✔
251
    return d_parent->db();
347,069✔
252
  }
347,069✔
253

254
  void releaseStatement()
255
  {
124,072✔
256
    d_prepared = false;
124,072✔
257
    reset();
124,072✔
258
    if (!d_stmt.empty()) {
124,072✔
259
      string cmd = string("DEALLOCATE " + d_stmt);
7,134✔
260
      PGresult* res = PQexec(d_db(), cmd.c_str());
7,134✔
261
      PQclear(res);
7,134✔
262
      d_stmt.clear();
7,134✔
263
    }
7,134✔
264
  }
124,072✔
265

266
  void prepareStatement()
267
  {
2,724,775✔
268
    if (d_prepared)
2,724,775✔
269
      return;
2,717,242✔
270
    if (d_parent->usePrepared()) {
7,536✔
271
      // prepare a statement; name must be unique per session (using d_nstatement to ensure this).
272
      this->d_stmt = string("stmt") + std::to_string(d_nstatement);
7,536✔
273
      PGresult* res = PQprepare(d_db(), d_stmt.c_str(), d_query.c_str(), d_nparams, nullptr);
7,536✔
274
      ExecStatusType status = PQresultStatus(res);
7,536✔
275
      string errmsg(PQresultErrorMessage(res));
7,536✔
276
      PQclear(res);
7,536✔
277
      if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
7,536!
278
        releaseStatement();
×
279
        throw SSqlException("Fatal error during prePQpreparepare: " + d_query + string(": ") + errmsg);
×
280
      }
×
281
    }
7,536✔
282
    paramValues = nullptr;
7,533✔
283
    paramLengths = nullptr;
7,533✔
284
    d_cur_set = d_paridx = d_residx = d_resnum = 0;
7,533✔
285
    d_res = nullptr;
7,533✔
286
    d_res_set = nullptr;
7,533✔
287
    d_prepared = true;
7,533✔
288
  }
7,533✔
289

290
  void allocate()
291
  {
2,229,394✔
292
    if (paramValues != nullptr)
2,229,394✔
293
      return;
1,897,019✔
294
    paramValues = new char*[d_nparams];
332,375✔
295
    paramLengths = new int[d_nparams];
332,375✔
296
    memset(paramValues, 0, sizeof(char*) * d_nparams);
332,375✔
297
    memset(paramLengths, 0, sizeof(int) * d_nparams);
332,375✔
298
  }
332,375✔
299

300
  string d_query;
301
  string d_stmt;
302
  SPgSQL* d_parent;
303
  PGresult* d_res_set{nullptr};
304
  PGresult* d_res{nullptr};
305
  bool d_dolog;
306
  std::shared_ptr<Logr::Logger> d_slog;
307
  DTime d_dtime; // only used if d_dolog is set
308
  bool d_prepared{false};
309
  int d_nparams;
310
  int d_paridx{0};
311
  char** paramValues{nullptr};
312
  int* paramLengths{nullptr};
313
  int d_residx{0};
314
  int d_resnum{0};
315
  int d_cur_set{0};
316
  unsigned int d_nstatement;
317
};
318

319
bool SPgSQL::s_dolog;
320

321
static string escapeForPQparam(const string& v)
322
{
3,340✔
323
  string ret = v;
3,340✔
324
  boost::replace_all(ret, "\\", "\\\\");
3,340✔
325
  boost::replace_all(ret, "'", "\\'");
3,340✔
326

327
  return string("'") + ret + string("'");
3,340✔
328
}
3,340✔
329

330
SPgSQL::SPgSQL(Logr::log_t log, const string& database, const string& host, const string& port, const string& user,
331
               const string& password, const string& extra_connection_parameters, const bool use_prepared)
332
{
1,932✔
333
  d_slog = log;
1,932✔
334
  d_db = nullptr;
1,932✔
335
  d_in_trx = false;
1,932✔
336
  d_connectstr = "";
1,932✔
337
  d_nstatements = 0;
1,932✔
338

339
  if (!database.empty())
1,932✔
340
    d_connectstr += "dbname=" + escapeForPQparam(database);
1,933✔
341

342
  if (!user.empty())
1,932✔
343
    d_connectstr += " user=" + escapeForPQparam(user);
1,414✔
344

345
  if (!host.empty())
1,932!
346
    d_connectstr += " host=" + escapeForPQparam(host);
×
347

348
  if (!port.empty())
1,932!
349
    d_connectstr += " port=" + escapeForPQparam(port);
×
350

351
  if (!extra_connection_parameters.empty())
1,932!
352
    d_connectstr += " " + extra_connection_parameters;
×
353

354
  d_connectlogstr = d_connectstr;
1,932✔
355

356
  if (!password.empty()) {
1,932!
357
    d_connectlogstr += " password=<HIDDEN>";
×
358
    d_connectstr += " password=" + escapeForPQparam(password);
×
359
  }
×
360

361
  d_use_prepared = use_prepared;
1,932✔
362

363
  d_db = PQconnectdb(d_connectstr.c_str());
1,932✔
364

365
  if (!d_db || PQstatus(d_db) == CONNECTION_BAD) {
1,934!
366
    try {
×
367
      throw sPerrorException("Unable to connect to database, connect string: " + d_connectlogstr);
×
368
    }
×
369
    catch (...) {
×
370
      if (d_db)
×
371
        PQfinish(d_db);
×
372
      d_db = 0;
×
373
      throw;
×
374
    }
×
375
  }
×
376
}
1,932✔
377

378
void SPgSQL::setLog(bool state)
379
{
1,934✔
380
  s_dolog = state;
1,934✔
381
}
1,934✔
382

383
SPgSQL::~SPgSQL()
384
{
1,829✔
385
  PQfinish(d_db);
1,829✔
386
}
1,829✔
387

388
SSqlException SPgSQL::sPerrorException(const string& reason)
389
{
×
390
  return SSqlException(reason + string(": ") + (d_db ? PQerrorMessage(d_db) : "no connection"));
×
391
}
×
392

393
void SPgSQL::execute(const string& query)
394
{
1,155✔
395
  PGresult* res = PQexec(d_db, query.c_str());
1,155✔
396
  ExecStatusType status = PQresultStatus(res);
1,155✔
397
  string errmsg(PQresultErrorMessage(res));
1,155✔
398
  PQclear(res);
1,155✔
399
  if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK && status != PGRES_NONFATAL_ERROR) {
1,155!
400
    throw sPerrorException("Fatal error during query: " + errmsg);
×
401
  }
×
402
}
1,155✔
403

404
std::unique_ptr<SSqlStatement> SPgSQL::prepare(const string& query, int nparams)
405
{
131,499✔
406
  d_nstatements++;
131,499✔
407
  return std::make_unique<SPgSQLStatement>(d_slog, query, s_dolog, nparams, this, d_nstatements);
131,499✔
408
}
131,499✔
409

410
void SPgSQL::startTransaction()
411
{
585✔
412
  execute("begin");
585✔
413
  d_in_trx = true;
585✔
414
}
585✔
415

416
void SPgSQL::commit()
417
{
544✔
418
  execute("commit");
544✔
419
  d_in_trx = false;
544✔
420
}
544✔
421

422
void SPgSQL::rollback()
423
{
26✔
424
  execute("rollback");
26✔
425
  d_in_trx = false;
26✔
426
}
26✔
427

428
bool SPgSQL::isConnectionUsable()
429
{
23,520✔
430
  if (PQstatus(d_db) != CONNECTION_OK) {
23,520!
431
    return false;
×
432
  }
×
433

434
  bool usable = false;
23,520✔
435
  int sd = PQsocket(d_db);
23,520✔
436
  bool wasNonBlocking = isNonBlocking(sd);
23,520✔
437

438
  if (!wasNonBlocking) {
23,520!
439
    if (!setNonBlocking(sd)) {
×
440
      return usable;
×
441
    }
×
442
  }
×
443

444
  usable = isTCPSocketUsable(sd);
23,520✔
445

446
  if (!wasNonBlocking) {
23,520!
447
    if (!setBlocking(sd)) {
×
448
      usable = false;
×
449
    }
×
450
  }
×
451

452
  return usable;
23,520✔
453
}
23,520✔
454

455
void SPgSQL::reconnect()
456
{
×
457
  PQreset(d_db);
×
458
}
×
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

© 2026 Coveralls, Inc