summaryrefslogtreecommitdiff
path: root/libpqpp/pq-connection.cpp
blob: 5c50b7c31b9f4598bdd1425cc07297c530873997 (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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#include "pq-connection.h"
#include "column.h"
#include "command.h"
#include "connection.h"
#include "pq-bulkselectcommand.h"
#include "pq-command.h"
#include "pq-cursorselectcommand.h"
#include "pq-error.h"
#include "pq-modifycommand.h"
#include "selectcommand.h"
#include <boost/assert.hpp>
#include <compileTimeFormatter.h>
#include <factory.h>
#include <libpq-fe.h>
#include <memory>
#include <poll.h>
#include <unistd.h>

NAMEDFACTORY("postgresql", PQ::Connection, DB::ConnectionFactory)

namespace {
	void setup() __attribute__((constructor(101)));

	void
	setup()
	{
		// NOLINTNEXTLINE(hicpp-no-array-decay)
		BOOST_ASSERT(PQisthreadsafe() == 1);
		PQinitOpenSSL(1, 0);
	}

	void
	noNoticeProcessor(void *, const char *)
	{
	}
}

// NOLINTNEXTLINE(bugprone-throw-keyword-missing)
PQ::ConnectionError::ConnectionError(const PGconn * conn) : PQ::Error(conn) { }

PQ::Connection::Connection(const std::string & info) : conn(PQconnectdb(info.c_str()))
{
	if (PQstatus(conn) != CONNECTION_OK) {
		auto dc = std::unique_ptr<PGconn, decltype(&PQfinish)>(conn, &PQfinish);
		throw ConnectionError(dc.get());
	}
	PQsetNoticeProcessor(conn, noNoticeProcessor, nullptr);
}

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

void
PQ::Connection::beginTxInt()
{
	checkResult(PQexec(conn, "BEGIN"), PGRES_COMMAND_OK);
}

void
PQ::Connection::commitTxInt()
{
	checkResult(PQexec(conn, "COMMIT"), PGRES_COMMAND_OK);
}

void
PQ::Connection::rollbackTxInt()
{
	checkResult(PQexec(conn, "ROLLBACK"), PGRES_COMMAND_OK);
}

void
PQ::Connection::execute(const std::string & sql, const DB::CommandOptionsCPtr &)
{
	checkResult(PQexec(conn, sql.c_str()), PGRES_COMMAND_OK, PGRES_TUPLES_OK);
}

DB::BulkDeleteStyle
PQ::Connection::bulkDeleteStyle() const
{
	return DB::BulkDeleteStyle::UsingSubSelect;
}

DB::BulkUpdateStyle
PQ::Connection::bulkUpdateStyle() const
{
	return DB::BulkUpdateStyle::UsingFromSrc;
}

void
PQ::Connection::ping() const
{
	struct pollfd fd {
		// NOLINTNEXTLINE(hicpp-signed-bitwise)
		PQsocket(conn), POLLRDHUP | POLLERR | POLLHUP | POLLNVAL, 0
	};

	if (PQstatus(conn) != CONNECTION_OK || poll(&fd, 1, 0)) {
		if (inTx()) {
			throw ConnectionError(conn);
		}
		preparedStatements.clear();
		PQreset(conn);
		if (PQstatus(conn) != CONNECTION_OK) {
			throw ConnectionError(conn);
		}
	}
}

DB::SelectCommandPtr
PQ::Connection::select(const std::string & sql, const DB::CommandOptionsCPtr & opts)
{
	auto pqco = std::dynamic_pointer_cast<const CommandOptions>(opts);
	if (pqco && !pqco->useCursor) {
		return std::make_shared<BulkSelectCommand>(this, sql, pqco, opts);
	}
	return std::make_shared<CursorSelectCommand>(this, sql, pqco, opts);
}

DB::ModifyCommandPtr
PQ::Connection::modify(const std::string & sql, const DB::CommandOptionsCPtr & opts)
{
	return std::make_shared<ModifyCommand>(this, sql, opts);
}

template<std::same_as<ExecStatusType>... Expected>
PQ::ResultPtr
PQ::Connection::checkResult(PGresult * res, Expected... expected) const
{
	if (const auto status = PQresultStatus(res); (... && (status != expected))) {
		PQclear(res);
		throw Error(conn);
	}
	return ResultPtr {res};
}

template PQ::ResultPtr PQ::Connection::checkResult(PGresult *, ExecStatusType) const;
template PQ::ResultPtr PQ::Connection::checkResult(PGresult *, ExecStatusType, ExecStatusType) const;

AdHocFormatter(PQConnectionCopyFrom, "COPY %? FROM STDIN %?");

void
PQ::Connection::beginBulkUpload(const char * table, const char * extra)
{
	checkResult(PQexec(conn, PQConnectionCopyFrom::get(table, extra).c_str()), PGRES_COPY_IN);
}

void
PQ::Connection::endBulkUpload(const char * msg)
{
	int rc;
	while (!(rc = PQputCopyEnd(conn, msg))) {
		sleep(1);
	}
	if (rc != 1) {
		throw Error(conn);
	}
	checkResult(PQgetResult(conn), PGRES_COMMAND_OK);
}

size_t
PQ::Connection::bulkUploadData(const char * data, size_t len) const
{
	int rc;
	while (!(rc = PQputCopyData(conn, data, static_cast<int>(len)))) {
		sleep(1);
	}
	if (rc != 1) {
		throw Error(conn);
	}
	return len;
}

static const std::string selectLastVal("SELECT lastval()");
static const DB::CommandOptionsCPtr selectLastValOpts
		= std::make_shared<DB::CommandOptions>(std::hash<std::string>()(selectLastVal));

int64_t
PQ::Connection::insertId()
{
	BulkSelectCommand getId(this, selectLastVal, nullptr, selectLastValOpts);
	int64_t id = -1;
	while (getId.fetch()) {
		getId[0] >> id;
	}
	return id;
}

int
PQ::Connection::serverVersion() const
{
	return PQserverVersion(conn);
}