diff options
author | Dan Goodliffe <dan@randomdan.homeip.net> | 2015-10-17 22:11:44 +0100 |
---|---|---|
committer | Dan Goodliffe <dan@randomdan.homeip.net> | 2015-10-17 22:11:44 +0100 |
commit | cf7a1dc4c55d9388ba4015c36627f507d1b3f73a (patch) | |
tree | 0fe50b1812647f219deae4eef8b2b9727dad39bd | |
parent | Add override attributes (diff) | |
download | libdbpp-postgresql-0.9.1.tar.bz2 libdbpp-postgresql-0.9.1.tar.xz libdbpp-postgresql-0.9.1.zip |
Add support for getting last insert valuelibdbpp-postgresql-0.9.1
-rw-r--r-- | libpqpp/connection.cpp | 11 | ||||
-rw-r--r-- | libpqpp/connection.h | 1 | ||||
-rw-r--r-- | libpqpp/unittests/pqschema.sql | 4 | ||||
-rw-r--r-- | libpqpp/unittests/testpq.cpp | 12 |
4 files changed, 28 insertions, 0 deletions
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(); |