From cf7a1dc4c55d9388ba4015c36627f507d1b3f73a Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sat, 17 Oct 2015 22:11:44 +0100 Subject: Add support for getting last insert value --- libpqpp/connection.cpp | 11 +++++++++++ libpqpp/connection.h | 1 + libpqpp/unittests/pqschema.sql | 4 ++++ libpqpp/unittests/testpq.cpp | 12 ++++++++++++ 4 files changed, 28 insertions(+) diff --git a/libpqpp/connection.cpp b/libpqpp/connection.cpp index e41cd3b..98f9054 100644 --- a/libpqpp/connection.cpp +++ b/libpqpp/connection.cpp @@ -186,3 +186,14 @@ PQ::Connection::bulkUploadData(const char * data, size_t len) const } } +int64_t +PQ::Connection::insertId() const +{ + SelectCommand getId(this, "SELECT lastval()", pstmntNo++); + int64_t id = -1; + while (getId.fetch()) { + getId[0] >> id; + } + return id; +} + diff --git a/libpqpp/connection.h b/libpqpp/connection.h index 1b2824d..40fb00e 100644 --- a/libpqpp/connection.h +++ b/libpqpp/connection.h @@ -23,6 +23,7 @@ namespace PQ { DB::SelectCommand * newSelectCommand(const std::string & sql) const override; DB::ModifyCommand * newModifyCommand(const std::string & sql) const override; + int64_t insertId() const override; void beginBulkUpload(const char *, const char *) const override; void endBulkUpload(const char *) const override; diff --git a/libpqpp/unittests/pqschema.sql b/libpqpp/unittests/pqschema.sql index 80d9183..2a7dd09 100644 --- a/libpqpp/unittests/pqschema.sql +++ b/libpqpp/unittests/pqschema.sql @@ -35,3 +35,7 @@ CREATE TABLE bulktest( id int, string text); +CREATE TABLE idtest( + id serial, + foo int); + diff --git a/libpqpp/unittests/testpq.cpp b/libpqpp/unittests/testpq.cpp index 3942cfd..cf366cb 100644 --- a/libpqpp/unittests/testpq.cpp +++ b/libpqpp/unittests/testpq.cpp @@ -155,5 +155,17 @@ BOOST_AUTO_TEST_CASE( bigIterate ) delete ro; } +BOOST_AUTO_TEST_CASE( insertId ) +{ + auto ro = DB::MockDatabase::openConnectionTo("pqmock"); + auto ins = ro->newModifyCommand("INSERT INTO idtest(foo) VALUES(1)"); + for (int x = 1; x < 4; x++) { + ins->execute(); + BOOST_REQUIRE_EQUAL(x, ro->insertId()); + } + delete ins; + delete ro; +} + BOOST_AUTO_TEST_SUITE_END(); -- cgit v1.2.3