61 lines
1.4 KiB
C
61 lines
1.4 KiB
C
|
#include "../../include/database.h"
|
||
|
#include "../../include/package.h"
|
||
|
#include "../../include/error.h"
|
||
|
#include "../../include/util.h"
|
||
|
|
||
|
#include <sqlite3.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <strings.h>
|
||
|
|
||
|
char *queries[] = {
|
||
|
"CREATE TABLE IF NOT EXISTS packages (" \
|
||
|
" name TEXT PRIMARY KEY NOT NULL," \
|
||
|
" desc TEXT NOT NULL," \
|
||
|
" version TEXT NOT NULL," \
|
||
|
" size INT NOT NULL," \
|
||
|
" depends TEXT NOT NULL);",
|
||
|
|
||
|
"INSERT INTO packages VALUES (?, ?, ?, ?, ?)",
|
||
|
};
|
||
|
|
||
|
lm_database_t *lm_database_new(char *path){
|
||
|
lm_database_t *db = malloc(sizeof(lm_database_t));
|
||
|
char *err = NULL;
|
||
|
bzero(db, sizeof(lm_database_t));
|
||
|
|
||
|
if(exists(path) && !can_read(path)){
|
||
|
lm_error_set(LM_ERR_DbCantAccess);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
if(sqlite3_open(path, &db->sql)){
|
||
|
pdebug(__func__, "(%s) failed to open databse: %s", path, sqlite3_errmsg(db->sql));
|
||
|
lm_error_set(LM_ERR_DbSqlOpenFail);
|
||
|
return NULL;
|
||
|
}
|
||
|
|
||
|
if(sqlite3_exec(db->sql, queries[QUERY_CREATE_TABLE], NULL, 0, &err) != SQLITE_OK){
|
||
|
pdebug(__func__, "(%s) failed to create packages table: %s", path, err);
|
||
|
lm_error_set(LM_ERR_DbSqlCreateFail);
|
||
|
sqlite3_free(err);
|
||
|
}
|
||
|
|
||
|
db->path = strdup(path);
|
||
|
return db;
|
||
|
}
|
||
|
|
||
|
void lm_database_free(lm_database_t *db){
|
||
|
sqlite3_close(db->sql);
|
||
|
free(db->path);
|
||
|
|
||
|
lm_pkg_t *cur = db->pkg, *prev = NULL;
|
||
|
while(NULL != cur){
|
||
|
prev = cur;
|
||
|
cur = cur->next;
|
||
|
lm_package_free(prev);
|
||
|
}
|
||
|
|
||
|
free(db);
|
||
|
}
|