From kcgi-framework, use ksql

This commit is contained in:
Meutel 2016-12-29 20:41:31 +01:00
parent 220ada8c7e
commit 09d594bdee

70
db.c
View File

@ -24,60 +24,36 @@
#include <kcgi.h> #include <kcgi.h>
#include <kcgijson.h> #include <kcgijson.h>
#include <sqlite3.h> #include "ksql.h"
#include "extern.h" #include "extern.h"
/* /*
* When the database is busy or locked, sleep for a random amount of * Open the database and stash the resulting handle in the d
* 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
*/ */
int int
db_open(struct kreq *r, const char *file) db_open(struct kreq *r, const char *file)
{ {
size_t attempt; struct ksqlcfg cfg;
sqlite3 *db; struct ksql *sql;
int rc;
attempt = 0; /* Configure normal database except with foreign keys. */
// TODO max attempt, return 0
again: memset(&cfg, 0, sizeof(struct ksqlcfg));
// TODO open readonly cfg.flags = KSQL_EXIT_ON_ERR |
rc = sqlite3_open(file, &db); KSQL_FOREIGN_KEYS |
if (SQLITE_BUSY == rc) { KSQL_SAFE_EXIT;
db_sleep(attempt++); cfg.err = ksqlitemsg;
goto again; cfg.dberr = ksqlitedbmsg;
} else if (SQLITE_LOCKED == rc) {
fprintf(stderr, "sqlite3_open: %s\n", /* Allocate database. */
sqlite3_errmsg(db));
db_sleep(attempt++); if (NULL == (sql = ksql_alloc(&cfg)))
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); return(0);
ksql_open(sql, file);
r->arg = sql;
return(1);
} }
/* /*
@ -86,9 +62,7 @@ again:
void void
db_close(struct kreq *r) db_close(struct kreq *r)
{ {
if (SQLITE_OK == sqlite3_close(r->arg)) {
ksql_free(r->arg);
r->arg = NULL; r->arg = NULL;
return;
}
fprintf(stderr, "sqlite3_close: %s\n", sqlite3_errmsg(r->arg));
} }