summaryrefslogtreecommitdiff
path: root/lib/output/pq/pqConn.cpp
blob: ba95cad67bca7838e43be62e54cd528f14aa32ab (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
#include "pqConn.h"
#include "pqBindings.h"
#include "pqStmt.h"
#include <dbConn.h>
#include <helpers.h>
#include <libpq-fe.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>

namespace MyGrate::Output::Pq {
	PqErr::PqErr(const std::string & when, PGconn * c) : std::runtime_error(when + ": " + PQerrorMessage((c))) { }
	PqErr::PqErr(const std::string & when, PGresult * r) : std::runtime_error(when + ": " + PQresultErrorMessage((r)))
	{
	}

	PqConn::PqConn(const char * const str) : connstr {str}, conn {PQconnectdb(str), PQfinish}
	{
		verify<PqErr>(PQstatus(conn.get()) == CONNECTION_OK, "Connection failure", conn.get());
		PQsetNoticeProcessor(conn.get(), notice_processor, this);
	}

	void
	PqConn::query(const char * const q)
	{
		ResPtr res {PQexec(conn.get(), q), &PQclear};
		verify<PqErr>(PQresultStatus(res.get()) == PGRES_COMMAND_OK, q, res.get());
	}

	void
	PqConn::query(const char * const q, const std::initializer_list<DbValue> & vs)
	{
		Bindings b {vs};
		ResPtr res {PQexecParams(conn.get(), q, (int)vs.size(), nullptr, b.values.data(), b.lengths.data(), nullptr, 0),
				&PQclear};
		verify<PqErr>(PQresultStatus(res.get()) == PGRES_COMMAND_OK, q, res.get());
	}

	DbPrepStmtPtr
	PqConn::prepare(const char * const q, std::size_t n)
	{
		return std::make_unique<PqPrepStmt>(q, n, this);
	}

	void
	PqConn::beginTx()
	{
		query("BEGIN");
	}

	void
	PqConn::commitTx()
	{
		query("COMMIT");
	}

	void
	PqConn::rollbackTx()
	{
		query("ROLLBACK");
	}

	void
	PqConn::notice_processor(void * p, const char * n)
	{
		return static_cast<PqConn *>(p)->notice_processor(n);
	}

	void
	PqConn::notice_processor(const char *) const
	{
	}
}