parameterized IN query
Jasperav opened this issue · comments
Is there a macro to support a parameterized IN query?
@Jasperav
Could you please provide a query example?
Say for example I have a table user_by_username
, and this is the declaration of the table:
create table user_by_username(
username text primary key ,
user_id uuid,
);
Now a user can request user_id's by sending a request to the server with a list of usernames. With a parameterized ? query, I can execute this if the list equals 2 elements:
select * from user_by_username where username in (?, ?);
and with query_values
I provide the values for the question marks.
@Jasperav
Non-named query values must help
query_values!(uuid_1, uuid_2)
Please let me know if you have issues with that.
@AlexPikalov yes that will work out for a fixed sized array. The users can send any amount of usernames which I can query, so I need a dynamically sized parameterized in query
@Jasperav
Thanks. I see your case.
I've prepared a solution for this case, you can find the example in #311. To be able to use it you need to use CDRS from a branch feat/310
.
Or, alternatively, you can use
use cdrs::query:: QueryValues;
let values = QueryValues::from(your_vector); // <-- this is what you can use instead of query_values! macro
Please keep in mind that for both cases it is required for a vector to be of type Vec<T>
where T
must implement Clone
@AlexPikalov Thanks for the quick response! That will work out for the values, do you have an example how this would work out when using an IN query? I am having trouble to understand how I can make it work. Let's say this is my query:
select * from user_by_username where username in (WhatShouldGoInsideHere?)
And I get a request from a client with 3 usernames, the query should look like this (can be parameterized or not):
select * from user_by_username where username in (username1, username2, username3)
It should work for any amount of elements in the request of the client, so 2 usernames should work as well. I now have this method which works , but I was hoping there was a native IN query helper:
pub fn in_clause(usernames: Vec<String>) -> String {
" in (".to_owned() + ids.join(",") + ")"
}
Hi @Jasperav
It's possible to do it with current CDRS version via SELECT * FROM table WHERE id IN ?
query and query values query_values!(ids_vector)
Please check the tests I've added recently https://github.com/AlexPikalov/cdrs/blob/master/tests/query_values.rs#L39
Please feel free to re-open the issue in case of any problems