How do you implement Table Inheritance in Kotlin Exposed?

1.2k views Asked by At

Example:

I have a base table called Pet with a BirthDate and Name columns.

I have a two more tables that derive from that table, one called PetDog table with column NumberOfTeeth and another called PetBird table with column BeakColor.

How to implement this using Kotlin Exposed? https://github.com/JetBrains/Exposed

Or is there any documentation on this available?

1

There are 1 answers

2
Freek de Bruijn On

What sort of database and schema do you have in mind? How does it support table inheritance? As Михаил Нафталь already mentioned in the comment, a common approach with a relational database would be to either use one table with all columns or two tables (pet and dog, with some way to link the records in both tables to each other).

A simple example with two tables:

create table pet (id int auto_increment primary key, birthdate varchar(10) not null, "name" varchar(50) not null)
create table dog (id int auto_increment primary key, pet_id int not null, number_of_teeth int not null, constraint fk_dog_pet_id_id foreign key (pet_id) references pet(id) on delete restrict on update restrict)

Your Exposed table definition code could then look something like this:

object Pet : IntIdTable() {
    val birthdate = varchar("birthdate", 10)
    val name = varchar("name", 50)
}

object Dog : IntIdTable() {
    val petId = reference("pet_id", Pet).nullable()
    val numberOfTeeth = integer("number_of_teeth")
}