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
|
#include "pq-cursorselectcommand.h"
#include "command.h"
#include "pq-command.h"
#include "pq-connection.h"
#include "pq-selectbase.h"
#include <compileTimeFormatter.h>
#include <libpq-fe.h>
#include <type_traits>
#include <utility>
#include <vector>
AdHocFormatter(PQCursorSelectDeclare, "DECLARE %? NO SCROLL CURSOR WITH HOLD FOR ");
AdHocFormatter(PQCursorSelectFetch, "FETCH %? IN %?");
AdHocFormatter(PQCursorSelectClose, "CLOSE %?");
PQ::CursorSelectCommand::CursorSelectCommand(Connection * conn, const std::string & sql,
const PQ::CommandOptionsCPtr & pqco, const DB::CommandOptionsCPtr & opts) :
DB::Command(sql),
PQ::SelectBase(sql, pqco), PQ::Command(conn, sql, opts), executed(false), fTuples(pqco ? pqco->fetchTuples : 35),
s_fetch(PQCursorSelectFetch::get(fTuples, stmntName)), s_close(PQCursorSelectClose::get(stmntName))
{
}
PQ::CursorSelectCommand::~CursorSelectCommand()
{
if (executed && PQtransactionStatus(c->conn) != PQTRANS_INERROR) {
c->checkResult(PQexec(c->conn, s_close.c_str()), PGRES_COMMAND_OK);
}
}
std::string
PQ::CursorSelectCommand::mkdeclare() const
{
std::stringstream psql;
PQCursorSelectDeclare::write(psql, stmntName);
prepareSql(psql, sql);
return std::move(psql).str();
}
void
PQ::CursorSelectCommand::execute()
{
if (!executed) {
if (s_declare.empty()) {
s_declare = mkdeclare();
}
c->checkResult(PQexecParams(c->conn, s_declare.c_str(), static_cast<int>(values.size()), nullptr, values.data(),
lengths.data(), formats.data(), binary),
PGRES_COMMAND_OK);
fetchTuples();
createColumns();
executed = true;
}
}
void
PQ::CursorSelectCommand::fetchTuples()
{
execRes = c->checkResult(
PQexecParams(c->conn, s_fetch.c_str(), 0, nullptr, nullptr, nullptr, nullptr, binary), PGRES_TUPLES_OK);
nTuples = static_cast<decltype(nTuples)>(PQntuples(execRes.get()));
tuple = static_cast<decltype(tuple)>(-1);
}
bool
PQ::CursorSelectCommand::fetch()
{
execute();
if ((tuple + 1 >= nTuples) && (nTuples == fTuples)) {
// Delete the previous result set
execRes.reset();
fetchTuples();
}
if (++tuple < nTuples) {
return true;
}
else {
PQclear(PQexec(c->conn, s_close.c_str()));
execRes.reset();
executed = false;
return false;
}
}
|