Support PgHstore by default in macros (#3514)

* Support PgHstore in macros

* Change tests

* Remove unused import
This commit is contained in:
joeydewaal 2024-10-02 20:56:13 +02:00 committed by GitHub
parent 5b8bb3b28b
commit 72512f7311
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 38 additions and 1 deletions

View file

@ -83,6 +83,7 @@ impl_type_checking!(
#[cfg(feature = "bit-vec")]
sqlx::types::BitVec,
sqlx::postgres::types::PgHstore,
// Arrays
Vec<bool> | &[bool],
@ -139,6 +140,8 @@ impl_type_checking!(
#[cfg(feature = "json")]
Vec<sqlx::types::JsonValue> | &[sqlx::types::JsonValue],
Vec<sqlx::postgres::types::PgHstore> | &[sqlx::postgres::types::PgHstore],
// Ranges
sqlx::postgres::types::PgRange<i32>,

View file

@ -10,7 +10,7 @@ use crate::{
encode::{Encode, IsNull},
error::BoxDynError,
types::Type,
PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres,
PgArgumentBuffer, PgHasArrayType, PgTypeInfo, PgValueRef, Postgres,
};
use serde::{Deserialize, Serialize};
use sqlx_core::bytes::Buf;
@ -138,6 +138,12 @@ impl Type<Postgres> for PgHstore {
}
}
impl PgHasArrayType for PgHstore {
fn array_type_info() -> PgTypeInfo {
PgTypeInfo::array_of("hstore")
}
}
impl<'r> Decode<'r, Postgres> for PgHstore {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
let mut buf = <&[u8] as Decode<Postgres>>::decode(value)?;

View file

@ -1,4 +1,5 @@
use sqlx::{Connection, PgConnection, Postgres, Transaction};
use sqlx_postgres::types::PgHstore;
use sqlx_test::new;
use futures::TryStreamExt;
@ -636,3 +637,25 @@ async fn test_to_from_citext() -> anyhow::Result<()> {
Ok(())
}
#[sqlx_macros::test]
async fn pghstore_tests() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;
let mut store = PgHstore::default();
let stores = vec![store.clone(), store.clone()];
store.insert("key".into(), Some("value".to_string()));
sqlx::query!(" insert into mytable(f) values ($1)", store)
.execute(&mut conn)
.await?;
sqlx::query!(
" insert into mytable(f) select * from unnest($1::hstore[])",
&stores
)
.execute(&mut conn)
.await?;
Ok(())
}

View file

@ -7,6 +7,9 @@ CREATE EXTENSION IF NOT EXISTS cube;
-- https://www.postgresql.org/docs/current/citext.html
CREATE EXTENSION IF NOT EXISTS citext;
-- https://www.postgresql.org/docs/current/hstore.html
CREATE EXTENSION IF NOT EXISTS hstore;
-- https://www.postgresql.org/docs/current/sql-createtype.html
CREATE TYPE status AS ENUM ('new', 'open', 'closed');
@ -58,3 +61,5 @@ CREATE TABLE test_citext (
CREATE SCHEMA IF NOT EXISTS foo;
CREATE TYPE foo."Foo" as ENUM ('Bar', 'Baz');
CREATE TABLE mytable(f HSTORE);