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#[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 #[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#[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
82pub trait PostgresCodec<K, V>: Send + Sync + 'static {
87 type EncodedKey: PostgresKey;
89 type EncodedValue: PostgresValue;
91
92 fn encode_key(&self, key: &K) -> Result<Self::EncodedKey, PostgresBackendError>;
99
100 fn encode_value(&self, value: &V) -> Result<Self::EncodedValue, PostgresBackendError>;
107
108 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#[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#[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}