Skip to content

Commit 9ca1fbf

Browse files
authored
Support Rust arrays in Postgres (#1953)
1 parent cfef70a commit 9ca1fbf

File tree

3 files changed

+106
-9
lines changed

3 files changed

+106
-9
lines changed

sqlx-core/src/postgres/types/array.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ where
5555
}
5656
}
5757

58+
impl<T, const N: usize> Type<Postgres> for [T; N]
59+
where
60+
T: PgHasArrayType,
61+
{
62+
fn type_info() -> PgTypeInfo {
63+
T::array_type_info()
64+
}
65+
66+
fn compatible(ty: &PgTypeInfo) -> bool {
67+
T::array_compatible(ty)
68+
}
69+
}
70+
5871
impl<'q, T> Encode<'q, Postgres> for Vec<T>
5972
where
6073
for<'a> &'a [T]: Encode<'q, Postgres>,
@@ -66,6 +79,16 @@ where
6679
}
6780
}
6881

82+
impl<'q, T, const N: usize> Encode<'q, Postgres> for [T; N]
83+
where
84+
for<'a> &'a [T]: Encode<'q, Postgres>,
85+
T: Encode<'q, Postgres>,
86+
{
87+
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
88+
self.as_slice().encode_by_ref(buf)
89+
}
90+
}
91+
6992
impl<'q, T> Encode<'q, Postgres> for &'_ [T]
7093
where
7194
T: Encode<'q, Postgres> + Type<Postgres>,
@@ -100,6 +123,19 @@ where
100123
}
101124
}
102125

126+
impl<'r, T, const N: usize> Decode<'r, Postgres> for [T; N]
127+
where
128+
T: for<'a> Decode<'a, Postgres> + Type<Postgres>,
129+
{
130+
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
131+
// This could be done more efficiently by refactoring the Vec decoding below so that it can
132+
// be used for arrays and Vec.
133+
let vec: Vec<T> = Decode::decode(value)?;
134+
let array: [T; N] = vec.try_into().map_err(|_| "wrong number of elements")?;
135+
Ok(array)
136+
}
137+
}
138+
103139
impl<'r, T> Decode<'r, Postgres> for Vec<T>
104140
where
105141
T: for<'a> Decode<'a, Postgres> + Type<Postgres>,

sqlx-core/src/postgres/types/bytes.rs

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,12 @@ impl PgHasArrayType for Vec<u8> {
2424
}
2525
}
2626

27+
impl<const N: usize> PgHasArrayType for [u8; N] {
28+
fn array_type_info() -> PgTypeInfo {
29+
<[&[u8]] as Type<Postgres>>::type_info()
30+
}
31+
}
32+
2733
impl Encode<'_, Postgres> for &'_ [u8] {
2834
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
2935
buf.extend_from_slice(self);
@@ -38,6 +44,12 @@ impl Encode<'_, Postgres> for Vec<u8> {
3844
}
3945
}
4046

47+
impl<const N: usize> Encode<'_, Postgres> for [u8; N] {
48+
fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> IsNull {
49+
<&[u8] as Encode<Postgres>>::encode(self.as_slice(), buf)
50+
}
51+
}
52+
4153
impl<'r> Decode<'r, Postgres> for &'r [u8] {
4254
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
4355
match value.format() {
@@ -49,18 +61,33 @@ impl<'r> Decode<'r, Postgres> for &'r [u8] {
4961
}
5062
}
5163

64+
fn text_hex_decode_input(value: PgValueRef<'_>) -> Result<&[u8], BoxDynError> {
65+
// BYTEA is formatted as \x followed by hex characters
66+
value
67+
.as_bytes()?
68+
.strip_prefix(b"\\x")
69+
.ok_or("text does not start with \\x")
70+
.map_err(Into::into)
71+
}
72+
5273
impl Decode<'_, Postgres> for Vec<u8> {
5374
fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
5475
Ok(match value.format() {
5576
PgValueFormat::Binary => value.as_bytes()?.to_owned(),
56-
PgValueFormat::Text => {
57-
// BYTEA is formatted as \x followed by hex characters
58-
let text = value
59-
.as_bytes()?
60-
.strip_prefix(b"\\x")
61-
.ok_or("text does not start with \\x")?;
62-
hex::decode(text)?
63-
}
77+
PgValueFormat::Text => hex::decode(text_hex_decode_input(value)?)?,
6478
})
6579
}
6680
}
81+
82+
impl<const N: usize> Decode<'_, Postgres> for [u8; N] {
83+
fn decode(value: PgValueRef<'_>) -> Result<Self, BoxDynError> {
84+
let mut bytes = [0u8; N];
85+
match value.format() {
86+
PgValueFormat::Binary => {
87+
bytes = value.as_bytes()?.try_into()?;
88+
}
89+
PgValueFormat::Text => hex::decode_to_slice(text_hex_decode_input(value)?, &mut bytes)?,
90+
};
91+
Ok(bytes)
92+
}
93+
}

