Subversion Repositories RepoView

Rev

Rev 3 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 nishi 1
/* $Id: sqlite.c 1 2024-08-20 19:18:25Z nishi $ */
2
 
3
#include "rv_db.h"
4
 
5
#include "../../config.h"
6
 
7
#include "rv_util.h"
8
 
9
#include <sqlite3.h>
10
 
11
#include <stdio.h>
12
#include <stdlib.h>
13
#include <stdbool.h>
14
 
15
sqlite3* sql;
16
 
17
void rv_init_db(void){
18
	int ret;
19
	ret = sqlite3_open(DB_ROOT "/db.sqlite3", &sql);
20
	if(ret != SQLITE_OK){
21
		rv_error_http();
22
		printf("SQLite3 database error\n");
23
		exit(1);
24
	}
25
	char* err;
26
	ret = sqlite3_exec(
27
		sql,
28
		"create table if not exists users(user text, password text)",
29
		NULL,
30
		NULL,
31
		&err
32
	);
33
	if(ret != SQLITE_OK){
34
		sqlite3_free(err);
35
		rv_error_http();
36
		printf("SQLite3 database error\n");
37
		exit(1);
38
	}
39
	ret = sqlite3_exec(
40
		sql,
41
		"create table if not exists tokens(user text, token text)",
42
		NULL,
43
		NULL,
44
		&err
45
	);
46
	if(ret != SQLITE_OK){
47
		sqlite3_free(err);
48
		rv_error_http();
49
		printf("SQLite3 database error\n");
50
		exit(1);
51
	}
52
}
53
 
54
void rv_close_db(void){
55
	sqlite3_close(sql);
56
}
57
 
58
int count = 0;
59
 
60
int sqlcount(void* param, int ncol, char** row, char** col){
61
	count = ncol;
62
	fprintf(stderr, "%d\n", ncol);
63
	return 0;
64
}
65
 
66
bool rv_has_user(const char* username){
67
	char* err;
68
	char cbuf[2];
69
	cbuf[1] = 0;
70
	char* query = rv_strdup("select * from users where user = '");
71
	int i;
72
	for(i = 0; username[i] != 0; i++){
73
		if(username[i] == '\''){
74
			cbuf[0] = username[i];
75
			char* tmp = query;
76
			tmp = rv_strcat(tmp, cbuf);
77
			free(tmp);
78
			cbuf[0] = username[i];
79
			tmp = query;
80
			query = rv_strcat(tmp, cbuf);
81
			free(tmp);
82
		}else{
83
			cbuf[0] = username[i];
84
			char* tmp = query;
85
			query = rv_strcat(tmp, cbuf);
86
			free(tmp);
87
		}
88
	}
89
	char* tmp = query;
90
	query = rv_strcat(tmp, "'");
91
	free(tmp);
92
	int ret;
93
	fprintf(stderr, "%s\n", query);
94
	ret = sqlite3_exec(
95
		sql,
96
		query,
97
		sqlcount,
98
		NULL,
99
		&err
100
	);
101
	free(query);
102
	if(ret != SQLITE_OK){
103
		sqlite3_free(err);
104
	}
105
	return count > 0;
106
}