You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support user-defined types with the query_as! and query_file_as! macros #148
#[derive(sqlx::Type)]enumRole{Admin,Staff,Normal,Advisor}#[sqlx::record]structUser{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.
Reacted by sigod, shekohex, Joe Grund, Nicolas Bourras, Martin Charles, Smit, Longsueynin, Nicolas Gryman, webmstk, BigWebCat and 10 more
sqlx::query_as!(User{// field "role" is assigned the SQL result column "role"// and force cast to the type Role
role:"role"asRole,// other fields are default
..
},r#"SELECT id, name, roleFROM usersORDER BY created_at DESCLIMIT 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.
Reacted by Nicolas Gryman, webmstk and Ben Richeson
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.
Reacted by Cheban Oleksii, spiffytech, John, Anton Solovyev, kanpov, belowm and dzmitry-lahoda
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?..
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?
Reacted by Max Countryman, jayrave, webmstk, Wiley McKay Conte, Oyelowo, teenjuna, unbyte, Maxim Matyunin, damccull, Ivan Chinenov and 23 more
How do you insert a custom enum? Everything i see here is about selecting one.
Reacted by Tolumide Shopein, Jarrad Littleford, Luis Roel, Brandon Stilson, Zack Mitkin, Alexander Polakov, Olivier 'reivilibre', nfedyashev, Baris Idemen, Kirill and 2 more
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.
Activity
mehcode commentedon Mar 24, 2020
An idea that I just had.
The
{ ... }would become an optional block after the type name inquery_as!andquery_file_as!.This would allow:
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.Freax13 commentedon Mar 24, 2020
how about a derive for
sqlx::FromRow? Isn't that basically what you need?mehcode commentedon Mar 24, 2020
@Freax13 I actually just added one to
master. However that would only be forquery_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.
phated commentedon May 9, 2020
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.mehcode commentedon Jun 10, 2020
We've decided that #339 is the direction we want to go in for this for the forseeable future.
How it will look
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.
Pzixel commentedon Apr 8, 2021
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 isu8? 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
sqlxchecking at compile-time that my enum isu8but I'm setting it atu32and similarish stuff. Maybe I can be at your help?..ngryman commentedon Jul 12, 2021
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 usingquery_as!. Not being able to use*anymore can make queries more verbose than necessary. This is especially true when building an ORM on top ofsqlxfor example.For instance, if I use a custom type for my user's email, the query becomes:
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:
I believe it is easier to read and refactor.
Would you consider introducing this notation or something similar to what @joaquindk is proposing?
randomairborne commentedon Dec 3, 2022
How do you insert a custom enum? Everything i see here is about selecting one.
reivilibre commentedon Apr 2, 2023
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::myenumtypein your query and then pass in a string as a bound argument.constantingoeldel commentedon Apr 15, 2023
For insertion, see this: https://users.rust-lang.org/t/sqlx-postgres-how-to-insert-a-enum-value/53044
RAprogramm commentedon Feb 8, 2024
jmoiron/sqlx#911
can anybody help me with my issue?
I have a problem with UPDATE query and ENUM type
bastibense commentedon Feb 5, 2025
It's 2025 and this is really the only itch for me with sqlx.