use std::cell::Cell;
use rusqlite::Connection;
use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
use crate::{Error, Result};
macro_rules! own {
($sql:literal) => {
concat!("/* tinystore */ ", $sql)
};
}
pub(super) use own;
pub(super) const OWN: &str = own!("");
const READS: [&str; 10] = [
"table_info",
"table_xinfo",
"table_list",
"index_list",
"index_info",
"index_xinfo",
"foreign_key_list",
"foreign_key_check",
"integrity_check",
"quick_check",
];
const ATTACHES: &str = "a statement attaches no file: its connection is shared, and the file would stay on it";
const ENDS: &str = "a statement neither begins nor ends a transaction: the one it runs in is shared with other writes";
const SETS: &str = "a statement sets no pragma: its connection is shared, and the setting would stay on it";
const UNNAMED: &str = "a statement does what SQLite gives no name to, as an attach of a file that is not a literal";
const AS_OWN: &str = "a statement starts with no `/* tinystore */`, which the store's own statements do";
thread_local! {
static GIVEN: Cell<bool> = const { Cell::new(false) };
static REFUSED: Cell<Option<&'static str>> = const { Cell::new(None) };
}
pub(super) fn guard(connection: &Connection) -> rusqlite::Result<()> {
connection.authorizer(Some(authorize))
}
pub(crate) fn given<T>(text: &str, work: impl FnOnce() -> Result<T>) -> Result<T> {
if text.trim_start().starts_with(OWN) {
return Err(Error::invalid(AS_OWN));
}
let _running = Running::enter();
let done = work();
match REFUSED.take() {
Some(why) if done.is_err() => Err(Error::invalid(why)),
_ => done,
}
}
fn authorize(context: AuthContext<'_>) -> Authorization {
if !GIVEN.get() {
return Authorization::Allow;
}
let Some(why) = refused(&context.action) else {
return Authorization::Allow;
};
REFUSED.set(Some(why));
Authorization::Deny
}
fn refused(action: &AuthAction<'_>) -> Option<&'static str> {
match action {
AuthAction::Attach { .. } | AuthAction::Detach { .. } => Some(ATTACHES),
AuthAction::Transaction { .. } | AuthAction::Savepoint { .. } => Some(ENDS),
AuthAction::Pragma { pragma_name, pragma_value } => {
let reads = pragma_value.is_none() || READS.iter().any(|read| pragma_name.eq_ignore_ascii_case(read));
(!reads).then_some(SETS)
}
AuthAction::Unknown { .. } => Some(UNNAMED),
_ => None,
}
}
struct Running {
before: bool,
}
impl Running {
fn enter() -> Running {
REFUSED.set(None);
Running { before: GIVEN.replace(true) }
}
}
impl Drop for Running {
fn drop(&mut self) {
GIVEN.set(self.before);
}
}