【问题标题】:How can I call a sequence.nextVal using kotlin exposed如何使用暴露的 kotlin 调用 sequence.nextVal
【发布时间】:2020-11-25 09:46:05
【问题描述】:
我们有一个项目,我们使用 Postgres 序列来生成递增的数字,但我不知道如何在暴露的 kotlin 中实际使用该序列。
我看到有一个 Sequence 类和一个 NextVal 类封装了一个序列,但据我所知,它们不能自己使用。我以为我可以使用 Sequence.nextLongVal() 但是这个返回 NextVal 类,没有办法从这个中获取 through 值。
那么如何获取 nextVal() 执行的值呢?
【问题讨论】:
标签:
kotlin
kotlin-exposed
【解决方案1】:
我们在尝试使用 Postgre 直接使用 Sequence.nextLongVal() 时偶然发现了同样的问题并暴露了。我们找到了以下解决方法。
使用exec的解决方案
假设我们在数据源中定义并创建了一个序列:
val sequence = Sequence(/* our sequence's parameters */)
...
transaction {
SchemaUtils.createSequence(sequence)
}
我们建议使用暴露的exec 定义一个辅助函数来检索给定序列的下一个值。
fun Transaction.nextValueOf(sequence: Sequence): Long = exec("SELECT nextval('${sequence.identifier}');") { resultSet ->
if (resultSet.next().not()) {
throw Error("Missing nextValue in resultSet of sequence '${sequence.identifier}'")
}
else {
resultSet.getLong(1)
}
} ?: throw Error("Unable to get nextValue of sequence '${sequence.identifier}'")
现在,我们可以在transaction 中使用这个函数,如下所示:
transaction {
...
val nextValue = nextValueOf(sequence)
...
}