SeaQL / sea-orm

šŸš An async & dynamic ORM for Rust
https://www.sea-ql.org/SeaORM/
Apache License 2.0
6.57k stars 461 forks source link

Add method for retrieiving column names #2148

Closed jharrilim closed 2 months ago

jharrilim commented 3 months ago

tl;dr: Add a method for retrieving column names from query results so that applications can use them alongside retrieved rows

Background

For creating some database tooling, I'd like to be able to retrieve database column names that come with the query results. This would be very dynamic because the queries are either generated at runtime from the user, or from introspection. Ideally I'd be able to get to a point where I have something like this:

let results: Vec<QueryResult> = db // DatabaseConnection
    .query_all(Statement::from_string(db.db_type.into(), query))
    .await?;
let headers = results
    .first()
    .and_then(|r| Some(r.columns())) // This PR addresses this part
    .unwrap_or_default();

// This doesn't work yet. Ideally there's a way to convert all row values
// to some enum for which I can match against and implement std::fmt::Display for
let rows = results
    .iter()
    .flat_map(|r| r.try_get_many_by_index::<serde_json::Value>())
    .map(|r| r.to_string())
    .collect::<Vec<_>>();

so that I can display headers in a table and the rows underneath them. Not so different from the output that you'd see in psql.

Aside


New Features

Breaking Changes

tyt2y3 commented 3 months ago

And tried to run it with cargo t --test query_tests --features sqlx-dep, but I get a bunch of compile errors saying use of undeclared crate or module sqlx

sqlx-dep is a 'transitive dependency'. You have to specify a specific backend, e.g. sqlx-postgres and also a runtime, `runtime

tyt2y3 commented 3 months ago

I'm not sure if it would be better to return an impl Iterator for the column names, or return actual column structs with their metadata instead.

Whatever suits your need is good enough for now! Although I'd rename the method to column_names so that we can implement the other versions in the future.

jharrilim commented 3 months ago

Alright, I've made the requested changes and added a test!

github-actions[bot] commented 1 month ago

:tada: Released In 1.0.0-rc.4 :tada:

Thank you everyone for the contribution! This feature is now available in the latest release. Now is a good time to upgrade! Your participation is what makes us unique; your adoption is what drives us forward. You can support SeaQL šŸŒŠ by starring our repos, sharing our libraries and becoming a sponsor ā­.