From 0cba188f819e7a63a601bcfe32bec4584988886c Mon Sep 17 00:00:00 2001 From: Piotr Sarna Date: Fri, 13 Oct 2023 10:48:50 +0200 Subject: [PATCH] libsql: attach databases from other namespaces as readonly With this proof-of-concept patch, other namespaces hosted on the same sqld machine are now attached in readonly mode, so that users can read from other databases when connected to a particular one. --- sqld/src/connection/libsql.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/sqld/src/connection/libsql.rs b/sqld/src/connection/libsql.rs index 25dd4a6b..9c1e2629 100644 --- a/sqld/src/connection/libsql.rs +++ b/sqld/src/connection/libsql.rs @@ -212,6 +212,26 @@ where )?; conn.conn .pragma_update(None, "max_page_count", max_db_size)?; + let dbs_path = path + .as_ref() + .parent() + .unwrap_or_else(|| std::path::Path::new("..")) + .canonicalize() + .unwrap_or_else(|_| std::path::PathBuf::from("..")); + for entry in (std::fs::read_dir(&dbs_path)?).flatten() { + if let Some(namespace) = entry.file_name().to_str() { + let db_path = entry.path().join("data"); + let query = format!( + "ATTACH DATABASE 'file:{}?mode=ro' AS \"{namespace}\"", + db_path.display() + ); + if let Err(e) = conn.conn.execute(&query, ()) { + tracing::warn!("Failed to attach database {}: {}", db_path.display(), e); + } else { + tracing::debug!("Attached {} as {namespace}", db_path.display()); + } + } + } Ok(conn) }) .await