From kcgi-framework, use ksql

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

74
db.c
View File

@ -24,60 +24,36 @@
#include <kcgi.h>
#include <kcgijson.h>
#include <sqlite3.h>
#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;
}