From 25a8f2a606dfbb1c4960f2ef1a14e64667e691d7 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Thu, 25 Feb 2016 22:24:53 +0000 Subject: Reuse prepared statements --- libpqpp/pq-modifycommand.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) (limited to 'libpqpp/pq-modifycommand.cpp') diff --git a/libpqpp/pq-modifycommand.cpp b/libpqpp/pq-modifycommand.cpp index 4c4ca0c..e59908e 100644 --- a/libpqpp/pq-modifycommand.cpp +++ b/libpqpp/pq-modifycommand.cpp @@ -7,7 +7,7 @@ PQ::ModifyCommand::ModifyCommand(Connection * conn, const std::string & sql, uns DB::Command(sql), DB::ModifyCommand(sql), PQ::Command(conn, sql, no), - prepared(false) + hash(std::hash()(sql)) { } @@ -15,24 +15,25 @@ PQ::ModifyCommand::~ModifyCommand() { } -void +PQ::Connection::PreparedStatements::const_iterator PQ::ModifyCommand::prepare() const { - if (!prepared) { - std::string psql; - psql.reserve(sql.length() + 20); - prepareSql(psql, sql); - c->checkResultFree(PQprepare( - c->conn, stmntName.c_str(), psql.c_str(), values.size(), NULL), PGRES_COMMAND_OK); - prepared = true; + auto i = c->preparedStatements.find(hash); + if (i != c->preparedStatements.end()) { + return i; } + std::string psql; + psql.reserve(sql.length() + 20); + prepareSql(psql, sql); + c->checkResultFree(PQprepare( + c->conn, stmntName.c_str(), psql.c_str(), values.size(), NULL), PGRES_COMMAND_OK); + return c->preparedStatements.insert({hash, stmntName}).first; } unsigned int PQ::ModifyCommand::execute(bool anc) { - prepare(); - PGresult * res = PQexecPrepared(c->conn, stmntName.c_str(), values.size(), &values.front(), &lengths.front(), NULL, 0); + PGresult * res = PQexecPrepared(c->conn, prepare()->second.c_str(), values.size(), &values.front(), &lengths.front(), NULL, 0); c->checkResult(res, PGRES_COMMAND_OK, PGRES_TUPLES_OK); unsigned int rows = atoi(PQcmdTuples(res)); PQclear(res); -- cgit v1.2.3