89 lines
2.1 KiB
C
89 lines
2.1 KiB
C
#include "database.h"
|
|
#include <sqlite3.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <stdio.h>
|
|
#include <jansson.h>
|
|
|
|
static sqlite3 *db;
|
|
|
|
int db_init() {
|
|
int rc = sqlite3_open("database.db", &db);
|
|
if (rc) {
|
|
return rc;
|
|
}
|
|
|
|
// Initialize tables if necessary
|
|
const char *sql = "CREATE TABLE IF NOT EXISTS data (id INTEGER PRIMARY KEY, value TEXT);";
|
|
char *errmsg = 0;
|
|
rc = sqlite3_exec(db, sql, 0, 0, &errmsg);
|
|
if (rc != SQLITE_OK) {
|
|
sqlite3_free(errmsg);
|
|
}
|
|
return rc;
|
|
}
|
|
|
|
char* db_query(const char *query) {
|
|
// Prepare SQL statement
|
|
const char *sql = "SELECT * FROM data WHERE value LIKE ?;";
|
|
sqlite3_stmt *stmt;
|
|
char *response = NULL;
|
|
|
|
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
|
|
return strdup("{\"error\": \"Failed to prepare statement\"}");
|
|
}
|
|
|
|
// Bind the query parameter
|
|
sqlite3_bind_text(stmt, 1, query, -1, SQLITE_TRANSIENT);
|
|
|
|
// Build JSON response
|
|
json_t *json_arr = json_array();
|
|
while (sqlite3_step(stmt) == SQLITE_ROW) {
|
|
json_t *json_obj = json_object();
|
|
int id = sqlite3_column_int(stmt, 0);
|
|
const unsigned char *value = sqlite3_column_text(stmt, 1);
|
|
|
|
json_object_set_new(json_obj, "id", json_integer(id));
|
|
json_object_set_new(json_obj, "value", json_string((const char *)value));
|
|
|
|
json_array_append_new(json_arr, json_obj);
|
|
}
|
|
|
|
char *json_str = json_dumps(json_arr, JSON_INDENT(2));
|
|
response = strdup(json_str);
|
|
|
|
// Cleanup
|
|
free(json_str);
|
|
json_decref(json_arr);
|
|
sqlite3_finalize(stmt);
|
|
|
|
return response;
|
|
}
|
|
|
|
int db_insert(const char *value) {
|
|
const char *sql = "INSERT INTO data (value) VALUES (?);";
|
|
sqlite3_stmt *stmt;
|
|
int rc;
|
|
|
|
if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {
|
|
return 1;
|
|
}
|
|
|
|
// Bind the value parameter
|
|
sqlite3_bind_text(stmt, 1, value, -1, SQLITE_TRANSIENT);
|
|
|
|
// Execute the statement
|
|
rc = sqlite3_step(stmt);
|
|
sqlite3_finalize(stmt);
|
|
|
|
if (rc != SQLITE_DONE) {
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
void db_close() {
|
|
sqlite3_close(db);
|
|
}
|