4#if __has_include(<libpq-fe.h>)
7# include <postgresql/libpq-fe.h>
23 const std::string& pass,
24 const std::string& host,
26 const std::string& dbname)
28 std::string conninfo =
32 " port=" + std::to_string(port) +
34 conn = PQconnectdb(conninfo.c_str());
35 if (PQstatus(
conn) != CONNECTION_OK)
36 throw std::runtime_error(PQerrorMessage(
conn));
44 PGresult* res = PQexec(
conn, sql.c_str());
45 if (PQresultStatus(res) != PGRES_COMMAND_OK) {
46 std::string err = PQerrorMessage(
conn);
48 throw std::runtime_error(err);
55 const std::string &table,
56 const std::string &columns,
57 const std::function<
void()> &writeRows
60 "COPY " + table +
" " + columns +
" FROM STDIN WITH (FORMAT binary)";
61 PGresult* res = PQexec(
conn, stmt.c_str());
62 if (PQresultStatus(res) != PGRES_COPY_IN) {
63 std::string err = PQerrorMessage(
conn);
65 throw std::runtime_error(
"COPY start failed: " + err);
71 if (PQputCopyEnd(
conn,
nullptr) != 1)
72 throw std::runtime_error(
"COPY end failed");
74 res = PQgetResult(
conn);
75 if (PQresultStatus(res) != PGRES_COMMAND_OK) {
76 std::string err = PQerrorMessage(
conn);
78 throw std::runtime_error(
"COPY finalization failed: " + err);
88 static const unsigned char sig[11] = {
'P',
'G',
'C',
'O',
'P',
'Y',
'\n', 0xFF,
'\r',
'\n',
'\0' };
91 int32_t zero = htonl(0);
98 int16_t tr = htons(-1);
105 size_t headerSize = 19;
106 size_t footerSize = 2;
107 size_t totalSize = headerSize + N * rowSize + footerSize;
112 int16_t be = htons(nCols);
118 auto p =
reinterpret_cast<const char*
>(data);
124 int32_t len_be = htonl((int32_t)len);
130 int32_t len_be = htonl(1);
132 unsigned char v = b ? 1 : 0;
136 int32_t v_be = htonl(
static_cast<int32_t
>(v));
142 std::memcpy(&u, &d,
sizeof(u));
143 u = __builtin_bswap64(u);
Connection(const std::string &user, const std::string &pass, const std::string &host, int port, const std::string &dbname)
void prepareBuffer(size_t N, size_t rowSize)
void CopyBinary(const std::string &table, const std::string &columns, const std::function< void()> &writeRows)
void appendField(const void *data, size_t len)
std::vector< char > rowBuf
void appendDouble(double d)
void headerCopy(size_t N, size_t rowSize)
void appendRaw(const void *data, size_t len)
void beginRow(int16_t nCols)
void Execute(const std::string &sql)
void reserve(size_t newCapacity)
Reserves storage for the specified number of elements.
void clear()
Clears the contents of the vector.
iterator end()
Returns an iterator to the last element.
size_t size() const
Returns the number of elements in the vector.
void insert(iterator position, const T &value)
Inserts an element at the specified position.