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
13.42k stars 1.28k forks source link

Accept any `AsRef<str>` for `ColumnIndex` #2158

Open nitnelave opened 2 years ago

nitnelave commented 2 years ago

When using sea-query to build SQL queries, extracting the columns from a row is a bit awkward:

let query = Query::select()
    .from(Users::Table)
    .column(Users::Name)
    .to_string(SqliteQueryBuilder);

let names = sqlx::query(&query)
    .map(|row| row.get::<String, _>(&*Users::Name.to_string()))
    .fetch_all(&pool);

I'm mainly focusing on the &*Users::Name.to_string() part, which essentially resolves to "name". Here, Users is an enum that derives sea_query::Iden. I opened an issue to make the values implement Into<&'static str> when possible, but that only partly solves the problem.

I'd like to be able to write: row.get::<String, _>(Users::Name). The argument to get must implement ColumnIndex but it's a sealed trait that is only implemented for usize and &str. Could we instead implement it for any AsRef<str>? With both proposals, the interface would become much nicer. I suspect that it would also help with any other query builders/ORM that have newtypes around their column names.

nitnelave commented 1 year ago

The sea-query change has been merged, so now we can use the column name with as_str(). Still, it would be good to be able to pass a AsStr.