summaryrefslogtreecommitdiff
path: root/libpqpp/connection.cpp
blob: 4330b3f088c04cf65dd1bfc5afd6f3226b8ffa53 (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
#include "connection.h"
#include "error.h"
#include "selectcommand.h"
#include "modifycommand.h"

PQ::Connection::Connection(const std::string & info) :
	conn(PQconnectdb(info.c_str())),
	txDepth(0),
	pstmntNo(0)
{
	if (PQstatus(conn) != CONNECTION_OK) {
		throw ConnectionError();
	}
}

PQ::Connection::~Connection()
{
	PQfinish(conn);
}

int
PQ::Connection::beginTx() const
{
	if (txDepth == 0) {
		checkResultFree(PQexec(conn, "BEGIN"), PGRES_COMMAND_OK, __PRETTY_FUNCTION__);
	}
	return ++txDepth;
}

int
PQ::Connection::commitTx() const
{
	if (--txDepth == 0) {
		checkResultFree(PQexec(conn, "COMMIT"), PGRES_COMMAND_OK, __PRETTY_FUNCTION__);
	}
	return txDepth;
}

int
PQ::Connection::rollbackTx() const
{
	if (--txDepth == 0) {
		checkResultFree(PQexec(conn, "ROLLBACK"), PGRES_COMMAND_OK, __PRETTY_FUNCTION__);
	}
	return txDepth;
}

bool
PQ::Connection::inTx() const
{
	return txDepth;
}

void
PQ::Connection::ping() const
{
}


DB::SelectCommand *
PQ::Connection::newSelectCommand(const std::string & sql) const
{
	return new SelectCommand(this, sql, pstmntNo++);
}

DB::ModifyCommand *
PQ::Connection::newModifyCommand(const std::string & sql) const
{
	return new ModifyCommand(this, sql, pstmntNo++);
}

bool
PQ::Connection::checkResultInt(PGresult * res, int expected)
{
	return (PQresultStatus(res) == expected);
}

void
PQ::Connection::checkResult(PGresult * res, int expected, const char * doing) const
{
	if (!checkResultInt(res, expected)) {
		PQclear(res);
		throw Error(PQerrorMessage(conn));
	}
}

void
PQ::Connection::checkResultFree(PGresult * res, int expected, const char * doing) const
{
	if (!checkResultInt(res, expected)) {
		PQclear(res);
		throw Error(PQerrorMessage(conn));
	}
	PQclear(res);
}