0

I would like to know how I can pass multiple fields (with variables) to the SELECT statement. For example:

let sql = "SELECT name, skills FROM user:1";

Turn it into something like:

let sql = "SELECT $fields FROM $th";

I know how to do the $th part, but how can I implement the $fields part?

I have tried the following:

let sql = "SELECT $fields FROM $th";

let fields = ["name", "skills"];

let vars: BTreeMap<String, Value> = [
    ("fields".into(), fields.into()),
    ("th".into(), thing(&id)?.into())
].into();

EDIT:

For now, I am doing the following, but I would like to know a better way of doing it.

let sql = "SELECT $fields FROM $th";

let join_vec;
let fields_vec: Option<Vec<&str>> = fields.into();
let mut fields = fields_vec.into_iter();

match fields.next() {
    Some(f) => join_vec = f.join(", "),
    None => join_vec = "*".to_string(),
}
        
let replace_with: String = "SELECT ".to_owned() + &join_vec;
let sql = &*sql.replace("SELECT $fields", &replace_with);
Gixty
  • 202
  • 4
  • 13

1 Answers1

2

I believe your best option is indeed to just use string interpolation as I don't think it has support for providing fields as a parameter for the query yet.

I took the liberty to clean up your solution a little bit as it seemed a little contrived

let fields: [&str; 2] = ["name", "skills"];

let sql = format!("SELECT {} FROM $th", if fields.len() == 0 {
    "*".to_string()
} else {
    fields.join(", ")
});
CEbbinghaus
  • 86
  • 1
  • 10