aboutsummaryrefslogtreecommitdiff
path: root/db.c
blob: c6ddab20645348bd8fbc70a5d5d303640c057941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#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;
}

char *
textdup(const unsigned char *s)
{
	return s? strdup((char *)s): NULL;
}

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 = textdup(sqlite3_column_text(stmt, 4));
	post->text = textdup(sqlite3_column_text(stmt, 5));
	
	sqlite3_finalize(stmt);
	return post;
}

struct user *
getuser(int id)
{
	sqlite3_stmt *stmt;
	struct user *user;
	
	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 = textdup(sqlite3_column_text(stmt, 0));
	user->full = textdup(sqlite3_column_text(stmt, 1));
	user->hash = textdup(sqlite3_column_text(stmt, 2));
	
	sqlite3_finalize(stmt);
	return user;
}