From 5a8fa2161ba5b53ab05e43649e8ae5532cf0a8df Mon Sep 17 00:00:00 2001 From: Trygve Laugstøl Date: Thu, 26 Feb 2015 08:43:27 +0100 Subject: o Adding utility to insert samples from json files. --- apps/sm-db-insert.cpp | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 apps/sm-db-insert.cpp (limited to 'apps/sm-db-insert.cpp') diff --git a/apps/sm-db-insert.cpp b/apps/sm-db-insert.cpp new file mode 100644 index 0000000..a3ebb76 --- /dev/null +++ b/apps/sm-db-insert.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include +#include "json.hpp" +#include + +template +using o = boost::optional; +using namespace std; +using json = nlohmann::json; + +class missing_key : public runtime_error { +public: + missing_key(const json::string_t key) : runtime_error("Missing key: " + key), key(key) { + } + + const json::string_t key; +}; + +template +T get(json j, string key) { + auto ref = j[key]; + + if (ref.is_null()) { + throw missing_key(key); + } + + return ref; +} + +int main(int argc, char *argv[]) { + cout << "reading from " << argv[1] << endl; + + fstream f(argv[1]); + + json j; + + j << f; + + pqxx::connection c("host=localhost dbname=soil-moisture"); + + pqxx::work work(c); + + string mac = j["mac"]; // "aa:bb:cc:dd:ee:ff"; + + auto rs = work.parameterized("select id from soil_moisture_device where mac=$1")(mac).exec(); + + if (!rs.size()) { + cout << "New device: " << mac << endl; + + rs = work.parameterized("insert into soil_moisture_device(mac) values($1) returning id")(mac).exec(); + } + + auto deviceId = rs.begin()["id"].as(); + + int sensor = j["sensor"]; + + rs = work.parameterized("select id from soil_moisture_sensor where device=$1 and sensor=$2")(deviceId)(sensor).exec(); + + if (!rs.size()) { + cout << "New sensor: " << sensor << endl; + + rs = work.parameterized("insert into soil_moisture_sensor(device, sensor) values($1, $2) returning id")(deviceId)(sensor).exec(); + } + auto sensorId = rs.begin()["id"].as(); + + unsigned long timestamp = get(j, "timestamp"); + unsigned int value = get(j, "value"); + + work.parameterized("insert into soil_moisture_sample(sensor, timestamp, value) values($1, $2, $3)")(sensorId)(timestamp)(value).exec(); + + cout << "Sample inserted" << endl; + + work.commit(); + + return EXIT_SUCCESS; +} -- cgit v1.2.3