What is a good way to keep the SQL queries in a Rust application that uses sqlx?

At the moment I have my SQL queries as a multiline string in my Rust files.

        let sql = r#"
            SELECT
                *
            FROM
                public.users
            WHERE
                "email" = $1
        "#;

        let user = match sqlx::query_as::<Postgres, User>(sql)...

Due to indentation the queries have a lot of whitespaces in them.

Is this a problem? having all this extra whitespace sent to the SQL server over and over again?

Is there any better way of keeping the SQL? or some SQL builder that would allow to have the code nice and will generate the SQL more compact and without all those extra whitespaces?

To be fair to volunteers answering your questions, please make sure to indicate cross posts in order to spare them any unnecessary duplicate effort.

Nope. For such small pieces of data, latency is a much bigger problem (==orders of magnitude slower) than throughput. If your ping time is, say, 25ms, then any amount of data that takes less than a couple of ms to transmit (not counting latency) will be insignificant.

2 Likes

Here's how I structured (some of) my database library, I'm leaving stuff like migrations out:

$ tree libs/db
libs/db/
├── Cargo.toml
└── src
    ├── lib.rs
    └── query
        ├── <stuff>
        │   ├── current.sql
        │   ├── delete.sql
        │   ├── insert.sql
        │   ├── starting_before.sql
        │   └── within_range.sql
        ├── init.sql
        ├── <foo>
        │   ├── current_state.sql
        │   ├── insert.sql
        │   └── by_id.sql
        └── <bar>
            ├── all.sql
            ├── by_id.sql
            └── insert.sql

The SQL queries are in .sql files. And I include_str! them in my code.

sqlx::query(include_str!("query/stuff/insert.sql").bind(stuff).execute(e)

This way I can format the queries however I want, while not having a different language in the middle of my Rust code.

And absolutely don't worry about whitespace in your SQL.

3 Likes

I like this. Thanks.

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.