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 int 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));
84 return sqlite3_finalize(st);
87 int zpm_findhash(struct zpm *zpm, char *find, char *dest) {
91 count = zpm_db_int(zpm, "select count(*) from files where hash like '%q%%';", find);
96 found = zpm_db_string(zpm, "select hash from files where hash like '%s%%' limit 1;", find);
108 char *zpm_db_string(struct zpm *zpm, char *query, ...) {
114 va_start(args, query);
115 st = zpm_dbqueryv(zpm, query, args);
118 rv = sqlite3_step(st);
122 result = (char *)sqlite3_column_text(st, 0);
124 result = strdup(result);
127 case SQLITE_DONE: break;
130 zpm_seterror(zpm, "db error: %s", sqlite3_errstr(rv));
134 sqlite3_finalize(st);
138 int zpm_db_int(struct zpm *zpm, char *query, ...) {
144 va_start(args, query);
145 st = zpm_dbqueryv(zpm, query, args);
148 rv = sqlite3_step(st);
150 if (rv == SQLITE_ROW) {
151 result = sqlite3_column_int(st, 0);
153 /* TODO set error if it's not SQLITE_ROW */
155 sqlite3_finalize(st);