Skip to main content

dbrest_core/schema_cache/
representations.rs

1//! Data representation types for dbrest
2//!
3//! Data representations define type mapping functions that convert between
4//! database types (e.g., converting a bytea to a custom image format).
5
6use compact_str::CompactString;
7use std::collections::HashMap;
8
9/// A data representation mapping function
10///
11/// Maps from one database type to another via a PostgreSQL function.
12/// Used for custom type casting in content negotiation.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct DataRepresentation {
15    /// Source PostgreSQL type name
16    pub source_type: CompactString,
17    /// Target PostgreSQL type name
18    pub target_type: CompactString,
19    /// PostgreSQL function that performs the conversion
20    pub function: CompactString,
21}
22
23/// Map from (source_type, target_type) pair to the representation
24pub type RepresentationsMap = HashMap<(CompactString, CompactString), DataRepresentation>;
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn test_data_representation_creation() {
32        let repr = DataRepresentation {
33            source_type: "bytea".into(),
34            target_type: "image/png".into(),
35            function: "bytea_to_png".into(),
36        };
37        assert_eq!(repr.source_type.as_str(), "bytea");
38        assert_eq!(repr.target_type.as_str(), "image/png");
39        assert_eq!(repr.function.as_str(), "bytea_to_png");
40    }
41
42    #[test]
43    fn test_representations_map() {
44        let mut map: RepresentationsMap = HashMap::new();
45        let repr = DataRepresentation {
46            source_type: "bytea".into(),
47            target_type: "text".into(),
48            function: "encode".into(),
49        };
50        map.insert(("bytea".into(), "text".into()), repr.clone());
51
52        assert_eq!(map.get(&("bytea".into(), "text".into())), Some(&repr));
53        assert!(!map.contains_key(&("text".into(), "bytea".into())));
54    }
55
56    #[test]
57    fn test_data_representation_equality() {
58        let a = DataRepresentation {
59            source_type: "int".into(),
60            target_type: "text".into(),
61            function: "int_to_text".into(),
62        };
63        let b = a.clone();
64        assert_eq!(a, b);
65    }
66}