sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Cannot provide a custom default value for `#[sqlx(default = "..")]`

Open andrew-rj opened this issue 1 year ago • 1 comments

Bug Description

I apologize if what I am trying to do is not possible or if I simply misunderstand how to achieve this, but I'm trying to have certain fields of a struct use a custom default value with sqlx(default = ".."). From https://docs.rs/sqlx/latest/sqlx/trait.FromRow.html#default, it states:

but a manual Default implementation can provide different placeholder values, if applicable.

This is similar to how #[serde(default)] behaves.

When I try to reproduce with the minimal code below I get this compiler error:

error: proc-macro derive panicked
 --> src/main.rs:2:10
  |
2 | #[derive(sqlx::FromRow)]
  |          ^^^^^^^^^^^^^
  |
  = help: message: called `Result::unwrap()` on an `Err` value: Error("unexpected attribute")

Is what I'm trying to do at all possible? I can achieve what I want by manually implementing sqlx::FromRow, but it would be nice if I didn't have to do this.

Minimal Reproduction

Here is a minimal program that I think should at least compile:


#[derive(sqlx::FromRow)]
struct MyStruct {
    #[sqlx(default = "default_optional_int")]
    a: i32,
}

fn default_int() -> i32 {
    23
}

fn main() {
    println!("Hello, world!");
}

Info

  • SQLx version: 0.7.4
  • SQLx features enabled: "postgres", "runtime-tokio", "time", "uuid", "chrono", "macros"]
  • Database server and version: Postgres
  • Operating system: Mac OS
  • rustc --version: 1.78

andrew-rj avatar May 29 '24 20:05 andrew-rj

Not a bug. At no point does the documentation show that you can do this specifically.

I wouldn't be against adding it or improving the error message, though. I'll gladly accept a PR for that.

abonander avatar May 31 '24 20:05 abonander