Skip to content

Vectors in query_as! with Postgres #714

Closed

Description

@cschmatzler

Using sqlx 0.4.0-beta.1.

I have two tables in a one-to-many relation and I am trying to use query_as to retrieve them.

The tables are as follows:

CREATE TABLE IF NOT EXISTS one (
    "id" INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    "name" VARCHAR NOT NULL,
)

CREATE TABLE IF NOT EXISTS many (
    "id" INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    "name" VARCHAR NOT NULL,
    "one" INT,
    CONSTRAINT "fk_one"
        FOREIGN KEY("one")
            REFERENCES one
)

Then, my models in Rust are these:

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, sqlx::FromRow)]
pub struct One {
    pub id: i32,
    pub name: String,
    pub many: Vec<Many>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, sqlx::FromRow, sqlx::Type)]
pub struct Many {
    pub id: i32,
    pub name: String,
}

Now, what I want to do is do a left join on these two and receive a One object with a filled many field.
Querying the database is no problem:

let rows = sqlx::query_as!(
            One,
            r#"
                SELECT
                    one.id,
                    one.name,
                    (
                        many.id,
                        many.name,
                    ) AS "many!: Vec<Many>"
                FROM one
                LEFT OUTER JOIN many
                ON one.id = many.one
            "#
        )
        .fetch_all(&self.pool())
        .await?;

This query runs fine in psql, but... the trait sqlx::Type<sqlx::Postgres> is not implemented for std::vec::Vec<models::Many>

Is there any way to make this work with query_as!? I thought that using the sqlx::Type macro would help here but it doesn't seem to apply for vectors.

Sorry if I missed something, any pointers are much appreciated.

Activity

  1. lyckligtax commented on Oct 2, 2020

    @lyckligtax

    I have the same Problems when querying something like

    SELECT * FROM table WHERE status = $1 AND id IN $2;
    

    where I bind a Vec<SameTypeAsTheFieldId> to $2

  2. ekzhang commented on Oct 2, 2020

    @ekzhang

    Please correct me if I'm wrong, but is this the same as #298 ?

  3. abonander commented on Oct 16, 2020

    @abonander
    Collaborator

    @lyckligtax the IN operator in Postgres takes a subquery, not an array. You want id = any($2) where $2 is an array.

    Otherwise yes, this is a duplicate of #298,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions