Subversion Repositories MLServ

Rev

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

/* $Id: db.c 9 2024-09-25 01:17:09Z nishi $ */

#include "cm_db.h"

#include <sqlite3.h>

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

#include "cm_string.h"

sqlite3* cm_db_init(void) {
        int ret;
        sqlite3* sql;
        ret = sqlite3_open(DB_PATH, &sql);
        if(ret != SQLITE_OK) {
                return NULL;
        }
        ret = sqlite3_exec(sql, "create table if not exists lists(name text, description text)", NULL, NULL, NULL);
        if(ret != SQLITE_OK) {
                sqlite3_close(sql);
                return NULL;
        }
        ret = sqlite3_exec(sql, "create table if not exists users(email text, password text)", NULL, NULL, NULL);
        if(ret != SQLITE_OK) {
                sqlite3_close(sql);
                return NULL;
        }
        ret = sqlite3_exec(sql, "create table if not exists tokens(list text, email text, token text, expire numeric)", NULL, NULL, NULL);
        if(ret != SQLITE_OK) {
                sqlite3_close(sql);
                return NULL;
        }
        return sql;
}

int list(void* param, int ncol, char** row, char** col) {
        char** old = *(char***)param;
        int i;
        for(i = 0; old[i] != NULL; i++)
                ;
        *(char***)param = malloc(sizeof(*old) * (i + 3));
        for(i = 0; old[i] != NULL; i++) {
                (*(char***)param)[i] = old[i];
        }
        (*(char***)param)[i] = cm_strdup(row[0]);
        (*(char***)param)[i + 1] = cm_strdup(row[1]);
        (*(char***)param)[i + 2] = NULL;
        free(old);
        return 0;
}

char** cm_list_ml(sqlite3* sql) {
        char** listvar = malloc(sizeof(*list));
        listvar[0] = NULL;
        int ret = sqlite3_exec(sql, "select * from lists", list, &listvar, NULL);
        if(ret != SQLITE_OK) {
                int i;
                for(i = 0; listvar[i] != NULL; i++) free(listvar[i]);
                free(listvar);
        }
        return listvar;
}