tests/postgres/types.rs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ test_type!(null_vec<Vec<Option<i16>>>(Postgres,
1515
"array[10,NULL,50]::int2[]" == vec![Some(10_i16), None, Some(50)],
1616
));
1717

18+
test_type!(null_array<[Option<i16>; 3]>(Postgres,
19+
"array[10,NULL,50]::int2[]" == vec![Some(10_i16), None, Some(50)],
20+
));
21+
1822
test_type!(bool<bool>(Postgres,
1923
"false::boolean" == false,
2024
"true::boolean" == true
@@ -24,6 +28,10 @@ test_type!(bool_vec<Vec<bool>>(Postgres,
2428
"array[true,false,true]::bool[]" == vec![true, false, true],
2529
));
2630

31+
test_type!(bool_array<[bool; 3]>(Postgres,
32+
"array[true,false,true]::bool[]" == vec![true, false, true],
33+
));
34+
2735
test_type!(byte_vec<Vec<u8>>(Postgres,
2836
"E'\\\\xDEADBEEF'::bytea"
2937
== vec![0xDE_u8, 0xAD, 0xBE, 0xEF],
@@ -41,6 +49,14 @@ test_prepared_type!(byte_slice<&[u8]>(Postgres,
4149
== &[0_u8, 0, 0, 0, 0x52][..]
4250
));
4351

52+
test_type!(byte_array_empty<[u8; 0]>(Postgres,
53+
"E'\\\\x'::bytea" == [0_u8; 0],
54+
));
55+
56+
test_type!(byte_array<[u8; 4]>(Postgres,
57+
"E'\\\\xDEADBEEF'::bytea" == [0xDE_u8, 0xAD, 0xBE, 0xEF],
58+
));
59+
4460
test_type!(str<&str>(Postgres,
4561
"'this is foo'" == "this is foo",
4662
"''" == "",
@@ -64,6 +80,10 @@ test_type!(string_vec<Vec<String>>(Postgres,
6480
== vec!["Hello, World", "", "Goodbye"]
6581
));
6682

83+
test_type!(string_array<[String; 3]>(Postgres,
84+
"array['one','two','three']::text[]" == ["one","two","three"],
85+
));
86+
6787
test_type!(i8(
6888
Postgres,
6989
"0::\"char\"" == 0_i8,
@@ -91,6 +111,14 @@ test_type!(i32_vec<Vec<i32>>(Postgres,
91111
"'{1,3,-5}'::int[]" == vec![1_i32, 3, -5]
92112
));
93113

114+
test_type!(i32_array_empty<[i32; 0]>(Postgres,
115+
"'{}'::int[]" == [0_i32; 0],
116+
));
117+
118+
test_type!(i32_array<[i32; 4]>(Postgres,
119+
"'{5,10,50,100}'::int[]" == [5_i32, 10, 50, 100],
120+
));
121+
94122
test_type!(i64(Postgres, "9358295312::bigint" == 9358295312_i64));
95123

96124
test_type!(f32(Postgres, "9419.122::real" == 9419.122_f32));
@@ -339,12 +367,18 @@ mod json {
339367
"'[\"Hello\", \"World!\"]'::json" == json!(["Hello", "World!"])
340368
));
341369

342-
test_type!(json_array<Vec<JsonValue>>(
370+
test_type!(json_vec<Vec<JsonValue>>(
343371
Postgres,
344372
"SELECT ({0}::jsonb[] is not distinct from $1::jsonb[])::int4, {0} as _2, $2 as _3",
345373
"array['\"😎\"'::json, '\"🙋‍♀️\"'::json]::json[]" == vec![json!("😎"), json!("🙋‍♀️")],
346374
));
347375

376+
test_type!(json_array<[JsonValue; 2]>(
377+
Postgres,
378+
"SELECT ({0}::jsonb[] is not distinct from $1::jsonb[])::int4, {0} as _2, $2 as _3",
379+
"array['\"😎\"'::json, '\"🙋‍♀️\"'::json]::json[]" == [json!("😎"), json!("🙋‍♀️")],
380+
));
381+
348382
test_type!(jsonb<JsonValue>(
349383
Postgres,
350384
"'\"Hello, World\"'::jsonb" == json!("Hello, World"),

0 commit comments

Comments
 (0)