diff --git a/srcs/libs/database/database.c b/srcs/libs/database/database.c new file mode 100644 index 0000000..f0e6937 --- /dev/null +++ b/srcs/libs/database/database.c @@ -0,0 +1,63 @@ +// +// Created by xajhuang on 2023/3/29. +// +#ifdef SQLITE_ON +#include +#include +#include "zlog_module.h" +#include "user_errno.h" +#include "config.h" +#include "database.h" + +static sqlite3 *g_pSqlHandle = NULL; + +int db_sqlite3_init() { + int rc; + const char *pDbPath = cfg_get_sqlite_db_name(); + + if (pDbPath == NULL || strlen(pDbPath) == 0) { + return ERR_SUCCESS; + } + + if (g_pSqlHandle == NULL) { + rc = sqlite3_open_v2(pDbPath, &g_pSqlHandle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); + + if (rc != SQLITE_OK) { + LOG_MOD(error, ZLOG_MOD_DB, "Create SQLite3 Database at %s error: %s(%d)\n", pDbPath, sqlite3_errstr(rc), rc); + return -ERR_DB_CONNECT; + } + } + + LOG_MOD(info, ZLOG_MOD_DB, "Used SQLite3 database: %s\n", pDbPath); + + return ERR_SUCCESS; +} + +int db_sqlite3_sql_exec(const char *pSqlCmd, void *pCallback, void *pData, char **pErr) { + + if (pSqlCmd == NULL || strlen(pSqlCmd) == 0) { + LOG_MOD(error, ZLOG_MOD_DB, "Input params pSqlCmd error\n"); + return -ERR_INPUT_PARAMS; + } + + if (g_pSqlHandle) { + int rc = sqlite3_exec(g_pSqlHandle, pSqlCmd, pCallback, pData, pErr); + + if (rc != SQLITE_OK) { + LOG_MOD(error, ZLOG_MOD_DB, "Run {%s} SQL command error:\n%s\n", pSqlCmd, sqlite3_errmsg(g_pSqlHandle)); + return -ERR_DB_SQL_EXEC; + } + + return ERR_SUCCESS; + } else { + LOG_MOD(error, ZLOG_MOD_DB, "SQlite3 database uninit\n"); + return -ERR_DB_UNINIT; + } +} + +void db_sqlite3_uninit() { + if (g_pSqlHandle) { + sqlite3_close(g_pSqlHandle); + } +} +#endif \ No newline at end of file