paper/core/index/
connection.rs1use anyhow::{Context, Result};
2use rusqlite::OptionalExtension;
3use std::path::Path;
4use std::sync::Once;
5
6static REGISTER_VEC: Once = Once::new();
7
8#[allow(clippy::missing_transmute_annotations)]
13pub fn register_sqlite_vec() {
14 REGISTER_VEC.call_once(|| unsafe {
15 rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
27 sqlite_vec::sqlite3_vec_init as *const (),
28 )));
29 });
30}
31
32#[cfg(unix)]
37fn restrict_to_owner(path: &Path) -> Result<()> {
38 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
39 match std::fs::OpenOptions::new()
40 .write(true)
41 .create_new(true)
42 .mode(0o600)
43 .open(path)
44 {
45 Err(err) if err.kind() != std::io::ErrorKind::AlreadyExists => {
46 return Err(err).with_context(|| format!("creating {}", path.display()));
47 }
48 _ => {}
49 }
50 for suffix in ["", "-wal", "-shm"] {
51 let mut file = path.as_os_str().to_os_string();
52 file.push(suffix);
53 let file = Path::new(&file);
54 let Ok(meta) = std::fs::symlink_metadata(file) else {
56 continue;
57 };
58 let mode = meta.permissions().mode();
59 if !meta.is_file() || mode & 0o077 == 0 {
60 continue;
61 }
62 let owner_only = std::fs::Permissions::from_mode(mode & 0o700);
63 if let Err(err) = std::fs::set_permissions(file, owner_only) {
64 tracing::warn!("could not make {} owner-only: {err}", file.display());
65 }
66 }
67 Ok(())
68}
69
70pub struct Connection {
73 conn: rusqlite::Connection,
74}
75
76impl Connection {
77 pub fn open(path: &Path) -> Result<Self> {
85 register_sqlite_vec();
86 let existed = path.exists();
87 if let Some(parent) = path.parent() {
88 crate::core::paths::create_private_dir(parent)
89 .with_context(|| format!("creating db directory {}", parent.display()))?;
90 }
91 #[cfg(unix)]
92 restrict_to_owner(path)?;
93 let conn = rusqlite::Connection::open(path)
94 .with_context(|| format!("opening {}", path.display()))?;
95 if !existed {
96 let quick_check: String = conn.query_row("PRAGMA quick_check", [], |row| row.get(0))?;
98 if quick_check != "ok" {
99 anyhow::bail!("database quick_check failed: {quick_check}");
100 }
101 }
102 Self::finish(conn, !existed) }
104
105 pub fn open_or_create(path: &Path) -> Result<Self> {
111 Self::open(path)
112 }
113
114 pub fn open_in_memory() -> Result<Self> {
115 register_sqlite_vec();
116 let conn = rusqlite::Connection::open_in_memory()?;
117 Self::finish(conn, false) }
119
120 fn finish(conn: rusqlite::Connection, allow_page_size: bool) -> Result<Self> {
124 conn.busy_timeout(std::time::Duration::from_secs(5))?;
125 conn.execute_batch(
127 "PRAGMA journal_mode = WAL;
128 PRAGMA synchronous = NORMAL;
129 PRAGMA foreign_keys = ON;
130 PRAGMA mmap_size = 268435456;
131 PRAGMA wal_autocheckpoint = 1000;",
132 )?;
133 if allow_page_size {
134 conn.execute_batch("PRAGMA page_size = 8192;")?;
137 }
138 Ok(Self { conn })
139 }
140
141 pub fn inner(&self) -> &rusqlite::Connection {
142 &self.conn
143 }
144
145 pub fn inner_mut(&mut self) -> &mut rusqlite::Connection {
146 &mut self.conn
147 }
148
149 pub fn execute_batch(&self, sql: &str) -> Result<()> {
150 self.conn.execute_batch(sql)?;
151 Ok(())
152 }
153
154 pub fn query_i64(&self, sql: &str) -> Result<i64> {
156 Ok(self.conn.query_row(sql, [], |row| row.get(0))?)
157 }
158
159 pub fn query_row<T, P: rusqlite::Params>(
160 &self,
161 sql: &str,
162 params: P,
163 f: impl FnOnce(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
164 ) -> Result<T> {
165 Ok(self.conn.query_row(sql, params, f)?)
166 }
167
168 pub fn stored_embedding_model(&self) -> Result<Option<String>> {
170 let model: Option<String> = self
171 .conn
172 .query_row(
173 "SELECT value FROM index_meta WHERE key = 'embedding_model'",
174 [],
175 |row| row.get(0),
176 )
177 .optional()?;
178 Ok(model)
179 }
180}
181
182#[cfg(all(test, target_os = "linux"))]
183mod tests {
184 #[test]
187 fn a_file_that_cannot_be_chmodded_does_not_block_opening() {
188 super::restrict_to_owner(std::path::Path::new("/proc/self/stat")).unwrap();
189 }
190}