use std::collections::HashMap;
#[allow(unused_imports)]
use std::sync::atomic::{AtomicU64, Ordering};
#[allow(unused_imports)]
use std::sync::Arc;
pub use super::operations::SpatialIndexMetadata as ExportedSpatialIndexMetadata;
use super::{lifecycle::Lifecycle, metadata::Metadata, operations::Operations};
use crate::{
change_events::ChangeEventSender, columnar_cache::ColumnarCache, wal::PersistenceEngine,
QueryBufferPool, Table,
};
#[derive(Debug)]
pub struct Database {
pub catalog: vibesql_catalog::Catalog,
pub(super) lifecycle: Lifecycle,
pub(super) metadata: Metadata,
pub(super) operations: Operations,
pub tables: HashMap<String, Table>,
pub(super) sql_mode: vibesql_types::SqlMode,
pub(super) query_buffer_pool: QueryBufferPool,
pub(super) columnar_cache: Arc<ColumnarCache>,
pub(super) change_sender: Option<ChangeEventSender>,
pub(super) last_insert_rowid: i64,
pub(super) last_changes_count: usize,
pub(super) total_changes_count: usize,
pub(super) search_count: AtomicU64,
pub(super) persistence_engine: Option<PersistenceEngine>,
pub(super) next_table_id: u32,
pub(super) reserved_rowids: HashMap<String, (u64, bool)>,
}
impl Database {
pub fn query_buffer_pool(&self) -> &QueryBufferPool {
&self.query_buffer_pool
}
pub fn get_cached_procedure_body(
&mut self,
name: &str,
) -> Result<&vibesql_catalog::ProcedureBody, crate::StorageError> {
if self.metadata.get_cached_procedure_body(name).is_none() {
let procedure = &self.catalog.get_procedure(name).ok_or_else(|| {
crate::StorageError::CatalogError(format!("Procedure '{}' not found", name))
})?;
self.metadata.cache_procedure_body(name.to_string(), procedure.body.clone());
}
Ok(self.metadata.get_cached_procedure_body(name).unwrap())
}
pub fn invalidate_procedure_cache(&mut self, name: &str) {
self.metadata.invalidate_procedure_cache(name);
}
pub fn clear_routine_cache(&mut self) {
self.metadata.clear_routine_cache();
}
#[inline]
pub(super) fn snapshot_operations_for_mutation(&mut self) {
let before = self.lifecycle.transaction_manager().operations_snapshot_clones();
self.lifecycle.transaction_manager_mut().ensure_operations_snapshot(&self.operations);
let after = self.lifecycle.transaction_manager().operations_snapshot_clones();
if after != before {
self.operations.begin_disk_undo_logging();
}
}
}