Last active
July 10, 2024 01:26
-
-
Save yahorbarkouski/bcfbf2bf1b10ff7757f2c629eab33a46 to your computer and use it in GitHub Desktop.
Binding pgvector::vector type to List<Double> using jOOQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
In the case that
I got much better memory usage from the following