Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Postgres): support nested domain types #3641

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion sqlx-postgres/src/type_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1013,7 +1013,7 @@ impl PgType {
/// If `soft_eq` is true and `self` or `other` is `DeclareWithOid` but not both, return `true`
/// before checking names.
fn eq_impl(&self, other: &Self, soft_eq: bool) -> bool {
if let (Some(a), Some(b)) = (self.try_oid(), other.try_oid()) {
if let (Some(a), Some(b)) = (self.base_oid(), other.base_oid()) {
// If there are OIDs available, use OIDs to perform a direct match
return a == b;
}
Expand All @@ -1035,6 +1035,17 @@ impl PgType {
// Otherwise, perform a match on the name
name_eq(self.name(), other.name())
}

// Returns the OID of the type, returns the OID of the base_type for Domain types
fn base_oid(&self) -> Option<Oid> {
match self {
PgType::Custom(custom) => match &custom.kind {
PgTypeKind::Domain(domain) => domain.base_oid(),
_ => Some(custom.oid),
},
ty => ty.try_oid(),
}
}
}

impl TypeInfo for PgTypeInfo {
Expand Down
9 changes: 9 additions & 0 deletions tests/postgres/setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,12 @@ CREATE SCHEMA IF NOT EXISTS foo;
CREATE TYPE foo."Foo" as ENUM ('Bar', 'Baz');

CREATE TABLE mytable(f HSTORE);

CREATE DOMAIN positive_int AS integer CHECK (VALUE >= 0);
CREATE DOMAIN percentage AS positive_int CHECK (VALUE < 100);

CREATE TYPE person as (
id int,
age positive_int,
percent percentage
);
23 changes: 23 additions & 0 deletions tests/postgres/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,3 +657,26 @@ CREATE TEMPORARY TABLE user_login (

Ok(())
}

#[sqlx_macros::test]
async fn test_nested_domain_types() -> anyhow::Result<()> {
#[derive(sqlx::Type)]
struct Person {
id: i32,
age: i32,
percent: i32,
}

let mut conn = new::<Postgres>().await?;

let p: Person = sqlx::query_scalar("select ROW(1, 21::positive_int, 50::percentage)::person")
.fetch_one(&mut conn)
.await
.unwrap();

assert!(p.id == 1);
assert!(p.age == 21);
assert!(p.percent == 50);

Ok(())
}
Loading