1use libxml::tree::Node;
19use rustc_hash::{FxHashMap as HashMap, FxHashSet};
20
21#[derive(Debug, Clone)]
25pub struct Entry {
26 pub key: String,
28 values: HashMap<String, Value>,
30 push_new_seen: HashMap<String, FxHashSet<String>>,
36}
37
38#[derive(Debug, Clone)]
42pub enum Value {
43 String(String),
45 Int(i64),
47 Bool(bool),
49 List(Vec<Value>),
51 Hash(HashMap<String, Value>),
53 Xml(Node),
55 Null,
57}
58
59impl Value {
60 pub fn as_str(&self) -> Option<&str> {
62 match self {
63 Value::String(s) => Some(s),
64 _ => None,
65 }
66 }
67
68 pub fn as_string(&self) -> String {
70 match self {
71 Value::String(s) => s.clone(),
72 Value::Int(n) => n.to_string(),
73 Value::Bool(b) => b.to_string(),
74 Value::Xml(node) => node.get_content(),
75 Value::Null => String::new(),
76 _ => String::new(),
77 }
78 }
79
80 pub fn is_truthy(&self) -> bool {
82 match self {
83 Value::Null => false,
84 Value::String(s) => !s.is_empty(),
85 Value::Bool(b) => *b,
86 Value::List(v) => !v.is_empty(),
87 Value::Hash(h) => !h.is_empty(),
88 _ => true,
89 }
90 }
91}
92
93impl From<&str> for Value {
94 fn from(s: &str) -> Self { Value::String(s.to_string()) }
95}
96
97impl From<String> for Value {
98 fn from(s: String) -> Self { Value::String(s) }
99}
100
101impl std::fmt::Display for Value {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 match self {
104 Value::String(s) => write!(f, "{}", s),
105 Value::Int(n) => write!(f, "{}", n),
106 Value::Bool(b) => write!(f, "{}", b),
107 Value::Null => Ok(()),
108 Value::Xml(node) => write!(f, "{}", node.get_content()),
109 Value::List(_) | Value::Hash(_) => Ok(()),
110 }
111 }
112}
113
114impl From<bool> for Value {
121 fn from(b: bool) -> Self { Value::Bool(b) }
122}
123
124impl From<Vec<String>> for Value {
125 fn from(v: Vec<String>) -> Self { Value::List(v.into_iter().map(Value::String).collect()) }
126}
127
128impl Entry {
129 pub fn new(key: &str) -> Self {
131 Entry {
132 key: key.to_string(),
133 values: HashMap::default(),
134 push_new_seen: HashMap::default(),
135 }
136 }
137
138 pub fn get_key(&self) -> &str { &self.key }
140
141 pub fn has_value(&self, attr: &str) -> bool { self.values.contains_key(attr) }
143
144 pub fn attributes(&self) -> impl Iterator<Item = &str> { self.values.keys().map(String::as_str) }
146
147 pub fn get_value(&self, attr: &str) -> Option<&Value> { self.values.get(attr) }
149
150 pub fn get_string(&self, attr: &str) -> Option<&str> {
152 self.values.get(attr).and_then(|v| v.as_str())
153 }
154
155 pub fn get_xml(&self, attr: &str) -> Option<&Node> {
157 match self.values.get(attr) {
158 Some(Value::Xml(n)) => Some(n),
159 _ => None,
160 }
161 }
162
163 pub fn get_children(&self) -> Vec<String> {
165 match self.values.get("children") {
166 Some(Value::List(items)) => items
167 .iter()
168 .filter_map(|v| v.as_str().map(String::from))
169 .collect(),
170 _ => vec![],
171 }
172 }
173
174 pub fn set_values(&mut self, pairs: Vec<(&str, Value)>) {
178 for (key, value) in pairs {
179 self.push_new_seen.remove(key);
180 match value {
181 Value::Null => {
182 self.values.remove(key);
183 },
184 _ => {
185 self.values.insert(key.to_string(), value);
186 },
187 }
188 }
189 }
190
191 pub fn set_value(&mut self, attr: &str, value: Value) {
193 self.push_new_seen.remove(attr);
194 match value {
195 Value::Null => {
196 self.values.remove(attr);
197 },
198 _ => {
199 self.values.insert(attr.to_string(), value);
200 },
201 }
202 }
203
204 pub fn push_values(&mut self, attr: &str, values: Vec<Value>) {
208 self.push_new_seen.remove(attr);
209 let list = self
210 .values
211 .entry(attr.to_string())
212 .or_insert_with(|| Value::List(Vec::new()));
213 if let Value::List(items) = list {
214 for v in values {
215 items.push(v);
216 }
217 }
218 }
219
220 pub fn push_new(&mut self, attr: &str, values: Vec<Value>) {
224 let list = self
225 .values
226 .entry(attr.to_string())
227 .or_insert_with(|| Value::List(Vec::new()));
228 if let Value::List(items) = list {
229 let seen = self
230 .push_new_seen
231 .entry(attr.to_string())
232 .or_insert_with(|| items.iter().map(Value::to_string).collect());
233 for v in values {
234 if seen.insert(v.to_string()) {
235 items.push(v);
236 }
237 }
238 }
239 }
240
241 pub fn note_association(&mut self, keys: &[&str]) {
246 if keys.is_empty() {
247 return;
248 }
249 self.push_new_seen.remove(keys[0]);
250 if keys.len() == 1 {
251 self.values.insert(keys[0].to_string(), Value::Bool(true));
252 return;
253 }
254
255 let first = keys[0];
257 let rest = &keys[1..];
258
259 let hash = self
260 .values
261 .entry(first.to_string())
262 .or_insert_with(|| Value::Hash(HashMap::default()));
263
264 if let Value::Hash(h) = hash {
265 let mut current = h;
266 for (i, &key) in rest.iter().enumerate() {
267 if i == rest.len() - 1 {
268 current.insert(key.to_string(), Value::Bool(true));
270 } else {
271 let entry = current
273 .entry(key.to_string())
274 .or_insert_with(|| Value::Hash(HashMap::default()));
275 if let Value::Hash(inner) = entry {
276 current = inner;
277 } else {
278 break;
279 }
280 }
281 }
282 }
283 }
284}
285
286pub struct ObjectDB {
292 objects: HashMap<String, Entry>,
294 xml_holder: Option<libxml::tree::Document>,
311 external: Option<ExternalDb>,
314}
315
316impl ObjectDB {
317 pub fn new() -> Self {
319 ObjectDB {
320 objects: HashMap::default(),
321 xml_holder: None,
322 external: None,
323 }
324 }
325
326 fn xml_holder_mut(&mut self) -> Option<&mut libxml::tree::Document> {
331 if self.xml_holder.is_none() {
332 let mut doc = libxml::tree::Document::new().ok()?;
333 let root = Node::new("_objectdb_", None, &doc).ok()?;
334 doc.set_root_element(&root);
335 self.xml_holder = Some(doc);
336 }
337 self.xml_holder.as_mut()
338 }
339
340 pub fn adopt_xml(&mut self, node: &Node) -> Option<Value> {
359 let scratch = libxml::tree::Document::dup_node_into_new_doc(node).ok()?;
360 let mut extracted = scratch.get_root_element()?;
361 extracted.unlink_node();
362 let holder = self.xml_holder_mut()?;
363 let mut adopted = holder.import_node(&mut extracted).ok()?;
364 let mut root = holder.get_root_element()?;
365 root.add_child(&mut adopted).ok()?;
366 extracted.free_subtree();
367 Some(Value::Xml(adopted))
368 }
369
370 pub fn lookup(&self, key: &str) -> Option<&Entry> { self.objects.get(key) }
374
375 pub fn lookup_mut(&mut self, key: &str) -> Option<&mut Entry> { self.objects.get_mut(key) }
377
378 pub fn register(&mut self, key: &str, props: Vec<(&str, Value)>) -> &mut Entry {
383 let entry = self
384 .objects
385 .entry(key.to_string())
386 .or_insert_with(|| Entry::new(key));
387 if !props.is_empty() {
388 entry.set_values(props);
389 }
390 self.objects.get_mut(key).unwrap()
391 }
392
393 pub fn unregister(&mut self, key: &str) {
397 self.objects.remove(key);
398 if let Some(external) = &mut self.external {
402 external.baseline.remove(key);
403 if !external.readonly {
404 let _ = external
405 .conn
406 .execute("DELETE FROM entries WHERE key = ?1", rusqlite::params![key]);
407 }
408 }
409 }
410
411 pub fn get_keys(&self) -> Vec<&String> {
415 let mut keys: Vec<_> = self.objects.keys().collect();
416 keys.sort();
417 keys
418 }
419
420 pub fn len(&self) -> usize { self.objects.len() }
423
424 pub fn is_empty(&self) -> bool { self.objects.is_empty() }
426
427 pub fn keys_iter(&self) -> impl Iterator<Item = &String> { self.objects.keys() }
430
431 pub fn status(&self) -> String { format!("{} objects", self.objects.len()) }
435}
436
437impl Default for ObjectDB {
438 fn default() -> Self { Self::new() }
439}
440
441pub const DBFILE_FORMAT_VERSION: i64 = 1;
466
467struct ExternalDb {
471 conn: rusqlite::Connection,
472 readonly: bool,
473 baseline: HashMap<String, String>,
474}
475
476#[derive(Default)]
479pub struct DbAttachOptions {
480 pub clean: bool,
482 pub readonly: bool,
484}
485
486impl ObjectDB {
487 pub fn attach(dbfile: &std::path::Path, options: DbAttachOptions) -> Result<Self, String> {
490 if options.clean && options.readonly {
491 return Err("dbfile: clean requires write access (Perl always opens O_RDWR)".to_string());
492 }
493 if options.clean && dbfile.exists() {
494 latexml_core::common::error::emit_warn(
495 "expected",
496 "dbfile",
497 &format!("Removing Object database file {}!", dbfile.display()),
498 );
499 std::fs::remove_file(dbfile)
500 .map_err(|e| format!("cannot remove {}: {e}", dbfile.display()))?;
501 }
502 let conn = if options.readonly {
503 rusqlite::Connection::open_with_flags(dbfile, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
504 } else {
505 rusqlite::Connection::open(dbfile)
506 }
507 .map_err(|e| format!("cannot attach DB {}: {e}", dbfile.display()))?;
508 if !options.readonly {
512 let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()));
513 }
514 conn
515 .busy_timeout(std::time::Duration::from_secs(10))
516 .map_err(|e| format!("cannot set busy_timeout: {e}"))?;
517
518 let version: i64 = conn
519 .query_row("PRAGMA user_version", [], |r| r.get(0))
520 .map_err(|e| format!("cannot read user_version: {e}"))?;
521 let entries_table: bool = conn
522 .query_row(
523 "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='entries'",
524 [],
525 |r| r.get::<_, i64>(0),
526 )
527 .map(|n| n > 0)
528 .unwrap_or(false);
529 let any_table: bool = conn
530 .query_row(
531 "SELECT COUNT(*) FROM sqlite_master WHERE type='table'",
532 [],
533 |r| r.get::<_, i64>(0),
534 )
535 .map(|n| n > 0)
536 .unwrap_or(false);
537 if version == 0 && any_table && !entries_table {
538 return Err(format!(
539 "{} is a SQLite file but not an ObjectDB (no entries table) — refusing to adopt it",
540 dbfile.display()
541 ));
542 }
543 if version == 0 && !options.readonly {
544 conn
545 .execute_batch(&format!(
546 "PRAGMA user_version = {DBFILE_FORMAT_VERSION};
547 CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
548 CREATE TABLE IF NOT EXISTS entries(key TEXT PRIMARY KEY, props TEXT NOT NULL);"
549 ))
550 .map_err(|e| format!("cannot initialize {}: {e}", dbfile.display()))?;
551 } else if version != 0 && version != DBFILE_FORMAT_VERSION {
552 return Err(format!(
553 "object database {} has format version {version}, this binary reads {DBFILE_FORMAT_VERSION} — rebuild it (--dbfile with a clean run)",
554 dbfile.display()
555 ));
556 }
557
558 let mut db = ObjectDB::new();
559 let mut baseline = HashMap::default();
560 let table_exists: bool = conn
562 .query_row(
563 "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='entries'",
564 [],
565 |r| r.get::<_, i64>(0),
566 )
567 .map(|n| n > 0)
568 .unwrap_or(false);
569 if table_exists {
570 let mut stmt = conn
571 .prepare("SELECT key, props FROM entries")
572 .map_err(|e| format!("cannot read entries: {e}"))?;
573 let rows = stmt
574 .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
575 .map_err(|e| format!("cannot scan entries: {e}"))?;
576 for row in rows {
577 let (key, props) = row.map_err(|e| format!("bad row: {e}"))?;
578 match db.decode_entry(&key, &props) {
581 Ok(entry) if options.readonly => {
584 db.objects.insert(key, entry);
585 },
586 Ok(entry) => {
587 db.objects.insert(key.clone(), entry);
588 baseline.insert(key, props);
589 },
590 Err(e) => latexml_core::common::error::emit_warn("malformed", "dbfile_entry", &e),
591 }
592 }
593 drop(stmt);
594 }
595 db.external = Some(ExternalDb {
596 conn,
597 readonly: options.readonly,
598 baseline,
599 });
600 Ok(db)
601 }
602
603 pub fn save_as(&self, path: &std::path::Path) -> Result<usize, String> {
609 if path.exists() {
610 std::fs::remove_file(path).map_err(|e| format!("cannot replace {}: {e}", path.display()))?;
611 }
612 let mut conn = rusqlite::Connection::open(path)
613 .map_err(|e| format!("cannot create dbfile {}: {e}", path.display()))?;
614 let _ = conn.query_row("PRAGMA journal_mode = WAL", [], |_| Ok(()));
615 conn
616 .execute_batch(&format!(
617 "PRAGMA user_version = {DBFILE_FORMAT_VERSION};
618 CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL);
619 CREATE TABLE entries(key TEXT PRIMARY KEY, props TEXT NOT NULL);"
620 ))
621 .map_err(|e| format!("cannot initialize {}: {e}", path.display()))?;
622 let tx = conn
623 .transaction()
624 .map_err(|e| format!("cannot begin save_as transaction: {e}"))?;
625 let mut stored = 0usize;
626 {
627 let mut stmt = tx
628 .prepare("INSERT INTO entries(key, props) VALUES (?1, ?2)")
629 .map_err(|e| format!("cannot prepare save_as insert: {e}"))?;
630 let mut buf = Vec::with_capacity(512);
631 for (key, entry) in &self.objects {
632 buf.clear();
633 write_entry_json(&mut buf, self.xml_holder.as_ref(), entry)
634 .map_err(|e| format!("cannot encode entry {key}: {e}"))?;
635 let props =
636 std::str::from_utf8(&buf).map_err(|e| format!("encoded entry {key} not utf-8: {e}"))?;
637 stmt
638 .execute(rusqlite::params![key, props])
639 .map_err(|e| format!("cannot store entry {key}: {e}"))?;
640 stored += 1;
641 }
642 }
643 tx.execute(
644 "INSERT INTO meta(key, value) VALUES ('latexml_version', ?1)",
645 rusqlite::params![env!("CARGO_PKG_VERSION")],
646 )
647 .map_err(|e| format!("cannot store meta: {e}"))?;
648 tx.commit()
649 .map_err(|e| format!("cannot commit save_as: {e}"))?;
650 Ok(stored)
651 }
652
653 pub fn finish(&mut self) -> Result<usize, String> {
657 let Some(external) = self.external.take() else {
658 return Ok(0);
659 };
660 if external.readonly {
661 return Ok(0);
662 }
663 let mut stored = 0usize;
668 let mut conn = external.conn;
669 let tx = conn
670 .transaction()
671 .map_err(|e| format!("cannot begin dbfile transaction: {e}"))?;
672 {
673 let mut stmt = tx
674 .prepare(
675 "INSERT INTO entries(key, props) VALUES (?1, ?2)
676 ON CONFLICT(key) DO UPDATE SET props = excluded.props",
677 )
678 .map_err(|e| format!("cannot prepare dbfile upsert: {e}"))?;
679 for (key, entry) in &self.objects {
680 let props = {
681 let map: serde_json::Map<String, serde_json::Value> = entry
682 .values
683 .iter()
684 .map(|(k, v)| (k.clone(), value_to_json_with(self.xml_holder.as_ref(), v)))
685 .collect();
686 serde_json::Value::Object(map).to_string()
687 };
688 if external.baseline.get(key) == Some(&props) {
689 continue;
690 }
691 stmt
692 .execute(rusqlite::params![key, props])
693 .map_err(|e| format!("cannot store entry {key}: {e}"))?;
694 stored += 1;
695 }
696 }
697 tx.execute(
698 "INSERT INTO meta(key, value) VALUES ('latexml_version', ?1)
699 ON CONFLICT(key) DO UPDATE SET value = excluded.value",
700 rusqlite::params![env!("CARGO_PKG_VERSION")],
701 )
702 .map_err(|e| format!("cannot store meta: {e}"))?;
703 tx.commit()
704 .map_err(|e| format!("cannot commit dbfile: {e}"))?;
705 Ok(stored)
706 }
707
708 fn value_to_json(&self, value: &Value) -> serde_json::Value {
713 value_to_json_with(self.xml_holder.as_ref(), value)
714 }
715
716 fn decode_entry(&mut self, key: &str, props: &str) -> Result<Entry, String> {
717 let parsed: serde_json::Value =
718 serde_json::from_str(props).map_err(|e| format!("entry {key} is not valid JSON: {e}"))?;
719 let serde_json::Value::Object(map) = parsed else {
720 return Err(format!("entry {key} is not a JSON object"));
721 };
722 let mut entry = Entry::new(key);
723 for (attr, jv) in map {
724 let value = self.json_to_value(&jv, key)?;
725 entry.set_value(&attr, value);
726 }
727 Ok(entry)
728 }
729
730 fn json_to_value(&mut self, jv: &serde_json::Value, key: &str) -> Result<Value, String> {
731 use serde_json::Value as J;
732 let J::Object(o) = jv else {
733 return match jv {
734 J::Null => Ok(Value::Null),
735 other => Err(format!("entry {key}: unexpected bare JSON value {other}")),
736 };
737 };
738 if let Some((tag, inner)) = o.iter().next()
739 && o.len() == 1
740 {
741 return match (tag.as_str(), inner) {
742 ("s", J::String(s)) => Ok(Value::String(s.clone())),
743 ("i", J::Number(n)) => n
744 .as_i64()
745 .map(Value::Int)
746 .ok_or_else(|| format!("entry {key}: non-integer numeric value {n}")),
747 ("b", J::Bool(b)) => Ok(Value::Bool(*b)),
748 ("l", J::Array(items)) => Ok(Value::List(
749 items
750 .iter()
751 .map(|v| self.json_to_value(v, key))
752 .collect::<Result<Vec<_>, _>>()?,
753 )),
754 ("h", J::Object(map)) => {
755 let mut out = HashMap::default();
756 for (k, v) in map {
757 out.insert(k.clone(), self.json_to_value(v, key)?);
758 }
759 Ok(Value::Hash(out))
760 },
761 ("x", J::String(xml)) => {
762 let parsed = libxml::parser::Parser::default()
763 .parse_string(xml)
764 .map_err(|e| format!("entry {key}: stored XML does not parse: {e}"))?;
765 let root = parsed
766 .get_root_element()
767 .ok_or_else(|| format!("entry {key}: stored XML is empty"))?;
768 self
769 .adopt_xml(&root)
770 .ok_or_else(|| format!("entry {key}: could not adopt stored XML"))
771 },
772 (tag, _) => Err(format!("entry {key}: unknown value tag '{tag}'")),
773 };
774 }
775 Err(format!("entry {key}: malformed value object"))
776 }
777}
778
779fn write_entry_json(
783 out: &mut Vec<u8>,
784 holder: Option<&libxml::tree::Document>,
785 entry: &Entry,
786) -> serde_json::Result<()> {
787 write_map_json(out, holder, &entry.values)
788}
789
790fn write_map_json(
791 out: &mut Vec<u8>,
792 holder: Option<&libxml::tree::Document>,
793 map: &HashMap<String, Value>,
794) -> serde_json::Result<()> {
795 let mut keys: Vec<&String> = map.keys().collect();
799 keys.sort_unstable();
800 out.push(b'{');
801 for (idx, k) in keys.into_iter().enumerate() {
802 if idx > 0 {
803 out.push(b',');
804 }
805 serde_json::to_writer(&mut *out, k)?;
806 out.push(b':');
807 write_value_json(out, holder, &map[k])?;
808 }
809 out.push(b'}');
810 Ok(())
811}
812
813fn write_value_json(
814 out: &mut Vec<u8>,
815 holder: Option<&libxml::tree::Document>,
816 value: &Value,
817) -> serde_json::Result<()> {
818 match value {
819 Value::Null => out.extend_from_slice(b"null"),
820 Value::String(s) => {
821 out.extend_from_slice(b"{\"s\":");
822 serde_json::to_writer(&mut *out, s)?;
823 out.push(b'}');
824 },
825 Value::Int(i) => {
826 out.extend_from_slice(b"{\"i\":");
827 serde_json::to_writer(&mut *out, i)?;
828 out.push(b'}');
829 },
830 Value::Bool(b) => {
831 out.extend_from_slice(if *b {
832 b"{\"b\":true}"
833 } else {
834 b"{\"b\":false}"
835 });
836 },
837 Value::List(items) => {
838 out.extend_from_slice(b"{\"l\":[");
839 for (idx, item) in items.iter().enumerate() {
840 if idx > 0 {
841 out.push(b',');
842 }
843 write_value_json(out, holder, item)?;
844 }
845 out.extend_from_slice(b"]}");
846 },
847 Value::Hash(map) => {
848 out.extend_from_slice(b"{\"h\":");
849 write_map_json(out, holder, map)?;
850 out.push(b'}');
851 },
852 Value::Xml(node) => {
853 let xml = holder
854 .map(|doc| doc.node_to_string(node))
855 .unwrap_or_default();
856 out.extend_from_slice(b"{\"x\":");
857 serde_json::to_writer(&mut *out, &xml)?;
858 out.push(b'}');
859 },
860 }
861 Ok(())
862}
863
864fn value_to_json_with(holder: Option<&libxml::tree::Document>, value: &Value) -> serde_json::Value {
867 use serde_json::{Value as J, json};
868 match value {
869 Value::String(s) => json!({ "s": s }),
870 Value::Int(i) => json!({ "i": i }),
871 Value::Bool(b) => json!({ "b": b }),
872 Value::Null => J::Null,
873 Value::List(items) => {
874 json!({ "l": items.iter().map(|v| value_to_json_with(holder, v)).collect::<Vec<_>>() })
875 },
876 Value::Hash(map) => {
877 json!({ "h": map.iter().map(|(k, v)| (k.clone(), value_to_json_with(holder, v))).collect::<serde_json::Map<_, _>>() })
878 },
879 Value::Xml(node) => {
880 let xml = holder
881 .map(|doc| doc.node_to_string(node))
882 .unwrap_or_default();
883 json!({ "x": xml })
884 },
885 }
886}
887
888#[cfg(test)]
889mod tests {
890 use super::*;
891
892 #[test]
893 fn test_entry_basic() {
894 let mut entry = Entry::new("test:key");
895 assert_eq!(entry.get_key(), "test:key");
896 assert!(!entry.has_value("name"));
897
898 entry.set_value("name", Value::from("Alice"));
899 assert!(entry.has_value("name"));
900 assert_eq!(entry.get_string("name"), Some("Alice"));
901 }
902
903 #[test]
904 fn test_entry_push_new() {
905 let mut entry = Entry::new("test");
906 entry.push_new("children", vec![Value::from("a"), Value::from("b")]);
907 entry.push_new("children", vec![Value::from("b"), Value::from("c")]);
908 let children = entry.get_children();
910 assert_eq!(children, vec!["a", "b", "c"]);
911 entry.push_values("children", vec![Value::from("d")]);
913 entry.push_new("children", vec![
914 Value::from("d"),
915 Value::from("a"),
916 Value::from("e"),
917 ]);
918 assert_eq!(entry.get_children(), vec!["a", "b", "c", "d", "e"]);
919 entry.set_value("children", Value::List(vec![Value::from("x")]));
920 entry.push_new("children", vec![Value::from("a"), Value::from("x")]);
921 assert_eq!(entry.get_children(), vec!["x", "a"]);
922 entry.set_value("children", Value::Null);
923 entry.push_new("children", vec![Value::from("x"), Value::from("x")]);
924 assert_eq!(entry.get_children(), vec!["x"]);
925 }
926
927 #[test]
928 fn test_entry_note_association() {
929 let mut entry = Entry::new("test");
930 entry.note_association(&["referrers", "doc1"]);
931 entry.note_association(&["referrers", "doc2"]);
932
933 assert!(entry.has_value("referrers"));
934 if let Some(Value::Hash(refs)) = entry.get_value("referrers") {
935 assert!(refs.contains_key("doc1"));
936 assert!(refs.contains_key("doc2"));
937 } else {
938 panic!("Expected Hash value for referrers");
939 }
940 }
941
942 #[test]
943 fn test_db_register_lookup() {
944 let mut db = ObjectDB::new();
945
946 db.register("ID:doc1", vec![
947 ("type", Value::from("ltx:document")),
948 ("title", Value::from("Test Document")),
949 ]);
950
951 let entry = db.lookup("ID:doc1");
952 assert!(entry.is_some());
953 assert_eq!(entry.unwrap().get_string("type"), Some("ltx:document"));
954 assert_eq!(entry.unwrap().get_string("title"), Some("Test Document"));
955
956 assert!(db.lookup("ID:missing").is_none());
958 }
959
960 #[test]
961 fn test_db_register_updates() {
962 let mut db = ObjectDB::new();
963 db.register("ID:x", vec![("a", Value::from("1"))]);
964 db.register("ID:x", vec![("b", Value::from("2"))]);
965
966 let entry = db.lookup("ID:x").unwrap();
967 assert_eq!(entry.get_string("a"), Some("1"));
968 assert_eq!(entry.get_string("b"), Some("2"));
969 }
970
971 #[test]
972 fn test_db_get_keys() {
973 let mut db = ObjectDB::new();
974 db.register("B", vec![]);
975 db.register("A", vec![]);
976 db.register("C", vec![]);
977
978 let keys = db.get_keys();
979 assert_eq!(keys, vec![
980 &"A".to_string(),
981 &"B".to_string(),
982 &"C".to_string()
983 ]);
984 }
985
986 #[test]
987 fn test_db_status() {
988 let mut db = ObjectDB::new();
989 assert_eq!(db.status(), "0 objects");
990 db.register("x", vec![]);
991 assert_eq!(db.status(), "1 objects");
992 }
993
994 #[test]
995 fn many_adoptions_share_one_holding_document() {
996 let parser = libxml::parser::Parser::default();
1003 let mut db = ObjectDB::new();
1004 let mut sources = Vec::new();
1005 for i in 0..64 {
1006 let doc = parser
1007 .parse_string(format!("<title>Section <em>{i}</em></title>").as_bytes())
1008 .expect("parse source");
1009 let root = doc.get_root_element().expect("root");
1010 let adopted = db.adopt_xml(&root).expect("adopt");
1011 db.register(&format!("ID:S{i}"), vec![("title", adopted)]);
1012 sources.push(doc);
1013 }
1014 drop(sources); for i in 0..64 {
1016 let entry = db.lookup(&format!("ID:S{i}")).expect("entry");
1017 let node = entry.get_xml("title").expect("stored node");
1018 assert_eq!(node.get_content(), format!("Section {i}"));
1019 }
1020 let holder = db
1023 .xml_holder
1024 .as_ref()
1025 .expect("holder exists after adoption");
1026 let root = holder.get_root_element().expect("holder root");
1027 assert_eq!(root.get_child_elements().len(), 64);
1028 }
1029
1030 #[test]
1031 fn adopted_xml_survives_source_document_drop() {
1032 let parser = libxml::parser::Parser::default();
1036 let source = parser
1037 .parse_string(
1038 "<title xmlns:m=\"http://www.w3.org/1998/Math/MathML\">\
1039 The <m:mi>\u{03b1}</m:mi> section</title>",
1040 )
1041 .expect("parse source");
1042 let title = source.get_root_element().expect("root");
1043
1044 let mut db = ObjectDB::new();
1045 let adopted = db.adopt_xml(&title).expect("adopt");
1046 db.register("ID:S1", vec![("title", adopted)]);
1047 drop(source); let entry = db.lookup("ID:S1").expect("entry");
1050 let node = entry.get_xml("title").expect("stored node");
1051 assert_eq!(node.get_name(), "title");
1052 assert_eq!(node.get_content(), "The \u{03b1} section");
1053 let mi = node
1056 .get_child_nodes()
1057 .into_iter()
1058 .find(|c| c.get_name() == "mi")
1059 .expect("m:mi child survives");
1060 assert_eq!(
1061 mi.get_namespace().map(|ns| ns.get_href()),
1062 Some(String::from("http://www.w3.org/1998/Math/MathML"))
1063 );
1064 }
1065
1066 #[test]
1067 fn test_value_truthy() {
1068 assert!(!Value::Null.is_truthy());
1069 assert!(!Value::String(String::new()).is_truthy());
1070 assert!(Value::String("hello".to_string()).is_truthy());
1071 assert!(Value::Bool(true).is_truthy());
1072 assert!(!Value::Bool(false).is_truthy());
1073 assert!(Value::Int(42).is_truthy());
1074 assert!(!Value::List(vec![]).is_truthy());
1075 assert!(Value::List(vec![Value::Int(1)]).is_truthy());
1076 }
1077
1078 #[test]
1082 fn dbfile_round_trips_all_value_shapes() {
1083 let dir = tempfile::tempdir().expect("tempdir");
1084 let dbfile = dir.path().join("site.db");
1085
1086 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach fresh");
1087 let title_doc = libxml::parser::Parser::default()
1088 .parse_string("<ltx:text xmlns:ltx=\"http://dlmf.nist.gov/LaTeXML\">A <ltx:emph>title</ltx:emph></ltx:text>")
1089 .expect("title parses");
1090 let title = db
1091 .adopt_xml(&title_doc.get_root_element().expect("root"))
1092 .expect("adopted");
1093 db.register("doc1#s1", vec![
1094 ("type", Value::String("ltx:section".into())),
1095 ("pageid", Value::Int(3)),
1096 ("fresh", Value::Bool(true)),
1097 (
1098 "children",
1099 Value::List(vec![
1100 Value::String("doc1#s1.p1".into()),
1101 Value::String("doc1#s1.p2".into()),
1102 ]),
1103 ),
1104 (
1105 "referrers",
1106 Value::Hash({
1107 let mut h = HashMap::default();
1108 h.insert("doc2".to_string(), Value::String("ref".into()));
1109 h
1110 }),
1111 ),
1112 ("title", title),
1113 ("missing", Value::Null),
1114 ]);
1115 let stored = db.finish().expect("finish writes");
1116 assert_eq!(stored, 1, "one changed entry stored");
1117
1118 let mut reloaded = ObjectDB::attach(&dbfile, DbAttachOptions {
1119 readonly: true,
1120 ..Default::default()
1121 })
1122 .expect("attach readonly");
1123 assert!(
1124 reloaded
1125 .external
1126 .as_ref()
1127 .is_some_and(|e| e.baseline.is_empty()),
1128 "a readonly attach keeps no as-stored copy"
1129 );
1130 let entry = reloaded.lookup("doc1#s1").expect("entry survives");
1131 assert_eq!(entry.get_string("type"), Some("ltx:section"));
1132 assert!(matches!(entry.get_value("pageid"), Some(Value::Int(3))));
1133 assert!(matches!(entry.get_value("fresh"), Some(Value::Bool(true))));
1134 assert_eq!(entry.get_children(), vec!["doc1#s1.p1", "doc1#s1.p2"]);
1135 assert!(matches!(entry.get_value("referrers"), Some(Value::Hash(_))));
1136 let title = entry.get_xml("title").expect("XML value survives");
1137 assert!(
1138 title.get_content().contains("A title"),
1139 "adopted XML content round-trips"
1140 );
1141 assert_eq!(reloaded.finish().expect("readonly finish"), 0);
1142
1143 let mut again = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach rw");
1148 assert_eq!(
1149 again.finish().expect("idempotent finish"),
1150 0,
1151 "an untouched XML-bearing entry must not re-store"
1152 );
1153
1154 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach 3");
1157 db.unregister("doc1#s1");
1158 db.finish().expect("finish after unregister");
1159 let db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach 4");
1160 assert!(
1161 db.lookup("doc1#s1").is_none(),
1162 "an unregistered key must not resurrect on re-attach"
1163 );
1164 }
1165
1166 #[test]
1170 fn dbfile_finish_writes_only_changes() {
1171 let dir = tempfile::tempdir().expect("tempdir");
1172 let dbfile = dir.path().join("site.db");
1173 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("attach");
1174 db.register("a", vec![("v", Value::Int(1))]);
1175 db.register("b", vec![("v", Value::Int(2))]);
1176 assert_eq!(db.finish().expect("first finish"), 2);
1177
1178 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach");
1179 assert_eq!(
1180 db.finish().expect("no-op finish"),
1181 0,
1182 "unchanged DB stores nothing"
1183 );
1184
1185 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach 2");
1186 db.register("b", vec![("v", Value::Int(99))]);
1187 db.register("c", vec![("v", Value::Int(3))]);
1188 assert_eq!(
1189 db.finish().expect("delta finish"),
1190 2,
1191 "one changed + one new"
1192 );
1193 let db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("re-attach 3");
1194 assert!(matches!(
1195 db.lookup("b").and_then(|e| e.get_value("v")),
1196 Some(Value::Int(99))
1197 ));
1198 assert_eq!(db.len(), 3);
1199 }
1200
1201 #[test]
1208 fn dbfile_concurrent_readers_and_writer_contention() {
1209 let dir = tempfile::tempdir().expect("tempdir");
1210 let dbfile = dir.path().join("site.db");
1211 {
1212 let mut db = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("seed");
1213 for i in 0..500 {
1214 db.register(&format!("k{i}"), vec![("v", Value::Int(i))]);
1215 }
1216 assert_eq!(db.finish().expect("seed finish"), 500);
1217 }
1218
1219 let blocker = rusqlite::Connection::open(&dbfile).expect("blocker open");
1222 blocker
1223 .execute_batch("BEGIN IMMEDIATE; UPDATE entries SET props = props WHERE key = 'k0';")
1224 .expect("blocker tx");
1225 let release = std::thread::spawn(move || {
1226 std::thread::sleep(std::time::Duration::from_millis(300));
1227 blocker.execute_batch("COMMIT;").expect("blocker commit");
1228 });
1229 let mut writer = ObjectDB::attach(&dbfile, DbAttachOptions::default()).expect("writer");
1230 writer.register("k0", vec![("v", Value::Int(-1))]);
1231 let t0 = std::time::Instant::now();
1232 assert_eq!(
1233 writer.finish().expect("contended finish succeeds"),
1234 1,
1235 "the second writer stores its one change after the blocker commits"
1236 );
1237 assert!(
1238 t0.elapsed() < std::time::Duration::from_secs(9),
1239 "finish waited out the blocker, not the full timeout"
1240 );
1241 release.join().expect("blocker thread");
1242
1243 std::thread::scope(|scope| {
1245 let dbfile = &dbfile;
1246 let mut handles = Vec::new();
1247 for _ in 0..4 {
1248 handles.push(scope.spawn(move || {
1249 for _ in 0..10 {
1250 let db = ObjectDB::attach(dbfile, DbAttachOptions {
1251 readonly: true,
1252 ..Default::default()
1253 })
1254 .expect("reader attaches during writes");
1255 assert_eq!(db.len(), 500, "readers always see a full snapshot");
1256 assert!(db.lookup("k42").is_some());
1257 }
1258 }));
1259 }
1260 scope.spawn(move || {
1261 for round in 0..10 {
1262 let mut db =
1263 ObjectDB::attach(dbfile, DbAttachOptions::default()).expect("writer attaches");
1264 db.register("k1", vec![("v", Value::Int(1000 + round))]);
1265 db.finish().expect("interleaved writer finish");
1266 }
1267 });
1268 for h in handles {
1269 h.join().expect("reader thread");
1270 }
1271 });
1272 }
1273
1274 #[test]
1277 fn dbfile_version_mismatch_is_refused() {
1278 let dir = tempfile::tempdir().expect("tempdir");
1279 let dbfile = dir.path().join("site.db");
1280 {
1281 let conn = rusqlite::Connection::open(&dbfile).expect("open");
1282 conn
1283 .execute_batch("PRAGMA user_version = 999;")
1284 .expect("stamp");
1285 }
1286 let err = ObjectDB::attach(&dbfile, DbAttachOptions::default())
1287 .err()
1288 .expect("mismatched version must refuse");
1289 assert!(
1290 err.contains("format version 999"),
1291 "names the found version: {err}"
1292 );
1293 let db = ObjectDB::attach(&dbfile, DbAttachOptions {
1295 clean: true,
1296 ..Default::default()
1297 })
1298 .expect("clean rebuild attaches");
1299 assert!(db.is_empty());
1300 }
1301
1302 #[test]
1307 fn save_as_streaming_json_matches_value_to_json_for_all_variants() {
1308 use crate::document::{PostDocument, PostDocumentOptions};
1309
1310 let dir = tempfile::tempdir().expect("tempdir");
1311 let dbfile = dir.path().join("snapshot.db");
1312
1313 let mut db = ObjectDB::new();
1314 let doc = PostDocument::new_from_string(
1315 r#"<ltx:document xmlns:ltx="http://dlmf.nist.gov/LaTeXML"><ltx:title>Hi & "Bye"</ltx:title></ltx:document>"#,
1316 PostDocumentOptions::default(),
1317 )
1318 .expect("parse xml");
1319 let title = doc
1320 .findnodes("//ltx:title")
1321 .into_iter()
1322 .next()
1323 .expect("title node");
1324 let adopted = db.adopt_xml(&title).expect("adopt xml");
1325
1326 let mut nested = HashMap::default();
1327 nested.insert("z_key".to_string(), Value::Int(-42));
1328 nested.insert("a_key".to_string(), Value::Bool(false));
1329
1330 db.register("ID:all7", vec![
1331 ("k_null", Value::Null),
1332 ("k_str", Value::from("line1\n\"quoted\"\\slash")),
1333 ("k_int", Value::Int(123_456)),
1334 ("k_bool_t", Value::Bool(true)),
1335 ("k_bool_f", Value::Bool(false)),
1336 (
1337 "k_list",
1338 Value::List(vec![Value::from("x"), Value::Int(7), Value::Null]),
1339 ),
1340 ("k_hash", Value::Hash(nested)),
1341 ("k_xml", adopted),
1342 ]);
1343
1344 let entry = db.lookup("ID:all7").expect("registered entry");
1345 let holder = db.xml_holder.as_ref();
1346 let mut streamed = Vec::new();
1347 write_entry_json(&mut streamed, holder, entry).expect("stream json");
1348 let streamed_str = String::from_utf8(streamed).expect("utf8");
1349
1350 let mut serde_map = serde_json::Map::new();
1351 for (k, v) in &entry.values {
1352 serde_map.insert(k.clone(), value_to_json_with(holder, v));
1353 }
1354 let expected_str = serde_json::to_string(&serde_json::Value::Object(serde_map)).expect("serde");
1355 assert_eq!(streamed_str, expected_str);
1356
1357 assert_eq!(db.save_as(&dbfile).expect("save_as"), 1);
1358 let reloaded = ObjectDB::attach(&dbfile, DbAttachOptions {
1359 readonly: true,
1360 ..Default::default()
1361 })
1362 .expect("reattach");
1363 let r = reloaded.lookup("ID:all7").expect("reloaded entry");
1364 assert!(r.get_value("k_null").is_none());
1366 assert_eq!(r.get_string("k_str"), Some("line1\n\"quoted\"\\slash"));
1367 assert!(matches!(r.get_value("k_int"), Some(Value::Int(123_456))));
1368 assert!(matches!(r.get_value("k_bool_t"), Some(Value::Bool(true))));
1369 assert!(matches!(r.get_value("k_bool_f"), Some(Value::Bool(false))));
1370 assert!(matches!(
1371 r.get_value("k_list"),
1372 Some(Value::List(l)) if l.len() == 3 && matches!(l[2], Value::Null)
1373 ));
1374 assert!(matches!(r.get_value("k_hash"), Some(Value::Hash(h)) if h.len() == 2));
1375 assert!(matches!(r.get_value("k_xml"), Some(Value::Xml(_))));
1376 }
1377}