2

We have a project where we use a Postgres sequence for generating an increasing number, but I cannot figure out how to actually use the sequence in kotlin exposed.

I see there is a Sequence class and a NextVal class encapsulating a sequence but those cannot be used by its own as far as I can see. I thought I could use Sequence.nextLongVal() but this one returns the NextVal class, no way to get the through value out of this one.

So how can I get the value of the nextVal() execution?

1 Answers1

1

We stumbled across the same problem trying to utilize Sequence.nextLongVal() directly using Postgre and exposed. We found the following workaround.

A solution using exec

Assuming we have defined and created a sequence in our datasource:

val sequence = Sequence(/* our sequence's parameters */)

...

transaction {
    SchemaUtils.createSequence(sequence)
}

We suggest to define a helper function to retrieve the next value of a given sequence using exposed's 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}'")

Now, we can use this function in a transaction as shown here:

transaction { 
    ...

    val nextValue = nextValueOf(sequence) 

    ...
}
imhanner
  • 11
  • 1