summaryrefslogtreecommitdiff
path: root/libpqpp/selectcommand.cpp
blob: 603cffdba1c14e87ac9ce724985ddb8571f72975 (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
#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),
	nTuples(0),
	tuple(0),
	execRes(NULL)
{
}

PQ::SelectCommand::~SelectCommand()
{
	if (execRes) {
		PQclear(execRes);
	}
	for (unsigned int f = 0; f < fields.size(); f += 1) {
		delete fields[f];
	}
}

void
PQ::SelectCommand::execute()
{
	if (!executed) {
		prepare();
		execRes = PQexecPrepared(c->conn, stmntName.c_str(), values.size(), &values.front(), &lengths.front(), &formats.front(), 0);
		c->checkResult(execRes, PGRES_TUPLES_OK, __PRETTY_FUNCTION__);
		unsigned int nFields = PQnfields(execRes);
		fields.resize(nFields);
		for (unsigned int f = 0; f < nFields; f += 1) {
			Column * c = new Column(this, f);
			fields[f] = c;
			fieldsName[c->name] = c;
		}
        nTuples = PQntuples(execRes);
		tuple = -1;
		executed = true;
	}
}

bool
PQ::SelectCommand::fetch()
{
	execute();
	if (tuple++ < (nTuples - 1)) {
		return true;
	}
	else {
		executed = false;
		return false;
	}
}

const DB::Column&
PQ::SelectCommand::operator[](unsigned int n) const
{
	if (n < fields.size()) {
		return *fields[n];
	}
	throw Error();
}

const DB::Column&
PQ::SelectCommand::operator[](const Glib::ustring & n) const
{
	std::map<Glib::ustring, Column *>::const_iterator i = fieldsName.find(n);
	if (i != fieldsName.end()) {
		return *i->second;
	}
	throw Error();
}

unsigned int
PQ::SelectCommand::getOrdinal(const Glib::ustring & n) const
{
	std::map<Glib::ustring, Column *>::const_iterator i = fieldsName.find(n);
	if (i != fieldsName.end()) {
		return i->second->colNo;
	}
	throw Error();
}

unsigned int
PQ::SelectCommand::columnCount() const
{
	return fields.size();
}