1

<Hi I have Postgres table:

CREATE TABLE persons (
  id SERIAL NOT NULL PRIMARY KEY,
  age INT NOT NULL,
  sex CHAR(1)
);

Where sex can be char 'M' or 'F' or null. Unfortunately, migration sex column to postgres enum is not possible in this case.

I am using rust sqlx to load data from this table. I have:

#[derive(sqlx::FromRow)]
pub struct PersonSql {
  pub age: int,
  pub sex: Option<String>, // TODO improve it
}

Everything works perfectly, but I am afraid that using String type is not the most efficient. It would be nice to Option<char>, enum Option<Sex>, or at least Option<&str>, I tried to use enum like:

#[derive(Copy, Clone, sqlx::Type, Debug)]
#[sqlx(type_name = "VARCHAR")]
pub enum Sex {
  F,
  M,
}

compilation is ok, but error is returned when I run app:

mismatched types; Rust type core::option::Option<app::Sex> (as SQL type VARCHAR) is not compatible with SQL type CHAR',

cafce25
  • 15,907
  • 4
  • 25
  • 31
  • you can create an enum: https://docs.rs/sqlx/latest/sqlx/types/trait.Type.html#enumeration – belst Dec 26 '22 at 14:26
  • I tried, but i returns error: mismatched types; Rust type core::option::Option (as SQL type VARCHAR) is not compatible with SQL type CHAR', – billy voiderer Dec 26 '22 at 15:21

0 Answers0