summaryrefslogtreecommitdiff
path: root/libpqpp/selectcommand.cpp
blob: 8e3ec369d64de2fda2b600c99f05d6cd84b1b174 (plain)
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
#include "selectcommand.h"
#include "connection.h"
#include "column.h"
#include "error.h"

PQ::SelectCommand::SelectCommand(const 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 (txOpened) {
		c->commitTx();
	}
	if (executed) {
		PQclear(PQexec(c->conn, s_close.c_str()));
		if (execRes) {
			PQclear(execRes);
		}
	}
}

std::string
PQ::SelectCommand::mkdeclare() const
{
	std::string psql;
	psql.reserve(sql.length() + 40);
	char buf[4];
	int p = 1;
	bool inquote = false;
	psql += "DECLARE ";
	psql += stmntName;
	psql += " CURSOR FOR ";
	for(std::string::const_iterator i = sql.begin(); i != sql.end(); ++i) {
		if (*i == '?' && !inquote) {
			snprintf(buf, 4, "$%d", p++);
			psql += buf;
		}
		else if (*i == '\'') {
			inquote = !inquote;
			psql += *i;
		}
		else {
			psql += *i;
		}
	}
	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 (!txOpened) {
			c->beginTx();
			txOpened = true;
		}
		execRes = c->checkResult(
				PQexecParams(c->conn, s_declare.c_str(), values.size(), NULL, &values.front(), &lengths.front(), &formats.front(), 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;
	}
}