Skip to content

Instantly share code, notes, and snippets.

fun findAllBy(articleId: ArticleId): List<Comment>
// or
fun findAllByPaged(articleId: ArticleId, pageRequest: PageRequest): Page<Comment>
fun Iterable<ResultRow>.toArticles(): List<Article> {
return fold(mutableMapOf<ArticleId, Article>()) { map, resultRow ->
val article = resultRow.toArticle()
val tagId = resultRow.tryGet(ArticleTagTable.tagId)
val tag = tagId?.let { resultRow.toTag() }
val current = map.getOrDefault(article.id, article)
map[article.id] = current.copy(tags = current.tags + listOfNotNull(tag))
map
}.values.toList()
}
val ArticleWithTags = (ArticleTable leftJoin ArticleTagTable leftJoin TagTable)
override fun findBy(articleId: ArticleId) =
ArticleWithTags
.select { ArticleTable.id eq articleId }
.toArticles()
.singleOrNull()
override fun create(article: Article): Article {
val savedArticle = ArticleTable.insert { it.from(article) }
.getOrThrow(ArticleTable.id)
.let { article.copy(id = it) }
savedArticle.tags.forEach { tag ->
ArticleTagTable.insert {
it[ArticleTagTable.tagId] = tag.id
it[ArticleTagTable.articleId] = savedArticle.id
}
}
object ArticleTagTable : Table("article_tags") {
val tagId = tagId("tag_id").references(TagTable.id)
val articleId = articleId("article_id").references(ArticleTable.id)
}
override fun findBy(userId: UserId) =
UserTable.select { UserTable.id eq userId }?.toUser()
sealed class UserId : RefId<Long>() {
object New : UserId() {
override val value: Long by IdNotPersistedDelegate<Long>()
}
data class Persisted(override val value: Long) : UserId() {
override fun toString() = "UserId(value=$value)"
}
}
data class User(
UserTable.select { UserTable.username eq username }?.toUser()
// or
UserTable.select { UserTable.username like username }.map { it.toUser() }
fun ResultRow.toUser() = User(
username = this[UserTable.username],
email = this[UserTable.email],
password = this[UserTable.password]
@pjagielski
pjagielski / User.kt
Last active February 11, 2019 18:15
data class User(
val username: Username,
val password: String,
val email: String
)
object UserTable : Table("users") {
val username = text("username")
val email = text("email")
val password = text("password")
(defn part [goal]
(let [time (first goal)]
(cond
(<= time 45) 1
(<= time 90) 2
(<= time 105) 3
(<= time 120) 4)))
(defn parts [time-str]
(->>