Skip to content

Support user-defined types with the query_as! and query_file_as! macros #148

Closed

Description

@mehcode

An example of what I would like to see for usage

#[derive(sqlx::Type)]
enum Role { Admin, Staff, Normal, Advisor }

#[sqlx::record] 
struct User { id: i32, name: String, role: Role }

let usr: User = sqlx::query_as!("SELECT id, name FROM user")
    .fetch_one(&mut conn).await?;
  • The #[sqlx::record] is merely saying I would be okay with requiring a proc attribute here if we need to inspect the struct and attach additional metadata to inspect later ( which I think we do )

I think this is blocked on Rust stabilizing const_panic and const_if. I can't think of another clean way to support this apart from generating a series of const _: () = { ... } blocks where we enforce the type equivalence (between the SQL result type and the given Rust type).

I'm definitely open to other suggestions though. What @abonander and I don't want though is to significantly degrade the errors.

Activity

  1. added
    enhancement
    needs rust feature
    on Mar 24, 2020
  2. mehcode commented on Mar 24, 2020

    @mehcode
    ContributorAuthor

    An idea that I just had.

    sqlx::query_as!(User {
        // field "role" is assigned the SQL result column "role"
        // and force cast to the type Role
        role: "role" as Role,
        
        // other fields are default
        ..
    },
        r#"
    SELECT
        id,
        name,
        role
    
    FROM users
    
    ORDER BY created_at DESC
    LIMIT 25
        "#,
    );

    The { ... } would become an optional block after the type name in query_as! and query_file_as!.

    This would allow:

    • Forcing the use of a specific Rust type ( assuming the proper Encode/Decode impls exist )
    • Override the Rust field name <-> SQL name mapping

    Ideally we evolve query_as! to make user-defined types, type-safe but this would make a reasonable stop gap until we can reach that.

  3. Freax13 commented on Mar 24, 2020

    @Freax13
    Contributor

    how about a derive for sqlx::FromRow? Isn't that basically what you need?

  4. mehcode commented on Mar 24, 2020

    @mehcode
    ContributorAuthor

    @Freax13 I actually just added one to master. However that would only be for query_as().

    The output verification in query_as! additionally provides:

    • Compile-time guarantees on output type with errors like expected i32; found bool.

    • Compile-time guarantees on matching column names with rust field names without the overhead of run-time column name lookup.

  5. phated commented on May 9, 2020

    @phated
    Contributor

    I just ran into this issue too. I'm experimenting with query_as_unchecked! but it doesn't quite give me the type safety I am looking for.

  6. mehcode commented on Jun 10, 2020

    @mehcode
    ContributorAuthor

    We've decided that #339 is the direction we want to go in for this for the forseeable future.

    How it will look

    sqlx::query_as!("SELECT field as "field: _" FROM table WHERE other = ?", value: _);
    

    The : _ syntax in both the column and argument position instructs the macro to do a runtime type check instead of a compile-time type equivalency check.

    Additionally you'll be able to explicitly name a user-defined type such as as "field: MyField" which will move to a compile-time check.

    At some point we want to discuss the user being able to add types to the internal type equivalency dictionaries but that's not generally possible outside of postgres so we're postponing that part for at least the near future.

  7. Pzixel commented on Apr 8, 2021

    @Pzixel

    The : _ syntax in both the column and argument position instructs the macro to do a runtime type check instead of a compile-time type equivalency check.

    Thus user defined types are not checked at runtime if I am correct? Can we still have compile-time equvalence. For example if struct is repr(u8) can we just check that this enum in db is u8? I'm not quite sure what trouble this way, could you elaborate please?

    I'm in very this situation and I'd like to see sqlx checking at compile-time that my enum is u8 but I'm setting it at u32 and similarish stuff. Maybe I can be at your help?..

  8. ngryman commented on Jul 12, 2021

    @ngryman

    Hey folks,

    Re #397 (comment) about ergonomics.

    The current solution works great to cherry pick columns (ie. query!). However, it can become pretty tedious when using query_as!. Not being able to use * anymore can make queries more verbose than necessary. This is especially true when building an ORM on top of sqlx for example.

    For instance, if I use a custom type for my user's email, the query becomes:

    -sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id);
    +sqlx::query_as!(User, r#"SELECT id, email as "email: _", username, first_name, last_name, [...] WHERE id = $1"#, id);

    What I like with the initial proposition is that it decorrelates the SQL statement from the type annotation . We can keep the SQL statement untouched while refining the types of our fields.

    If we take the example above, it would give us:

    -sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id);
    +sqlx::query_as!(User { email as Email }, "SELECT * WHERE id = $1", id);

    I believe it is easier to read and refactor.

    Would you consider introducing this notation or something similar to what @joaquindk is proposing?

  9. randomairborne commented on Dec 3, 2022

    @randomairborne

    How do you insert a custom enum? Everything i see here is about selecting one.

  10. reivilibre commented on Apr 2, 2023

    @reivilibre

    I couldn't find a way to insert a custom enum, but as a workaround: in a query! it seems to be in order to use $1::text::myenumtype in your query and then pass in a string as a bound argument.

  11. RAprogramm commented on Feb 8, 2024

    @RAprogramm

    jmoiron/sqlx#911

    can anybody help me with my issue?

    I have a problem with UPDATE query and ENUM type

  12. bastibense commented on Feb 5, 2025

    @bastibense

    It's 2025 and this is really the only itch for me with sqlx.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    blockedenhancementmacrosneeds rust feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions