Instantly share code, notes, and snippets.
CreatedSeptember 26, 2022 14:13
Save dgrr/fb6aa8534def1a35d8dfc4c1af11ceba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<pqxx/pqxx> | |
#include<string> | |
#include<string> | |
template<size_t I,classIt,classT,classTuple> | |
std::enable_if_t<(I == std::tuple_size<Tuple>::value -1)>assign(It it, It end, T& v, Tuple& tp) | |
{ | |
if (it == end) | |
return; | |
v = it->templateas<T>(); | |
} | |
template<size_t I,classIt,classT,classTuple> | |
std::enable_if_t<(I < std::tuple_size<Tuple>::value -1)>assign(It it, It end, T& v, Tuple& tp) | |
{ | |
if (it == end) | |
return; | |
v = it->templateas<T>(); | |
assign<I+1>(++it, end, std::get<I+1>(tp), tp); | |
} | |
template<classQuery,class... Types> | |
voidexec(std::string conn_str, Query query, std::vector<std::tuple<Types...>>& vs) | |
{ | |
pqxx::connectionC(conn_str); | |
pqxx::nontransactionN(C); | |
auto r = N.exec(query); | |
vs.resize(r.size()); | |
for (constauto& row : r) | |
{ | |
auto& tp = vs[row.rownumber()]; | |
assign<0>(row.begin(), row.end(), std::get<0>(tp), tp); | |
} | |
} | |
template<classQuery,class... Types> | |
voidexec(std::string conn_str, Query query, std::tuple<Types...>& tp) | |
{ | |
pqxx::connectionC(conn_str); | |
pqxx::nontransactionN(C); | |
auto r = N.exec(query); | |
for (constauto& row : r) | |
{ | |
assign<0>(row.begin(), row.end(), std::get<0>(tp), tp); | |
} | |
} | |
template<classQuery,classT> | |
voidexec(std::string conn_str, Query query, T& v) | |
{ | |
pqxx::connectionC(conn_str); | |
pqxx::nontransactionN(C); | |
auto r = N.exec(query); | |
for (constauto& row : r) | |
{ | |
if (row.size() >0) | |
{ | |
v = row[0].templateas<T>(); | |
break; | |
} | |
} | |
C.disconnect(); | |
} | |
intmain() | |
{ | |
constchar *conn_str ="host=localhost port=8812 user=admin password=quest dbname=qdb"; | |
std::vector<std::tuple<std::string,int,double>> vs; | |
exec(conn_str,"SELECT DISTINCT coin, trades FROM market", vs); | |
for (auto& v : vs) | |
std::cout << std::get<0>(v) <<" |" << std::get<1>(v) << std::endl; | |
int x; | |
exec(conn_str,"SELECT count() from market", x); | |
std::cout <<"count() =" << x << std::endl; | |
} |
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment