Single Table Inheritance

Hi all ! I have the following schema and structs. I would like to get a Vec<Question> from a query. It doesn’t seem possible with Diesel but I’m maybe missing something? Also, is there a better architecture for this kind of schema, which respect the Diesel-way to do things ?

create type question_type as enum ('text', 'image');

create table "questions" (
    id uuid primary key not null,
    type question_type not null,
    label text,
    image_url text    
)
enum Question {
    TextQuestion(TextQuestion),
    ImageQuestion(ImageQuestion),
}

struct QuestionBase {
    id: String,

    // other fields ...
}

struct TextQuestion {
    base: QuestionBase,
    label: String,

    // other fields ...
}

struct ImageQuestion {
    base: QuestionBase,
    image_url: String,

    // other fields ...
}

It is certainly possible to implement such a behavior with diesel, but I wouldn’t consider this as idiomatic database code.

As for the implementation:

  • You need to implement a custom sql type mapping for your enum (question_type). See here for an example.
  • You need to provide a custom Queryable impl for your Question enum implementing your desired mapping there.

Perfect, thanks @weiznich!