Commit 35d40d9c authored by Hugo Beauzée-Luyssen's avatar Hugo Beauzée-Luyssen
Browse files

Sqlite: Encapsulate constraint violations in their own exceptions

parent 5e9a43a4
......@@ -140,6 +140,26 @@ struct Traits<T, typename std::enable_if<IsSameDecay<T, int64_t>::value>::type>
(*Load)(sqlite3_stmt *, int) = &sqlite3_column_int64;
};
namespace errors
{
class ConstraintViolation : std::exception
{
public:
ConstraintViolation( const std::string& req )
{
m_reason = std::string( "Request <" ) + req + "> aborted due to "
"constraint violation";
}
virtual const char* what() const noexcept override
{
return m_reason.c_str();
}
private:
std::string m_reason;
};
}
class Row
{
public:
......@@ -195,6 +215,7 @@ class Statement
public:
Statement( DBConnection dbConnection, const std::string& req )
: m_stmt( nullptr, &sqlite3_finalize )
, m_req( req )
{
sqlite3_stmt* stmt;
int res = sqlite3_prepare_v2( dbConnection->getConn(), req.c_str(), -1, &stmt, NULL );
......@@ -215,16 +236,24 @@ public:
Row row()
{
auto res = sqlite3_step( m_stmt.get() );
if ( res == SQLITE_ROW )
switch ( res )
{
case SQLITE_ROW:
return Row( m_stmt.get() );
else if ( res == SQLITE_DONE )
case SQLITE_DONE:
return Row();
case SQLITE_CONSTRAINT:
throw errors::ConstraintViolation( m_req );
default:
{
#if SQLITE_VERSION_NUMBER >= 3007015
auto err = sqlite3_errstr( res );
auto err = sqlite3_errstr( res );
#else
auto err = std::to_string( res );
auto err = std::to_string( res );
#endif
throw std::runtime_error( err );
throw std::runtime_error( err );
}
}
}
private:
......@@ -243,6 +272,7 @@ private:
private:
std::unique_ptr<sqlite3_stmt, int (*)(sqlite3_stmt*)> m_stmt;
std::string m_req;
};
class Tools
......
......@@ -83,12 +83,11 @@ TEST_F( Files, Delete )
TEST_F( Files, Duplicate )
{
auto f = ml->addFile( "media.avi", nullptr );
auto f2 = std::static_pointer_cast<Media>( ml->addFile( "media.avi", nullptr ) );
ASSERT_NE( f, nullptr );
ASSERT_EQ( f2, nullptr );
ASSERT_THROW( ml->addFile( "media.avi", nullptr ), sqlite::errors::ConstraintViolation );
f2 = std::static_pointer_cast<Media>( ml->file( "media.avi" ) );
auto f2 = ml->file( "media.avi" );
ASSERT_EQ( f, f2 );
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment