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
|
#include "pq-selectcommand.h"
#include "pq-connection.h"
#include "pq-column.h"
#include "pq-error.h"
PQ::SelectCommand::SelectCommand(Connection * conn, const std::string & sql, unsigned int no) :
DB::Command(sql),
DB::SelectCommand(sql),
PQ::Command(conn, sql, no),
executed(false),
txOpened(false),
nTuples(0),
tuple(0),
fTuples(35),
execRes(NULL),
s_declare(mkdeclare()),
s_fetch(mkfetch()),
s_close(mkclose())
{
}
PQ::SelectCommand::~SelectCommand()
{
if (execRes) {
PQclear(execRes);
}
if (executed && PQtransactionStatus(c->conn) != PQTRANS_INERROR) {
c->checkResultFree((PQexec(c->conn, s_close.c_str())), PGRES_COMMAND_OK);
}
if (txOpened) {
c->commitTx();
}
}
std::string
PQ::SelectCommand::mkdeclare() const
{
std::string psql;
psql.reserve(sql.length() + 40);
psql += "DECLARE ";
psql += stmntName;
psql += " CURSOR FOR ";
prepareSql(psql, sql);
return psql;
}
std::string
PQ::SelectCommand::mkfetch() const
{
char buf[BUFSIZ];
snprintf(buf, sizeof(buf), "FETCH %d IN %s", fTuples, stmntName.c_str());
return buf;
}
std::string
PQ::SelectCommand::mkclose() const
{
char buf[BUFSIZ];
snprintf(buf, sizeof(buf), "CLOSE %s", stmntName.c_str());
return buf;
}
void
PQ::SelectCommand::execute()
{
if (!executed) {
if (!c->inTx()) {
c->beginTx();
txOpened = true;
}
execRes = c->checkResult(
PQexecParams(c->conn, s_declare.c_str(), values.size(), NULL, &values.front(), &lengths.front(), NULL, 0),
PGRES_COMMAND_OK);
fetchTuples();
unsigned int nFields = PQnfields(execRes);
for (unsigned int f = 0; f < nFields; f += 1) {
insertColumn(DB::ColumnPtr(new Column(this, f)));
}
executed = true;
}
}
void
PQ::SelectCommand::fetchTuples()
{
if (execRes) {
PQclear(execRes);
}
execRes = NULL;
execRes = c->checkResult(PQexec(c->conn, s_fetch.c_str()), PGRES_TUPLES_OK);
nTuples = PQntuples(execRes);
tuple = -1;
}
bool
PQ::SelectCommand::fetch()
{
execute();
if ((tuple >= (nTuples - 1)) && (nTuples == fTuples)) {
fetchTuples();
}
if (tuple++ < (nTuples - 1)) {
return true;
}
else {
PQclear(PQexec(c->conn, s_close.c_str()));
PQclear(execRes);
execRes = NULL;
executed = false;
return false;
}
}
|