use std::{
path::{Path, PathBuf},
sync::atomic::{AtomicBool, Ordering},
};
use rusqlite::Connection;
use super::{ConnectionSpec, Result, SQLiteError};
#[cfg(unix)]
mod platform {
use std::{os::unix::fs::MetadataExt, path::Path};
pub(super) type Identity = (u64, u64);
pub(super) fn path_identity(path: &Path) -> std::io::Result<Identity> {
let metadata = path.metadata()?;
Ok((metadata.dev(), metadata.ino()))
}
}
#[cfg(windows)]
mod platform {
use std::{fs::File, mem::MaybeUninit, os::windows::io::AsRawHandle, path::Path};
use windows_sys::Win32::Storage::FileSystem::{
FileIdInfo, GetFileInformationByHandleEx, FILE_ID_INFO,
};
pub(super) type Identity = (u64, [u8; 16]);
#[allow(unsafe_code)] fn identity(file: &File) -> std::io::Result<Identity> {
let mut information = MaybeUninit::<FILE_ID_INFO>::uninit();
let success = unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileIdInfo,
information.as_mut_ptr().cast(),
std::mem::size_of::<FILE_ID_INFO>() as u32,
)
};
if success == 0 {
return Err(std::io::Error::last_os_error());
}
let information = unsafe { information.assume_init() };
Ok((
information.VolumeSerialNumber,
information.FileId.Identifier,
))
}
pub(super) fn path_identity(path: &Path) -> std::io::Result<Identity> {
identity(&File::open(path)?)
}
}
#[cfg(not(any(unix, windows)))]
mod platform {
use std::path::Path;
pub(super) type Identity = ();
pub(super) fn path_identity(_path: &Path) -> std::io::Result<Identity> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"retained SQLite file identity is unavailable on this target",
))
}
}
pub(super) struct DatabaseSource {
path: PathBuf,
identity: platform::Identity,
changed: AtomicBool,
}
impl DatabaseSource {
pub(super) fn capture(spec: &mut ConnectionSpec, initial: &Connection) -> Result<Option<Self>> {
let path = match spec {
ConnectionSpec::File { path, .. } | ConnectionSpec::Auxiliary { path, .. }
if !path.as_os_str().is_empty() && path != Path::new(":memory:") =>
{
path
}
_ => return Ok(None),
};
*path = path.canonicalize()?;
let source = Self {
path: path.clone(),
identity: platform::path_identity(path)?,
changed: AtomicBool::new(false),
};
source.check_connection(initial)?;
Ok(Some(source))
}
fn invalidate<T>(&self) -> Result<T> {
self.changed.store(true, Ordering::Release);
Err(SQLiteError::DatabaseSourceChanged)
}
pub(super) fn check(&self) -> Result<()> {
if self.changed.load(Ordering::Acquire) {
return Err(SQLiteError::DatabaseSourceChanged);
}
match platform::path_identity(&self.path) {
Ok(identity) if identity == self.identity => {
if self.changed.load(Ordering::Acquire) {
return Err(SQLiteError::DatabaseSourceChanged);
}
Ok(())
}
Ok(_) => self.invalidate(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => self.invalidate(),
Err(error) => Err(error.into()),
}
}
#[allow(unsafe_code)] pub(super) fn check_connection(&self, connection: &Connection) -> Result<()> {
self.check()?;
let mut moved: std::ffi::c_int = 0;
let code = unsafe {
rusqlite::ffi::sqlite3_file_control(
connection.handle(),
c"main".as_ptr(),
rusqlite::ffi::SQLITE_FCNTL_HAS_MOVED,
std::ptr::addr_of_mut!(moved).cast(),
)
};
match code {
rusqlite::ffi::SQLITE_OK if moved != 0 => self.invalidate(),
rusqlite::ffi::SQLITE_OK | rusqlite::ffi::SQLITE_NOTFOUND => Ok(()),
_ => Err(rusqlite::Error::SqliteFailure(rusqlite::ffi::Error::new(code), None).into()),
}
}
}