From 7e2e1abbfcdadbd2fc3e3adb84873973920c0d60 Mon Sep 17 00:00:00 2001 From: rbock Date: Mon, 24 Dec 2018 17:32:16 +0100 Subject: [PATCH] Add example for MYSQL's ON DUPLICATE KEY UPDATE --- tests/CustomQuery.cpp | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/CustomQuery.cpp b/tests/CustomQuery.cpp index 94af9bff..6a15b90d 100644 --- a/tests/CustomQuery.cpp +++ b/tests/CustomQuery.cpp @@ -29,7 +29,35 @@ #include #include -int CustomQuery(int, char* []) +namespace +{ + struct on_duplicate_key_update + { + std::string _serialized; + + template + on_duplicate_key_update(Db&, Assignment assignment) + { + typename Db::_serializer_context_t context; + _serialized = " ON DUPLICATE KEY UPDATE " + serialize(assignment, context).str(); + } + + template + auto operator()(Db&, Assignment assignment) -> on_duplicate_key_update& + { + typename Db::_serializer_context_t context; + _serialized += ", " + serialize(assignment, context).str(); + return *this; + } + + auto get() const -> sqlpp::verbatim_t<::sqlpp::no_value_t> + { + return ::sqlpp::verbatim(_serialized); + } + }; +} // namespace + +int CustomQuery(int, char*[]) { MockDb db = {}; MockDb::_serializer_context_t printer = {}; @@ -61,6 +89,10 @@ int CustomQuery(int, char* []) db(custom_query(sqlpp::insert(), sqlpp::verbatim(" OR IGNORE"), into(t), insert_set(t.beta = "sample", t.gamma = true))); + // Create a MYSQL style custom "insert on duplicate update" + db(custom_query(sqlpp::insert_into(t).set(t.beta = "sample", t.gamma = true), + on_duplicate_key_update(db, t.beta = "sample")(db, t.gamma = false).get())); + // A custom (select ... into) with adjusted return type // The first argument with a return type is the select, but the custom query is really an insert. Thus, we tell it so. printer.reset();