iiotfeeder/dbhandler.c
Wolfgang Hottgenroth a99c3b7121
queue and so on
2021-10-17 14:41:21 +02:00

93 lines
2.6 KiB
C

#include <logging.h>
#include <dbhandler.h>
#include <config.h>
#include <libpq-fe.h>
#include <stdlib.h>
t_dbHandle *initDatabaseHandler(t_configHandle *configHandle) {
t_dbHandle *dbHandle = (t_dbHandle*) malloc(sizeof(t_dbHandle));
if (! dbHandle) {
logmsg(LOG_ERR, "out of memory when trying to allocate dbHandle");
return NULL;
}
dbHandle->configHandle = configHandle;
dbHandle->postgresqlConnInfo = NULL;
config_lookup_string(&(configHandle->cfg), "postgresqlConnInfo", &(dbHandle->postgresqlConnInfo));
if (! dbHandle->postgresqlConnInfo) {
logmsg(LOG_ERR, "no postgresql connInfo configured");
free(dbHandle);
dbHandle = NULL;
return NULL;
}
dbHandle->conn = NULL;
return dbHandle;
}
void deinitDatabaseHandler(t_dbHandle *handle) {
if (handle) {
PQfinish(handle->conn);
free(handle);
handle = NULL;
}
}
int openDatabase(t_dbHandle *handle) {
int res = 0;
if (! handle->conn) {
logmsg(LOG_DEBUG, "Opening connection to database");
handle->conn = PQconnectdb(handle->postgresqlConnInfo);
} else if (PQstatus(handle->conn) != CONNECTION_OK) {
logmsg(LOG_DEBUG, "Resetting connection to database");
PQreset(handle->conn);
}
if (PQstatus(handle->conn) != CONNECTION_OK) {
logmsg(LOG_ERR, "Connection to database failed: %s", PQerrorMessage(handle->conn));
res = -1;
}
return res;
}
int sendToDB(t_dbHandle *handle, const uint32_t experimentId, const uint32_t value,
const uint64_t timestamp) {
int retcode = 0;
if (0 == openDatabase(handle)) {
char stmt[256];
int res1 = snprintf(stmt, sizeof(stmt),
"INSERT INTO mainsfrequency (time, host, location, valid, freq) "
"VALUES(to_timestamp('%lu'), '%d', '%d')",
timestamp, experimentId, value);
if (res1 > sizeof(stmt)) {
logmsg(LOG_ERR, "stmt buffer to small");
retcode = -1;
} else {
logmsg(LOG_DEBUG, "Statement: %s", stmt);
PGresult *res2 = PQexec(handle->conn, stmt);
if (PQresultStatus(res2) != PGRES_COMMAND_OK) {
logmsg(LOG_ERR, "Failed to insert into database (%s), data lost",
PQresultErrorMessage(res2));
retcode = -2;
}
PQclear(res2);
}
} else {
logmsg(LOG_ERR, "No database connection available, data lost");
retcode = -1;
}
return retcode;
}