Rust Diesel sql_types::Binary to Vec<u8>

Viewed 34

I am trying to read and write a byte array from from a postgres database using Diesel.

the schema is like so:

table! {
    data_table (id) {
        id -> Int4,
        data_name -> Nullable<Text>,
        data_bytes -> Nullable<Bytea>,
    }
}

The model is as follows:

#[derive(Queryable)]
pub struct DataItem {
    pub id: i32,
    pub data_name: String,
    pub data_bytes: Vec<u8>,
}

use super::schema::data_table;

#[derive(Insertable)]
#[table_name="data_table"]
pub struct NewDataItem {

    pub data_name: String,
    pub data_bytes: Vec<u8>,
}

The unit tests are:

#[test]
fn write_data() {
    let conn = establish_connection();
    let data_name = String::from("test");
    let data_bytes = rand::thread_rng().gen::<[u8; 32]>().to_vec();
    let new_data_item = NewDataItem  { data_name, data_bytes };

    diesel::insert_into(data_table::table)
        .values(&new_data_item)
        .execute(&conn)
        .expect("Error saving data");
}
#[test]
fn read_data() {
    let conn = establish_connection();
    let results = data_table.filter(data_name.eq("test"))
        .limit(5)
        .load::<DataItem>(&conn)
        .expect("Error reading data");
}

The write_data data test works as expected yet when adding the read_data test I see the following errors which are difficult to understand the origin of and find answers for in existing posts:

error[E0277]: the trait bound `*const str: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not satisfied
    --> src/tests.rs:36:10
     |
36   |         .load::<DataItem>(&conn)
     |          ^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Text>, _>` is not implemented for `*const str`
error[E0277]: the trait bound `*const [u8]: FromSql<diesel::sql_types::Nullable<diesel::sql_types::Binary>, _>` is not satisfied
    --> src/tests.rs:36:10
     |
36   |         .load::<DataItem>(&conn)
     |          ^^^^ the trait `FromSql<diesel::sql_types::Nullable<diesel::sql_types::Binary>, _>` is not implemented for `*const [u8]`

I presume I'm missing a reference to allocated the trait to the field? e.g. sql_type="Binary"?

Guidance gratefully received

Sincerely Simon

1 Answers

The crux of this issue is the use of Nullable<T>.

In my case I made the following changes:

up.sql:

CREATE TABLE data_table (
  id SERIAL PRIMARY KEY,
  data_name text NOT NULL,
  data_bytes bytea  NOT NULL
);

schema.rs

table! {
    data_table (id) {
        id -> Int4,
        data_name -> Text,
        data_bytes -> Bytea,
    }
}

There is also the option to change the model to be compatible with a change to the model.rs:

#[derive(Queryable)]
pub struct DataItem {
    pub id: i32,
    pub data_name: Option<String>,
    pub data_bytes: Option<Vec<u8>>,
}

The model vs schema changes are mutually exclusive and the former change more appropriate to my instance

Related