db.c (1579B)


      1 #include <ctype.h>
      2 #include <stddef.h>
      3 #include <string.h>
      4 #include <stdlib.h>
      5 #include <stdio.h>
      6 
      7 #include <sqlite3.h>
      8 
      9 #include "db.h"
     10 
     11 int
     12 db_open(sqlite3** db, const char* path)
     13 {
     14   int rc = sqlite3_open("library.db", db);
     15   if (rc != SQLITE_OK)
     16     return 1;
     17 
     18   char* err = NULL;
     19   sqlite3_exec(*db,
     20                "CREATE TABLE IF NOT EXISTS books("
     21                "id INTEGER PRIMARY KEY AUTOINCREMENT,"
     22                "lcc TEXT NOT NULL,"
     23                "year INTEGER NOT NULL,"
     24                "title TEXT NOT NULL,"
     25                "author TEXT NOT NULL"
     26                ");"
     27                "CREATE INDEX IF NOT EXISTS idx_books_lcc ON books(lcc);",
     28                NULL,
     29                NULL,
     30                &err);
     31 
     32   if (err) {
     33     fprintf(stderr, "db: Failed to open!\n\t%s\n", err);
     34     return 1;
     35   }
     36 
     37   return 0;
     38 }
     39 
     40 int
     41 db_add(sqlite3* db, const char* lcc, const char* title, const char* author)
     42 {
     43   const char* year_start = strrchr(lcc, ' ');
     44 
     45   if (year_start)
     46     year_start++;
     47   else
     48     return 1;
     49 
     50   int year = atoi(year_start);
     51   if (!year)
     52     return 1;
     53 
     54   sqlite3_stmt* res;
     55   if (sqlite3_prepare_v2(
     56         db,
     57         "INSERT INTO books (lcc, year, title, author) "
     58         "VALUES (?, ?, ?, ?);",
     59         -1,
     60         &res,
     61         0) != SQLITE_OK)
     62     return 2;
     63 
     64   sqlite3_bind_text(res, 1, lcc, -1, SQLITE_STATIC);
     65   sqlite3_bind_int(res, 2, year);
     66   sqlite3_bind_text(res, 3, title, -1, SQLITE_STATIC);
     67   sqlite3_bind_text(res, 4, author, -1, SQLITE_STATIC);
     68 
     69   if (sqlite3_step(res) != SQLITE_DONE)
     70     return 3;
     71 
     72   sqlite3_finalize(res);
     73 
     74   return 0;
     75 }