use happenstance_core::ProjectionId;
use rusqlite::{Connection, TransactionBehavior};
use super::{
PROTECTION_SCHEMA_VERSION, SCHEMA_VERSION_KEY, SqliteProjectionStore,
SqliteProjectionStoreError,
};
pub(super) const PROTECTION_TABLE: &str = "\
CREATE TABLE IF NOT EXISTS projection_protection (
projection_id TEXT NOT NULL PRIMARY KEY
) WITHOUT ROWID;";
impl SqliteProjectionStore {
pub async fn protect_from_reset(
&self,
id: &ProjectionId,
) -> Result<(), SqliteProjectionStoreError> {
let id = id.clone();
self.in_blocking_task(move |connection| protect_locked(connection, &id))
.await
}
pub async fn allow_reset(&self, id: &ProjectionId) -> Result<(), SqliteProjectionStoreError> {
let id = id.clone();
self.in_blocking_task(move |connection| {
connection.execute(
"DELETE FROM projection_protection WHERE projection_id = ?",
[id.as_str()],
)?;
Ok(())
})
.await
}
pub async fn is_protected_from_reset(
&self,
id: &ProjectionId,
) -> Result<bool, SqliteProjectionStoreError> {
let id = id.clone();
self.in_blocking_task(move |connection| is_protected(connection, &id))
.await
}
}
pub(super) fn is_protected(
connection: &Connection,
id: &ProjectionId,
) -> Result<bool, SqliteProjectionStoreError> {
Ok(connection.query_row(
"SELECT EXISTS(SELECT 1 FROM projection_protection WHERE projection_id = ?)",
[id.as_str()],
|row| row.get(0),
)?)
}
fn protect_locked(
connection: &mut Connection,
id: &ProjectionId,
) -> Result<(), SqliteProjectionStoreError> {
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
transaction.execute(
"INSERT OR IGNORE INTO projection_protection (projection_id) VALUES (?)",
[id.as_str()],
)?;
transaction.execute(
"UPDATE projection_meta SET v = ?1 WHERE k = ?2 AND v < ?1",
rusqlite::params![PROTECTION_SCHEMA_VERSION, SCHEMA_VERSION_KEY],
)?;
transaction.commit()?;
Ok(())
}