libmp/src/database/database.c

65 lines
1.6 KiB
C
Raw Normal View History

2024-07-02 01:44:07 +00:00
#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 (?, ?, ?, ?, ?)",
"SELECT * FROM packages WHERE name = '?'",
"DELETE from packages WHERE name = '?'",
2024-07-02 01:44:07 +00:00
};
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) && (is_file(path) || !can_read(path) || !can_write(path))){
2024-07-02 01:44:07 +00:00
lm_error_set(LM_ERR_DbCantAccess);
return NULL;
}
char dbfile[strlen(path)+20];
join(dbfile, path, "packages.db");
2024-07-02 01:44:07 +00:00
if(sqlite3_open(dbfile, &db->sql)){
2024-07-02 01:44:07 +00:00
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->dir = strdup(path);
2024-07-02 01:44:07 +00:00
return db;
}
void lm_database_free(lm_database_t *db){
sqlite3_close(db->sql);
free(db->dir);
2024-07-02 01:44:07 +00:00
lm_pkg_t *cur = db->pkg, *prev = NULL;
while(NULL != cur){
prev = cur;
cur = cur->next;
lm_package_free(prev);
}
free(db);
}