Skip to main content

spg_sqlx/types/
bytes.rs

1//! v7.16.0 — `Type` / `Encode` / `Decode` for `Vec<u8>` / BYTEA.
2
3use sqlx_core::decode::Decode;
4use sqlx_core::encode::{Encode, IsNull};
5use sqlx_core::error::BoxDynError;
6use sqlx_core::types::Type;
7
8use spg_embedded::Value as EngineValue;
9
10use crate::arguments::SpgArgumentValue;
11use crate::database::Spg;
12use crate::type_info::{Kind, SpgTypeInfo};
13use crate::value::SpgValueRef;
14
15impl Type<Spg> for [u8] {
16    fn type_info() -> SpgTypeInfo {
17        SpgTypeInfo::of(Kind::Bytes)
18    }
19
20    fn compatible(ty: &SpgTypeInfo) -> bool {
21        matches!(ty.kind(), Kind::Bytes)
22    }
23}
24
25impl Type<Spg> for Vec<u8> {
26    fn type_info() -> SpgTypeInfo {
27        <[u8] as Type<Spg>>::type_info()
28    }
29
30    fn compatible(ty: &SpgTypeInfo) -> bool {
31        <[u8] as Type<Spg>>::compatible(ty)
32    }
33}
34
35impl<'q> Encode<'q, Spg> for &'q [u8] {
36    fn encode_by_ref(&self, buf: &mut Vec<SpgArgumentValue<'q>>) -> Result<IsNull, BoxDynError> {
37        buf.push(SpgArgumentValue {
38            value: EngineValue::Bytes((*self).to_vec()),
39            type_info: Some(<[u8] as Type<Spg>>::type_info()),
40            _phantom: core::marker::PhantomData,
41        });
42        Ok(IsNull::No)
43    }
44}
45
46impl<'q> Encode<'q, Spg> for Vec<u8> {
47    fn encode_by_ref(&self, buf: &mut Vec<SpgArgumentValue<'q>>) -> Result<IsNull, BoxDynError> {
48        buf.push(SpgArgumentValue {
49            value: EngineValue::Bytes(self.clone()),
50            type_info: Some(<Vec<u8> as Type<Spg>>::type_info()),
51            _phantom: core::marker::PhantomData,
52        });
53        Ok(IsNull::No)
54    }
55}
56
57impl<'r> Decode<'r, Spg> for Vec<u8> {
58    fn decode(value: SpgValueRef<'r>) -> Result<Self, BoxDynError> {
59        match value.engine() {
60            EngineValue::Bytes(b) => Ok(b.clone()),
61            other => Err(format!("cannot decode {other:?} as Vec<u8> / BYTEA").into()),
62        }
63    }
64}