Skip to content

query! macro not detecting NOT NULL #3829

Open
@thejozika

Description

@thejozika

I have found these related issues/pull requests

Maybe those 2:
Improved detection of nullability for postgres #696
query_as!/query! inference returns nullable entries on join when a bound parameter is absent #1265

Description

Running the following code:

#[derive(Debug, Clone, FromRow)]
pub struct PrerequisiteRelation {
    pub foundation_id: Uuid,
    pub prerequisite_id: Uuid,
}        

let prerequisites = sqlx::query_as!(
            PrerequisiteRelation,
            r#"
            SELECT
                id_foundation AS foundation_id,
                id_prerequisite AS prerequisite_id
            FROM prerequisite_relations
            WHERE id_foundation = ANY($1)
              AND id_prerequisite = ANY($1)
              AND id_foundation IS NOT NULL
              AND id_prerequisite IS NOT NULL
            "#,
            &foundation_ids
        )
.fetch_all(&model_manager.db)
.await?;

gives the message:

the trait bound uuid::Uuid: From<std::option::Option<uuid::Uuid>> is not satisfied

This fixes it:

let prerequisites = sqlx::query_as!(
            PrerequisiteRelation,
            r#"
            SELECT
                id_foundation AS "foundation_id!:Uuid",
                id_prerequisite AS "prerequisite_id!:Uuid"
            FROM prerequisite_relations
            WHERE id_foundation = ANY($1)
              AND id_prerequisite = ANY($1)
              AND id_foundation IS NOT NULL
              AND id_prerequisite IS NOT NULL
            "#,
            &foundation_ids
        )
.fetch_all(&model_manager.db)
.await?;

is this intended behaviour?

Reproduction steps

Create a relation table with its own key. Insert some data and run the query_as! in a function as written above.

CREATE TABLE foundation 
(
    id uuid PRIMARY KEY DEFAULT gen_random_uuid()
);

CREATE TABLE prerequisite_relations
(
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    id_foundation uuid REFERENCES "foundation" (id) on DELETE CASCADE,
    id_prerequisite uuid REFERENCES "foundation" (id) on DELETE CASCADE,
);

SQLx version

0.8.3

Enabled SQLx features

"runtime-tokio", "tls-native-tls", "postgres", "uuid", "time", "chrono", "json", "macros"

Database server and version

psql 16.8

Operating system

Ubuntu 16.8-0ubuntu0.24.04.1

Rust version

rustc 1.85.0 (4d91de4e4 2025-02-17)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions