#include #include #include #include #include #include "db.h" static char * textdup(const unsigned char *); sqlite3_stmt * byid(char *table, int id) { char sql[100]; sqlite3_stmt *stmt; snprintf(sql, 100, "SELECT oid, * FROM %s WHERE oid = ?", table); if(sqlite3_prepare(db, sql, -1, &stmt, 0) != SQLITE_OK) return NULL; if(sqlite3_bind_int(stmt, 1, id) != SQLITE_OK) return NULL; return stmt; } struct att * getatt(sqlite3_stmt *stmt) { struct att *att; att = nextatt(stmt); sqlite3_finalize(stmt); return att; } struct post * getpost(sqlite3_stmt *stmt) { struct post *post; post = nextpost(stmt); sqlite3_finalize(stmt); return post; } struct user * getuser(sqlite3_stmt *stmt) { struct user *user; user = nextuser(stmt); sqlite3_finalize(stmt); return user; } struct att * nextatt(sqlite3_stmt *stmt) { struct att *att; if(!stmt) return NULL; if(sqlite3_step(stmt) != SQLITE_ROW) return NULL; if(!(att = malloc(sizeof(struct att)))) err(1, "malloc"); att->id = sqlite3_column_int(stmt, 0); att->post = sqlite3_column_int(stmt, 1); att->name = textdup(sqlite3_column_text(stmt, 2)); att->description = textdup(sqlite3_column_text(stmt, 3)); att->mime = textdup(sqlite3_column_text(stmt, 4)); att->bytes = sqlite3_column_bytes(stmt, 5); if(!(att->data = malloc(att->bytes))) err(1, "malloc"); memcpy(att->data, sqlite3_column_blob(stmt, 5), att->bytes); return att; } struct post * nextpost(sqlite3_stmt *stmt) { struct post *post; if(!stmt) return NULL; if(sqlite3_step(stmt) != SQLITE_ROW) return NULL; if(!(post = malloc(sizeof(struct post)))) err(1, "malloc"); post->id = sqlite3_column_int(stmt, 0); post->parent = sqlite3_column_int(stmt, 1); post->user = sqlite3_column_int(stmt, 2); post->created = sqlite3_column_int(stmt, 3); post->edited = sqlite3_column_int(stmt, 4); post->subject = textdup(sqlite3_column_text(stmt, 5)); post->text = textdup(sqlite3_column_text(stmt, 6)); return post; } struct user * nextuser(sqlite3_stmt *stmt) { struct user *user; if(!stmt) return NULL; if(sqlite3_step(stmt) != SQLITE_ROW) return NULL; if(!(user = malloc(sizeof(struct user)))) err(1, "malloc"); user->id = sqlite3_column_int(stmt, 0); user->name = textdup(sqlite3_column_text(stmt, 1)); user->full = textdup(sqlite3_column_text(stmt, 2)); user->hash = textdup(sqlite3_column_text(stmt, 3)); return user; } char * textdup(const unsigned char *s) { return s? strdup((char *)s): NULL; }