New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom types questions #1288

Closed
abhikp opened this Issue Nov 1, 2017 · 1 comment

Comments

Projects
None yet
3 participants
@abhikp

abhikp commented Nov 1, 2017

Hi! I'm starting to write some custom types and had a few questions:

  1. Diesel supports serde_json::Value attributes for DB's that support JSON columns. I'm using SQLite, so I'll have to serialize and deserialize to a TEXT column. Is there a way to use what Diesel has already implemented for JSON columns or will I need to write something from scratch?
  2. Can a custom type map to multiple SQL columns (trying to store a 4x4 matrix in SQLite)? If so, is there an example somewhere?

Thanks for your help!

@weiznich weiznich added the question label Nov 7, 2017

@weiznich

This comment has been minimized.

Contributor

weiznich commented Nov 7, 2017

  1. Diesel supports serde_json::Value attributes for DB's that support JSON columns. I'm using SQLite, so I'll have to serialize and deserialize to a TEXT column. Is there a way to use what Diesel has already implemented for JSON columns or will I need to write something from scratch?

It is generally possible to reuse type conversions that diesel already implements. For example if you want to map the values of an enum to integer values you could implement ToSql in the following way:

enum MyEnum {
     A = 1,
     B = 2,
}

impl<DB: Backend> ToSql<SmallInt, DB> for MyEnum {
    fn to_sql<W: Write>(&self, out: &mut ToSqlOutput<W, DB>) -> Result<IsNull, Box<Error + Send + Sync>> {
        match *self {
            MyEnum::A => <i16 as ToSql<SmallInt, DB>>::to_sql(&1, out),
            MyEnum::B => <i16 as ToSql<SmallInt, DB>>::to_sql(&2, out),
        } 
    }
}

(FromSql::from_sql could be implemented in a similar way)

Unfortunately it is not possible to implement this straightforward for serde_json::Value outside of diesel, because of the orphan rules preventing impl's for foreign types and foreign traits. This could by solved by using a local wrapper type. Furthermore all implements for serde_json::Value are mapping this type to a underlying database json type. For me it seems like a better solution to manually transform the serde_json::Value to a string first and then insert this string into sqlite.

  1. Can a custom type map to multiple SQL columns (trying to store a 4x4 matrix in SQLite)? If so, is there an example somewhere?

I think this is currently not possible, but I may be wrong about it.

@sgrif sgrif closed this Jan 8, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment