Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add method for retrieiving column names #2148

Merged
merged 2 commits into from
Apr 17, 2024

Conversation

jharrilim
Copy link
Contributor

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

  • I've considered using sqlx directly, but I can't map the inner types to rust types easily Export PgType launchbadge/sqlx#1369, and that seems to be covered in sea-orm.

  • My current implementation is really basic. 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.

  • I wasn't too sure how to write and execute tests for this. I had initially wrote one in the query.rs file like:

    #[cfg(feature = "sqlx-dep")]
    #[test]
    fn column_names_from_query_result() {
        let mut values = BTreeMap::new();
        values.insert("id", Value::Int(Some(1)));
        values.insert("name", Value::String(Some("Abc".to_owned())));
        let query_result = QueryResult {
            row: QueryResultRow::Mock(crate::MockRow { values }),
        };
        assert_eq!(
            query_result.columns(),
            vec!["id".to_owned(), "name".to_owned()]
        );
    }

    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`. Maybe there's a better way?


New Features

  • Adds a method for retrieving column names from a query result

Breaking Changes

  • None

@@ -115,6 +115,27 @@ impl QueryResult {
{
Ok(T::try_get_many_by_index(self)?)
}

/// Gets all column names in the order they were written.
#[cfg(feature = "sqlx-dep")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if we move this line to directly above use sqlx::Column, this can still compile?

@tyt2y3
Copy link
Member

tyt2y3 commented Mar 11, 2024

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
Copy link
Member

tyt2y3 commented Mar 11, 2024

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
Copy link
Contributor Author

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

@jharrilim jharrilim requested a review from tyt2y3 March 13, 2024 14:46
Copy link
Member

@tyt2y3 tyt2y3 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work, thanks!

@tyt2y3 tyt2y3 merged commit c724ec5 into SeaQL:master Apr 17, 2024
33 checks passed
Copy link

github-actions bot commented May 3, 2024

🎉 Released In 1.0.0-rc.4 🎉

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 ⭐.

Copy link

github-actions bot commented Aug 4, 2024

🎉 Released In 1.0.0 🎉

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 ⭐.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants