Skip to main content

kape_postgres/
codec.rs

1use sqlx::{Decode, Encode, Postgres, Type, postgres::PgHasArrayType};
2
3use crate::PostgresBackendError;
4
5pub(crate) mod sealed {
6    pub trait Sealed {}
7
8    impl Sealed for String {}
9    impl Sealed for Vec<u8> {}
10}
11
12/// A PostgreSQL column representation supported by [`PostgresCodec`].
13///
14/// `String` maps to `TEXT`; `Vec<u8>` maps to `BYTEA`. This trait is sealed so
15/// the adapter can keep SQL binding and decoding behavior complete.
16#[doc(hidden)]
17pub trait PostgresValue:
18    sealed::Sealed
19    + Clone
20    + Send
21    + Sync
22    + Type<Postgres>
23    + PgHasArrayType
24    + for<'q> Encode<'q, Postgres>
25    + for<'r> Decode<'r, Postgres>
26{
27    /// Returns the SQL array type used to resolve bulk `UNNEST` parameters.
28    #[doc(hidden)]
29    fn array_type_name() -> &'static str;
30}
31
32impl PostgresValue for String {
33    fn array_type_name() -> &'static str {
34        "TEXT[]"
35    }
36}
37
38impl PostgresValue for Vec<u8> {
39    fn array_type_name() -> &'static str {
40        "BYTEA[]"
41    }
42}
43
44/// A PostgreSQL key representation that can carry the namespace prefix.
45#[doc(hidden)]
46pub trait PostgresKey: PostgresValue {
47    #[doc(hidden)]
48    fn namespace_prefix(namespace: &str) -> Self;
49
50    #[doc(hidden)]
51    fn join(prefix: Self, key: Self) -> Self;
52}
53
54impl PostgresKey for String {
55    #[inline]
56    fn namespace_prefix(namespace: &str) -> Self {
57        format!("kape:{namespace}:")
58    }
59
60    #[inline]
61    fn join(mut prefix: Self, key: Self) -> Self {
62        prefix.push_str(&key);
63        prefix
64    }
65}
66
67impl PostgresKey for Vec<u8> {
68    fn namespace_prefix(namespace: &str) -> Self {
69        let mut prefix = Vec::with_capacity(6 + namespace.len());
70        prefix.extend_from_slice(b"kape:");
71        prefix.extend_from_slice(namespace.as_bytes());
72        prefix.push(b':');
73        prefix
74    }
75
76    fn join(mut prefix: Self, key: Self) -> Self {
77        prefix.extend_from_slice(&key);
78        prefix
79    }
80}
81
82/// Encodes typed keys and values for application-owned `PostgreSQL` columns.
83///
84/// The associated representations determine the required column types. Use
85/// `String` for `TEXT` and `Vec<u8>` for `BYTEA`.
86pub trait PostgresCodec<K, V>: Send + Sync + 'static {
87    /// `PostgreSQL` representation of the key column.
88    type EncodedKey: PostgresKey;
89    /// `PostgreSQL` representation of the value column.
90    type EncodedValue: PostgresValue;
91
92    /// Encodes a typed key.
93    ///
94    /// # Errors
95    ///
96    /// Returns a backend error whose source is the codec error when the key
97    /// cannot be represented.
98    fn encode_key(&self, key: &K) -> Result<Self::EncodedKey, PostgresBackendError>;
99
100    /// Encodes a typed value.
101    ///
102    /// # Errors
103    ///
104    /// Returns a backend error whose source is the codec error when the value
105    /// cannot be represented.
106    fn encode_value(&self, value: &V) -> Result<Self::EncodedValue, PostgresBackendError>;
107
108    /// Decodes a typed value.
109    ///
110    /// # Errors
111    ///
112    /// Returns a backend error whose source is the codec error when the stored
113    /// value is invalid.
114    fn decode_value(&self, value: Self::EncodedValue) -> Result<V, PostgresBackendError>;
115}
116
117pub(crate) fn encode_namespaced_key<K, V, C>(
118    codec: &C,
119    namespace: &str,
120    key: &K,
121) -> Result<C::EncodedKey, PostgresBackendError>
122where
123    C: PostgresCodec<K, V>,
124{
125    let encoded = codec.encode_key(key)?;
126    Ok(C::EncodedKey::join(
127        C::EncodedKey::namespace_prefix(namespace),
128        encoded,
129    ))
130}
131
132/// Identity codec for `String` keys and values stored in `TEXT` columns.
133#[derive(Clone, Copy, Debug, Default)]
134pub struct StringCodec;
135
136impl PostgresCodec<String, String> for StringCodec {
137    type EncodedKey = String;
138    type EncodedValue = String;
139
140    #[inline]
141    fn encode_key(&self, key: &String) -> Result<Self::EncodedKey, PostgresBackendError> {
142        Ok(key.clone())
143    }
144
145    #[inline]
146    fn encode_value(&self, value: &String) -> Result<Self::EncodedValue, PostgresBackendError> {
147        Ok(value.clone())
148    }
149
150    #[inline]
151    fn decode_value(&self, value: Self::EncodedValue) -> Result<String, PostgresBackendError> {
152        Ok(value)
153    }
154}
155
156/// Identity codec for byte-vector keys and values stored in `BYTEA` columns.
157#[derive(Clone, Copy, Debug, Default)]
158pub struct BytesCodec;
159
160impl PostgresCodec<Vec<u8>, Vec<u8>> for BytesCodec {
161    type EncodedKey = Vec<u8>;
162    type EncodedValue = Vec<u8>;
163
164    #[inline]
165    fn encode_key(&self, key: &Vec<u8>) -> Result<Self::EncodedKey, PostgresBackendError> {
166        Ok(key.clone())
167    }
168
169    #[inline]
170    fn encode_value(&self, value: &Vec<u8>) -> Result<Self::EncodedValue, PostgresBackendError> {
171        Ok(value.clone())
172    }
173
174    #[inline]
175    fn decode_value(&self, value: Self::EncodedValue) -> Result<Vec<u8>, PostgresBackendError> {
176        Ok(value)
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::{BytesCodec, PostgresCodec, PostgresKey, StringCodec};
183
184    #[test]
185    fn string_codec_keeps_text_readable() {
186        let codec = StringCodec;
187        let value = "hello".to_owned();
188        assert_eq!(codec.encode_key(&value).unwrap(), value);
189        assert_eq!(codec.encode_value(&value).unwrap(), value);
190        assert_eq!(codec.decode_value(value.clone()).unwrap(), value);
191        assert_eq!(String::namespace_prefix("orders"), "kape:orders:");
192    }
193
194    #[test]
195    fn bytes_codec_round_trips_bytes() {
196        let codec = BytesCodec;
197        let bytes = vec![0, 1, 2, 255];
198        assert_eq!(codec.encode_key(&bytes).unwrap(), bytes);
199        assert_eq!(codec.encode_value(&bytes).unwrap(), bytes);
200        assert_eq!(codec.decode_value(bytes.clone()).unwrap(), bytes);
201        assert_eq!(Vec::<u8>::namespace_prefix("raw"), b"kape:raw:");
202    }
203}