aboutsummaryrefslogtreecommitdiff
path: root/db.c
diff options
context:
space:
mode:
Diffstat (limited to 'db.c')
-rw-r--r--db.c66
1 files changed, 50 insertions, 16 deletions
diff --git a/db.c b/db.c
index fcb742d..bd2de17 100644
--- a/db.c
+++ b/db.c
@@ -1,36 +1,70 @@
#include <err.h>
#include <stdlib.h>
+#include <string.h>
#include <sqlite3.h>
#include "db.h"
+sqlite3_stmt *
+byid(int id, char *sql)
+{
+ sqlite3_stmt *stmt;
+
+ if(sqlite3_prepare(db, sql, -1, &stmt, 0) != SQLITE_OK)
+ return NULL;
+
+ if(sqlite3_bind_int(stmt, 1, id) != SQLITE_OK)
+ return NULL;
+
+ if(sqlite3_step(stmt) != SQLITE_ROW)
+ return NULL;
+
+ return stmt;
+}
+
+struct post *
+getpost(int id)
+{
+ sqlite3_stmt *stmt;
+ struct post *post;
+
+ if(!(stmt = byid(id, "SELECT parent, user, created, edited, subject, text FROM posts WHERE oid = ?"))){
+ sqlite3_finalize(stmt);
+ return NULL;
+ }
+
+ if(!(post = malloc(sizeof(struct post))))
+ err(1, "malloc");
+
+ post->parent = sqlite3_column_int(stmt, 0);
+ post->user = sqlite3_column_int(stmt, 1);
+ post->created = sqlite3_column_int(stmt, 2);
+ post->edited = sqlite3_column_int(stmt, 3);
+ post->subject = strdup((char *)sqlite3_column_text(stmt, 4));
+ post->text = strdup((char *)sqlite3_column_text(stmt, 5));
+
+ sqlite3_finalize(stmt);
+ return post;
+}
+
struct user *
getuser(int id)
{
sqlite3_stmt *stmt;
struct user *user;
-
- if(sqlite3_prepare(db,
- "SELECT name, hash FROM users WHERE oid = ?",
- -1, &stmt, 0) != SQLITE_OK)
- goto null;
- if(sqlite3_bind_int(stmt, 1, id) != SQLITE_OK)
- goto null;
-
- if(sqlite3_step(stmt) != SQLITE_ROW)
- goto null;
+ if(!(stmt = byid(id, "SELECT name, full, hash FROM users WHERE oid = ?"))){
+ sqlite3_finalize(stmt);
+ return NULL;
+ }
if(!(user = malloc(sizeof(struct user))))
err(1, "malloc");
user->id = id;
- user->name = sqlite3_column_text(stmt, 0);
- user->hash = sqlite3_column_text(stmt, 1);
+ user->name = strdup((char *)sqlite3_column_text(stmt, 0));
+ user->full = strdup((char *)sqlite3_column_text(stmt, 1));
+ user->hash = strdup((char *)sqlite3_column_text(stmt, 2));
sqlite3_finalize(stmt);
return user;
-
-null:
- sqlite3_finalize(stmt);
- return NULL;
} \ No newline at end of file