Skip to main content

cognee_database/
uuid_hex.rs

1//! UUID ↔ 32-char hex string conversions.
2//!
3//! Python's SQLAlchemy stores UUIDs as 32-character hex strings (no hyphens)
4//! in SQLite.  These helpers ensure the Rust database layer uses the same
5//! format, so the two SDKs can share a database file.
6
7use uuid::Uuid;
8
9/// Convert a `Uuid` to the 32-char hex format used by Python's SQLAlchemy.
10///
11/// Example: `550e8400-e29b-41d4-a716-446655440000` → `"550e8400e29b41d4a716446655440000"`
12#[inline]
13pub fn to_hex(u: Uuid) -> String {
14    u.simple().to_string()
15}
16
17/// Convert an `Option<Uuid>` to an optional hex string.
18#[inline]
19pub fn to_hex_opt(u: Option<Uuid>) -> Option<String> {
20    u.map(to_hex)
21}
22
23/// Parse a 32-char hex string (or hyphenated UUID) back to `Uuid`.
24///
25/// Accepts both `"550e8400e29b41d4a716446655440000"` and
26/// `"550e8400-e29b-41d4-a716-446655440000"` for backwards compatibility.
27#[inline]
28pub fn from_hex(s: &str) -> Result<Uuid, uuid::Error> {
29    Uuid::parse_str(s)
30}
31
32/// Parse an optional hex string back to `Option<Uuid>`.
33#[inline]
34pub fn from_hex_opt(s: Option<&str>) -> Result<Option<Uuid>, uuid::Error> {
35    match s {
36        Some(s) => from_hex(s).map(Some),
37        None => Ok(None),
38    }
39}
40
41#[cfg(test)]
42#[allow(
43    clippy::unwrap_used,
44    clippy::expect_used,
45    reason = "test code — panics are acceptable failures"
46)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn round_trip() {
52        let u = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
53        let hex = to_hex(u);
54        assert_eq!(hex, "550e8400e29b41d4a716446655440000");
55        assert_eq!(hex.len(), 32);
56        assert_eq!(from_hex(&hex).unwrap(), u);
57    }
58
59    #[test]
60    fn from_hex_accepts_hyphenated() {
61        let u = from_hex("550e8400-e29b-41d4-a716-446655440000").unwrap();
62        assert_eq!(to_hex(u), "550e8400e29b41d4a716446655440000");
63    }
64
65    #[test]
66    fn option_round_trip() {
67        let u = Uuid::new_v4();
68        assert_eq!(
69            from_hex_opt(to_hex_opt(Some(u)).as_deref()).unwrap(),
70            Some(u)
71        );
72        assert_eq!(from_hex_opt(to_hex_opt(None).as_deref()).unwrap(), None);
73    }
74}