edgedb / edgedb-rust

The official Rust binding for EdgeDB
https://edgedb.com
Apache License 2.0
208 stars 26 forks source link

Named parameters in queries #261

Open AdrienPensart opened 1 year ago

AdrienPensart commented 1 year ago

Hello!

Would it be possible to execute queries like this :

#[derive(Queryable)]
struct MusicOutput {
    pub id: Uuid,
    pub name: String
}

let parameters = HashMap::from([
    ("artist", "John 5"),
]);
let music_output: Result<MusicOutput, _> = conn.query_required_single(
"select (
        insert Artist {
        name := <str>$artist
   } unless conflict on .name else (select Artist)
) {id, name}", &parameters).await;
tailhook commented 1 year ago

The problem with using HashMap is that arguments can be of different types. So dynamic typing should be used. I.e. edgedb_protocol::value::Value type. Unforutately, we don't have a nice constructor for that at least yet.

The plan in, however, to make a derive:

#[derive(QueryArgs)]
struct Artist {
  name: String,
}

But this is still on our todo list. For now, tuples are what is the easiest to use as query arguments.

hongquan commented 1 year ago

Before edgedb-rust offers a convenient way to construct named parameters from your struct, you can use named parameters with Client.query by:

To construct edgedb_protocol::value::Value::Object from a map, you can reference https://github.com/edgedb/edgedb-rust/blob/releases/edgedb-protocol/v0.6.0/edgedb-protocol/src/value.rs#L100. Note that, the example is to build SparseObject, we just learn it to build Value:Object.

You can take a look at my examples:

https://github.com/hongquan/QuanWeb/blob/2bcb09b4e62dd7742e8ebb9fee809a7e9970111c/src/stores/blog.rs#L123-L157

https://github.com/hongquan/QuanWeb/blob/2bcb09b4e62dd7742e8ebb9fee809a7e9970111c/src/api/structs.rs#L168-L206

AlexDaniel commented 10 months ago

Also: https://quan.hoabinh.vn/post/2023/8/querying-edgedb-with-name-parameters-in-rust

MrFoxPro commented 3 months ago

https://github.com/edgedb/edgedb-rust/pull/304 should solve this