lib/sqlite, sticker: migrate from class Error to C++ exceptions

This commit is contained in:
Max Kellermann 2016-10-27 07:50:08 +02:00
parent 8d41e9658f
commit 10e32454ef
11 changed files with 255 additions and 306 deletions

View File

@ -380,7 +380,7 @@ endif
if ENABLE_SQLITE if ENABLE_SQLITE
libmpd_a_SOURCES += \ libmpd_a_SOURCES += \
src/command/StickerCommands.cxx src/command/StickerCommands.hxx \ src/command/StickerCommands.cxx src/command/StickerCommands.hxx \
src/lib/sqlite/Domain.cxx src/lib/sqlite/Domain.hxx \ src/lib/sqlite/Error.cxx src/lib/sqlite/Error.hxx \
src/lib/sqlite/Util.hxx \ src/lib/sqlite/Util.hxx \
src/sticker/Match.hxx \ src/sticker/Match.hxx \
src/sticker/StickerDatabase.cxx src/sticker/StickerDatabase.hxx \ src/sticker/StickerDatabase.cxx src/sticker/StickerDatabase.hxx \

View File

@ -22,7 +22,6 @@
#include "Partition.hxx" #include "Partition.hxx"
#include "Idle.hxx" #include "Idle.hxx"
#include "Stats.hxx" #include "Stats.hxx"
#include "util/Error.hxx"
#ifdef ENABLE_DATABASE #ifdef ENABLE_DATABASE
#include "db/DatabaseError.hxx" #include "db/DatabaseError.hxx"
@ -33,6 +32,8 @@
#endif #endif
#endif #endif
#include <stdexcept>
#ifdef ENABLE_DATABASE #ifdef ENABLE_DATABASE
const Database & const Database &
@ -63,8 +64,12 @@ Instance::OnDatabaseSongRemoved(const char *uri)
#ifdef ENABLE_SQLITE #ifdef ENABLE_SQLITE
/* if the song has a sticker, remove it */ /* if the song has a sticker, remove it */
if (sticker_enabled()) if (sticker_enabled()) {
sticker_song_delete(uri, IgnoreError()); try {
sticker_song_delete(uri);
} catch (const std::runtime_error &) {
}
}
#endif #endif
partition->StaleSong(uri); partition->StaleSong(uri);

View File

@ -252,8 +252,7 @@ glue_sticker_init(void)
return; return;
} }
if (!sticker_global_init(std::move(sticker_file), error)) sticker_global_init(std::move(sticker_file));
FatalError(error);
#endif #endif
} }

View File

@ -25,13 +25,11 @@
#include "sticker/SongSticker.hxx" #include "sticker/SongSticker.hxx"
#include "sticker/StickerPrint.hxx" #include "sticker/StickerPrint.hxx"
#include "sticker/StickerDatabase.hxx" #include "sticker/StickerDatabase.hxx"
#include "CommandError.hxx"
#include "client/Client.hxx" #include "client/Client.hxx"
#include "client/Response.hxx" #include "client/Response.hxx"
#include "Partition.hxx" #include "Partition.hxx"
#include "util/Error.hxx"
#include "util/ConstBuffer.hxx"
#include "util/StringAPI.hxx" #include "util/StringAPI.hxx"
#include "util/ScopeExit.hxx"
struct sticker_song_find_data { struct sticker_song_find_data {
Response &r; Response &r;
@ -53,7 +51,6 @@ sticker_song_find_print_cb(const LightSong &song, const char *value,
static CommandResult static CommandResult
handle_sticker_song(Response &r, Partition &partition, Request args) handle_sticker_song(Response &r, Partition &partition, Request args)
{ {
Error error;
const Database &db = partition.GetDatabaseOrThrow(); const Database &db = partition.GetDatabaseOrThrow();
const char *const cmd = args.front(); const char *const cmd = args.front();
@ -61,14 +58,11 @@ handle_sticker_song(Response &r, Partition &partition, Request args)
/* get song song_id key */ /* get song song_id key */
if (args.size == 4 && StringIsEqual(cmd, "get")) { if (args.size == 4 && StringIsEqual(cmd, "get")) {
const LightSong *song = db.GetSong(args[2]); const LightSong *song = db.GetSong(args[2]);
assert(song != nullptr);
AtScopeExit(&db, song) { db.ReturnSong(song); };
const auto value = sticker_song_get_value(*song, args[3], const auto value = sticker_song_get_value(*song, args[3]);
error);
db.ReturnSong(song);
if (value.empty()) { if (value.empty()) {
if (error.IsDefined())
return print_error(r, error);
r.Error(ACK_ERROR_NO_EXIST, "no such sticker"); r.Error(ACK_ERROR_NO_EXIST, "no such sticker");
return CommandResult::ERROR; return CommandResult::ERROR;
} }
@ -80,48 +74,34 @@ handle_sticker_song(Response &r, Partition &partition, Request args)
} else if (args.size == 3 && StringIsEqual(cmd, "list")) { } else if (args.size == 3 && StringIsEqual(cmd, "list")) {
const LightSong *song = db.GetSong(args[2]); const LightSong *song = db.GetSong(args[2]);
assert(song != nullptr); assert(song != nullptr);
AtScopeExit(&db, song) { db.ReturnSong(song); };
Sticker *sticker = sticker_song_get(*song, error); Sticker *sticker = sticker_song_get(*song);
db.ReturnSong(song);
if (sticker) { if (sticker) {
sticker_print(r, *sticker); sticker_print(r, *sticker);
sticker_free(sticker); sticker_free(sticker);
} else if (error.IsDefined()) }
return print_error(r, error);
return CommandResult::OK; return CommandResult::OK;
/* set song song_id id key */ /* set song song_id id key */
} else if (args.size == 5 && StringIsEqual(cmd, "set")) { } else if (args.size == 5 && StringIsEqual(cmd, "set")) {
const LightSong *song = db.GetSong(args[2]); const LightSong *song = db.GetSong(args[2]);
assert(song != nullptr); assert(song != nullptr);
AtScopeExit(&db, song) { db.ReturnSong(song); };
bool ret = sticker_song_set_value(*song, args[3], args[4], sticker_song_set_value(*song, args[3], args[4]);
error);
db.ReturnSong(song);
if (!ret) {
if (error.IsDefined())
return print_error(r, error);
r.Error(ACK_ERROR_SYSTEM,
"failed to set sticker value");
return CommandResult::ERROR;
}
return CommandResult::OK; return CommandResult::OK;
/* delete song song_id [key] */ /* delete song song_id [key] */
} else if ((args.size == 3 || args.size == 4) && } else if ((args.size == 3 || args.size == 4) &&
StringIsEqual(cmd, "delete")) { StringIsEqual(cmd, "delete")) {
const LightSong *song = db.GetSong(args[2]); const LightSong *song = db.GetSong(args[2]);
assert(song != nullptr); assert(song != nullptr);
AtScopeExit(&db, song) { db.ReturnSong(song); };
bool ret = args.size == 3 bool ret = args.size == 3
? sticker_song_delete(*song, error) ? sticker_song_delete(*song)
: sticker_song_delete_value(*song, args[3], error); : sticker_song_delete_value(*song, args[3]);
db.ReturnSong(song);
if (!ret) { if (!ret) {
if (error.IsDefined())
return print_error(r, error);
r.Error(ACK_ERROR_SYSTEM, "no such sticker"); r.Error(ACK_ERROR_SYSTEM, "no such sticker");
return CommandResult::ERROR; return CommandResult::ERROR;
} }
@ -161,17 +141,9 @@ handle_sticker_song(Response &r, Partition &partition, Request args)
args[3], args[3],
}; };
if (!sticker_song_find(db, base_uri, data.name, sticker_song_find(db, base_uri, data.name,
op, value, op, value,
sticker_song_find_print_cb, &data, sticker_song_find_print_cb, &data);
error)) {
if (error.IsDefined())
return print_error(r, error);
r.Error(ACK_ERROR_SYSTEM,
"failed to set search sticker database");
return CommandResult::ERROR;
}
return CommandResult::OK; return CommandResult::OK;
} else { } else {

View File

@ -17,8 +17,18 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/ */
#include "config.h" #include "Error.hxx"
#include "Domain.hxx"
#include "util/Domain.hxx"
const Domain sqlite_domain("sqlite"); #include <sqlite3.h>
static std::string
MakeSqliteErrorMessage(sqlite3 *db, const char *msg)
{
return std::string(msg) + ": " + sqlite3_errmsg(db);
}
SqliteError::SqliteError(sqlite3 *db, int _code, const char *msg)
:std::runtime_error(MakeSqliteErrorMessage(db, msg)), code(_code) {}
SqliteError::SqliteError(sqlite3_stmt *stmt, int _code, const char *msg)
:SqliteError(sqlite3_db_handle(stmt), _code, msg) {}

View File

@ -17,11 +17,24 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/ */
#ifndef MPD_SQLITE_DOMAIN_HXX #ifndef MPD_SQLITE_ERROR_HXX
#define MPD_SQLITE_DOMAIN_HXX #define MPD_SQLITE_ERROR_HXX
class Domain; #include <stdexcept>
extern const Domain sqlite_domain; struct sqlite3;
struct sqlite3_stmt;
class SqliteError final : public std::runtime_error {
int code;
public:
SqliteError(sqlite3 *db, int _code, const char *msg);
SqliteError(sqlite3_stmt *stmt, int _code, const char *msg);
int GetCode() const {
return code;
}
};
#endif #endif

View File

@ -20,77 +20,49 @@
#ifndef MPD_SQLITE_UTIL_HXX #ifndef MPD_SQLITE_UTIL_HXX
#define MPD_SQLITE_UTIL_HXX #define MPD_SQLITE_UTIL_HXX
#include "Domain.hxx" #include "Error.hxx"
#include "util/Error.hxx"
#include <sqlite3.h> #include <sqlite3.h>
#include <assert.h> #include <assert.h>
/**
* Throws #SqliteError on error.
*/
static void static void
SetError(Error &error, sqlite3 *db, int code, const char *msg) Bind(sqlite3_stmt *stmt, unsigned i, const char *value)
{
error.Format(sqlite_domain, code, "%s: %s",
msg, sqlite3_errmsg(db));
}
static void
SetError(Error &error, sqlite3_stmt *stmt, int code, const char *msg)
{
SetError(error, sqlite3_db_handle(stmt), code, msg);
}
static bool
Bind(sqlite3_stmt *stmt, unsigned i, const char *value, Error &error)
{ {
int result = sqlite3_bind_text(stmt, i, value, -1, nullptr); int result = sqlite3_bind_text(stmt, i, value, -1, nullptr);
if (result != SQLITE_OK) { if (result != SQLITE_OK)
SetError(error, stmt, result, "sqlite3_bind_text() failed"); throw SqliteError(stmt, result, "sqlite3_bind_text() failed");
return false;
}
return true;
} }
template<typename... Args> template<typename... Args>
static bool static void
BindAll2(gcc_unused Error &error, gcc_unused sqlite3_stmt *stmt, BindAll2(gcc_unused sqlite3_stmt *stmt, gcc_unused unsigned i)
gcc_unused unsigned i)
{ {
assert(int(i - 1) == sqlite3_bind_parameter_count(stmt)); assert(int(i - 1) == sqlite3_bind_parameter_count(stmt));
return true;
} }
template<typename... Args> template<typename... Args>
static bool static void
BindAll2(Error &error, sqlite3_stmt *stmt, unsigned i, BindAll2(sqlite3_stmt *stmt, unsigned i,
const char *value, Args&&... args) const char *value, Args&&... args)
{ {
return Bind(stmt, i, value, error) && Bind(stmt, i, value);
BindAll2(error, stmt, i + 1, std::forward<Args>(args)...); BindAll2(stmt, i + 1, std::forward<Args>(args)...);
}
template<typename... Args>
static bool
BindAll(Error &error, sqlite3_stmt *stmt, Args&&... args)
{
assert(int(sizeof...(args)) == sqlite3_bind_parameter_count(stmt));
return BindAll2(error, stmt, 1, std::forward<Args>(args)...);
} }
/** /**
* Wrapper for BindAll() that returns the specified sqlite3_stmt* on * Throws #SqliteError on error.
* success and nullptr on error.
*/ */
template<typename... Args> template<typename... Args>
static sqlite3_stmt * static void
BindAllOrNull(Error &error, sqlite3_stmt *stmt, Args&&... args) BindAll(sqlite3_stmt *stmt, Args&&... args)
{ {
return BindAll(error, stmt, std::forward<Args>(args)...) assert(int(sizeof...(args)) == sqlite3_bind_parameter_count(stmt));
? stmt
: nullptr; BindAll2(stmt, 1, std::forward<Args>(args)...);
} }
/** /**
@ -110,16 +82,18 @@ ExecuteBusy(sqlite3_stmt *stmt)
/** /**
* Wrapper for ExecuteBusy() that returns true on SQLITE_ROW. * Wrapper for ExecuteBusy() that returns true on SQLITE_ROW.
*
* Throws #SqliteError on error.
*/ */
static bool static bool
ExecuteRow(sqlite3_stmt *stmt, Error &error) ExecuteRow(sqlite3_stmt *stmt)
{ {
int result = ExecuteBusy(stmt); int result = ExecuteBusy(stmt);
if (result == SQLITE_ROW) if (result == SQLITE_ROW)
return true; return true;
if (result != SQLITE_DONE) if (result != SQLITE_DONE)
SetError(error, stmt, result, "sqlite3_step() failed"); throw SqliteError(stmt, result, "sqlite3_step() failed");
return false; return false;
} }
@ -127,46 +101,46 @@ ExecuteRow(sqlite3_stmt *stmt, Error &error)
/** /**
* Wrapper for ExecuteBusy() that interprets everything other than * Wrapper for ExecuteBusy() that interprets everything other than
* SQLITE_DONE as error. * SQLITE_DONE as error.
*
* Throws #SqliteError on error.
*/ */
static bool static void
ExecuteCommand(sqlite3_stmt *stmt, Error &error) ExecuteCommand(sqlite3_stmt *stmt)
{ {
int result = ExecuteBusy(stmt); int result = ExecuteBusy(stmt);
if (result != SQLITE_DONE) { if (result != SQLITE_DONE)
SetError(error, stmt, result, "sqlite3_step() failed"); throw SqliteError(stmt, result, "sqlite3_step() failed");
return false;
}
return true;
} }
/** /**
* Wrapper for ExecuteCommand() that returns the number of rows * Wrapper for ExecuteCommand() that returns the number of rows
* modified via sqlite3_changes(). Returns -1 on error. * modified via sqlite3_changes().
*
* Throws #SqliteError on error.
*/ */
static inline int static inline unsigned
ExecuteChanges(sqlite3_stmt *stmt, Error &error) ExecuteChanges(sqlite3_stmt *stmt)
{ {
if (!ExecuteCommand(stmt, error)) ExecuteCommand(stmt);
return -1;
return sqlite3_changes(sqlite3_db_handle(stmt)); return sqlite3_changes(sqlite3_db_handle(stmt));
} }
/** /**
* Wrapper for ExecuteChanges() that returns true if at least one row * Wrapper for ExecuteChanges() that returns true if at least one row
* was modified. Returns false if nothing was modified or if an error * was modified. Returns false if nothing was modified.
* occurred. *
* Throws #SqliteError on error.
*/ */
static inline bool static inline bool
ExecuteModified(sqlite3_stmt *stmt, Error &error) ExecuteModified(sqlite3_stmt *stmt)
{ {
return ExecuteChanges(stmt, error) > 0; return ExecuteChanges(stmt) > 0;
} }
template<typename F> template<typename F>
static inline bool static inline void
ExecuteForEach(sqlite3_stmt *stmt, Error &error, F &&f) ExecuteForEach(sqlite3_stmt *stmt, F &&f)
{ {
while (true) { while (true) {
int result = ExecuteBusy(stmt); int result = ExecuteBusy(stmt);
@ -176,11 +150,10 @@ ExecuteForEach(sqlite3_stmt *stmt, Error &error, F &&f)
break; break;
case SQLITE_DONE: case SQLITE_DONE:
return true; return;
default: default:
SetError(error, stmt, result, "sqlite3_step() failed"); throw SqliteError(stmt, result, "sqlite3_step() failed");
return false;
} }
} }
} }

View File

@ -22,8 +22,8 @@
#include "StickerDatabase.hxx" #include "StickerDatabase.hxx"
#include "db/LightSong.hxx" #include "db/LightSong.hxx"
#include "db/Interface.hxx" #include "db/Interface.hxx"
#include "util/Error.hxx"
#include "util/Alloc.hxx" #include "util/Alloc.hxx"
#include "util/ScopeExit.hxx"
#include <stdexcept> #include <stdexcept>
@ -31,46 +31,44 @@
#include <stdlib.h> #include <stdlib.h>
std::string std::string
sticker_song_get_value(const LightSong &song, const char *name, Error &error) sticker_song_get_value(const LightSong &song, const char *name)
{ {
const auto uri = song.GetURI(); const auto uri = song.GetURI();
return sticker_load_value("song", uri.c_str(), name, error); return sticker_load_value("song", uri.c_str(), name);
} }
bool void
sticker_song_set_value(const LightSong &song, sticker_song_set_value(const LightSong &song,
const char *name, const char *value, const char *name, const char *value)
Error &error)
{ {
const auto uri = song.GetURI(); const auto uri = song.GetURI();
return sticker_store_value("song", uri.c_str(), name, value, error); sticker_store_value("song", uri.c_str(), name, value);
} }
bool bool
sticker_song_delete(const char *uri, Error &error) sticker_song_delete(const char *uri)
{ {
return sticker_delete("song", uri, error); return sticker_delete("song", uri);
} }
bool bool
sticker_song_delete(const LightSong &song, Error &error) sticker_song_delete(const LightSong &song)
{ {
return sticker_song_delete(song.GetURI().c_str(), error); return sticker_song_delete(song.GetURI().c_str());
} }
bool bool
sticker_song_delete_value(const LightSong &song, const char *name, sticker_song_delete_value(const LightSong &song, const char *name)
Error &error)
{ {
const auto uri = song.GetURI(); const auto uri = song.GetURI();
return sticker_delete_value("song", uri.c_str(), name, error); return sticker_delete_value("song", uri.c_str(), name);
} }
Sticker * Sticker *
sticker_song_get(const LightSong &song, Error &error) sticker_song_get(const LightSong &song)
{ {
const auto uri = song.GetURI(); const auto uri = song.GetURI();
return sticker_load("song", uri.c_str(), error); return sticker_load("song", uri.c_str());
} }
struct sticker_song_find_data { struct sticker_song_find_data {
@ -102,13 +100,12 @@ sticker_song_find_cb(const char *uri, const char *value, void *user_data)
} }
} }
bool void
sticker_song_find(const Database &db, const char *base_uri, const char *name, sticker_song_find(const Database &db, const char *base_uri, const char *name,
StickerOperator op, const char *value, StickerOperator op, const char *value,
void (*func)(const LightSong &song, const char *value, void (*func)(const LightSong &song, const char *value,
void *user_data), void *user_data),
void *user_data, void *user_data)
Error &error)
{ {
struct sticker_song_find_data data; struct sticker_song_find_data data;
data.db = &db; data.db = &db;
@ -125,12 +122,10 @@ sticker_song_find(const Database &db, const char *base_uri, const char *name,
/* searching in root directory - no trailing slash */ /* searching in root directory - no trailing slash */
allocated = nullptr; allocated = nullptr;
AtScopeExit(allocated) { free(allocated); };
data.base_uri_length = strlen(data.base_uri); data.base_uri_length = strlen(data.base_uri);
bool success = sticker_find("song", data.base_uri, name, op, value, sticker_find("song", data.base_uri, name, op, value,
sticker_song_find_cb, &data, sticker_song_find_cb, &data);
error);
free(allocated);
return success;
} }

View File

@ -28,50 +28,56 @@
struct LightSong; struct LightSong;
struct Sticker; struct Sticker;
class Database; class Database;
class Error;
/** /**
* Returns one value from a song's sticker record. The caller must * Returns one value from a song's sticker record.
* free the return value with g_free(). *
* Throws #SqliteError on error.
*/ */
gcc_pure gcc_pure
std::string std::string
sticker_song_get_value(const LightSong &song, const char *name, Error &error); sticker_song_get_value(const LightSong &song, const char *name);
/** /**
* Sets a sticker value in the specified song. Overwrites existing * Sets a sticker value in the specified song. Overwrites existing
* values. * values.
*
* Throws #SqliteError on error.
*/ */
bool void
sticker_song_set_value(const LightSong &song, sticker_song_set_value(const LightSong &song,
const char *name, const char *value, const char *name, const char *value);
Error &error);
/** /**
* Deletes a sticker from the database. All values are deleted. * Deletes a sticker from the database. All values are deleted.
*
* Throws #SqliteError on error.
*/ */
bool bool
sticker_song_delete(const char *uri, Error &error); sticker_song_delete(const char *uri);
bool bool
sticker_song_delete(const LightSong &song, Error &error); sticker_song_delete(const LightSong &song);
/** /**
* Deletes a sticker value. Does nothing if the sticker did not * Deletes a sticker value. Does nothing if the sticker did not
* exist. * exist.
*
* Throws #SqliteError on error.
*/ */
bool bool
sticker_song_delete_value(const LightSong &song, const char *name, sticker_song_delete_value(const LightSong &song, const char *name);
Error &error);
/** /**
* Loads the sticker for the specified song. * Loads the sticker for the specified song.
* *
* Throws #SqliteError on error.
*
* @param song the song object * @param song the song object
* @return a sticker object, or NULL on error or if there is no sticker * @return a sticker object, or nullptr if there is no sticker
*/ */
Sticker * Sticker *
sticker_song_get(const LightSong &song, Error &error); sticker_song_get(const LightSong &song);
/** /**
* Finds stickers with the specified name below the specified * Finds stickers with the specified name below the specified
@ -79,17 +85,16 @@ sticker_song_get(const LightSong &song, Error &error);
* *
* Caller must lock the #db_mutex. * Caller must lock the #db_mutex.
* *
* Throws #SqliteError on error.
*
* @param base_uri the base directory to search in * @param base_uri the base directory to search in
* @param name the name of the sticker * @param name the name of the sticker
* @return true on success (even if no sticker was found), false on
* failure
*/ */
bool void
sticker_song_find(const Database &db, const char *base_uri, const char *name, sticker_song_find(const Database &db, const char *base_uri, const char *name,
StickerOperator op, const char *value, StickerOperator op, const char *value,
void (*func)(const LightSong &song, const char *value, void (*func)(const LightSong &song, const char *value,
void *user_data), void *user_data),
void *user_data, void *user_data);
Error &error);
#endif #endif

View File

@ -19,13 +19,12 @@
#include "config.h" #include "config.h"
#include "StickerDatabase.hxx" #include "StickerDatabase.hxx"
#include "lib/sqlite/Domain.hxx"
#include "lib/sqlite/Util.hxx" #include "lib/sqlite/Util.hxx"
#include "fs/Path.hxx" #include "fs/Path.hxx"
#include "Idle.hxx" #include "Idle.hxx"
#include "util/Error.hxx"
#include "util/Macros.hxx" #include "util/Macros.hxx"
#include "util/StringCompare.hxx" #include "util/StringCompare.hxx"
#include "util/ScopeExit.hxx"
#include <string> #include <string>
#include <map> #include <map>
@ -90,22 +89,19 @@ static sqlite3 *sticker_db;
static sqlite3_stmt *sticker_stmt[ARRAY_SIZE(sticker_sql)]; static sqlite3_stmt *sticker_stmt[ARRAY_SIZE(sticker_sql)];
static sqlite3_stmt * static sqlite3_stmt *
sticker_prepare(const char *sql, Error &error) sticker_prepare(const char *sql)
{ {
sqlite3_stmt *stmt; sqlite3_stmt *stmt;
int ret = sqlite3_prepare_v2(sticker_db, sql, -1, &stmt, nullptr); int ret = sqlite3_prepare_v2(sticker_db, sql, -1, &stmt, nullptr);
if (ret != SQLITE_OK) { if (ret != SQLITE_OK)
error.Format(sqlite_domain, ret, throw SqliteError(sticker_db, ret,
"sqlite3_prepare_v2() failed: %s", "sqlite3_prepare_v2() failed");
sqlite3_errmsg(sticker_db));
return nullptr;
}
return stmt; return stmt;
} }
bool void
sticker_global_init(Path path, Error &error) sticker_global_init(Path path)
{ {
assert(!path.IsNull()); assert(!path.IsNull());
@ -116,34 +112,26 @@ sticker_global_init(Path path, Error &error)
ret = sqlite3_open(path.c_str(), &sticker_db); ret = sqlite3_open(path.c_str(), &sticker_db);
if (ret != SQLITE_OK) { if (ret != SQLITE_OK) {
const std::string utf8 = path.ToUTF8(); const std::string utf8 = path.ToUTF8();
error.Format(sqlite_domain, ret, throw SqliteError(sticker_db, ret,
"Failed to open sqlite database '%s': %s", ("Failed to open sqlite database '" +
utf8.c_str(), sqlite3_errmsg(sticker_db)); utf8 + "'").c_str());
return false;
} }
/* create the table and index */ /* create the table and index */
ret = sqlite3_exec(sticker_db, sticker_sql_create, ret = sqlite3_exec(sticker_db, sticker_sql_create,
nullptr, nullptr, nullptr); nullptr, nullptr, nullptr);
if (ret != SQLITE_OK) { if (ret != SQLITE_OK)
error.Format(sqlite_domain, ret, throw SqliteError(sticker_db, ret,
"Failed to create sticker table: %s", "Failed to create sticker table");
sqlite3_errmsg(sticker_db));
return false;
}
/* prepare the statements we're going to use */ /* prepare the statements we're going to use */
for (unsigned i = 0; i < ARRAY_SIZE(sticker_sql); ++i) { for (unsigned i = 0; i < ARRAY_SIZE(sticker_sql); ++i) {
assert(sticker_sql[i] != nullptr); assert(sticker_sql[i] != nullptr);
sticker_stmt[i] = sticker_prepare(sticker_sql[i], error); sticker_stmt[i] = sticker_prepare(sticker_sql[i]);
if (sticker_stmt[i] == nullptr)
return false;
} }
return true;
} }
void void
@ -169,8 +157,7 @@ sticker_enabled()
} }
std::string std::string
sticker_load_value(const char *type, const char *uri, const char *name, sticker_load_value(const char *type, const char *uri, const char *name)
Error &error)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_GET]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_GET];
@ -182,23 +169,23 @@ sticker_load_value(const char *type, const char *uri, const char *name,
if (StringIsEmpty(name)) if (StringIsEmpty(name))
return std::string(); return std::string();
if (!BindAll(error, stmt, type, uri, name)) BindAll(stmt, type, uri, name);
return std::string();
AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
};
std::string value; std::string value;
if (ExecuteRow(stmt, error)) if (ExecuteRow(stmt))
value = (const char*)sqlite3_column_text(stmt, 0); value = (const char*)sqlite3_column_text(stmt, 0);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return value; return value;
} }
static bool static void
sticker_list_values(std::map<std::string, std::string> &table, sticker_list_values(std::map<std::string, std::string> &table,
const char *type, const char *uri, const char *type, const char *uri)
Error &error)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_LIST]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_LIST];
@ -206,25 +193,23 @@ sticker_list_values(std::map<std::string, std::string> &table,
assert(uri != nullptr); assert(uri != nullptr);
assert(sticker_enabled()); assert(sticker_enabled());
if (!BindAll(error, stmt, type, uri)) BindAll(stmt, type, uri);
return false;
const bool success = ExecuteForEach(stmt, error, [stmt, &table](){ AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
};
ExecuteForEach(stmt, [stmt, &table](){
const char *name = (const char *)sqlite3_column_text(stmt, 0); const char *name = (const char *)sqlite3_column_text(stmt, 0);
const char *value = (const char *)sqlite3_column_text(stmt, 1); const char *value = (const char *)sqlite3_column_text(stmt, 1);
table.insert(std::make_pair(name, value)); table.insert(std::make_pair(name, value));
}); });
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return success;
} }
static bool static bool
sticker_update_value(const char *type, const char *uri, sticker_update_value(const char *type, const char *uri,
const char *name, const char *value, const char *name, const char *value)
Error &error)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_UPDATE]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_UPDATE];
@ -236,23 +221,23 @@ sticker_update_value(const char *type, const char *uri,
assert(sticker_enabled()); assert(sticker_enabled());
if (!BindAll(error, stmt, value, type, uri, name)) BindAll(stmt, value, type, uri, name);
return false;
bool modified = ExecuteModified(stmt, error); AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
};
sqlite3_reset(stmt); bool modified = ExecuteModified(stmt);
sqlite3_clear_bindings(stmt);
if (modified) if (modified)
idle_add(IDLE_STICKER); idle_add(IDLE_STICKER);
return modified; return modified;
} }
static bool static void
sticker_insert_value(const char *type, const char *uri, sticker_insert_value(const char *type, const char *uri,
const char *name, const char *value, const char *name, const char *value)
Error &error)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_INSERT]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_INSERT];
@ -264,23 +249,20 @@ sticker_insert_value(const char *type, const char *uri,
assert(sticker_enabled()); assert(sticker_enabled());
if (!BindAll(error, stmt, type, uri, name, value)) BindAll(stmt, type, uri, name, value);
return false;
bool success = ExecuteCommand(stmt, error); AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
};
sqlite3_reset(stmt); ExecuteCommand(stmt);
sqlite3_clear_bindings(stmt); idle_add(IDLE_STICKER);
if (success)
idle_add(IDLE_STICKER);
return success;
} }
bool void
sticker_store_value(const char *type, const char *uri, sticker_store_value(const char *type, const char *uri,
const char *name, const char *value, const char *name, const char *value)
Error &error)
{ {
assert(sticker_enabled()); assert(sticker_enabled());
assert(type != nullptr); assert(type != nullptr);
@ -289,14 +271,14 @@ sticker_store_value(const char *type, const char *uri,
assert(value != nullptr); assert(value != nullptr);
if (StringIsEmpty(name)) if (StringIsEmpty(name))
return false; return;
return sticker_update_value(type, uri, name, value, error) || if (!sticker_update_value(type, uri, name, value))
sticker_insert_value(type, uri, name, value, error); sticker_insert_value(type, uri, name, value);
} }
bool bool
sticker_delete(const char *type, const char *uri, Error &error) sticker_delete(const char *type, const char *uri)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_DELETE]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_DELETE];
@ -304,22 +286,21 @@ sticker_delete(const char *type, const char *uri, Error &error)
assert(type != nullptr); assert(type != nullptr);
assert(uri != nullptr); assert(uri != nullptr);
if (!BindAll(error, stmt, type, uri)) BindAll(stmt, type, uri);
return false;
bool modified = ExecuteModified(stmt, error); AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_reset(stmt); sqlite3_clear_bindings(stmt);
sqlite3_clear_bindings(stmt); };
bool modified = ExecuteModified(stmt);
if (modified) if (modified)
idle_add(IDLE_STICKER); idle_add(IDLE_STICKER);
return modified; return modified;
} }
bool bool
sticker_delete_value(const char *type, const char *uri, const char *name, sticker_delete_value(const char *type, const char *uri, const char *name)
Error &error)
{ {
sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_DELETE_VALUE]; sqlite3_stmt *const stmt = sticker_stmt[STICKER_SQL_DELETE_VALUE];
@ -327,14 +308,14 @@ sticker_delete_value(const char *type, const char *uri, const char *name,
assert(type != nullptr); assert(type != nullptr);
assert(uri != nullptr); assert(uri != nullptr);
if (!BindAll(error, stmt, type, uri, name)) BindAll(stmt, type, uri, name);
return false;
bool modified = ExecuteModified(stmt, error); AtScopeExit(stmt) {
sqlite3_reset(stmt);
sqlite3_reset(stmt); sqlite3_clear_bindings(stmt);
sqlite3_clear_bindings(stmt); };
bool modified = ExecuteModified(stmt);
if (modified) if (modified)
idle_add(IDLE_STICKER); idle_add(IDLE_STICKER);
return modified; return modified;
@ -367,12 +348,11 @@ sticker_foreach(const Sticker &sticker,
} }
Sticker * Sticker *
sticker_load(const char *type, const char *uri, Error &error) sticker_load(const char *type, const char *uri)
{ {
Sticker s; Sticker s;
if (!sticker_list_values(s.table, type, uri, error)) sticker_list_values(s.table, type, uri);
return nullptr;
if (s.table.empty()) if (s.table.empty())
/* don't return empty sticker objects */ /* don't return empty sticker objects */
@ -383,8 +363,7 @@ sticker_load(const char *type, const char *uri, Error &error)
static sqlite3_stmt * static sqlite3_stmt *
BindFind(const char *type, const char *base_uri, const char *name, BindFind(const char *type, const char *base_uri, const char *name,
StickerOperator op, const char *value, StickerOperator op, const char *value)
Error &error)
{ {
assert(type != nullptr); assert(type != nullptr);
assert(name != nullptr); assert(name != nullptr);
@ -394,54 +373,50 @@ BindFind(const char *type, const char *base_uri, const char *name,
switch (op) { switch (op) {
case StickerOperator::EXISTS: case StickerOperator::EXISTS:
return BindAllOrNull(error, sticker_stmt[STICKER_SQL_FIND], BindAll(sticker_stmt[STICKER_SQL_FIND], type, base_uri, name);
type, base_uri, name); return sticker_stmt[STICKER_SQL_FIND];
case StickerOperator::EQUALS: case StickerOperator::EQUALS:
return BindAllOrNull(error, BindAll(sticker_stmt[STICKER_SQL_FIND_VALUE],
sticker_stmt[STICKER_SQL_FIND_VALUE], type, base_uri, name, value);
type, base_uri, name, value); return sticker_stmt[STICKER_SQL_FIND_VALUE];
case StickerOperator::LESS_THAN: case StickerOperator::LESS_THAN:
return BindAllOrNull(error, BindAll(sticker_stmt[STICKER_SQL_FIND_LT],
sticker_stmt[STICKER_SQL_FIND_LT], type, base_uri, name, value);
type, base_uri, name, value); return sticker_stmt[STICKER_SQL_FIND_LT];
case StickerOperator::GREATER_THAN: case StickerOperator::GREATER_THAN:
return BindAllOrNull(error, BindAll(sticker_stmt[STICKER_SQL_FIND_GT],
sticker_stmt[STICKER_SQL_FIND_GT], type, base_uri, name, value);
type, base_uri, name, value); return sticker_stmt[STICKER_SQL_FIND_GT];
} }
assert(false); assert(false);
gcc_unreachable(); gcc_unreachable();
} }
bool void
sticker_find(const char *type, const char *base_uri, const char *name, sticker_find(const char *type, const char *base_uri, const char *name,
StickerOperator op, const char *value, StickerOperator op, const char *value,
void (*func)(const char *uri, const char *value, void (*func)(const char *uri, const char *value,
void *user_data), void *user_data),
void *user_data, void *user_data)
Error &error)
{ {
assert(func != nullptr); assert(func != nullptr);
assert(sticker_enabled()); assert(sticker_enabled());
sqlite3_stmt *const stmt = BindFind(type, base_uri, name, op, value, sqlite3_stmt *const stmt = BindFind(type, base_uri, name, op, value);
error); assert(stmt != nullptr);
if (stmt == nullptr)
return false;
const bool success = ExecuteForEach(stmt, error, AtScopeExit(stmt) {
[stmt, func, user_data](){ sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
};
ExecuteForEach(stmt, [stmt, func, user_data](){
func((const char*)sqlite3_column_text(stmt, 0), func((const char*)sqlite3_column_text(stmt, 0),
(const char*)sqlite3_column_text(stmt, 1), (const char*)sqlite3_column_text(stmt, 1),
user_data); user_data);
}); });
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return success;
} }

View File

@ -54,10 +54,10 @@ struct Sticker;
/** /**
* Opens the sticker database. * Opens the sticker database.
* *
* @return true on success, false on error * Throws std::runtime_error on error.
*/ */
bool void
sticker_global_init(Path path, Error &error); sticker_global_init(Path path);
/** /**
* Close the sticker database. * Close the sticker database.
@ -75,35 +75,39 @@ sticker_enabled();
/** /**
* Returns one value from an object's sticker record. Returns an * Returns one value from an object's sticker record. Returns an
* empty string if the value doesn't exist. * empty string if the value doesn't exist.
*
* Throws #SqliteError on error.
*/ */
std::string std::string
sticker_load_value(const char *type, const char *uri, const char *name, sticker_load_value(const char *type, const char *uri, const char *name);
Error &error);
/** /**
* Sets a sticker value in the specified object. Overwrites existing * Sets a sticker value in the specified object. Overwrites existing
* values. * values.
*
* Throws #SqliteError on error.
*/ */
bool void
sticker_store_value(const char *type, const char *uri, sticker_store_value(const char *type, const char *uri,
const char *name, const char *value, const char *name, const char *value);
Error &error);
/** /**
* Deletes a sticker from the database. All sticker values of the * Deletes a sticker from the database. All sticker values of the
* specified object are deleted. * specified object are deleted.
*
* Throws #SqliteError on error.
*/ */
bool bool
sticker_delete(const char *type, const char *uri, sticker_delete(const char *type, const char *uri);
Error &error);
/** /**
* Deletes a sticker value. Fails if no sticker with this name * Deletes a sticker value. Fails if no sticker with this name
* exists. * exists.
*
* Throws #SqliteError on error.
*/ */
bool bool
sticker_delete_value(const char *type, const char *uri, const char *name, sticker_delete_value(const char *type, const char *uri, const char *name);
Error &error);
/** /**
* Frees resources held by the sticker object. * Frees resources held by the sticker object.
@ -140,13 +144,14 @@ sticker_foreach(const Sticker &sticker,
/** /**
* Loads the sticker for the specified resource. * Loads the sticker for the specified resource.
* *
* Throws #SqliteError on error.
*
* @param type the resource type, e.g. "song" * @param type the resource type, e.g. "song"
* @param uri the URI of the resource, e.g. the song path * @param uri the URI of the resource, e.g. the song path
* @return a sticker object, or nullptr on error or if there is no sticker * @return a sticker object, or nullptr if there is no sticker
*/ */
Sticker * Sticker *
sticker_load(const char *type, const char *uri, sticker_load(const char *type, const char *uri);
Error &error);
/** /**
* Finds stickers with the specified name below the specified URI. * Finds stickers with the specified name below the specified URI.
@ -157,15 +162,12 @@ sticker_load(const char *type, const char *uri,
* @param name the name of the sticker * @param name the name of the sticker
* @param op the comparison operator * @param op the comparison operator
* @param value the operand * @param value the operand
* @return true on success (even if no sticker was found), false on
* failure
*/ */
bool void
sticker_find(const char *type, const char *base_uri, const char *name, sticker_find(const char *type, const char *base_uri, const char *name,
StickerOperator op, const char *value, StickerOperator op, const char *value,
void (*func)(const char *uri, const char *value, void (*func)(const char *uri, const char *value,
void *user_data), void *user_data),
void *user_data, void *user_data);
Error &error);
#endif #endif