logoalt Hacker News

cogman10yesterday at 11:20 PM0 repliesview on HN

I agree with what you are saying, this is exactly what I was thinking when I said it was sometimes necessary. It's just not preferable IMO.

For this specific example, the better way is something like this

    let result = if let Some(date) = args.date {
      sqlx::query("SELECT * FROM posts WHERE title LIKE '%' + $1 + '%' AND date = $2")
        .bind(args.keyword)
        .bind(date)
        .fetch()
    } else {
      sqlx::query("SELECT * FROM posts WHERE title LIKE '%' + $1 + '%")
        .bind(args.keyword)
        .fetch()
    }
But I get how this would be untenable if as the number of query param combos goes up. In that case dynamic SQL really is the only sane way to handle something like that.