2025-03-05 14:11:27 -05:00

113 lines
2.4 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <sqlite3.h>
#include <string.h>
#include <math.h>
#include "include/db.h"
static void open_db(sqlite3** db)
{
int err;
err = sqlite3_open("books.db", db);
if (err != SQLITE_OK) {
fprintf(stderr, "Cannot open db: %s\n", sqlite3_errmsg(*db));
sqlite3_close(*db);
exit(EXIT_FAILURE);
}
}
static int get_num_rows(sqlite3* db)
{
int rows = 0;
sqlite3_stmt* msg;
sqlite3_prepare(db, "SELECT * FROM books;", -1, &msg, NULL);
while (sqlite3_step(msg) == SQLITE_ROW)
rows++;
sqlite3_finalize(msg);
return rows;
}
void setup_db(sqlite3* db)
{
int err;
char* err_buf = 0;
open_db(&db);
err = sqlite3_exec(db,
"CREATE TABLE IF NOT EXISTS books (id UNSIGNED INT PRIMARY KEY, \
title TEXT, subtitle TEXT, isbn TEXT, authors TEXT, subjects TEXT, \
langs TEXT, date_added TEXT, pub_date TEXT, \
image_code TEXT, year_of_pub YEAR, page_len UNSIGNED INT);",
0, 0, &err_buf);
if (err != SQLITE_OK) {
fprintf(stderr, "sqlite3_exec: %s\n", err_buf);
sqlite3_free(err_buf);
sqlite3_close(db);
exit(EXIT_FAILURE);
}
sqlite3_close(db);
}
static void add_str_entry(char** dst, char** src)
{
size_t len;
len = strlen(*src) + strlen(*dst) + 1;
*dst = malloc(sizeof(char) * len);
*dst = strcat(*dst, *src);
}
static void add_int_entry(char** dst, int src)
{
size_t len_int, len;
if (src == 0)
len_int = 1;
else
len_int = floor(log10(abs(src))) + 1;
len = strlen(*dst) + len_int + 1;
*dst = malloc(sizeof(char) * len);
snprintf(*dst, len, "%s%d", *dst, src);
}
static void string_cat_vals(char** dst, book_t* book, int id)
{
add_int_entry(dst, id);
add_str_entry(dst, &(book->title));
add_str_entry(dst, &(book->subtitle));
add_str_entry(dst, &(book->isbn));
add_str_entry(dst, &(book->authors));
add_str_entry(dst, &(book->subjects));
add_str_entry(dst, &(book->langs));
add_str_entry(dst, &(book->date_added));
add_str_entry(dst, &(book->pub_date));
add_str_entry(dst, &(book->image_code));
add_int_entry(dst, book->page_len);
}
#define INSERT_STR "INSERT INTO books (id, title, subtitle, isbn, authors, subjects, langs, date_added, pub_date, image_code, page_len) VALUES("
void add_to_db(book_t* book, sqlite3* db)
{
int id;
char* cmd;
open_db(&db);
id = get_num_rows(db) + 1;
cmd = malloc(sizeof(char) * (strlen(INSERT_STR) + 1));
snprintf(cmd, strlen(INSERT_STR), "%s", INSERT_STR);
string_cat_vals(&cmd, book, id);
}