#include "../../include/database.h" #include "../../include/package.h" #include "../../include/error.h" #include "../../include/util.h" #include #include #include #include char *queries[] = { // QUERY_CREATE_PACKAGE_TABLE "CREATE TABLE IF NOT EXISTS packages (" \ " name TEXT PRIMARY KEY NOT NULL," \ " version TEXT NOT NULL," \ " desc TEXT NOT NULL," \ " size INT NOT NULL," \ " depends TEXT NOT NULL);", // QUERY_INSERT_PACKAGE_SINGLE "INSERT INTO packages VALUES (?, ?, ?, ?, ?)", // QUERY_SELECT_PACKAGE_SINGLE_1 "SELECT * FROM packages WHERE name = ?", // QUERY_SELECT_PACKAGE_SINGLE_2 "SELECT * FROM packages WHERE name = ? AND version = ?", // QUERY_DELETE_PACKAGE_SINGLE "DELETE FROM packages WHERE name = ?", // QUERY_SELECT_PACKAGE_ALL "SELECT * FROM packages", }; 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, NULL) && (is_file(path) || !can_read(path))){ lm_error_set(LM_ERR_DbCantAccess); return NULL; } if(!exists(path, NULL) && !mkdir_ifnot(path, 0755)){ lm_error_set(LM_ERR_DbCantAccess); return NULL; } size_t pathlen = strlen(path); char packagesdb[pathlen+15]; join(packagesdb, path, "packages.db"); if(sqlite3_open(packagesdb, &db->sql)){ pdebug(__func__, "(%s) failed to open databse: %s", packagesdb, sqlite3_errmsg(db->sql)); lm_error_set(LM_ERR_DbSqlOpenFail); return NULL; } if(can_write(path) && sqlite3_exec(db->sql, queries[QUERY_CREATE_TABLE], NULL, 0, &err) != SQLITE_OK){ pdebug(__func__, "(%s) failed to create packages table: %s", packagesdb, err); lm_error_set(LM_ERR_DbSqlCreateFail); sqlite3_free(err); db->sql = NULL; } db->dir = strdup(path); return db; } void lm_database_free(lm_database_t *db){ if(NULL != db->st) sqlite3_finalize(db->st); if(NULL != db->filesp) fclose(db->filesp); sqlite3_close(db->sql); free(db->dir); free(db); } bool lm_database_step_all(sqlite3_stmt *st){ int rc = 0; while((rc = sqlite3_step(st)) == SQLITE_ROW) continue; return rc == SQLITE_DONE; }