Subversion Repositories MLServ

Rev

Rev 7 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 nishi 1
/* $Id: db.c 9 2024-09-25 01:17:09Z nishi $ */
5 nishi 2
 
3
#include "cm_db.h"
4
 
5
#include <sqlite3.h>
6
 
7
#include <stddef.h>
9 nishi 8
#include <stdlib.h>
9
#include <stdio.h>
5 nishi 10
 
9 nishi 11
#include "cm_string.h"
12
 
5 nishi 13
sqlite3* cm_db_init(void) {
14
	int ret;
15
	sqlite3* sql;
16
	ret = sqlite3_open(DB_PATH, &sql);
17
	if(ret != SQLITE_OK) {
18
		return NULL;
19
	}
20
	ret = sqlite3_exec(sql, "create table if not exists lists(name text, description text)", NULL, NULL, NULL);
21
	if(ret != SQLITE_OK) {
22
		sqlite3_close(sql);
23
		return NULL;
24
	}
25
	ret = sqlite3_exec(sql, "create table if not exists users(email text, password text)", NULL, NULL, NULL);
26
	if(ret != SQLITE_OK) {
27
		sqlite3_close(sql);
28
		return NULL;
29
	}
30
	ret = sqlite3_exec(sql, "create table if not exists tokens(list text, email text, token text, expire numeric)", NULL, NULL, NULL);
31
	if(ret != SQLITE_OK) {
32
		sqlite3_close(sql);
33
		return NULL;
34
	}
35
	return sql;
36
}
7 nishi 37
 
9 nishi 38
int list(void* param, int ncol, char** row, char** col) {
39
	char** old = *(char***)param;
40
	int i;
41
	for(i = 0; old[i] != NULL; i++)
42
		;
43
	*(char***)param = malloc(sizeof(*old) * (i + 3));
44
	for(i = 0; old[i] != NULL; i++) {
45
		(*(char***)param)[i] = old[i];
46
	}
47
	(*(char***)param)[i] = cm_strdup(row[0]);
48
	(*(char***)param)[i + 1] = cm_strdup(row[1]);
49
	(*(char***)param)[i + 2] = NULL;
50
	free(old);
51
	return 0;
52
}
53
 
54
char** cm_list_ml(sqlite3* sql) {
55
	char** listvar = malloc(sizeof(*list));
56
	listvar[0] = NULL;
57
	int ret = sqlite3_exec(sql, "select * from lists", list, &listvar, NULL);
58
	if(ret != SQLITE_OK) {
59
		int i;
60
		for(i = 0; listvar[i] != NULL; i++) free(listvar[i]);
61
		free(listvar);
62
	}
63
	return listvar;
64
}