bouquins-bchs/db.c

95 lines
2.3 KiB
C
Raw Normal View History

2016-12-18 15:50:56 +00:00
/* $Id$ */
/*
* Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <kcgi.h>
#include <kcgijson.h>
#include <sqlite3.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
*/
int
db_open(struct kreq *r, const char *file)
{
size_t attempt;
sqlite3 *db;
int rc;
attempt = 0;
// TODO max attempt, return 0
again:
2016-12-18 16:09:20 +00:00
// TODO open readonly
2016-12-18 15:50:56 +00:00
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);
2016-12-18 17:28:00 +00:00
r->arg = db;
2016-12-18 15:50:56 +00:00
return(1);
}
2016-12-18 17:48:54 +00:00
return(0);
2016-12-18 15:50:56 +00:00
}
/*
* Close the database stashed in the kreq's argument.
*/
void
db_close(struct kreq *r)
{
if (SQLITE_OK == sqlite3_close(r->arg)) {
r->arg = NULL;
return;
}
2016-12-18 17:28:00 +00:00
fprintf(stderr, "sqlite3_close: %s\n", sqlite3_errmsg(r->arg));
2016-12-18 15:50:56 +00:00
}