1 #define _POSIX_C_SOURCE 200809L
10 #define SQLERROR(x) fprintf(stderr, "%s %d: %s\n", __func__, __LINE__, (x))
12 sqlite3_stmt *zpm_dbqueryv(struct zpm *zpm, char *query, va_list args) {
18 if (!zpm || zpm->error) {
29 sql = sqlite3_vmprintf(query, args);
36 rv = sqlite3_prepare_v2(db, sql, strlen(sql), &st, NULL);
37 if (rv != SQLITE_OK) {
38 SQLERROR(sqlite3_errmsg(db));
39 fprintf(stderr, "sql (%d): %s\n", rv, sql);
48 sqlite3_stmt *zpm_dbquery(struct zpm *zpm, char *query, ...) {
52 if (!zpm || zpm->error) {
61 va_start(args, query);
62 st = zpm_dbqueryv(zpm, query, args);
68 void zpm_db_run(struct zpm *zpm, char *query, ...) {
73 va_start(args, query);
74 st = zpm_dbqueryv(zpm, query, args);
77 rv = sqlite3_step(st);
79 if (rv != SQLITE_DONE) {
81 zpm_seterror(zpm, "db error: %s", sqlite3_errstr(rv));
88 int zpm_findhash(struct zpm *zpm, char *find, char *dest) {
92 count = zpm_db_int(zpm, "select count(*) from files where hash like '%q%%';", find);
97 found = zpm_db_string(zpm, "select hash from files where hash like '%s%%' limit 1;", find);
109 char *zpm_db_string(struct zpm *zpm, char *query, ...) {
115 va_start(args, query);
116 st = zpm_dbqueryv(zpm, query, args);
119 rv = sqlite3_step(st);
123 result = (char *)sqlite3_column_text(st, 0);
125 result = strdup(result);
128 case SQLITE_DONE: break;
131 zpm_seterror(zpm, "db error: %s", sqlite3_errstr(rv));
135 sqlite3_finalize(st);
139 int zpm_db_int(struct zpm *zpm, char *query, ...) {
145 va_start(args, query);
146 st = zpm_dbqueryv(zpm, query, args);
149 rv = sqlite3_step(st);
151 if (rv == SQLITE_ROW) {
152 result = sqlite3_column_int(st, 0);
154 /* TODO set error if it's not SQLITE_ROW */
156 sqlite3_finalize(st);