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

fix #[derive(sqlx::Type)] in Postgres #3252

Merged
merged 6 commits into from
Jun 15, 2024
Merged
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
6 changes: 0 additions & 6 deletions sqlx-macros-core/src/derives/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,6 @@ pub fn check_enum_attributes(input: &DeriveInput) -> syn::Result<SqlxContainerAt
input
);

assert_attribute!(
!attributes.no_pg_array,
"unused #[sqlx(no_pg_array)]; derive does not emit `PgHasArrayType` impls for enums",
input
);

Ok(attributes)
}

Expand Down
26 changes: 23 additions & 3 deletions sqlx-macros-core/src/derives/type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ fn expand_derive_has_sql_type_weak_enum(
input: &DeriveInput,
variants: &Punctuated<Variant, Comma>,
) -> syn::Result<TokenStream> {
let attr = check_weak_enum_attributes(input, variants)?;
let repr = attr.repr.unwrap();
let attrs = check_weak_enum_attributes(input, variants)?;
let repr = attrs.repr.unwrap();
let ident = &input.ident;
let ts = quote!(
let mut ts = quote!(
#[automatically_derived]
impl<DB: ::sqlx::Database> ::sqlx::Type<DB> for #ident
where
Expand All @@ -146,6 +146,16 @@ fn expand_derive_has_sql_type_weak_enum(
}
);

if cfg!(feature = "postgres") && !attrs.no_pg_array {
ts.extend(quote!(
impl ::sqlx::postgres::PgHasArrayType for #ident {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#ident as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}
}
));
}

Ok(ts)
}

Expand Down Expand Up @@ -184,6 +194,16 @@ fn expand_derive_has_sql_type_strong_enum(
}
}
));

if !attributes.no_pg_array {
tts.extend(quote!(
impl ::sqlx::postgres::PgHasArrayType for #ident {
fn array_type_info() -> ::sqlx::postgres::PgTypeInfo {
<#ident as ::sqlx::postgres::PgHasArrayType>::array_type_info()
}
}
));
}
}

