String literal type / Force macro to accept string variable

I'm currently using the sqlx library to fetch data for a GraphQL backend.
To get the compile time schema checks, I need to use the macro functions, like query_as!.

let table_name = "posts";
sqlx::query_as!(Post, "SELECT * FROM " + table_name);

This doesn't work, because I didn't supply a string literal to query_as!.

Can this be somehow solved without resorting to the non-macro functions (thus, no compile-time checks)?

My current solution is to pattern match the inputs from the GraphQL resolvers and call the functions with string literals, which results in tons of duplicated code, but at least compile-time schema checks.

Is there no way to force the compiler to accept the strings, as I know that only valid strings get to the resolvers (I'm using enums, that correspond to the column names, for example for filtering by a specific column)?

Looking at your example, I'd suggest...

macro_rules! table_name { () => { "posts" } }
sqlx::query_as!(Post, concat!("SELECT * FROM ", table_name!()));

...but given what you said about enums, I suspect this won't help much.

Seems that query_as! doesn't even accept a macro as input, because I'm getting
error: expected string literal when trying to run that function with a string from concat!.

Looks like this issue, due to a mix of proc and declarative macros. The developer of ormx commented on the issue and came up with this. I don't know anything about ormx or the developer, but it's something you might want to look into.

Thanks for the link!
Unfortunately, it seems that the conditional_query_as! macro only allows inserting placeholders, no string concatenation.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.