/home/martin/workspace/OpenStreetNav/src/psql/CopyTypes.h
Go to the documentation of this file.
00001 /*
00002  * CopyTypes.h
00003  *
00004  *  Created on: Jan 7, 2012
00005  *      Author: martin
00006  */
00007 
00008 #ifndef COPYTYPES_H_
00009 #define COPYTYPES_H_
00010 
00011 #include <string>
00012 #include "Database.h"
00013 #include "PgSqlException.h"
00014 #include "../util.h"
00015 
00016 namespace psql
00017 {
00018 
00019 namespace cptypes
00020 {
00021 
00022 template<typename... Args>
00023 class sanitize
00024 {
00025 };
00026 
00027 template<>
00028 class sanitize<>
00029 {
00030 public:
00031     void operator()()
00032     {
00033     }
00034 };
00035 
00036 template<typename Head, typename... Tail>
00037 class sanitize<Head, Tail...>
00038 {
00039 public:
00040     void operator()(Head&, Tail& ... t)
00041     {
00042         sanitize<Tail...>()(t...);
00043     }
00044 };
00045 
00046 template<typename... Tail>
00047 class sanitize<std::string, Tail...>
00048 {
00049 public:
00050     void operator()(std::string& s, Tail& ... t)
00051     {
00052         std::map<char, std::string> m
00053         {
00054             std::make_pair('\t', "\\t"),
00055             std::make_pair('\r', "\\r"),
00056             std::make_pair('\n', "\\n"),
00057             std::make_pair('\\', "\\\\")
00058         };
00059         s = util::replace(s, m);
00060         sanitize<Tail...>()(t...);
00061     }
00062 };
00063 
00064 }
00065 
00066 template<typename... Args>
00067 class CopyTypes
00068 {
00069 public:
00070     CopyTypes(std::string const& row_sep = "\n", std::string const& col_sep = "\t"):
00071         row_sep(row_sep),
00072         col_sep(col_sep)
00073     {
00074     }
00075     void copy(Database& db, Args... a)
00076     {
00077         cptypes::sanitize<Args...>()(a...);
00078         auto s = util::concatenate("\t", a...) + "\n";
00079         auto conn = db.get_db();
00080         auto result = PQputCopyData(conn, s.c_str(), s.size());
00081         if (result == 0)
00082             throw PgSqlException("Sorry copy for asynchronous connections is not implemented");
00083         if (result == -1)
00084             throw PgSqlException("Error sending copy data: " + std::string(PQerrorMessage(conn)));
00085     }
00086 protected:
00087     std::string row_sep, col_sep;
00088 };
00089 
00090 } /* namespace psql*/
00091 #endif /* COPYTYPES_H_ */
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines