Commit 94eae3c4 authored by Hugo Beauzée-Luyssen's avatar Hugo Beauzée-Luyssen

sqlite: Add a type to handle foreign keys.

This is more convenient to set a FK to null when it's unset, rather than
having to write 2 different insert statements
parent cb788e87
......@@ -53,17 +53,8 @@ FilePtr File::create( DBConnection dbConnection, const std::string& mrl, unsigne
static const std::string req = "INSERT INTO " + policy::FileTable::Name +
"(mrl, folder_id) VALUES(?, ?)";
//FIXME: Consider having a ForeignKey type that will handle the '0' special case
if ( folderId != 0 )
{
if ( _Cache::insert( dbConnection, self, req, mrl, folderId ) == false )
return nullptr;
}
else
{
if ( _Cache::insert( dbConnection, self, req, mrl, nullptr ) == false )
return nullptr;
}
if ( _Cache::insert( dbConnection, self, req, mrl, sqlite::ForeignKey( folderId ) ) == false )
return nullptr;
self->m_dbConnection = dbConnection;
return self;
}
......
......@@ -53,16 +53,8 @@ FolderPtr Folder::create(DBConnection connection, const std::string& path, unsig
auto self = std::make_shared<Folder>( path, parent );
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, id_parent) VALUES(?, ?)";
if ( parent == 0 )
{
if ( _Cache::insert( connection, self, req, path, nullptr ) == false )
return nullptr;
}
else
{
if ( _Cache::insert( connection, self, req, path, parent ) == false )
return nullptr;
}
if ( _Cache::insert( connection, self, req, path, sqlite::ForeignKey( parent ) ) == false )
return nullptr;
self->m_dbConection = connection;
return self;
}
......
......@@ -14,6 +14,12 @@
namespace sqlite
{
struct ForeignKey
{
constexpr ForeignKey(unsigned int v) : value(v) {}
unsigned int value;
};
template <typename T, typename Enable = void>
struct Traits;
......@@ -27,6 +33,17 @@ struct Traits<T, typename std::enable_if<std::is_integral<T>::value>::type>
int (*Load)(sqlite3_stmt *, int) = &sqlite3_column_int;
};
template <>
struct Traits<ForeignKey>
{
static int Bind( sqlite3_stmt *stmt, int pos, ForeignKey fk)
{
if ( fk.value != 0 )
return Traits<unsigned int>::Bind( stmt, pos, fk.value );
return sqlite3_bind_null( stmt, pos );
}
};
template <>
struct Traits<std::string>
{
......
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