gateway-old/database.c

54 lines
1.8 KiB
C
Raw Normal View History

2020-02-17 15:51:44 -08:00
#include "database.h"
#include <assert.h>
#include <stdio.h>
#include <stddef.h>
void database_state_init(struct database_state* s, const char* db_path) {
int return_code;
return_code = sqlite3_open_v2(db_path, &s->vm, SQLITE_OPEN_READWRITE, NULL);
assert(return_code == SQLITE_OK);
}
void database_state_free(struct database_state* s) {
sqlite3_close_v2(s->vm);
}
void database_write_active(struct database_state* s, int collar_id, int active_status) {
const char query[] = "UPDATE collar SET active=? WHERE id=?";
int return_code;
sqlite3_stmt* stmt;
return_code = sqlite3_prepare_v2(s->vm, query, sizeof(query), &stmt, NULL);
assert(return_code == SQLITE_OK);
return_code = sqlite3_bind_int(stmt, 1, active_status);
assert(return_code == SQLITE_OK);
return_code = sqlite3_bind_int(stmt, 2, collar_id);
assert(return_code == SQLITE_OK);
do {
return_code = sqlite3_step(stmt);
} while(return_code == SQLITE_ROW);
assert(return_code == SQLITE_DONE);
}
void database_write_location(struct database_state* s, int collar_id, double x, double y) {
const char query[] = "INSERT INTO data_point(collar_id, longitude, latitude, datetime)"
"VALUES (?, ?, ?, datetime('now'))";
int return_code;
sqlite3_stmt* stmt;
return_code = sqlite3_prepare_v2(s->vm, query, sizeof(query), &stmt, NULL);
assert(return_code == SQLITE_OK);
return_code = sqlite3_bind_int(stmt, 1, collar_id);
assert(return_code == SQLITE_OK);
return_code = sqlite3_bind_double(stmt, 2, x);
assert(return_code == SQLITE_OK);
return_code = sqlite3_bind_double(stmt, 3, y);
assert(return_code == SQLITE_OK);
do {
return_code = sqlite3_step(stmt);
} while(return_code == SQLITE_ROW);
assert(return_code == SQLITE_DONE);
}