use from- and to-sql traits

This commit is contained in:
Simon Laux
2020-02-08 12:54:26 +01:00
parent 6d80b3675a
commit e04d28c885

View File

@@ -444,7 +444,7 @@ impl Chat {
archived: row.get(4)?, archived: row.get(4)?,
blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(), blocked: row.get::<_, Option<_>>(5)?.unwrap_or_default(),
is_sending_locations: row.get(6)?, is_sending_locations: row.get(6)?,
mute_duration: MuteDuration::deserialize(row.get(7)?), mute_duration: row.get(7)?,
}; };
Ok(c) Ok(c)
}, },
@@ -1924,28 +1924,37 @@ pub enum MuteDuration {
MutedUntilTimestamp(i64), MutedUntilTimestamp(i64),
} }
impl MuteDuration { impl rusqlite::types::ToSql for MuteDuration {
// TODO use serde compatible functions? fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput> {
pub fn serialize(&self) -> i64 { let duration = match &self {
match &self {
MuteDuration::NotMuted => 0, MuteDuration::NotMuted => 0,
MuteDuration::Forever => -1, MuteDuration::Forever => -1,
MuteDuration::MutedUntilTimestamp(timestamp) => *timestamp as i64, // TODO make this pretier? MuteDuration::MutedUntilTimestamp(timestamp) => *timestamp as i64,
};
let val = rusqlite::types::Value::Integer(duration as i64);
let out = rusqlite::types::ToSqlOutput::Owned(val);
Ok(out)
} }
} }
pub fn deserialize(value: i64) -> MuteDuration { impl rusqlite::types::FromSql for MuteDuration {
match value { fn column_result(value: rusqlite::types::ValueRef) -> rusqlite::types::FromSqlResult<Self> {
// Would be nice if we could use match here, but alas.
i64::column_result(value).and_then(|val| {
Ok({
match val {
0 => MuteDuration::NotMuted, 0 => MuteDuration::NotMuted,
-1 => MuteDuration::Forever, -1 => MuteDuration::Forever,
_ => { _ => {
if value <= time() { if val <= time() {
MuteDuration::NotMuted MuteDuration::NotMuted
} else { } else {
MuteDuration::MutedUntilTimestamp(value) MuteDuration::MutedUntilTimestamp(val)
} }
} }
} }
})
})
} }
} }
@@ -1956,7 +1965,7 @@ pub fn set_muted(context: &Context, chat_id: ChatId, duration: MuteDuration) ->
context, context,
&context.sql, &context.sql,
"UPDATE chats SET muted_until=? WHERE id=?;", "UPDATE chats SET muted_until=? WHERE id=?;",
params![duration.serialize(), chat_id], params![duration, chat_id],
) )
.is_ok() .is_ok()
{ {