summaryrefslogtreecommitdiff
path: root/lib/output/pq/pqStmt.cpp
blob: c6399e4e3e65d71867afe2c7bfb4d7a422c4f16e (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
#include "pqStmt.h"
#include "libpq-fe.h"
#include "pqBindings.h"
#include "pqConn.h"
#include "pqRecordSet.h"
#include <compileTimeFormatter.h>
#include <cstdlib>
#include <functional>
#include <helpers.h>
#include <map>
#include <stdexcept>
#include <utility>
#include <vector>

namespace MyGrate::Output::Pq {
	PqPrepStmt::PqPrepStmt(const char * const q, std::size_t n, PqConn * c) :
		conn {c->conn.get()}, name {prepareAsNeeded(q, n, c)}, res {nullptr, nullptr}
	{
	}

	void
	PqPrepStmt::execute(const std::span<const DbValue> vs)
	{
		Bindings b {vs};
		res = {PQexecPrepared(
					   conn, name.c_str(), (int)vs.size(), b.values.data(), b.lengths.data(), b.formats.data(), 0),
				&PQclear};
		verify<PqErr>(PQresultStatus(res.get()) == PGRES_COMMAND_OK || PQresultStatus(res.get()) == PGRES_TUPLES_OK,
				name, conn);
	}

	std::size_t
	PqPrepStmt::rows() const
	{
		return std::strtoul(PQcmdTuples(res.get()), nullptr, 10);
	}

	RecordSetPtr
	PqPrepStmt::recordSet()
	{
		return std::make_unique<PqRecordSet>(std::move(res));
	}

	CursorPtr
	PqPrepStmt::cursor()
	{
		throw std::logic_error("Not implemented");
	}

	std::string
	PqPrepStmt::prepareAsNeeded(const char * const q, std::size_t n, PqConn * c)
	{
		if (const auto i = c->stmts.find(q); i != c->stmts.end()) {
			return i->second;
		}
		auto nam {scprintf<"pst%0lx">(c->stmts.size())};
		ResPtr res {PQprepare(c->conn.get(), nam.c_str(), q, (int)n, nullptr), PQclear};
		verify<PqErr>(PQresultStatus(res.get()) == PGRES_COMMAND_OK, q, c->conn.get());
		return c->stmts.emplace(q, std::move(nam)).first->second;
	}
}