Subversion Repositories RepoView

Rev

Rev 1 | Rev 5 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 nishi 1
/* $Id: sqlite.c 3 2024-08-20 21:05:24Z 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
 
3 nishi 17
void rv_init_db(void) {
1 nishi 18
	int ret;
19
	ret = sqlite3_open(DB_ROOT "/db.sqlite3", &sql);
3 nishi 20
	if(ret != SQLITE_OK) {
1 nishi 21
		rv_error_http();
22
		printf("SQLite3 database error\n");
23
		exit(1);
24
	}
25
	char* err;
3 nishi 26
	ret = sqlite3_exec(sql, "create table if not exists users(user text, password text)", NULL, NULL, &err);
27
	if(ret != SQLITE_OK) {
1 nishi 28
		sqlite3_free(err);
29
		rv_error_http();
30
		printf("SQLite3 database error\n");
31
		exit(1);
32
	}
3 nishi 33
	ret = sqlite3_exec(sql, "create table if not exists tokens(user text, token text)", NULL, NULL, &err);
34
	if(ret != SQLITE_OK) {
1 nishi 35
		sqlite3_free(err);
36
		rv_error_http();
37
		printf("SQLite3 database error\n");
38
		exit(1);
39
	}
40
}
41
 
3 nishi 42
void rv_close_db(void) { sqlite3_close(sql); }
1 nishi 43
 
44
int count = 0;
45
 
3 nishi 46
int sqlcount(void* param, int ncol, char** row, char** col) {
1 nishi 47
	count = ncol;
48
	fprintf(stderr, "%d\n", ncol);
49
	return 0;
50
}
51
 
3 nishi 52
bool rv_has_user(const char* username) {
1 nishi 53
	char* err;
54
	char cbuf[2];
55
	cbuf[1] = 0;
56
	char* query = rv_strdup("select * from users where user = '");
57
	int i;
3 nishi 58
	for(i = 0; username[i] != 0; i++) {
59
		if(username[i] == '\'') {
1 nishi 60
			cbuf[0] = username[i];
61
			char* tmp = query;
62
			tmp = rv_strcat(tmp, cbuf);
63
			free(tmp);
64
			cbuf[0] = username[i];
65
			tmp = query;
66
			query = rv_strcat(tmp, cbuf);
67
			free(tmp);
3 nishi 68
		} else {
1 nishi 69
			cbuf[0] = username[i];
70
			char* tmp = query;
71
			query = rv_strcat(tmp, cbuf);
72
			free(tmp);
73
		}
74
	}
75
	char* tmp = query;
76
	query = rv_strcat(tmp, "'");
77
	free(tmp);
78
	int ret;
79
	fprintf(stderr, "%s\n", query);
3 nishi 80
	ret = sqlite3_exec(sql, query, sqlcount, NULL, &err);
1 nishi 81
	free(query);
3 nishi 82
	if(ret != SQLITE_OK) {
1 nishi 83
		sqlite3_free(err);
84
	}
85
	return count > 0;
86
}