if cfg!(feature = "sqlite") {
Expand Down
20 changes: 18 additions & 2 deletions sqlx-postgres/src/connection/describe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,24 @@ impl PgConnection {

fn fetch_type_by_oid(&mut self, oid: Oid) -> BoxFuture<'_, Result<PgTypeInfo, Error>> {
Box::pin(async move {
let (name, typ_type, category, relation_id, element, base_type): (String, i8, i8, Oid, Oid, Oid) = query_as(
"SELECT typname, typtype, typcategory, typrelid, typelem, typbasetype FROM pg_catalog.pg_type WHERE oid = $1",
let (name, typ_type, category, relation_id, element, base_type): (
String,
i8,
i8,
Oid,
Oid,
Oid,
) = query_as(
// Converting the OID to `regtype` and then `text` will give us the name that
// the type will need to be found at by search_path.
"SELECT oid::regtype::text, \
typtype, \
typcategory, \
typrelid, \
typelem, \
typbasetype \
FROM pg_catalog.pg_type \
WHERE oid = $1",
)
.bind(oid)
.fetch_one(&mut *self)
Expand Down
2 changes: 1 addition & 1 deletion sqlx-postgres/src/copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ impl<C: DerefMut<Target = PgConnection>> PgCopyIn<C> {
let buf = conn.stream.write_buffer_mut();

// Write the CopyData format code and reserve space for the length.
// This may end up sending an empty `CopyData` packet if, after this point,
// This may end up sending an empty `CopyData` packet if, after this point,
// we get canceled or read 0 bytes, but that should be fine.
buf.put_slice(b"d\0\0\0\x04");

Expand Down
98 changes: 97 additions & 1 deletion sqlx-postgres/src/type_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1154,7 +1154,103 @@ impl PartialEq<PgType> for PgType {
true
} else {
// Otherwise, perform a match on the name
self.name().eq_ignore_ascii_case(other.name())
name_eq(self.name(), other.name())
}
}
}

/// Check type names for equality, respecting Postgres' case sensitivity rules for identifiers.
///
/// https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
fn name_eq(name1: &str, name2: &str) -> bool {
// Cop-out of processing Unicode escapes by just using string equality.
if name1.starts_with("U&") {
// If `name2` doesn't start with `U&` this will automatically be `false`.
return name1 == name2;
}

let mut chars1 = identifier_chars(name1);
let mut chars2 = identifier_chars(name2);

while let (Some(a), Some(b)) = (chars1.next(), chars2.next()) {
if !a.eq(&b) {
return false;
}
}

chars1.next().is_none() && chars2.next().is_none()
}

struct IdentifierChar {
ch: char,
case_sensitive: bool,
}

impl IdentifierChar {
fn eq(&self, other: &Self) -> bool {
if self.case_sensitive || other.case_sensitive {
self.ch == other.ch
} else {
self.ch.eq_ignore_ascii_case(&other.ch)
}
}
}

/// Return an iterator over all significant characters of an identifier.
///
/// Ignores non-escaped quotation marks.
fn identifier_chars(ident: &str) -> impl Iterator<Item = IdentifierChar> + '_ {
let mut case_sensitive = false;
let mut last_char_quote = false;

ident.chars().filter_map(move |ch| {
if ch == '"' {
if last_char_quote {
last_char_quote = false;
} else {
last_char_quote = true;
return None;
}
} else if last_char_quote {
last_char_quote = false;
case_sensitive = !case_sensitive;
}

Some(IdentifierChar { ch, case_sensitive })
})
}

#[test]
fn test_name_eq() {
let test_values = [
("foo", "foo", true),
("foo", "Foo", true),
("foo", "FOO", true),
("foo", r#""foo""#, true),
("foo", r#""Foo""#, false),
("foo", "foo.foo", false),
("foo.foo", "foo.foo", true),
("foo.foo", "foo.Foo", true),
("foo.foo", "foo.FOO", true),
("foo.foo", "Foo.foo", true),
("foo.foo", "Foo.Foo", true),
("foo.foo", "FOO.FOO", true),
("foo.foo", "foo", false),
("foo.foo", r#"foo."foo""#, true),
("foo.foo", r#"foo."Foo""#, false),
("foo.foo", r#"foo."FOO""#, false),
];

for (left, right, eq) in test_values {
assert_eq!(
name_eq(left, right),
eq,
"failed check for name_eq({left:?}, {right:?})"
);
assert_eq!(
name_eq(right, left),
eq,
"failed check for name_eq({right:?}, {left:?})"
);
}
}
41 changes: 39 additions & 2 deletions tests/postgres/derives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,15 @@ test_type!(transparent_array<TransparentArray>(Postgres,
test_type!(weak_enum<Weak>(Postgres,
"0::int4" == Weak::One,
"2::int4" == Weak::Two,
"4::int4" == Weak::Three
"4::int4" == Weak::Three,
"'{0, 2, 4}'::int4[]" == vec![Weak::One, Weak::Two, Weak::Three],
));

test_type!(strong_enum<Strong>(Postgres,
"'one'::text" == Strong::One,
"'two'::text" == Strong::Two,
"'four'::text" == Strong::Three
"'four'::text" == Strong::Three,
"'{'one', 'two', 'four'}'::text[]" == vec![Strong::One, Strong::Two, Strong::Three],
));

test_type!(floatrange<FloatRange>(Postgres,
Expand Down Expand Up @@ -724,3 +726,38 @@ async fn test_skip() -> anyhow::Result<()> {

Ok(())
}

#[cfg(feature = "macros")]
#[sqlx_macros::test]
async fn test_enum_with_schema() -> anyhow::Result<()> {
#[derive(Debug, PartialEq, Eq, sqlx::Type)]
#[sqlx(type_name = "foo.\"Foo\"")]
enum Foo {
Bar,
Baz,
}

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

let foo: Foo = sqlx::query_scalar("SELECT $1::foo.\"Foo\"")
.bind(Foo::Bar)
.fetch_one(&mut conn)
.await?;

assert_eq!(foo, Foo::Bar);

let foo: Foo = sqlx::query_scalar("SELECT $1::foo.\"Foo\"")
.bind(Foo::Baz)
.fetch_one(&mut conn)
.await?;

assert_eq!(foo, Foo::Baz);

let foos: Vec<Foo> = sqlx::query_scalar!("SELECT ARRAY($1::foo.\"Foo\", $2::foo.\"Foo\")")
.bind(Foo::Bar)
.bind(Foo::Baz)
.fetch_one(&mut conn)
.await?;

assert_eq!(foos, [Foo::Bar, Foo::Baz]);
}
4 changes: 4 additions & 0 deletions tests/postgres/setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,7 @@ CREATE OR REPLACE PROCEDURE forty_two(INOUT forty_two INT = NULL)
CREATE TABLE test_citext (
foo CITEXT NOT NULL
);

CREATE SCHEMA IF NOT EXISTS foo;

CREATE ENUM foo."Foo" ('Bar', 'Baz');
Loading