Ethan
Ethan

Reputation: 375

Sqlx only accept string literal in query macro, how to use variable?

The codes:

// very complex where clause combined from several runtime variables.

let query: String = String.from("where ..........");
let rows_num: i64 = sqlx::query!( &*query).fetch_one(connection)

The error from compiler:

error: expected string literal
--> src/abc.rs:80:25
|
80 | let rows_num: i64 = sqlx::query!(
| ____________^
81 | | &*query,
82 | | ).fetch_one(connection)
| |^
|
= note: this error originates in the macro sqlx::query (in Nightly builds, run with -Z macro-backtrace for more info)

And the doc states:

The query must be a string literal or else it cannot be introspected (and thus cannot be dynamic or the result of another macro).

I know the sqlx computes at compile time, my where clause computation is at run time. I really want to use variable, because the where clause depends other several conditions. Are there any ways to use variable in sqlx?

Upvotes: 7

Views: 2425

Answers (1)

Ethan
Ethan

Reputation: 375

Using sqlx::query() function instead of the sqlx::query!() macro. The document doesn't mention it in their page.

Upvotes: 7

Related Questions