use anyhow::{Context, Result};
use rusqlite::OptionalExtension;
use std::path::Path;
use std::sync::Once;
static REGISTER_VEC: Once = Once::new();
#[allow(clippy::missing_transmute_annotations)]
pub fn register_sqlite_vec() {
REGISTER_VEC.call_once(|| unsafe {
rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
sqlite_vec::sqlite3_vec_init as *const (),
)));
});
}
#[cfg(unix)]
fn restrict_to_owner(path: &Path) -> Result<()> {
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
{
Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => {
return Err(err).with_context(|| format!("creating {}", path.display()));
}
_ => {}
}
for suffix in ["", "-wal", "-shm"] {
let mut file = path.as_os_str().to_os_string();
file.push(suffix);
let file = Path::new(&file);
let Ok(meta) = std::fs::symlink_metadata(file) else {
continue;
};
let mode = meta.permissions().mode();
if !meta.is_file() || mode & 0o077 == 0 {
continue;
}
let owner_only = std::fs::Permissions::from_mode(mode & 0o700);
if let Err(err) = std::fs::set_permissions(file, owner_only) {
tracing::warn!("could not make {} owner-only: {err}", file.display());
}
}
Ok(())
}
pub struct Connection {
conn: rusqlite::Connection,
}
impl Connection {
pub fn open(path: &Path) -> Result<Self> {
register_sqlite_vec();
let existed = path.exists();
if let Some(parent) = path.parent() {
crate::core::paths::create_private_dir(parent)
.with_context(|| format!("creating db directory {}", parent.display()))?;
}
#[cfg(unix)]
restrict_to_owner(path)?;
let conn = rusqlite::Connection::open(path)
.with_context(|| format!("opening {}", path.display()))?;
if !existed {
let quick_check: String = conn.query_row("PRAGMA quick_check", [], |row| row.get(0))?;
if quick_check != "ok" {
anyhow::bail!("database quick_check failed: {quick_check}");
}
}
Self::finish(conn, !existed) }
pub fn open_or_create(path: &Path) -> Result<Self> {
Self::open(path)
}
pub fn open_in_memory() -> Result<Self> {
register_sqlite_vec();
let conn = rusqlite::Connection::open_in_memory()?;
Self::finish(conn, false) }
fn finish(conn: rusqlite::Connection, allow_page_size: bool) -> Result<Self> {
conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA mmap_size = 268435456;
PRAGMA wal_autocheckpoint = 1000;",
)?;
if allow_page_size {
conn.execute_batch("PRAGMA page_size = 8192;")?;
}
Ok(Self { conn })
}
pub fn inner(&self) -> &rusqlite::Connection {
&self.conn
}
pub fn inner_mut(&mut self) -> &mut rusqlite::Connection {
&mut self.conn
}
pub fn execute_batch(&self, sql: &str) -> Result<()> {
self.conn.execute_batch(sql)?;
Ok(())
}
pub fn query_i64(&self, sql: &str) -> Result<i64> {
Ok(self.conn.query_row(sql, [], |row| row.get(0))?)
}
pub fn query_row<T, P: rusqlite::Params>(
&self,
sql: &str,
params: P,
f: impl FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
) -> Result<T> {
Ok(self.conn.query_row(sql, params, f)?)
}
pub fn stored_embedding_model(&self) -> Result<Option<String>> {
let model: Option<String> = self
.conn
.query_row(
"SELECT value FROM index_meta WHERE key = 'embedding_model'",
[],
|row| row.get(0),
)
.optional()?;
Ok(model)
}
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
#[test]
fn a_file_that_cannot_be_chmodded_does_not_block_opening() {
super::restrict_to_owner(std::path::Path::new("/proc/self/stat")).unwrap();
}
}