From 09d594bdeefce7b186f13aeb06059b7b7ce5b3dc Mon Sep 17 00:00:00 2001 From: Meutel Date: Thu, 29 Dec 2016 20:41:31 +0100 Subject: [PATCH] From kcgi-framework, use ksql --- db.c | 74 ++++++++++++++++++++---------------------------------------- 1 file changed, 24 insertions(+), 50 deletions(-) diff --git a/db.c b/db.c index b403540..6f62570 100644 --- a/db.c +++ b/db.c @@ -24,60 +24,36 @@ #include #include -#include +#include "ksql.h" #include "extern.h" /* - * When the database is busy or locked, sleep for a random amount of - * time before continuing. - * We could put all sorts of heuristics in here to back off, but we do - * something really simple. - */ -static void -db_sleep(size_t attempt) -{ - - if (attempt < 10) - usleep(arc4random_uniform(100000)); - else - usleep(arc4random_uniform(500000)); -} - -/* - * Open the database and stash the resulting handle in the kreq + * Open the database and stash the resulting handle in the d */ int db_open(struct kreq *r, const char *file) { - size_t attempt; - sqlite3 *db; - int rc; + struct ksqlcfg cfg; + struct ksql *sql; - attempt = 0; - // TODO max attempt, return 0 -again: - // TODO open readonly - rc = sqlite3_open(file, &db); - if (SQLITE_BUSY == rc) { - db_sleep(attempt++); - goto again; - } else if (SQLITE_LOCKED == rc) { - fprintf(stderr, "sqlite3_open: %s\n", - sqlite3_errmsg(db)); - db_sleep(attempt++); - goto again; - } else if (SQLITE_PROTOCOL == rc) { - fprintf(stderr, "sqlite3_open: %s\n", - sqlite3_errmsg(db)); - db_sleep(attempt++); - goto again; - } else if (SQLITE_OK == rc) { - sqlite3_busy_timeout(db, 500); - r->arg = db; - return(1); - } - return(0); + /* Configure normal database except with foreign keys. */ + + memset(&cfg, 0, sizeof(struct ksqlcfg)); + cfg.flags = KSQL_EXIT_ON_ERR | + KSQL_FOREIGN_KEYS | + KSQL_SAFE_EXIT; + cfg.err = ksqlitemsg; + cfg.dberr = ksqlitedbmsg; + + /* Allocate database. */ + + if (NULL == (sql = ksql_alloc(&cfg))) + return(0); + + ksql_open(sql, file); + r->arg = sql; + return(1); } /* @@ -86,9 +62,7 @@ again: void db_close(struct kreq *r) { - if (SQLITE_OK == sqlite3_close(r->arg)) { - r->arg = NULL; - return; - } - fprintf(stderr, "sqlite3_close: %s\n", sqlite3_errmsg(r->arg)); + + ksql_free(r->arg); + r->arg = NULL; }