Skip to content

Instantly share code, notes, and snippets.

@tank-bohr
Created June 16, 2018 16:27
Show Gist options
  • Save tank-bohr/d07464b2146dba2a808d26cafb39c837 to your computer and use it in GitHub Desktop.
Save tank-bohr/d07464b2146dba2a808d26cafb39c837 to your computer and use it in GitHub Desktop.
import spark.Spark.*
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
fun initDb(connection: Connection) {
connection.createStatement().execute("""
CREATE TABLE adjectives(
id INT AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(255)
)
""".trimIndent())
connection.createStatement().execute("""
CREATE TABLE nouns(
id INT AUTO_INCREMENT PRIMARY KEY,
word VARCHAR(255)
)
""".trimIndent())
}
fun ResultSet.fetchAll(columnName: String): List<String> {
return ArrayList<String>().apply {
while (next()) {
add(getString(columnName))
}
}
}
fun Connection.fetchAll(table: String): List<String> {
return createStatement().executeQuery("""
SELECT * FROM ${table};
""".trimIndent()).fetchAll("word")
}
fun main(args: Array<String>) {
val connection = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "")
initDb(connection)
post("/words/:table", "application/x-www-form-urlencoded") { request, response ->
val table = request.params("table")
val word = request.queryParams("word") ?: "Хуй"
connection.prepareStatement("""
INSERT INTO ${table} SET word=?
""".trimIndent()).apply { setString(1, word) }.executeUpdate()
response.status(201)
}
get("/words/:table") { request, _response ->
val table = request.params("table")
connection.fetchAll(table).toString()
}
get("/gen") { _, _ ->
val nouns = connection.fetchAll("nouns")
val adjectives = connection.fetchAll("adjectives")
"${adjectives.shuffled().first()} ${nouns.shuffled().first()}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment