launchbadge / sqlx

🧰 The Rust SQL Toolkit. An async, pure Rust SQL crate featuring compile-time checked queries without a DSL. Supports PostgreSQL, MySQL, and SQLite.
Apache License 2.0
12.36k stars 1.18k forks source link

Allow using const values in the query! family of macros #3306

Closed RuboGubo closed 4 days ago

RuboGubo commented 1 week ago

Is your feature request related to a problem? Please describe. When writing trait implementations for a basic crud app, it would be nice to be able to set parameters such as table as a const trait value, do some string magic to combine it into a query, and then place it into the query! macro and friends

Describe the solution you'd like allow you to place const values instead of just string expressions into the query! family macros.

Describe alternatives you've considered Writing my own macro, but this is not a well documented part of rust that is almost completely different from regular code, making it inconvenient for the average user. You need to know how a compiler works to write macros, most people don't.

Example

pub trait ManageDB
where
    Self: Sized
{    
    const TABLE: &str;

    async fn delete_db(self, id: i64, mut conn: Connection<MainDB>) -> Result<(), sqlx::Error> {
        const query: &str = "DELETE FROM User WHERE id = ?"; // magic to combine string with const TABLE 

        sqlx::query!(
            query,
            id,
        )
        .execute(&mut **conn)
        .await
        .map(|_| ())
    }
}
abonander commented 4 days ago

Not possible. Macros can only directly observe their input, and don't have access to the surrounding scope. You can use + in the input to concatenate multiple string fragments together if you're using another macro to generate queries though.