Skip to content

Instantly share code, notes, and snippets.

@cheptsov
Created July 23, 2013 09:08
Show Gist options
  • Save cheptsov/6061029 to your computer and use it in GitHub Desktop.
Save cheptsov/6061029 to your computer and use it in GitHub Desktop.
Type-safe database table declaration using Kotlin language and Expose library
object Users : Table() {
val id = varchar("id", ColumnType.PRIMARY_KEY, length = 10) // PKColumn<String>
val name = varchar("name", length = 50) // Column<String>
val cityId = integer("city_id", ColumnType.NULLABLE, references = Cities.id) // Column<Int?>
val all = id + name + cityId // Column3<String, String, Int?>
}
object Cities : Table() {
val id = integer("id", ColumnType.PRIMARY_KEY, autoIncrement = true) // PKColumn<Int>
val name = varchar("name", 50) // Column<String>
val all = id + name // Column2<Int, String>
}
@cheptsov
Copy link
Author

fun main(args: Array) {
var db = Database("jdbc:h2:mem:test", driver = "org.h2.Driver")
db.withSession {
create (Cities, Users)
}
}

Generates:

CREATE TABLE Cities (id INT PRIMARY KEY AUTO_INCREMENT NOT NULL, name VARCHAR(50) NOT NULL)
CREATE TABLE Users (id VARCHAR(10) PRIMARY KEY NOT NULL, name VARCHAR(50) NOT NULL, city_id INT NULL)

@cheptsov
Copy link
Author

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