Skip to content

Instantly share code, notes, and snippets.

@7u4
Forked from yahorbarkouski/PGVectorBinding.kt
Created January 31, 2024 03:14
Show Gist options
  • Save 7u4/92719d6a72fa2f84c2e4a1e1f188938d to your computer and use it in GitHub Desktop.
Save 7u4/92719d6a72fa2f84c2e4a1e1f188938d to your computer and use it in GitHub Desktop.
Binding pgvector::vector type to List<Double> using jOOQ
import org.jooq.*
import org.jooq.impl.DSL
import java.sql.SQLFeatureNotSupportedException
import java.sql.Types
@Suppress("UNCHECKED_CAST")
class PGVectorBinding : Binding<Any, List<Double>> {
override fun converter(): Converter<Any, List<Double>> {
return object : Converter<Any, List<Double>> {
override fun from(databaseObject: Any?): List<Double> {
return databaseObject?.let { v ->
v.toString().removeSurrounding("[", "]").split(",").map { it.toDouble() }
} ?: emptyList()
}
override fun to(userObject: List<Double>): Any {
return userObject.toString()
}
override fun fromType(): Class<Any> = Any::class.java
override fun toType(): Class<List<Double>> = List::class.java as Class<List<Double>>
}
}
override fun sql(ctx: BindingSQLContext<List<Double>>) {
ctx.render().visit(DSL.`val`(ctx.convert(converter()).value())).sql("::vector")
}
override fun register(ctx: BindingRegisterContext<List<Double>>) {
ctx.statement().registerOutParameter(ctx.index(), Types.ARRAY)
}
override fun get(ctx: BindingGetResultSetContext<List<Double>>) {
val resultSet = ctx.resultSet()
val vectorAsString = resultSet.getString(ctx.index())
ctx.value(converter().from(vectorAsString))
}
override fun set(ctx: BindingSetStatementContext<List<Double>>) {
val value = ctx.value()
ctx.statement().setString(ctx.index(), value?.let { converter().to(it) as String } ?: "[]")
}
override fun get(ctx: BindingGetStatementContext<List<Double>>) {
val statement = ctx.statement()
val vectorAsString = statement.getString(ctx.index())
ctx.value(converter().from(vectorAsString))
}
// the below methods aren't needed in Postgres:
override fun get(ctx: BindingGetSQLInputContext<List<Double>>?) {
throw SQLFeatureNotSupportedException()
}
override fun set(ctx: BindingSetSQLOutputContext<List<Double>>?) {
throw SQLFeatureNotSupportedException()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment