3

I'm trying to run rust code from the postgres_types documentation.

The example code can be found here: postgres_types

my rust environment:

cargo --version cargo 1.40.0-nightly (5da4b4d47 2019-10-28)

rustc --version rustc 1.40.0-nightly (b520af6fd 2019-11-03)


main.rs

#[cfg(feature = "derive")]
use postgres_types::{ToSql, FromSql};

#[derive(Debug, ToSql, FromSql)]
enum Mood {
    Sad,
    Ok,
    Happy,
}

fn main() {
    let mood = Mood::Sad;

    println!("{:?}", mood);
}

Cargo.toml

...

[dependencies]
postgres-types = "0.1.0-alpha.1"

When I try and run with cargo run I get:

error: cannot find derive macro `ToSql` in this scope
 --> src\main.rs:4:17
  |
4 | #[derive(Debug, ToSql, FromSql)]
  |                 ^^^^^

error: cannot find derive macro `FromSql` in this scope
 --> src\main.rs:4:24
  |
4 | #[derive(Debug, ToSql, FromSql)]
  |                        ^^^^^^^

What am I doing wrong here? Clearly I'm missing something basic. Have I not imported the macro correctly?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
James Schinner
  • 1,549
  • 18
  • 28

1 Answers1

6

Quoting from the documentation,

If the derive cargo feature is enabled, you can derive ToSql and FromSql implementations for custom Postgres types.

To enable the derive feature, you'll need to put this in Cargo.toml:

[dependencies]
postgres-types = {version = "0.1.0-alpha.1", features = ["derive"]}
SCappella
  • 9,534
  • 1
  • 26
  • 35
  • Thanks, I updated the dependencies as required and I removed `#[cfg(feature = "derive")]` from main.rs and it worked! It's great that it's working, but I admit I don't completely understand the mechanism – James Schinner Nov 10 '19 at 03:22
  • @JamesSchinner You can learn more about features in the [Cargo manifest documentation](https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section). – SCappella Nov 10 '19 at 03:46
  • To complement this answer: Make sure you then import `FromSql` and `ToSql` from `postgres_types::{FromSql, ToSql};` and not the reexported version from `postgresql`. – mirosval Dec 10 '20 at 19:59