MXS-2544 Add utility class for handling SQLite
Preparation and cleanup for adding more data to handle user roles in PAM authenticator.
This commit is contained in:
@ -15,6 +15,7 @@
|
||||
#include <string>
|
||||
#include <maxscale/authenticator.hh>
|
||||
#include <maxscale/users.h>
|
||||
#include <maxbase/format.hh>
|
||||
|
||||
#include "pam_instance.hh"
|
||||
#include "pam_client_session.hh"
|
||||
@ -32,6 +33,79 @@ const int NUM_FIELDS = 6;
|
||||
const char* SQLITE_OPEN_FAIL = "Failed to open SQLite3 handle for file '%s': '%s'";
|
||||
const char* SQLITE_OPEN_OOM = "Failed to allocate memory for SQLite3 handle for file '%s'.";
|
||||
|
||||
using SSQLite = SQLite::SSQLite;
|
||||
|
||||
SSQLite SQLite::create(const string& filename, int flags, string* error_out)
|
||||
{
|
||||
SSQLite rval;
|
||||
sqlite3* dbhandle = nullptr;
|
||||
const char* zFilename = filename.c_str();
|
||||
int ret = sqlite3_open_v2(zFilename, &dbhandle, flags, NULL);
|
||||
string error_msg;
|
||||
if (ret == SQLITE_OK)
|
||||
{
|
||||
rval.reset(new SQLite(dbhandle));
|
||||
}
|
||||
// Even if the open failed, the handle may exist and an error message can be read.
|
||||
else if (dbhandle)
|
||||
{
|
||||
error_msg = mxb::string_printf(SQLITE_OPEN_FAIL, zFilename, sqlite3_errmsg(dbhandle));
|
||||
sqlite3_close_v2(dbhandle);
|
||||
}
|
||||
else
|
||||
{
|
||||
error_msg = mxb::string_printf(SQLITE_OPEN_OOM, zFilename);
|
||||
}
|
||||
|
||||
if (!error_msg.empty() && error_out)
|
||||
{
|
||||
*error_out = error_msg;
|
||||
}
|
||||
return rval;
|
||||
}
|
||||
|
||||
SQLite::SQLite(sqlite3* handle)
|
||||
: m_dbhandle(handle)
|
||||
{
|
||||
mxb_assert(handle);
|
||||
}
|
||||
|
||||
SQLite::~SQLite()
|
||||
{
|
||||
sqlite3_close_v2(m_dbhandle);
|
||||
}
|
||||
|
||||
bool SQLite::exec(const std::string& sql)
|
||||
{
|
||||
return exec_impl(sql, nullptr, nullptr);
|
||||
}
|
||||
|
||||
bool SQLite::exec_impl(const std::string& sql, CallbackVoid cb, void* cb_data)
|
||||
{
|
||||
char* err = nullptr;
|
||||
bool success = (sqlite3_exec(m_dbhandle, sql.c_str(), cb, cb_data, &err) == SQLITE_OK);
|
||||
if (success)
|
||||
{
|
||||
m_errormsg.clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_errormsg = err;
|
||||
sqlite3_free(err);
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
void SQLite::set_timeout(int ms)
|
||||
{
|
||||
sqlite3_busy_timeout(m_dbhandle, ms);
|
||||
}
|
||||
|
||||
const char* SQLite::error() const
|
||||
{
|
||||
return m_errormsg.c_str();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize PAM authenticator
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user