1 /* SQLite3 database backend. */
9 /* sqlite3_busy_timeout sleeps for a *second*. What a piece of shit. */
10 static int busy(void *unused __attribute__((unused)), int count)
14 /* If we've been stuck for 1000 iterations (at least 50
15 * seconds), give up. */
16 return (count < 1000);
19 void *db_open(const char *file)
23 int err = sqlite3_open(file, &handle);
25 printf("Error %i from sqlite3_open of db '%s'\n", err, file);
26 sqlite3_busy_handler(handle, busy, NULL);
31 static int query_cb(void *data, int num, char**vals,
32 char**names __attribute__((unused)))
35 struct db_query *query = data;
36 query->rows = realloc_array(query->rows, query->num_rows+1);
37 query->rows[query->num_rows] = new_array(char *, num);
38 for (i = 0; i < num; i++) {
39 /* We don't count rows with NULL results
40 * (eg. count(*),player where count turns out to be
44 query->rows[query->num_rows][i] = strdup(vals[i]);
50 /* Runs query (SELECT). Fails if > 1 row returned. Fills in columns. */
51 struct db_query *db_query(void *h, const char *query)
56 ret = (struct db_query*) palloc(sizeof(struct db_query));
59 if (sqlite3_exec(h, query, query_cb, ret, &err) != SQLITE_OK)
60 printf("Failed sqlite3 query '%s': %s", query, err);
64 /* Runs command (CREATE TABLE/INSERT) */
65 void db_command(void *h, const char *command)
69 if (sqlite3_exec(h, command, NULL, NULL, &err) != SQLITE_OK)
70 printf("Failed sqlite3 command '%s': %s", command, err);
73 /* Starts transaction. Doesn't need to nest. */
74 /*void db_transaction_start(void *h)
77 if (sqlite3_exec(h, "BEGIN EXCLUSIVE TRANSACTION", NULL, NULL, &err)!=SQLITE_OK)
78 printf("Starting sqlite3 transaction: %s\n", err);
81 /* Finishes transaction, or rolls it back and caller needs to start again. */
83 bool db_transaction_finish(void *h)
85 switch (sqlite3_exec(h, "COMMIT TRANSACTION;", NULL, NULL, NULL)) {
89 if (sqlite3_exec(h, "ROLLBACK TRANSACTION;", NULL, NULL, NULL)
91 printf("Ending sqlite3 busy rollback failed");
94 printf("Strange sqlite3 error return from COMMIT");
98 /* Closes database (only called when everything OK). */
99 void db_close(void *h)