1pub mod numeric;
6pub mod temporal;
7
8pub use numeric::Numeric;
9pub use temporal::{Date, Time, Timestamp};
10
11use crate::protocol::types::{decode_json, decode_jsonb, decode_text_array, decode_uuid, oid};
12
13#[derive(Debug, Clone)]
15pub enum TypeError {
16 UnexpectedOid {
18 expected: &'static str,
20 got: u32,
22 },
23 InvalidData(String),
25 UnexpectedNull,
27}
28
29impl std::fmt::Display for TypeError {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 TypeError::UnexpectedOid { expected, got } => {
33 write!(f, "Expected {} type, got OID {}", expected, got)
34 }
35 TypeError::InvalidData(msg) => write!(f, "Invalid data: {}", msg),
36 TypeError::UnexpectedNull => write!(f, "Unexpected NULL value"),
37 }
38 }
39}
40
41impl std::error::Error for TypeError {}
42
43pub trait FromPg: Sized {
45 fn from_pg(bytes: &[u8], oid: u32, format: i16) -> Result<Self, TypeError>;
51}
52
53pub trait ToPg {
55 fn to_pg(&self) -> (Vec<u8>, u32, i16);
58}
59
60impl FromPg for String {
63 fn from_pg(bytes: &[u8], _oid: u32, _format: i16) -> Result<Self, TypeError> {
64 String::from_utf8(bytes.to_vec())
65 .map_err(|e| TypeError::InvalidData(format!("Invalid UTF-8: {}", e)))
66 }
67}
68
69impl ToPg for String {
70 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
71 (self.as_bytes().to_vec(), oid::TEXT, 0)
72 }
73}
74
75impl ToPg for &str {
76 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
77 (self.as_bytes().to_vec(), oid::TEXT, 0)
78 }
79}
80
81impl FromPg for i32 {
84 fn from_pg(bytes: &[u8], _oid: u32, format: i16) -> Result<Self, TypeError> {
85 if format == 1 {
86 if bytes.len() != 4 {
88 return Err(TypeError::InvalidData(
89 "Expected 4 bytes for i32".to_string(),
90 ));
91 }
92 Ok(i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
93 } else {
94 std::str::from_utf8(bytes)
96 .map_err(|e| TypeError::InvalidData(e.to_string()))?
97 .parse()
98 .map_err(|e| TypeError::InvalidData(format!("Invalid i32: {}", e)))
99 }
100 }
101}
102
103impl ToPg for i32 {
104 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
105 (self.to_be_bytes().to_vec(), oid::INT4, 1)
106 }
107}
108
109impl FromPg for i64 {
110 fn from_pg(bytes: &[u8], _oid: u32, format: i16) -> Result<Self, TypeError> {
111 if format == 1 {
112 if bytes.len() != 8 {
114 return Err(TypeError::InvalidData(
115 "Expected 8 bytes for i64".to_string(),
116 ));
117 }
118 Ok(i64::from_be_bytes([
119 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
120 ]))
121 } else {
122 std::str::from_utf8(bytes)
124 .map_err(|e| TypeError::InvalidData(e.to_string()))?
125 .parse()
126 .map_err(|e| TypeError::InvalidData(format!("Invalid i64: {}", e)))
127 }
128 }
129}
130
131impl ToPg for i64 {
132 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
133 (self.to_be_bytes().to_vec(), oid::INT8, 1)
134 }
135}
136
137impl FromPg for f64 {
140 fn from_pg(bytes: &[u8], _oid: u32, format: i16) -> Result<Self, TypeError> {
141 if format == 1 {
142 if bytes.len() != 8 {
144 return Err(TypeError::InvalidData(
145 "Expected 8 bytes for f64".to_string(),
146 ));
147 }
148 Ok(f64::from_be_bytes([
149 bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
150 ]))
151 } else {
152 std::str::from_utf8(bytes)
154 .map_err(|e| TypeError::InvalidData(e.to_string()))?
155 .parse()
156 .map_err(|e| TypeError::InvalidData(format!("Invalid f64: {}", e)))
157 }
158 }
159}
160
161impl ToPg for f64 {
162 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
163 (self.to_be_bytes().to_vec(), oid::FLOAT8, 1)
164 }
165}
166
167impl FromPg for bool {
170 fn from_pg(bytes: &[u8], _oid: u32, format: i16) -> Result<Self, TypeError> {
171 if format == 1 {
172 Ok(bytes.first().map(|b| *b != 0).unwrap_or(false))
174 } else {
175 match bytes.first() {
177 Some(b't') | Some(b'T') | Some(b'1') => Ok(true),
178 Some(b'f') | Some(b'F') | Some(b'0') => Ok(false),
179 _ => Err(TypeError::InvalidData("Invalid boolean".to_string())),
180 }
181 }
182 }
183}
184
185impl ToPg for bool {
186 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
187 (vec![if *self { 1 } else { 0 }], oid::BOOL, 1)
188 }
189}
190
191#[derive(Debug, Clone, PartialEq)]
195pub struct Uuid(pub String);
196
197impl FromPg for Uuid {
198 fn from_pg(bytes: &[u8], oid_val: u32, format: i16) -> Result<Self, TypeError> {
199 if oid_val != oid::UUID {
200 return Err(TypeError::UnexpectedOid {
201 expected: "uuid",
202 got: oid_val,
203 });
204 }
205
206 if format == 1 && bytes.len() == 16 {
207 decode_uuid(bytes).map(Uuid).map_err(TypeError::InvalidData)
209 } else {
210 String::from_utf8(bytes.to_vec())
212 .map(Uuid)
213 .map_err(|e| TypeError::InvalidData(e.to_string()))
214 }
215 }
216}
217
218impl ToPg for Uuid {
219 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
220 (self.0.as_bytes().to_vec(), oid::UUID, 0)
222 }
223}
224
225#[derive(Debug, Clone, PartialEq)]
229pub struct Json(pub String);
230
231impl FromPg for Json {
232 fn from_pg(bytes: &[u8], oid_val: u32, _format: i16) -> Result<Self, TypeError> {
233 let json_str = if oid_val == oid::JSONB {
234 decode_jsonb(bytes).map_err(TypeError::InvalidData)?
235 } else {
236 decode_json(bytes).map_err(TypeError::InvalidData)?
237 };
238 Ok(Json(json_str))
239 }
240}
241
242impl ToPg for Json {
243 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
244 let mut buf = Vec::with_capacity(1 + self.0.len());
246 buf.push(1); buf.extend_from_slice(self.0.as_bytes());
248 (buf, oid::JSONB, 1)
249 }
250}
251
252impl FromPg for Vec<String> {
255 fn from_pg(bytes: &[u8], _oid: u32, _format: i16) -> Result<Self, TypeError> {
256 let s = std::str::from_utf8(bytes).map_err(|e| TypeError::InvalidData(e.to_string()))?;
257 Ok(decode_text_array(s))
258 }
259}
260
261impl FromPg for Vec<i64> {
262 fn from_pg(bytes: &[u8], _oid: u32, _format: i16) -> Result<Self, TypeError> {
263 let s = std::str::from_utf8(bytes).map_err(|e| TypeError::InvalidData(e.to_string()))?;
264 crate::protocol::types::decode_int_array(s).map_err(TypeError::InvalidData)
265 }
266}
267
268impl<T: FromPg> FromPg for Option<T> {
271 fn from_pg(bytes: &[u8], oid_val: u32, format: i16) -> Result<Self, TypeError> {
272 Ok(Some(T::from_pg(bytes, oid_val, format)?))
274 }
275}
276
277impl FromPg for Vec<u8> {
280 fn from_pg(bytes: &[u8], _oid: u32, _format: i16) -> Result<Self, TypeError> {
281 Ok(bytes.to_vec())
282 }
283}
284
285impl ToPg for Vec<u8> {
286 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
287 (self.clone(), oid::BYTEA, 1)
288 }
289}
290
291impl ToPg for &[u8] {
292 fn to_pg(&self) -> (Vec<u8>, u32, i16) {
293 (self.to_vec(), oid::BYTEA, 1)
294 }
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300
301 #[test]
302 fn test_string_from_pg() {
303 let result = String::from_pg(b"hello", oid::TEXT, 0).unwrap();
304 assert_eq!(result, "hello");
305 }
306
307 #[test]
308 fn test_i32_from_pg_text() {
309 let result = i32::from_pg(b"42", oid::INT4, 0).unwrap();
310 assert_eq!(result, 42);
311 }
312
313 #[test]
314 fn test_i32_from_pg_binary() {
315 let bytes = 42i32.to_be_bytes();
316 let result = i32::from_pg(&bytes, oid::INT4, 1).unwrap();
317 assert_eq!(result, 42);
318 }
319
320 #[test]
321 fn test_bool_from_pg() {
322 assert!(bool::from_pg(b"t", oid::BOOL, 0).unwrap());
323 assert!(!bool::from_pg(b"f", oid::BOOL, 0).unwrap());
324 assert!(bool::from_pg(&[1], oid::BOOL, 1).unwrap());
325 assert!(!bool::from_pg(&[0], oid::BOOL, 1).unwrap());
326 }
327
328 #[test]
329 fn test_uuid_from_pg_binary() {
330 let uuid_bytes: [u8; 16] = [
331 0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44,
332 0x00, 0x00,
333 ];
334 let result = Uuid::from_pg(&uuid_bytes, oid::UUID, 1).unwrap();
335 assert_eq!(result.0, "550e8400-e29b-41d4-a716-446655440000");
336 }
337}