no-mistakes-postgres-engine 0.109.129

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::{EngineHooks, MetricsObserver};
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};

thread_local! {
    static ACTIVE: RefCell<Vec<Option<Arc<TestObserver>>>> = const { RefCell::new(Vec::new()) };
}

pub(crate) struct TestSnapshot {
    pub(crate) work: BTreeMap<String, u64>,
}

pub(crate) struct TestObserver {
    verbose: bool,
    work: Mutex<BTreeMap<String, u64>>,
}

impl TestObserver {
    pub(crate) fn new(verbose: bool) -> Arc<Self> {
        Arc::new(Self {
            verbose,
            work: Mutex::new(BTreeMap::new()),
        })
    }

    pub(crate) fn snapshot(&self) -> TestSnapshot {
        TestSnapshot {
            work: self.work.lock().expect("test observer lock").clone(),
        }
    }
}

impl MetricsObserver for TestObserver {
    fn increment(&self, metric: &'static str, amount: u64) {
        *self
            .work
            .lock()
            .expect("test observer lock")
            .entry(metric.to_string())
            .or_insert(0) += amount;
    }

    fn verbose(&self) -> bool {
        self.verbose
    }
}

struct TestEngineHooks;

impl EngineHooks for TestEngineHooks {
    fn current_observer(&self) -> Option<Arc<dyn MetricsObserver>> {
        ACTIVE.with(|active| {
            active
                .borrow()
                .last()
                .cloned()
                .flatten()
                .map(|observer| observer as Arc<dyn MetricsObserver>)
        })
    }

    fn has_matching_disable_directive(&self, _source: &str, _line: u32, _rule_id: &str) -> bool {
        false
    }
}

static TEST_HOOKS: TestEngineHooks = TestEngineHooks;

pub(crate) fn with_observer<T>(
    observer: Option<Arc<TestObserver>>,
    operation: impl FnOnce() -> T,
) -> T {
    super::register_hooks(&TEST_HOOKS);
    ACTIVE.with(|active| active.borrow_mut().push(observer));
    struct Guard;
    impl Drop for Guard {
        fn drop(&mut self) {
            ACTIVE.with(|active| {
                active
                    .borrow_mut()
                    .pop()
                    .expect("test observer scope must be active");
            });
        }
    }
    let _guard = Guard;
    operation()
}