diff --git a/vertx-pg-client/pom.xml b/vertx-pg-client/pom.xml index 1949b36271..88f629a259 100644 --- a/vertx-pg-client/pom.xml +++ b/vertx-pg-client/pom.xml @@ -135,6 +135,7 @@ test_user test_password require + true diff --git a/vertx-pg-client/src/main/asciidoc/index.adoc b/vertx-pg-client/src/main/asciidoc/index.adoc index 309e95cec0..5374bdc507 100644 --- a/vertx-pg-client/src/main/asciidoc/index.adoc +++ b/vertx-pg-client/src/main/asciidoc/index.adoc @@ -172,6 +172,15 @@ For example, you can set a default schema for the connection with adding a `sear More information about the available properties can be found in the https://www.postgresql.org/docs/current/runtime-config-client.html[PostgreSQL Manuals]. +The https://github.com/pgvector/pgvector[`pgvector`] types are enabled with the `vectorTypeEnabled` option (default `false`), see <<_handling_vectors_>>. +This option can also be set with the `vector_type_enabled` parameter of a <<_connection_uri>>. + +[source,$lang] +---- +{@link examples.PgClientExamples#configureVectorType()} +---- + +[#_connection_uri] === Connection URI Apart from configuring with a `PgConnectOptions` data object, We also provide you an alternative way to connect when you want to configure with a connection URI: @@ -196,6 +205,7 @@ Currently, the client supports the following parameter keys: * `sslmode` * `sslnegotiation` * `channel_binding` +* `vector_type_enabled` Additional parameters will be added to the {@link io.vertx.sqlclient.SqlConnectOptions#getProperties properties}. @@ -216,6 +226,7 @@ for more details. The following parameters are supported: * `PGSSLMODE` * `PGSSLNEGOTIATION` * `PGCHANNELBINDING` +* `PGVECTORTYPEENABLED` If you don't specify a data object or a connection URI string to connect, environment variables will take precedence over them. @@ -473,6 +484,21 @@ Currently the client supports the following PostgreSQL types: | `io.vertx.pgclient.data.Money[]` | +| `VECTOR` +| `io.vertx.sqlclient.data.FloatVector` +| +| Requires the `pgvector` extension and the `vectorTypeEnabled` option + +| `HALFVEC` +| `io.vertx.sqlclient.data.HalfFloatVector` +| +| Requires the `pgvector` extension and the `vectorTypeEnabled` option + +| `SPARSEVEC` +| `io.vertx.sqlclient.data.SparseFloatVector` +| +| Requires the `pgvector` extension and the `vectorTypeEnabled` option + | `UNKNOWN` | `java.lang.String` | `java.lang.String[]` @@ -518,6 +544,59 @@ The {@link io.vertx.sqlclient.data.Numeric} Java type is used to represent the P {@link examples.PgClientExamples#numericExample} ---- +=== Handling vectors + +The https://github.com/pgvector/pgvector[`pgvector`] extension types are represented by the following Java types: + +[cols="<2,<3", options="header"] +|=== +| PostgreSQL Type | Java Type + +| `vector` +| {@link io.vertx.sqlclient.data.FloatVector} + +| `halfvec` +| {@link io.vertx.sqlclient.data.HalfFloatVector} + +| `sparsevec` +| {@link io.vertx.sqlclient.data.SparseFloatVector} +|=== + +Each type is supported independently: a type that is not found in the database is unavailable, the other ones can be used. + +The OIDs of the `pgvector` types are assigned when the extension is created, they cannot be known in advance. +When the `vectorTypeEnabled` option is set to `true`, the client discovers them with a single query executed when each connection is initialized. +Only the types that are members of the `pgvector` extension are considered. + +When the option is `false` (the default), or when a `pgvector` type is not found in the database, values of this type are decoded as `String` with the text protocol, and binding a vector parameter fails. + +[source,$lang] +---- +{@link examples.PgClientExamples#vectorExample} +---- + +The `halfvec` type stores half precision floats: values of a {@link io.vertx.sqlclient.data.HalfFloatVector} are converted to half precision when they are sent to the database, which is a lossy operation. + +A {@link io.vertx.sqlclient.data.SparseFloatVector} holds the total number of dimensions, the zero based indices of the non-zero components and their values. + +[source,$lang] +---- +{@link examples.PgClientExamples#halfVectorAndSparseVectorExample} +---- + +[#_bit_strings] +==== Bit strings + +`BIT` and `VARBIT` values keep being decoded as `String` with the text protocol. +With the binary protocol they are decoded as a `io.vertx.core.buffer.Buffer` holding the raw value: a big endian 32 bits bit length followed by the packed bits. + +A {@link io.vertx.sqlclient.data.BitVector} can be obtained from both representations with `Row#get(Class, int)`, it is primarily useful to exchange binary vectors with other databases. + +[source,$lang] +---- +{@link examples.PgClientExamples#bitVectorExample} +---- + === Unsupported types The following types are not currently supported: @@ -527,10 +606,10 @@ The following types are not currently supported: | Type | Notes | `BIT` -| Not implemented +| Decoded as `String` (text protocol) or `Buffer` (binary protocol), see <<_bit_strings>>. `Row#get(BitVector.class, ...)` is available | `VARBIT` -| Not implemented +| Decoded as `String` (text protocol) or `Buffer` (binary protocol), see <<_bit_strings>>. `Row#get(BitVector.class, ...)` is available | `MACADDR` | Not implemented diff --git a/vertx-pg-client/src/main/java/examples/PgClientExamples.java b/vertx-pg-client/src/main/java/examples/PgClientExamples.java index 48136ad157..e07b927ccf 100644 --- a/vertx-pg-client/src/main/java/examples/PgClientExamples.java +++ b/vertx-pg-client/src/main/java/examples/PgClientExamples.java @@ -21,7 +21,7 @@ import io.vertx.pgclient.*; import io.vertx.pgclient.pubsub.PgSubscriber; import io.vertx.sqlclient.*; -import io.vertx.sqlclient.data.Numeric; +import io.vertx.sqlclient.data.*; import java.math.BigDecimal; import java.time.LocalDate; @@ -125,6 +125,16 @@ public void configureDefaultSchema() { connectOptions.setProperties(props); } + public void configureVectorType() { + PgConnectOptions connectOptions = new PgConnectOptions() + .setHost("localhost") + .setDatabase("mydb") + .setUser("user") + .setPassword("secret") + // Discover the pgvector types when a connection is initialized + .setVectorTypeEnabled(true); + } + public void configureFromUri(Vertx vertx) { // Connection URI @@ -611,6 +621,44 @@ public void numericExample(Row row) { } } + public void vectorExample(SqlClient client) { + // Binding a vector parameter + client + .preparedQuery("INSERT INTO items (embedding) VALUES ($1)") + .execute(Tuple.of(FloatVector.create(new float[]{0.1f, 0.2f, 0.3f}))) + .onComplete(ar -> { + // Reading a vector + client + .preparedQuery("SELECT embedding FROM items ORDER BY embedding <-> $1 LIMIT 5") + .execute(Tuple.of(FloatVector.create("[0.1,0.2,0.3]"))) + .onComplete(ar2 -> { + if (ar2.succeeded()) { + for (Row row : ar2.result()) { + FloatVector vector = row.get(FloatVector.class, 0); + float[] components = vector.toFloatArray(); + } + } + }); + }); + } + + public void halfVectorAndSparseVectorExample(Row row) { + // halfvec + HalfFloatVector halfVector = row.get(HalfFloatVector.class, 0); + // sparsevec + SparseFloatVector sparseVector = row.get(SparseFloatVector.class, 1); + int dimension = sparseVector.dimension(); + // Zero based positions and values of the non zero components + int[] indices = sparseVector.indices(); + float[] values = sparseVector.values(); + } + + public void bitVectorExample(Row row) { + // bit and varbit values are decoded as String (text protocol) or Buffer (binary protocol) + BitVector bits = row.get(BitVector.class, 0); + boolean[] flags = bits.toBooleanArray(); + } + public void arrayExample() { // Create a tuple with a single array Tuple tuple = Tuple.of(new String[]{ "a", "tuple", "with", "arrays" }); diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/PgConnectOptions.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/PgConnectOptions.java index 520535a8b1..6d500bc78e 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/PgConnectOptions.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/PgConnectOptions.java @@ -102,6 +102,9 @@ public static PgConnectOptions fromEnv() { if (getenv("PGCHANNELBINDING") != null) { pgConnectOptions.setChannelBinding(ChannelBinding.of(getenv("PGCHANNELBINDING"))); } + if (getenv("PGVECTORTYPEENABLED") != null) { + pgConnectOptions.setVectorTypeEnabled(Boolean.parseBoolean(getenv("PGVECTORTYPEENABLED"))); + } return pgConnectOptions; } @@ -115,6 +118,7 @@ public static PgConnectOptions fromEnv() { public static final SslNegotiation DEFAULT_SSL_NEGOTIATION = SslNegotiation.POSTGRES; public static final ChannelBinding DEFAULT_CHANNEL_BINDING = ChannelBinding.PREFER; public static final boolean DEFAULT_USE_LAYER_7_PROXY = false; + public static final boolean DEFAULT_VECTOR_TYPE_ENABLED = false; public static final Map DEFAULT_PROPERTIES; static { @@ -131,6 +135,7 @@ public static PgConnectOptions fromEnv() { private SslNegotiation sslNegotiation = DEFAULT_SSL_NEGOTIATION; private ChannelBinding channelBinding = DEFAULT_CHANNEL_BINDING; private boolean useLayer7Proxy = DEFAULT_USE_LAYER_7_PROXY; + private boolean vectorTypeEnabled = DEFAULT_VECTOR_TYPE_ENABLED; public PgConnectOptions() { super(); @@ -149,6 +154,7 @@ public PgConnectOptions(SqlConnectOptions other) { sslMode = opts.sslMode; sslNegotiation = opts.sslNegotiation; channelBinding = opts.channelBinding; + vectorTypeEnabled = opts.vectorTypeEnabled; } } @@ -158,6 +164,7 @@ public PgConnectOptions(PgConnectOptions other) { sslMode = other.sslMode; sslNegotiation = other.sslNegotiation; channelBinding = other.channelBinding; + vectorTypeEnabled = other.vectorTypeEnabled; } @Override @@ -304,6 +311,28 @@ public PgConnectOptions setUseLayer7Proxy(boolean useLayer7Proxy) { return this; } + /** + * @return whether the pgvector types ({@code vector}, {@code halfvec} and {@code sparsevec}) are enabled + */ + public boolean isVectorTypeEnabled() { + return vectorTypeEnabled; + } + + /** + * Enable the support of the pgvector types ({@code vector}, {@code halfvec} and {@code sparsevec}). + *

+ * When enabled, the object identifiers of the pgvector types are discovered with a query executed once + * when a connection is initialized. A pgvector type that is not found in the database is not available and + * a warning is logged, the connection is not otherwise affected. + * + * @param vectorTypeEnabled whether the pgvector types are enabled + * @return a reference to this, so the API can be used fluently + */ + public PgConnectOptions setVectorTypeEnabled(boolean vectorTypeEnabled) { + this.vectorTypeEnabled = vectorTypeEnabled; + return this; + } + @Override public PgConnectOptions setReconnectAttempts(int attempts) { return (PgConnectOptions)super.setReconnectAttempts(attempts); @@ -368,6 +397,7 @@ public boolean equals(Object o) { if (sslMode != that.sslMode) return false; if (sslNegotiation != that.sslNegotiation) return false; if (channelBinding != that.channelBinding) return false; + if (vectorTypeEnabled != that.vectorTypeEnabled) return false; return true; } @@ -379,6 +409,7 @@ public int hashCode() { result = 31 * result + sslMode.hashCode(); result = 31 * result + sslNegotiation.hashCode(); result = 31 * result + channelBinding.hashCode(); + result = 31 * result + (vectorTypeEnabled ? 1 : 0); return result; } diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgConnectionUriParser.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgConnectionUriParser.java index 32848693af..f327b591f1 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgConnectionUriParser.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgConnectionUriParser.java @@ -187,6 +187,9 @@ private static void parseParameters(String parametersInfo, JsonObject configurat case "channel_binding": configuration.put("channelBinding", ChannelBinding.of(value)); break; + case "vector_type_enabled": + configuration.put("vectorTypeEnabled", parseBoolean(key, value)); + break; default: properties.put(key, value); break; @@ -198,6 +201,15 @@ private static void parseParameters(String parametersInfo, JsonObject configurat } } + private static boolean parseBoolean(String key, String value) { + if (value.equalsIgnoreCase("true")) { + return true; + } else if (value.equalsIgnoreCase("false")) { + return false; + } + throw new IllegalArgumentException("The parameter " + key + " must be true or false"); + } + private static void parseNetLocationValue(String hostValue, JsonObject configuration) { if (isRegardedAsIpv6Address(hostValue)) { configuration.put("host", hostValue.substring(1, hostValue.length() - 1)); diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgRow.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgRow.java index 04a3ef7063..fca74f8176 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgRow.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgRow.java @@ -21,7 +21,7 @@ import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.pgclient.data.*; -import io.vertx.sqlclient.data.Numeric; +import io.vertx.sqlclient.data.*; import io.vertx.sqlclient.impl.RowBase; import io.vertx.sqlclient.internal.RowDescriptorBase; @@ -152,6 +152,10 @@ public T get(Class type, int position) { return type.cast(getCircle(position)); } else if (type == Box.class) { return type.cast(getBox(position)); + } else if (type == FloatVector.class || type == HalfFloatVector.class || type == SparseFloatVector.class) { + return type.cast(getValue(position)); + } else if (type == BitVector.class) { + return type.cast(getBitVector(position)); } else if (type == JsonObject.class) { return type.cast(getJson(position)); } else if (type == JsonArray.class) { @@ -165,6 +169,24 @@ public T get(Class type, int position) { throw new UnsupportedOperationException("Unsupported type " + type.getName()); } + /** + * Convert a {@code bit} / {@code varbit} value, a {@code String} when the value is decoded from the text format, + * a {@code Buffer} holding the {@code int32} bit length followed by the packed bits when the value is decoded + * from the binary format. + */ + private BitVector getBitVector(int pos) { + Object val = getValue(pos); + if (val == null || val instanceof BitVector) { + return (BitVector) val; + } else if (val instanceof String) { + return BitVector.create((String) val); + } else if (val instanceof Buffer) { + Buffer buffer = (Buffer) val; + return BitVector.create(buffer.getBytes(4, buffer.length()), buffer.getInt(0)); + } + throw new ClassCastException("Invalid BitVector value type " + val.getClass()); + } + private Point getPoint(int pos) { return (Point) getValue(pos); } diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java index ef6c518e3d..9245ee6832 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgSocketConnection.java @@ -21,39 +21,49 @@ import io.netty.handler.codec.DecoderException; import io.vertx.core.*; import io.vertx.core.buffer.Buffer; -import io.vertx.core.net.ClientSSLOptions; -import io.vertx.core.spi.metrics.ClientMetrics; import io.vertx.core.internal.ContextInternal; +import io.vertx.core.internal.logging.Logger; +import io.vertx.core.internal.logging.LoggerFactory; import io.vertx.core.internal.net.NetSocketInternal; +import io.vertx.core.net.ClientSSLOptions; +import io.vertx.core.spi.metrics.ClientMetrics; import io.vertx.pgclient.ChannelBinding; import io.vertx.pgclient.PgConnectOptions; import io.vertx.pgclient.PgException; -import io.vertx.pgclient.impl.codec.ExtendedQueryPgCommandMessage; -import io.vertx.pgclient.impl.codec.NoticeResponse; -import io.vertx.pgclient.impl.codec.PgCodec; -import io.vertx.pgclient.impl.codec.PgCommandMessage; -import io.vertx.pgclient.impl.codec.TxStatusEvent; +import io.vertx.pgclient.impl.codec.*; +import io.vertx.sqlclient.PropertyKind; +import io.vertx.sqlclient.Row; import io.vertx.sqlclient.codec.CommandMessage; import io.vertx.sqlclient.codec.SocketConnectionBase; -import io.vertx.sqlclient.spi.connection.Connection; import io.vertx.sqlclient.internal.PreparedStatement; import io.vertx.sqlclient.internal.QueryResultHandler; +import io.vertx.sqlclient.internal.RowDescriptorBase; import io.vertx.sqlclient.spi.DatabaseMetadata; -import io.vertx.sqlclient.spi.protocol.CommandBase; -import io.vertx.sqlclient.spi.protocol.ExtendedQueryCommand; -import io.vertx.sqlclient.spi.protocol.InitCommand; -import io.vertx.sqlclient.spi.protocol.SavepointCommand; -import io.vertx.sqlclient.spi.protocol.SimpleQueryCommand; -import io.vertx.sqlclient.spi.protocol.TxCommand; +import io.vertx.sqlclient.spi.connection.Connection; +import io.vertx.sqlclient.spi.protocol.*; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.function.Predicate; +import java.util.stream.Collector; +import java.util.stream.Collectors; /** * @author Julien Viet */ public class PgSocketConnection extends SocketConnectionBase { + private static final Logger logger = LoggerFactory.getLogger(PgSocketConnection.class); + + private static final List VECTOR_TYPE_NAMES = List.of("vector", "halfvec", "sparsevec"); + + // Only the types that are members of the pgvector extension + private static final String VECTOR_OIDS_QUERY = "SELECT t.typname, t.oid FROM pg_type t " + + "JOIN pg_depend d ON d.classid = 'pg_type'::regclass AND d.objid = t.oid AND d.deptype = 'e' " + + "JOIN pg_extension e ON d.refclassid = 'pg_extension'::regclass AND e.oid = d.refobjid " + + "WHERE e.extname = 'vector' AND t.typname IN ('vector', 'halfvec', 'sparsevec')"; + private PgCodec codec; private final boolean useLayer7Proxy; public int processId; @@ -88,12 +98,65 @@ public void init() { super.init(); } - // TODO RETURN FUTURE ??? Future sendStartupMessage(String username, String password, String database, Map properties) { InitCommand cmd = new InitCommand(this, username, password, database, properties); Promise promise = context.promise(); schedule(cmd, promise); - return promise.future(); + Future future = promise.future(); + if (connectOptions.isVectorTypeEnabled()) { + future = future.compose(conn -> discoverVectorOids().map(conn)); + } + return future; + } + + /** + * Discover the OIDs of the pgvector types, they are assigned when the extension is created. + * When the extension is not installed, no OID is found and the vector types are not available on this connection. + */ + private Future discoverVectorOids() { + // An OID is an unsigned 32 bits integer, the simple query protocol returns it as text + Collector> collector = Collectors.toMap(row -> row.getString(0), row -> (int) Long.parseLong(row.getString(1))); + VectorOidsHandler handler = new VectorOidsHandler(); + SimpleQueryCommand> cmd = new SimpleQueryCommand<>(VECTOR_OIDS_QUERY, false, false, collector, handler); + Promise promise = context.promise(); + schedule(cmd, promise); + return promise.future().andThen(ar -> { + if (ar.succeeded()) { + codec.setVectorOids(handler.oids); + warnMissingVectorTypes(handler.oids); + } else { + // The connection is already established, nobody else will close it when the connection attempt fails + socket.close(); + } + }).mapEmpty(); + } + + private static void warnMissingVectorTypes(Map oids) { + List missing = new ArrayList<>(VECTOR_TYPE_NAMES.size()); + for (String name : VECTOR_TYPE_NAMES) { + if (!oids.containsKey(name)) { + missing.add(name); + } + } + if (!missing.isEmpty()) { + logger.warn("The pgvector types " + String.join(", ", missing) + " were not found in the database"); + } + } + + private static class VectorOidsHandler implements QueryResultHandler> { + + Map oids = Map.of(); + + @Override + public void addProperty(PropertyKind property, V value) { + } + + @Override + public void handleResult(int updatedCount, int size, RowDescriptorBase desc, Map result, Throwable failure) { + if (failure == null && result != null) { + oids = result; + } + } } Future sendCancelRequestMessage(int processId, int secretKey) { diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataType.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataType.java index f999cde280..9a415868ea 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataType.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataType.java @@ -26,7 +26,10 @@ import io.vertx.core.json.JsonObject; import io.vertx.pgclient.data.*; import io.vertx.sqlclient.Tuple; +import io.vertx.sqlclient.data.FloatVector; +import io.vertx.sqlclient.data.HalfFloatVector; import io.vertx.sqlclient.data.Numeric; +import io.vertx.sqlclient.data.SparseFloatVector; import io.vertx.sqlclient.internal.TupleBase; import java.sql.JDBCType; @@ -124,7 +127,11 @@ public enum DataType { TS_VECTOR(3614, false, String.class, JDBCType.OTHER, DataTypeEstimator.UNSUPPORTED), TS_VECTOR_ARRAY(3643, false, String[].class, JDBCType.OTHER, DataTypeEstimator.UNSUPPORTED), TS_QUERY(3615, false, String.class, JDBCType.OTHER, DataTypeEstimator.UNSUPPORTED), - TS_QUERY_ARRAY(3645, false, String[].class, JDBCType.OTHER, DataTypeEstimator.UNSUPPORTED); + TS_QUERY_ARRAY(3645, false, String[].class, JDBCType.OTHER, DataTypeEstimator.UNSUPPORTED), + // pgvector types: the OIDs are assigned when the extension is created and discovered per connection + VECTOR(-1, true, FloatVector.class, JDBCType.OTHER, DataTypeEstimator.VECTOR), + HALFVEC(-1, true, HalfFloatVector.class, JDBCType.OTHER, DataTypeEstimator.HALFVEC), + SPARSEVEC(-1, true, SparseFloatVector.class, JDBCType.OTHER, DataTypeEstimator.SPARSEVEC); private static final Logger logger = LoggerFactory.getLogger(DataType.class); private static final IntObjectMap oidToDataType = new IntObjectHashMap<>(); @@ -163,6 +170,13 @@ DataType(int id, boolean supportsBinary, Class encodingType, Class dec this.lengthEstimator = lengthEstimator; } + /** + * @return whether this is a pgvector type, whose OID is not known in advance + */ + boolean isVectorType() { + return this == VECTOR || this == HALFVEC || this == SPARSEVEC; + } + static DataType valueOf(int oid) { DataType value = oidToDataType.get(oid); if (value == null) { @@ -186,7 +200,10 @@ static DataType lookup(Class type) { static { for (DataType dataType : values()) { - oidToDataType.put(dataType.id, dataType); + // The pgvector types do not have a fixed OID + if (!dataType.isVectorType()) { + oidToDataType.put(dataType.id, dataType); + } } encodingTypeToDataType.put(String.class, VARCHAR); encodingTypeToDataType.put(String[].class, VARCHAR_ARRAY); @@ -231,6 +248,9 @@ static DataType lookup(Class type) { encodingTypeToDataType.put(Polygon[].class, POLYGON_ARRAY); encodingTypeToDataType.put(Circle.class, CIRCLE); encodingTypeToDataType.put(Circle[].class, CIRCLE_ARRAY); + encodingTypeToDataType.put(FloatVector.class, VECTOR); + encodingTypeToDataType.put(HalfFloatVector.class, HALFVEC); + encodingTypeToDataType.put(SparseFloatVector.class, SPARSEVEC); } private static class DefaultParamExtractor implements ParamExtractor { diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeCodec.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeCodec.java index 866833c711..50c7065673 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeCodec.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeCodec.java @@ -27,7 +27,10 @@ import io.vertx.pgclient.data.*; import io.vertx.pgclient.impl.util.UTF8StringEndDetector; import io.vertx.sqlclient.Tuple; +import io.vertx.sqlclient.data.FloatVector; +import io.vertx.sqlclient.data.HalfFloatVector; import io.vertx.sqlclient.data.Numeric; +import io.vertx.sqlclient.data.SparseFloatVector; import io.vertx.sqlclient.impl.Utils; import java.math.BigDecimal; @@ -361,6 +364,15 @@ public static void encodeBinary(DataType id, Object value, ByteBuf buff) { case CIDR: binaryEncodeCidr((Cidr) value, buff); break; + case VECTOR: + binaryEncodeVECTOR((FloatVector) value, buff); + break; + case HALFVEC: + binaryEncodeHALFVEC((HalfFloatVector) value, buff); + break; + case SPARSEVEC: + binaryEncodeSPARSEVEC((SparseFloatVector) value, buff); + break; default: logger.debug("Data type " + id + " does not support binary encoding"); defaultEncodeBinary(value, buff); @@ -500,6 +512,15 @@ public static Object decodeBinary(DataType id, int index, int len, ByteBuf buff) return binaryDecodeArray(MONEY_ARRAY_FACTORY, DataType.MONEY, index, len, buff); case CIDR: return binaryDecodeCidr(index, len, buff); + case BIT: + case VARBIT: + return binaryDecodeBIT(index, len, buff); + case VECTOR: + return binaryDecodeVECTOR(index, len, buff); + case HALFVEC: + return binaryDecodeHALFVEC(index, len, buff); + case SPARSEVEC: + return binaryDecodeSPARSEVEC(index, len, buff); default: logger.debug("Data type " + id + " does not support binary decoding"); return defaultDecodeBinary(index, len, buff); @@ -642,6 +663,12 @@ public static Object decodeText(DataType id, int index, int len, ByteBuf buff) { return textDecodeArray(MONEY_ARRAY_FACTORY, DataType.MONEY, index, len, buff); case CIDR: return textDecodeCidr(index, len, buff); + case VECTOR: + return FloatVector.create(textdecodeTEXT(index, len, buff)); + case HALFVEC: + return HalfFloatVector.create(textdecodeTEXT(index, len, buff)); + case SPARSEVEC: + return textDecodeSPARSEVEC(index, len, buff); default: return defaultDecodeText(index, len, buff); } @@ -1783,6 +1810,170 @@ private static void binaryEncodeCidr(Cidr value, ByteBuf buff) { buff.writeBytes(data); } + /** + * Decode the binary representation of {@code bit} and {@code varbit}: an {@code int32} bit length followed by the + * packed bits, the raw value is returned as is so the bit length is not lost. + */ + private static Buffer binaryDecodeBIT(int index, int len, ByteBuf buff) { + return binaryDecodeBYTEA(index, len, buff); + } + + private static void binaryEncodeVECTOR(FloatVector value, ByteBuf buff) { + float[] values = value.toFloatArray(); + buff.writeShort(values.length); + buff.writeShort(0); + for (float f : values) { + buff.writeFloat(f); + } + } + + private static FloatVector binaryDecodeVECTOR(int index, int len, ByteBuf buff) { + int dimensions = buff.getUnsignedShort(index); + float[] values = new float[dimensions]; + int pos = index + 4; + for (int i = 0; i < dimensions; i++) { + values[i] = buff.getFloat(pos); + pos += 4; + } + return FloatVector.create(values); + } + + private static void binaryEncodeHALFVEC(HalfFloatVector value, ByteBuf buff) { + float[] values = value.toFloatArray(); + buff.writeShort(values.length); + buff.writeShort(0); + for (float f : values) { + buff.writeShort(floatToHalf(f)); + } + } + + private static HalfFloatVector binaryDecodeHALFVEC(int index, int len, ByteBuf buff) { + int dimensions = buff.getUnsignedShort(index); + float[] values = new float[dimensions]; + int pos = index + 4; + for (int i = 0; i < dimensions; i++) { + values[i] = halfToFloat(buff.getUnsignedShort(pos)); + pos += 2; + } + return HalfFloatVector.create(values); + } + + private static void binaryEncodeSPARSEVEC(SparseFloatVector value, ByteBuf buff) { + int[] indices = value.indices(); + float[] values = value.values(); + buff.writeInt(value.dimension()); + buff.writeInt(indices.length); + buff.writeInt(0); + for (int index : indices) { + buff.writeInt(index); + } + for (float f : values) { + buff.writeFloat(f); + } + } + + private static SparseFloatVector binaryDecodeSPARSEVEC(int index, int len, ByteBuf buff) { + int dimensions = buff.getInt(index); + int nnz = buff.getInt(index + 4); + int pos = index + 12; + int[] indices = new int[nnz]; + for (int i = 0; i < nnz; i++) { + indices[i] = buff.getInt(pos); + pos += 4; + } + float[] values = new float[nnz]; + for (int i = 0; i < nnz; i++) { + values[i] = buff.getFloat(pos); + pos += 4; + } + return SparseFloatVector.create(dimensions, indices, values); + } + + /** + * Decode the text representation of a {@code sparsevec}, e.g. {@code {1:0.5,100:-0.25}/65535}, indices are one-based. + */ + private static SparseFloatVector textDecodeSPARSEVEC(int index, int len, ByteBuf buff) { + String s = textdecodeTEXT(index, len, buff).trim(); + int slash = s.lastIndexOf('/'); + if (slash < 0 || !s.startsWith("{") || s.charAt(slash - 1) != '}') { + throw new DecoderException("Invalid sparsevec value: " + s); + } + try { + int dimensions = Integer.parseInt(s.substring(slash + 1).trim()); + String body = s.substring(1, slash - 1).trim(); + if (body.isEmpty()) { + return SparseFloatVector.create(dimensions, new int[0], new float[0]); + } + String[] entries = body.split(","); + int[] indices = new int[entries.length]; + float[] values = new float[entries.length]; + for (int i = 0; i < entries.length; i++) { + String entry = entries[i]; + int colon = entry.indexOf(':'); + indices[i] = Integer.parseInt(entry.substring(0, colon).trim()) - 1; + values[i] = Float.parseFloat(entry.substring(colon + 1).trim()); + } + return SparseFloatVector.create(dimensions, indices, values); + } catch (RuntimeException e) { + throw new DecoderException("Invalid sparsevec value: " + s, e); + } + } + + private static float halfToFloat(int half) { + int sign = (half & 0x8000) << 16; + int exponent = (half >>> 10) & 0x1f; + int mantissa = half & 0x3ff; + if (exponent == 0) { + // Zero or subnormal: mantissa * 2^-24 + float value = mantissa * (1f / (1 << 24)); + return sign != 0 ? -value : value; + } else if (exponent == 0x1f) { + // Infinity or NaN + return Float.intBitsToFloat(sign | 0x7f800000 | (mantissa << 13)); + } + return Float.intBitsToFloat(sign | ((exponent + 112) << 23) | (mantissa << 13)); + } + + private static int floatToHalf(float value) { + int bits = Float.floatToRawIntBits(value); + int sign = (bits >>> 16) & 0x8000; + int floatExponent = (bits >>> 23) & 0xff; + int mantissa = bits & 0x7fffff; + if (floatExponent == 0xff) { + // Infinity or NaN + return sign | 0x7c00 | (mantissa != 0 ? 0x200 | (mantissa >>> 13) : 0); + } + int exponent = floatExponent - 127 + 15; + if (exponent >= 0x1f) { + // Overflow to infinity + return sign | 0x7c00; + } + int half; + int remainder; + int halfway; + if (exponent <= 0) { + if (exponent < -10) { + // Underflow to zero + return sign; + } + // Subnormal + mantissa |= 0x800000; + int shift = 14 - exponent; + half = mantissa >>> shift; + remainder = mantissa & ((1 << shift) - 1); + halfway = 1 << (shift - 1); + } else { + half = (exponent << 10) | (mantissa >>> 13); + remainder = mantissa & 0x1fff; + halfway = 0x1000; + } + // Round to nearest even, a carry propagates into the exponent which is the expected result + if (remainder > halfway || (remainder == halfway && (half & 1) != 0)) { + half++; + } + return sign | half; + } + private static Cidr textDecodeCidr(int index, int len, ByteBuf buff) { Cidr cidr = new Cidr(); int sepIdx = buff.indexOf(index, index + len, (byte) '/'); diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeEstimator.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeEstimator.java index ba4520d8e7..eeee835327 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeEstimator.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/DataTypeEstimator.java @@ -6,6 +6,9 @@ import io.vertx.pgclient.data.Inet; import io.vertx.pgclient.data.Path; import io.vertx.pgclient.data.Polygon; +import io.vertx.sqlclient.data.FloatVector; +import io.vertx.sqlclient.data.HalfFloatVector; +import io.vertx.sqlclient.data.SparseFloatVector; import java.net.Inet4Address; import java.net.Inet6Address; @@ -63,6 +66,10 @@ class DataTypeEstimator { static final int POLYGON = -4; static final int PATH = -5; + static final int VECTOR = -11; + static final int HALFVEC = -12; + static final int SPARSEVEC = -13; + // Eventually make this configurable per options private static final float AVG_BYTES_PER_CHAR_UTF8 = CharsetUtil.encoder(CharsetUtil.UTF_8).averageBytesPerChar(); @@ -137,6 +144,18 @@ private static int estimatePath(Path p) { return 1 + 4 + p.getPoints().size() * 16; } + private static int estimateVector(FloatVector v) { + return 2 + 2 + v.dimension() * 4; + } + + private static int estimateHalfVec(HalfFloatVector v) { + return 2 + 2 + v.dimension() * 2; + } + + private static int estimateSparseVec(SparseFloatVector v) { + return 4 + 4 + 4 + v.indices().length * 8; + } + static int estimate(int estimator, Object o) { if (estimator > 0) { return estimator; @@ -162,6 +181,12 @@ static int estimate(int estimator, Object o) { return estimatePolygon((Polygon) o); case DataTypeEstimator.PATH: return estimatePath((Path) o); + case DataTypeEstimator.VECTOR: + return estimateVector((FloatVector) o); + case DataTypeEstimator.HALFVEC: + return estimateHalfVec((HalfFloatVector) o); + case DataTypeEstimator.SPARSEVEC: + return estimateSparseVec((SparseFloatVector) o); default: throw new UnsupportedOperationException(); } diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgCodec.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgCodec.java index 94fb47c6e9..6fed7c65ab 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgCodec.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgCodec.java @@ -17,8 +17,12 @@ package io.vertx.pgclient.impl.codec; import io.netty.channel.CombinedChannelDuplexHandler; +import io.netty.util.collection.IntObjectHashMap; +import io.netty.util.collection.IntObjectMap; import java.util.ArrayDeque; +import java.util.EnumMap; +import java.util.Map; public class PgCodec extends CombinedChannelDuplexHandler { @@ -26,6 +30,10 @@ public class PgCodec extends CombinedChannelDuplexHandler private final PgDecoder decoder; private final PgEncoder encoder; + // The pgvector OIDs are assigned when the extension is created, they are discovered per connection + private final IntObjectMap vectorDataTypesByOid = new IntObjectHashMap<>(); + private final Map vectorOidsByDataType = new EnumMap<>(DataType.class); + public PgCodec(boolean useLayer7Proxy) { inflight = new ArrayDeque<>(); decoder = new PgDecoder(this); @@ -33,6 +41,40 @@ public PgCodec(boolean useLayer7Proxy) { init(decoder, encoder); } + /** + * Set the pgvector OIDs discovered for this connection. + * + * @param oidsByName the OIDs of the {@code vector}, {@code halfvec} and {@code sparsevec} types by type name + */ + public void setVectorOids(Map oidsByName) { + registerVectorType(oidsByName, "vector", DataType.VECTOR); + registerVectorType(oidsByName, "halfvec", DataType.HALFVEC); + registerVectorType(oidsByName, "sparsevec", DataType.SPARSEVEC); + } + + private void registerVectorType(Map oidsByName, String name, DataType dataType) { + Integer oid = oidsByName.get(name); + if (oid != null) { + vectorDataTypesByOid.put(oid, dataType); + vectorOidsByDataType.put(dataType, oid); + } + } + + /** + * Resolve the {@link DataType} of an OID reported by the server, taking the pgvector types of this connection into account. + */ + DataType dataType(int oid) { + DataType vectorDataType = vectorDataTypesByOid.get(oid); + return vectorDataType != null ? vectorDataType : DataType.valueOf(oid); + } + + /** + * @return the OID of a pgvector data type on this connection, or {@code null} when the type is not available + */ + Integer vectorOid(DataType dataType) { + return vectorOidsByDataType.get(dataType); + } + void add(PgCommandMessage codec) { codec.decoder = decoder; inflight.add(codec); diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgDecoder.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgDecoder.java index 1079310a64..ededbeb438 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgDecoder.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgDecoder.java @@ -23,8 +23,8 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.ByteProcessor; -import io.vertx.pgclient.impl.util.Util; import io.vertx.pgclient.impl.Notification; +import io.vertx.pgclient.impl.util.Util; import io.vertx.sqlclient.codec.CommandResponse; /** @@ -249,7 +249,7 @@ private void decodeRowDescription(ByteBuf in) { fieldName, tableOID, columnAttributeNumber, - DataType.valueOf(typeOID), + codec.dataType(typeOID), typeSize, typeModifier, DataFormat.valueOf(textOrBinary) @@ -471,7 +471,7 @@ private void decodeNoData() { private void decodeParameterDescription(ByteBuf in) { DataType[] paramDataTypes = new DataType[in.readUnsignedShort()]; for (int c = 0; c < paramDataTypes.length; ++c) { - paramDataTypes[c] = DataType.valueOf(in.readInt()); + paramDataTypes[c] = codec.dataType(in.readInt()); } codec.peek().handleParameterDescription(new PgParamDesc(paramDataTypes)); } diff --git a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgEncoder.java b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgEncoder.java index 8d58b22709..ff6ebdb448 100644 --- a/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgEncoder.java +++ b/vertx-pg-client/src/main/java/io/vertx/pgclient/impl/codec/PgEncoder.java @@ -360,7 +360,16 @@ private static int estimateDescribe(DescribeMessage describe) { return length; } - private static void renderParse(String sql, byte[] statement, DataType[] parameterTypes, ByteBuf out) { + private int parameterTypeOid(DataType type) { + if (type.isVectorType()) { + // The pgvector OIDs are discovered per connection, 0 lets the server infer the type when it is not available + Integer oid = codec.vectorOid(type); + return oid != null ? oid : 0; + } + return type.id; + } + + private void renderParse(String sql, byte[] statement, DataType[] parameterTypes, ByteBuf out) { int pos = out.writerIndex(); out.writeByte(PARSE); out.writeInt(0); @@ -372,7 +381,7 @@ private static void renderParse(String sql, byte[] statement, DataType[] paramet } else { out.writeShort(parameterTypes.length); for (DataType parameterType : parameterTypes) { - out.writeInt(parameterType.id); + out.writeInt(parameterTypeOid(parameterType)); } } out.setInt(pos + 1, out.writerIndex() - pos - 1); diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectOptionsTest.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectOptionsTest.java index 797db89990..70b7c729e1 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectOptionsTest.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectOptionsTest.java @@ -23,7 +23,7 @@ import java.util.Map; import java.util.ServiceConfigurationError; -import static org.junit.Assert.fail; +import static org.junit.Assert.*; /** * @author Billy Yuan @@ -181,6 +181,21 @@ public void testValidUriChannelBindingRequire() { assertEquals(expectedConfiguration, actualConfiguration); } + @Test + public void testValidUriVectorTypeEnabled() { + connectionUri = "postgresql://user@myhost?vector_type_enabled=true"; + actualConfiguration = PgConnectOptions.fromUri(connectionUri); + + expectedConfiguration = new PgConnectOptions() + .setHost("myhost") + .setUser("user") + .setVectorTypeEnabled(true); + + assertEquals(expectedConfiguration, actualConfiguration); + assertTrue(actualConfiguration.isVectorTypeEnabled()); + assertFalse(PgConnectOptions.fromUri("postgresql://user@myhost").isVectorTypeEnabled()); + } + @Test public void testValidUri11() { connectionUri = "postgresql://user@myhost?application_name=myapp"; diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectionUriParserTest.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectionUriParserTest.java index 594e148174..cd01f65788 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectionUriParserTest.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/PgConnectionUriParserTest.java @@ -323,6 +323,35 @@ public void testParsingInvalidSslNegotiation() { parse(uri); } + @Test + public void testParsingParameterVectorTypeEnabled() { + uri = "postgresql://?host=localhost&vector_type_enabled=true"; + + actualParsedResult = parse(uri); + + expectedParsedResult = new JsonObject() + .put("host", "localhost") + .put("vectorTypeEnabled", true); + + assertEquals(expectedParsedResult, actualParsedResult); + + uri = "postgresql://?host=localhost&VECTOR_TYPE_ENABLED=FALSE"; + + actualParsedResult = parse(uri); + + expectedParsedResult = new JsonObject() + .put("host", "localhost") + .put("vectorTypeEnabled", false); + + assertEquals(expectedParsedResult, actualParsedResult); + } + + @Test(expected = IllegalArgumentException.class) + public void testParsingInvalidVectorTypeEnabled() { + uri = "postgresql://?vector_type_enabled=yes"; + parse(uri); + } + @Test public void testParsingProperties() { uri = "postgresql://?application_name=myapp&search_path=myschema"; diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/it/EnvTest.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/it/EnvTest.java index 5e85f68a98..01ea2e4266 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/it/EnvTest.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/it/EnvTest.java @@ -21,6 +21,7 @@ import org.junit.Test; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class EnvTest { @@ -32,5 +33,6 @@ public void testFoo() { assertEquals("test_user", options.getUser()); assertEquals("test_password", options.getPassword()); assertEquals(SslMode.REQUIRE, options.getSslMode()); + assertTrue(options.isVectorTypeEnabled()); } } diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgRule.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgRule.java index 79aa67836c..1d3307e50d 100644 --- a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgRule.java +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgRule.java @@ -217,7 +217,7 @@ protected void after() { } } - private static class ServerContainer> extends GenericContainer { + static class ServerContainer> extends GenericContainer { public ServerContainer(String dockerImageName) { super(dockerImageName); diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgVectorRule.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgVectorRule.java new file mode 100644 index 0000000000..d6b1afee72 --- /dev/null +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/junit/ContainerPgVectorRule.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ +package io.vertx.tests.pgclient.junit; + +import io.vertx.pgclient.PgConnectOptions; +import io.vertx.tests.pgclient.junit.ContainerPgRule.ServerContainer; +import org.junit.rules.ExternalResource; +import org.testcontainers.containers.BindMode; +import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; + +import static io.vertx.pgclient.PgConnectOptions.DEFAULT_PORT; + +/** + * PostgreSQL test database with the pgvector extension. + *

+ * Set the {@code vectorContainerFixedPort} system property to bind the server to the default port of the host. + */ +public class ContainerPgVectorRule extends ExternalResource { + + public static final ContainerPgVectorRule SHARED_INSTANCE = new ContainerPgVectorRule(); + + private static final String USER = "postgres"; + private static final String PASSWORD = "postgres"; + + private ServerContainer server; + private PgConnectOptions options; + + public PgConnectOptions options() { + return new PgConnectOptions(options).setVectorTypeEnabled(true); + } + + private synchronized PgConnectOptions startServer() { + server = new ServerContainer<>("pgvector/pgvector:pg17") + .withEnv("POSTGRES_DB", "postgres") + .withEnv("POSTGRES_USER", USER) + .withEnv("POSTGRES_PASSWORD", PASSWORD) + .waitingFor(new LogMessageWaitStrategy() + .withRegEx(".*database system is ready to accept connections.*\\s") + .withTimes(2) + .withStartupTimeout(Duration.of(60, ChronoUnit.SECONDS))) + .withCommand("postgres", "-c", "fsync=off") + .withClasspathResourceMapping("create-postgres-vector.sql", "/docker-entrypoint-initdb.d/create-postgres-vector.sql", BindMode.READ_ONLY); + if (System.getProperties().containsKey("vectorContainerFixedPort")) { + server.withFixedExposedPort(DEFAULT_PORT, DEFAULT_PORT); + } else { + server.withExposedPorts(DEFAULT_PORT); + } + server.start(); + return new PgConnectOptions() + .setPort(server.getMappedPort(DEFAULT_PORT)) + .setHost(server.getHost()) + .setDatabase("postgres") + .setUser(USER) + .setPassword(PASSWORD); + } + + private synchronized void stopServer() { + if (server != null) { + try { + server.stop(); + } finally { + server = null; + } + } + } + + @Override + protected void before() throws Throwable { + if (server != null) { + return; + } + options = startServer(); + } + + @Override + protected void after() { + if (this != SHARED_INSTANCE) { + try { + stopServer(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } +} diff --git a/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/tck/PgVectorDataTypeTest.java b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/tck/PgVectorDataTypeTest.java new file mode 100644 index 0000000000..992b190edb --- /dev/null +++ b/vertx-pg-client/src/test/java/io/vertx/tests/pgclient/tck/PgVectorDataTypeTest.java @@ -0,0 +1,342 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.pgclient.tck; + +import io.vertx.core.Future; +import io.vertx.core.buffer.Buffer; +import io.vertx.ext.unit.Async; +import io.vertx.ext.unit.TestContext; +import io.vertx.ext.unit.junit.VertxUnitRunner; +import io.vertx.pgclient.PgConnectOptions; +import io.vertx.pgclient.PgConnection; +import io.vertx.pgclient.PgException; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.RowSet; +import io.vertx.sqlclient.Tuple; +import io.vertx.sqlclient.data.BitVector; +import io.vertx.sqlclient.data.FloatVector; +import io.vertx.sqlclient.data.HalfFloatVector; +import io.vertx.sqlclient.data.SparseFloatVector; +import io.vertx.tests.pgclient.junit.ContainerPgRule; +import io.vertx.tests.pgclient.junit.ContainerPgVectorRule; +import io.vertx.tests.sqlclient.ProxyServer; +import io.vertx.tests.sqlclient.tck.VectorDataTypeTestBase; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(VertxUnitRunner.class) +public class PgVectorDataTypeTest extends VectorDataTypeTestBase { + + @ClassRule + public static final ContainerPgVectorRule rule = ContainerPgVectorRule.SHARED_INSTANCE; + + // A database without the pgvector extension + @ClassRule + public static final ContainerPgRule plainRule = ContainerPgRule.SHARED_INSTANCE; + + private static final int INSERTED_ROW_ID = 100; + + @Override + protected void initConnector() { + connector = ClientConfig.CONNECT.connect(vertx, rule.options()); + } + + @Override + protected String statement(String... parts) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < parts.length; i++) { + if (i > 0) { + sb.append("$").append(i); + } + sb.append(parts[i]); + } + return sb.toString(); + } + + private static void assertHalfVector(TestContext ctx, Object value, float[] expected) { + ctx.assertTrue(value instanceof HalfFloatVector, "Expected HalfFloatVector but was: " + value); + float[] actual = ((HalfFloatVector) value).toFloatArray(); + ctx.assertEquals(expected.length, actual.length); + for (int i = 0; i < expected.length; i++) { + ctx.assertInRange(expected[i], actual[i], 1e-3); + } + } + + @Test + public void testDecodeHalfVec(TestContext ctx) { + String sql = "SELECT emb FROM vertx_test_halfvec WHERE id = 1"; + connector.connect(ctx.asyncAssertSuccess(conn -> { + // text protocol + conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(textResult -> { + ctx.assertEquals(1, textResult.size()); + assertHalfVector(ctx, textResult.iterator().next().getValue(0), new float[]{0.1f, 0.2f, 0.3f}); + // binary protocol + conn.preparedQuery(sql).execute().onComplete(ctx.asyncAssertSuccess(binaryResult -> { + ctx.assertEquals(1, binaryResult.size()); + assertHalfVector(ctx, binaryResult.iterator().next().getValue(0), new float[]{0.1f, 0.2f, 0.3f}); + conn.close(); + })); + })); + })); + } + + @Test + public void testEncodeHalfVec(TestContext ctx) { + float[] inserted = {0.25f, -0.5f, 3.0f}; + connector.connect(ctx.asyncAssertSuccess(conn -> { + conn.preparedQuery(statement("INSERT INTO vertx_test_halfvec (id, emb) VALUES (", ", ", ")")) + .execute(Tuple.of(INSERTED_ROW_ID, HalfFloatVector.create(inserted))) + .onComplete(ctx.asyncAssertSuccess(insertResult -> { + ctx.assertEquals(1, insertResult.rowCount()); + conn.preparedQuery("SELECT emb FROM vertx_test_halfvec WHERE id = " + INSERTED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + // The values are exactly representable in half precision + ctx.assertEquals(HalfFloatVector.create(inserted), result.iterator().next().getValue(0)); + conn.preparedQuery("DELETE FROM vertx_test_halfvec WHERE id = " + INSERTED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(deleteResult -> conn.close())); + })); + })); + })); + } + + @Test + public void testDecodeSparseVec(TestContext ctx) { + String sql = "SELECT emb FROM vertx_test_sparsevec WHERE id = 1"; + SparseFloatVector expected = SparseFloatVector.create(10, new int[]{0, 4}, new float[]{0.5f, -0.25f}); + connector.connect(ctx.asyncAssertSuccess(conn -> { + // text protocol + conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(textResult -> { + ctx.assertEquals(1, textResult.size()); + ctx.assertEquals(expected, textResult.iterator().next().getValue(0)); + // binary protocol + conn.preparedQuery(sql).execute().onComplete(ctx.asyncAssertSuccess(binaryResult -> { + ctx.assertEquals(1, binaryResult.size()); + ctx.assertEquals(expected, binaryResult.iterator().next().getValue(0)); + conn.close(); + })); + })); + })); + } + + @Test + public void testEncodeSparseVec(TestContext ctx) { + SparseFloatVector inserted = SparseFloatVector.create(10, new int[]{1, 9}, new float[]{1.5f, 2.0f}); + connector.connect(ctx.asyncAssertSuccess(conn -> { + conn.preparedQuery(statement("INSERT INTO vertx_test_sparsevec (id, emb) VALUES (", ", ", ")")) + .execute(Tuple.of(INSERTED_ROW_ID, inserted)) + .onComplete(ctx.asyncAssertSuccess(insertResult -> { + ctx.assertEquals(1, insertResult.rowCount()); + conn.preparedQuery("SELECT emb FROM vertx_test_sparsevec WHERE id = " + INSERTED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + ctx.assertEquals(inserted, result.iterator().next().getValue(0)); + conn.preparedQuery("DELETE FROM vertx_test_sparsevec WHERE id = " + INSERTED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(deleteResult -> conn.close())); + })); + })); + })); + } + + @Test + public void testDecodeBitVec(TestContext ctx) { + String sql = "SELECT emb FROM vertx_test_bitvec WHERE id = 1"; + BitVector expected = BitVector.create("10110100"); + connector.connect(ctx.asyncAssertSuccess(conn -> { + // text protocol + conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(textResult -> { + ctx.assertEquals(1, textResult.size()); + Row textRow = textResult.iterator().next(); + ctx.assertEquals("10110100", textRow.getValue(0)); + ctx.assertEquals(expected, textRow.get(BitVector.class, 0)); + // binary protocol + conn.preparedQuery(sql).execute().onComplete(ctx.asyncAssertSuccess(binaryResult -> { + ctx.assertEquals(1, binaryResult.size()); + Row binaryRow = binaryResult.iterator().next(); + ctx.assertTrue(binaryRow.getValue(0) instanceof Buffer, "Expected Buffer but was: " + binaryRow.getValue(0)); + ctx.assertEquals(expected, binaryRow.get(BitVector.class, 0)); + conn.close(); + })); + })); + })); + } + + @Test + public void testExplicitParamTypesFallback(TestContext ctx) { + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + connector.connect(ctx.asyncAssertSuccess(conn -> { + // The server cannot infer the type of the parameter, the statement is prepared again with the types of the tuple + conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)).onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + ctx.assertEquals(false, result.iterator().next().getValue(0)); + conn.close(); + })); + })); + } + + private static void assertMessage(TestContext ctx, Throwable err, String fragment) { + ctx.assertTrue(err.getMessage().contains(fragment), "Unexpected message: " + err.getMessage()); + } + + // The server cannot determine the type of the parameter: SQLSTATE 42P18 indeterminate_datatype + private static void assertIndeterminateParameterType(TestContext ctx, Throwable err) { + ctx.assertTrue(err instanceof PgException, "Unexpected failure: " + err); + ctx.assertEquals("42P18", ((PgException) err).getSqlState()); + } + + @Test + public void testVectorParamOptionDisabledServerInferredType(TestContext ctx) { + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + PgConnection.connect(vertx, rule.options().setVectorTypeEnabled(false)).onComplete(ctx.asyncAssertSuccess(conn -> { + // The server infers the vector type of the parameter, the type is not known by the connection + conn.preparedQuery(statement("INSERT INTO vertx_test_vector (id, emb, notes) VALUES (", ", ", ", ", ")")) + .execute(Tuple.of(INSERTED_ROW_ID, vector, "disabled")) + .onComplete(ctx.asyncAssertFailure(err -> { + assertMessage(ctx, err, "can not be coerced"); + conn.close(); + })); + })); + } + + @Test + public void testVectorParamOptionDisabledIndeterminateType(TestContext ctx) { + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + PgConnection.connect(vertx, rule.options().setVectorTypeEnabled(false)).onComplete(ctx.asyncAssertSuccess(conn -> { + // The server cannot infer the type of the parameter, the statement is prepared again with the types of the tuple + conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)).onComplete(ctx.asyncAssertFailure(err -> { + assertIndeterminateParameterType(ctx, err); + conn.close(); + })); + })); + } + + @Test + public void testVectorParamOptionEnabledExtensionMissing(TestContext ctx) { + // The pgvector types are not found in a database without the extension: the connection works, vectors are unavailable + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + HalfFloatVector halfVector = HalfFloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + PgConnection.connect(vertx, plainRule.options().setVectorTypeEnabled(true)).onComplete(ctx.asyncAssertSuccess(conn -> { + conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)).onComplete(ctx.asyncAssertFailure(err1 -> { + assertIndeterminateParameterType(ctx, err1); + conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(halfVector)).onComplete(ctx.asyncAssertFailure(err2 -> { + assertIndeterminateParameterType(ctx, err2); + conn.close(); + })); + })); + })); + } + + @Test + public void testConnectionUsableAfterVectorParamFailure(TestContext ctx) { + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + Async async = ctx.async(); + PgConnection.connect(vertx, rule.options().setVectorTypeEnabled(false)).onComplete(ctx.asyncAssertSuccess(conn -> { + // Pipelined commands around the failing one + Future> before = conn.query("SELECT 1 AS v FROM pg_sleep(0.2)").execute(); + Future> failing = conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)); + Future> after1 = conn.query("SELECT 2 AS v").execute(); + Future> after2 = conn.preparedQuery("SELECT $1::int4 AS v").execute(Tuple.of(3)); + Future.join(before, failing, after1, after2).onComplete(ar -> { + ctx.assertTrue(failing.failed()); + assertIndeterminateParameterType(ctx, failing.cause()); + ctx.assertEquals(1, before.result().iterator().next().getInteger("v")); + ctx.assertEquals(2, after1.result().iterator().next().getInteger("v")); + ctx.assertEquals(3, after2.result().iterator().next().getInteger("v")); + // The connection is still usable + conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)).onComplete(ctx.asyncAssertFailure(err -> { + conn.preparedQuery("SELECT $1::int4 AS v").execute(Tuple.of(4)).onComplete(ctx.asyncAssertSuccess(rows -> { + ctx.assertEquals(4, rows.iterator().next().getInteger("v")); + conn.close(); + async.complete(); + })); + })); + }); + })); + } + + @Test + public void testConnectionUsableAfterVectorParamFailureWithPreparedStatementCache(TestContext ctx) { + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + Async async = ctx.async(); + PgConnection.connect(vertx, rule.options().setVectorTypeEnabled(false).setCachePreparedStatements(true)).onComplete(ctx.asyncAssertSuccess(conn -> { + Future> failing1 = conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)); + Future> success1 = conn.preparedQuery("SELECT $1::int4 AS v").execute(Tuple.of(1)); + Future> failing2 = conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)); + Future> success2 = conn.preparedQuery("SELECT $1::int4 AS v").execute(Tuple.of(2)); + Future.join(failing1, success1, failing2, success2).onComplete(ar -> { + ctx.assertTrue(failing1.failed()); + ctx.assertTrue(failing2.failed()); + ctx.assertEquals(1, success1.result().iterator().next().getInteger("v")); + ctx.assertEquals(2, success2.result().iterator().next().getInteger("v")); + conn.close(); + async.complete(); + }); + })); + } + + @Test + public void testVectorOidDiscoveryFailureClosesConnection(TestContext ctx) { + Async async = ctx.async(2); + PgConnectOptions options = rule.options(); + ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost()); + proxy.proxyHandler(conn -> { + conn.clientHandler(buff -> { + if (buff.toString().contains("pg_extension")) { + // Fail the discovery of the vector OIDs: ErrorResponse then ReadyForQuery + Buffer response = Buffer.buffer() + .appendByte((byte) 'E').appendInt(25) + .appendByte((byte) 'S').appendString("ERROR").appendByte((byte) 0) + .appendByte((byte) 'C').appendString("XX000").appendByte((byte) 0) + .appendByte((byte) 'M').appendString("boom").appendByte((byte) 0) + .appendByte((byte) 0) + .appendByte((byte) 'Z').appendInt(5).appendByte((byte) 'I'); + conn.clientSocket().write(response); + } else { + conn.serverSocket().write(buff); + } + }); + // The client must close the connection that cannot be used + conn.clientCloseHandler(v -> async.countDown()); + conn.connect(); + }); + proxy.listen(18951, "localhost", ctx.asyncAssertSuccess(v -> { + PgConnection.connect(vertx, options.setHost("localhost").setPort(18951)).onComplete(ctx.asyncAssertFailure(err -> { + assertMessage(ctx, err, "boom"); + async.countDown(); + })); + })); + } + + @Test + public void testTypesOutsideTheExtensionAreIgnored(TestContext ctx) { + // A type named vector that is not a member of the pgvector extension must not be picked up + FloatVector vector = FloatVector.create(new float[]{0.5f, 1.5f, -2.5f}); + Async async = ctx.async(); + PgConnection.connect(vertx, plainRule.options()).compose(setup -> setup + .query("CREATE SCHEMA vertx_fake_pgvector").execute() + .compose(r -> setup.query("CREATE TYPE vertx_fake_pgvector.vector AS (a int4)").execute()) + .compose(r -> PgConnection.connect(vertx, plainRule.options().setVectorTypeEnabled(true))) + .compose(conn -> conn.preparedQuery("SELECT $1 IS NULL").execute(Tuple.of(vector)) + .transform(ar -> { + ctx.assertTrue(ar.failed()); + assertIndeterminateParameterType(ctx, ar.cause()); + return conn.close(); + })) + .eventually(() -> setup.query("DROP SCHEMA vertx_fake_pgvector CASCADE").execute().compose(r -> setup.close())) + ).onComplete(ctx.asyncAssertSuccess(v -> async.complete())); + } +} diff --git a/vertx-pg-client/src/test/resources/create-postgres-vector.sql b/vertx-pg-client/src/test/resources/create-postgres-vector.sql new file mode 100644 index 0000000000..da3c1152b9 --- /dev/null +++ b/vertx-pg-client/src/test/resources/create-postgres-vector.sql @@ -0,0 +1,14 @@ +CREATE EXTENSION IF NOT EXISTS vector; + +CREATE TABLE IF NOT EXISTS vertx_test_vector (id SERIAL PRIMARY KEY, emb vector(3), notes TEXT); +INSERT INTO vertx_test_vector (emb, notes) VALUES ('[0.1,0.2,0.3]', 'float32'); +INSERT INTO vertx_test_vector (emb, notes) VALUES (NULL, 'null'); + +CREATE TABLE IF NOT EXISTS vertx_test_halfvec (id SERIAL PRIMARY KEY, emb halfvec(3)); +INSERT INTO vertx_test_halfvec (emb) VALUES ('[0.1,0.2,0.3]'); + +CREATE TABLE IF NOT EXISTS vertx_test_sparsevec (id SERIAL PRIMARY KEY, emb sparsevec(10)); +INSERT INTO vertx_test_sparsevec (emb) VALUES ('{1:0.5,5:-0.25}/10'); + +CREATE TABLE IF NOT EXISTS vertx_test_bitvec (id SERIAL PRIMARY KEY, emb bit(8)); +INSERT INTO vertx_test_bitvec (emb) VALUES (B'10110100'); diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/BitVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/BitVector.java new file mode 100644 index 0000000000..0f25a9ac20 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/BitVector.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A vector of bits, packed most significant bit first. + *

+ * Instances map bit-packed vector types, e.g Oracle {@code VECTOR(n, BINARY)} columns, and + * the {@code bit}/{@code varbit} types of PostgreSQL (the latter through the + * {@code Row#get(BitVector.class, ...)} conversion). + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * bit length and the packed bytes, regardless of the representation an instance was created + * from. + */ +public final class BitVector implements Vector { + + private final byte[] packedBits; + private final int bitLength; + + /** + * Create a {@code BitVector} from its bits, packed most significant bit first. + * + * @param bits the bits + * @return the vector + * @throws NullPointerException when {@code bits} is {@code null} + */ + public static BitVector create(boolean[] bits) { + Objects.requireNonNull(bits, "bits cannot be null"); + int bitLength = bits.length; + byte[] packedBits = new byte[(bitLength + 7) / 8]; + for (int i = 0; i < bitLength; i++) { + if (bits[i]) { + packedBits[i / 8] |= (byte) (0x80 >> (i % 8)); + } + } + return new BitVector(packedBits, bitLength); + } + + /** + * Create a {@code BitVector} from bits packed most significant bit first. + *

+ * The given array is stored without copy, mutations are visible. + * + * @param packedBits the packed bits, of length {@code (bitLength + 7) / 8} + * @param bitLength the number of significant bits + * @return the vector + * @throws NullPointerException when {@code packedBits} is {@code null} + * @throws IllegalArgumentException when {@code bitLength} is negative or does not match the + * length of {@code packedBits} + */ + public static BitVector create(byte[] packedBits, int bitLength) { + Objects.requireNonNull(packedBits, "packedBits cannot be null"); + if (bitLength < 0) { + throw new IllegalArgumentException("bitLength must be non-negative: " + bitLength); + } + if (packedBits.length != (bitLength + 7) / 8) { + throw new IllegalArgumentException("packedBits length must be (bitLength + 7) / 8: expected " + + ((bitLength + 7) / 8) + " but was " + packedBits.length); + } + return new BitVector(packedBits, bitLength); + } + + /** + * Create a {@code BitVector} from its text representation, e.g {@code "10110100"}. + * + * @param binaryDigits the text representation, made of {@code '0'} and {@code '1'} digits + * @return the vector + * @throws NullPointerException when {@code binaryDigits} is {@code null} + * @throws IllegalArgumentException when {@code binaryDigits} contains characters other than + * {@code '0'} and {@code '1'} + */ + public static BitVector create(String binaryDigits) { + Objects.requireNonNull(binaryDigits, "binaryDigits cannot be null"); + int bitLength = binaryDigits.length(); + byte[] packedBits = new byte[(bitLength + 7) / 8]; + for (int i = 0; i < bitLength; i++) { + char c = binaryDigits.charAt(i); + if (c == '1') { + packedBits[i / 8] |= (byte) (0x80 >> (i % 8)); + } else if (c != '0') { + throw new IllegalArgumentException("Invalid bit vector text: " + binaryDigits); + } + } + return new BitVector(packedBits, bitLength); + } + + private BitVector(byte[] packedBits, int bitLength) { + this.packedBits = packedBits; + this.bitLength = bitLength; + } + + /** + * @return the bits of this vector + */ + public boolean[] toBooleanArray() { + boolean[] bits = new boolean[bitLength]; + for (int i = 0; i < bitLength; i++) { + bits[i] = (packedBits[i / 8] & (0x80 >> (i % 8))) != 0; + } + return bits; + } + + /** + * @return the bits of this vector packed most significant bit first; the internal array is + * returned, mutations are visible + */ + public byte[] toPackedByteArray() { + return packedBits; + } + + @Override + public int dimension() { + return bitLength; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof BitVector) { + BitVector that = (BitVector) o; + return bitLength == that.bitLength && Arrays.equals(packedBits, that.packedBits); + } + return false; + } + + @Override + public int hashCode() { + return 31 * bitLength + Arrays.hashCode(packedBits); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(bitLength); + for (int i = 0; i < bitLength; i++) { + sb.append((packedBits[i / 8] & (0x80 >> (i % 8))) != 0 ? '1' : '0'); + } + return sb.toString(); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/ByteVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/ByteVector.java new file mode 100644 index 0000000000..82604b595b --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/ByteVector.java @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A vector of signed {@code byte} components. + *

+ * Instances can be created from an array of values or from the text representation shared by + * most databases, e.g {@code "[1,2,3]"}. When created from text, the components are parsed + * lazily on first access and the result is cached. + *

+ * Instances are not thread-safe when created from text, due to the unsynchronized lazy parsing + * of the text representation. + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * dimension and the components, regardless of the representation an instance was created from. + */ +public final class ByteVector implements Vector { + + private String text; + private byte[] values; + + /** + * Create a {@code ByteVector} from its text representation, e.g {@code "[1,2,3]"}. + *

+ * The text is stored and parsed lazily when the components are first accessed. The overall + * string is trimmed and must be a bracketed list of comma-separated components. An empty + * list denotes a zero-dimension vector. + * + * @param text the text representation + * @return the vector + * @throws NullPointerException when {@code text} is {@code null} + * @throws IllegalArgumentException when {@code text} is not a bracketed list + */ + public static ByteVector create(String text) { + Objects.requireNonNull(text, "text cannot be null"); + VectorText.checkText(text); + return new ByteVector(text); + } + + /** + * Create a {@code ByteVector} from its components. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static ByteVector create(byte[] values) { + Objects.requireNonNull(values, "values cannot be null"); + return new ByteVector(values); + } + + private ByteVector(String text) { + this.text = text; + } + + private ByteVector(byte[] values) { + this.values = values; + } + + /** + * @return the components of this vector, parsed lazily from the text representation when + * this vector was created from text; the internal array is returned, mutations are visible + * @throws IllegalArgumentException when the text representation is malformed + */ + public byte[] toByteArray() { + byte[] v = values; + if (v == null) { + v = values = VectorText.parseBytes(text); + } + return v; + } + + @Override + public int dimension() { + return toByteArray().length; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof ByteVector) { + ByteVector that = (ByteVector) o; + return Arrays.equals(toByteArray(), that.toByteArray()); + } + return false; + } + + @Override + public int hashCode() { + return Arrays.hashCode(toByteArray()); + } + + @Override + public String toString() { + return VectorText.toString(toByteArray()); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/DoubleVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/DoubleVector.java new file mode 100644 index 0000000000..f83be6636d --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/DoubleVector.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A vector of double precision {@code double} components. + *

+ * Instances can be created from an array of values or from the text representation shared by + * most databases, e.g {@code "[0.1,0.2,0.3]"}. When created from text, the components are + * parsed lazily on first access and the result is cached. + *

+ * Instances are not thread-safe when created from text, due to the unsynchronized lazy parsing + * of the text representation. + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * dimension and the components, regardless of the representation an instance was created from. + */ +public final class DoubleVector implements Vector { + + private String text; + private double[] values; + + /** + * Create a {@code DoubleVector} from its text representation, e.g {@code "[0.1,0.2,0.3]"}. + *

+ * The text is stored and parsed lazily when the components are first accessed. The overall + * string is trimmed and must be a bracketed list of comma-separated components. An empty + * list denotes a zero-dimension vector. + * + * @param text the text representation + * @return the vector + * @throws NullPointerException when {@code text} is {@code null} + * @throws IllegalArgumentException when {@code text} is not a bracketed list + */ + public static DoubleVector create(String text) { + Objects.requireNonNull(text, "text cannot be null"); + VectorText.checkText(text); + return new DoubleVector(text); + } + + /** + * Create a {@code DoubleVector} from its components. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static DoubleVector create(double[] values) { + Objects.requireNonNull(values, "values cannot be null"); + return new DoubleVector(values); + } + + /** + * Create a {@code DoubleVector} from single precision components, widening them to double + * precision. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static DoubleVector create(float[] values) { + Objects.requireNonNull(values, "values cannot be null"); + double[] doubles = new double[values.length]; + for (int i = 0; i < values.length; i++) { + doubles[i] = values[i]; + } + return new DoubleVector(doubles); + } + + private DoubleVector(String text) { + this.text = text; + } + + private DoubleVector(double[] values) { + this.values = values; + } + + /** + * @return the components of this vector, parsed lazily from the text representation when + * this vector was created from text; the internal array is returned, mutations are visible + * @throws IllegalArgumentException when the text representation is malformed + */ + public double[] toDoubleArray() { + double[] v = values; + if (v == null) { + v = values = VectorText.parseDoubles(text); + } + return v; + } + + /** + * @return a copy of the components of this vector, narrowed lossily to single precision + */ + public float[] toFloatArray() { + double[] v = toDoubleArray(); + float[] floats = new float[v.length]; + for (int i = 0; i < v.length; i++) { + floats[i] = (float) v[i]; + } + return floats; + } + + @Override + public int dimension() { + return toDoubleArray().length; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof DoubleVector) { + DoubleVector that = (DoubleVector) o; + return Arrays.equals(toDoubleArray(), that.toDoubleArray()); + } + return false; + } + + @Override + public int hashCode() { + return Arrays.hashCode(toDoubleArray()); + } + + @Override + public String toString() { + return VectorText.toString(toDoubleArray()); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/FloatVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/FloatVector.java new file mode 100644 index 0000000000..8cdfae1d64 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/FloatVector.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A vector of single precision {@code float} components. + *

+ * Instances can be created from an array of values or from the text representation shared by + * most databases, e.g {@code "[0.1,0.2,0.3]"}. When created from text, the components are + * parsed lazily on first access and the result is cached. + *

+ * Instances are not thread-safe when created from text, due to the unsynchronized lazy parsing + * of the text representation. + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * dimension and the components, regardless of the representation an instance was created from. + */ +public final class FloatVector implements Vector { + + private String text; + private float[] values; + + /** + * Create a {@code FloatVector} from its text representation, e.g {@code "[0.1,0.2,0.3]"}. + *

+ * The text is stored and parsed lazily when the components are first accessed. The overall + * string is trimmed and must be a bracketed list of comma-separated components. An empty + * list denotes a zero-dimension vector. + * + * @param text the text representation + * @return the vector + * @throws NullPointerException when {@code text} is {@code null} + * @throws IllegalArgumentException when {@code text} is not a bracketed list + */ + public static FloatVector create(String text) { + Objects.requireNonNull(text, "text cannot be null"); + VectorText.checkText(text); + return new FloatVector(text); + } + + /** + * Create a {@code FloatVector} from its components. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static FloatVector create(float[] values) { + Objects.requireNonNull(values, "values cannot be null"); + return new FloatVector(values); + } + + /** + * Create a {@code FloatVector} from double components, narrowing them to single precision. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static FloatVector create(double[] values) { + Objects.requireNonNull(values, "values cannot be null"); + float[] floats = new float[values.length]; + for (int i = 0; i < values.length; i++) { + floats[i] = (float) values[i]; + } + return new FloatVector(floats); + } + + private FloatVector(String text) { + this.text = text; + } + + private FloatVector(float[] values) { + this.values = values; + } + + /** + * @return the components of this vector, parsed lazily from the text representation when + * this vector was created from text; the internal array is returned, mutations are visible + * @throws IllegalArgumentException when the text representation is malformed + */ + public float[] toFloatArray() { + float[] v = values; + if (v == null) { + v = values = VectorText.parseFloats(text); + } + return v; + } + + /** + * @return a copy of the components of this vector, widened to double precision + */ + public double[] toDoubleArray() { + float[] v = toFloatArray(); + double[] doubles = new double[v.length]; + for (int i = 0; i < v.length; i++) { + doubles[i] = v[i]; + } + return doubles; + } + + @Override + public int dimension() { + return toFloatArray().length; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof FloatVector) { + FloatVector that = (FloatVector) o; + return Arrays.equals(toFloatArray(), that.toFloatArray()); + } + return false; + } + + @Override + public int hashCode() { + return Arrays.hashCode(toFloatArray()); + } + + @Override + public String toString() { + return VectorText.toString(toFloatArray()); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/HalfFloatVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/HalfFloatVector.java new file mode 100644 index 0000000000..8244f975c8 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/HalfFloatVector.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A vector of half precision components. + *

+ * Java has no half precision floating point type, therefore the components are held as single + * precision {@code float} values. Databases storing half precision vectors (e.g PostgreSQL + * {@code halfvec} columns or SQL Server {@code VECTOR(n, FLOAT16)} columns) convert the + * components lossily between the two precisions. + *

+ * Instances can be created from an array of values or from the text representation shared by + * most databases, e.g {@code "[0.1,0.2,0.3]"}. When created from text, the components are + * parsed lazily on first access and the result is cached. + *

+ * Instances are not thread-safe when created from text, due to the unsynchronized lazy parsing + * of the text representation. + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * dimension and the components, regardless of the representation an instance was created from. + */ +public final class HalfFloatVector implements Vector { + + private String text; + private float[] values; + + /** + * Create a {@code HalfFloatVector} from its text representation, e.g {@code "[0.1,0.2,0.3]"}. + *

+ * The text is stored and parsed lazily when the components are first accessed. The overall + * string is trimmed and must be a bracketed list of comma-separated components. An empty + * list denotes a zero-dimension vector. + * + * @param text the text representation + * @return the vector + * @throws NullPointerException when {@code text} is {@code null} + * @throws IllegalArgumentException when {@code text} is not a bracketed list + */ + public static HalfFloatVector create(String text) { + Objects.requireNonNull(text, "text cannot be null"); + VectorText.checkText(text); + return new HalfFloatVector(text); + } + + /** + * Create a {@code HalfFloatVector} from its components. + * + * @param values the components + * @return the vector + * @throws NullPointerException when {@code values} is {@code null} + */ + public static HalfFloatVector create(float[] values) { + Objects.requireNonNull(values, "values cannot be null"); + return new HalfFloatVector(values); + } + + private HalfFloatVector(String text) { + this.text = text; + } + + private HalfFloatVector(float[] values) { + this.values = values; + } + + /** + * @return the components of this vector, parsed lazily from the text representation when + * this vector was created from text; the internal array is returned, mutations are visible + * @throws IllegalArgumentException when the text representation is malformed + */ + public float[] toFloatArray() { + float[] v = values; + if (v == null) { + v = values = VectorText.parseFloats(text); + } + return v; + } + + @Override + public int dimension() { + return toFloatArray().length; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof HalfFloatVector) { + HalfFloatVector that = (HalfFloatVector) o; + return Arrays.equals(toFloatArray(), that.toFloatArray()); + } + return false; + } + + @Override + public int hashCode() { + return Arrays.hashCode(toFloatArray()); + } + + @Override + public String toString() { + return VectorText.toString(toFloatArray()); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/NullValue.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/NullValue.java index d479659121..5292903558 100644 --- a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/NullValue.java +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/NullValue.java @@ -68,6 +68,12 @@ public class NullValue { public static final NullValue ArrayOfBuffer = createAndCache(Buffer[].class); public static final NullValue ArrayOfUUID = createAndCache(UUID[].class); public static final NullValue ArrayOfBigDecimal = createAndCache(BigDecimal[].class); + public static final NullValue FloatVector = createAndCache(io.vertx.sqlclient.data.FloatVector.class); + public static final NullValue HalfFloatVector = createAndCache(io.vertx.sqlclient.data.HalfFloatVector.class); + public static final NullValue DoubleVector = createAndCache(io.vertx.sqlclient.data.DoubleVector.class); + public static final NullValue ByteVector = createAndCache(io.vertx.sqlclient.data.ByteVector.class); + public static final NullValue BitVector = createAndCache(io.vertx.sqlclient.data.BitVector.class); + public static final NullValue SparseFloatVector = createAndCache(io.vertx.sqlclient.data.SparseFloatVector.class); private static NullValue createAndCache(Class type) { NullValue instance = new NullValue(type); diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/SparseFloatVector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/SparseFloatVector.java new file mode 100644 index 0000000000..916773060f --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/SparseFloatVector.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +import java.util.Arrays; +import java.util.Objects; + +/** + * A sparse vector of single precision {@code float} components, holding only the non-zero + * positions. + *

+ * Instances map sparse vector types, e.g PostgreSQL {@code sparsevec} columns. The text + * representation, e.g {@code "{1:0.5,100:-0.25}/65535"}, uses one-based indices. + *

+ * Instances have value semantics: {@link #equals(Object)} and {@link #hashCode()} compare the + * dimension, the indices and the values. + */ +public final class SparseFloatVector implements Vector { + + private final int dimensions; + private final int[] indices; + private final float[] values; + + /** + * Create a {@code SparseFloatVector}. + *

+ * The given arrays are stored without copy, mutations are visible. Zero-valued entries are + * not rejected, databases may reject them. + * + * @param dimensions the total number of dimensions, including zero-valued ones + * @param indices the zero-based positions of the components, strictly ascending + * @param values the values of the components at these positions + * @return the vector + * @throws NullPointerException when {@code indices} or {@code values} is {@code null} + * @throws IllegalArgumentException when {@code dimensions} is negative, when the arrays have + * different lengths, or when {@code indices} are not strictly ascending within + * {@code [0, dimensions)} + */ + public static SparseFloatVector create(int dimensions, int[] indices, float[] values) { + Objects.requireNonNull(indices, "indices cannot be null"); + Objects.requireNonNull(values, "values cannot be null"); + if (dimensions < 0) { + throw new IllegalArgumentException("dimensions must be non-negative: " + dimensions); + } + if (indices.length != values.length) { + throw new IllegalArgumentException("indices and values must have the same length: " + + indices.length + " != " + values.length); + } + int previous = -1; + for (int index : indices) { + if (index < 0 || index >= dimensions) { + throw new IllegalArgumentException("index out of bounds [0, " + dimensions + "): " + index); + } + if (index <= previous) { + throw new IllegalArgumentException("indices must be strictly ascending: " + index + " follows " + previous); + } + previous = index; + } + return new SparseFloatVector(dimensions, indices, values); + } + + private SparseFloatVector(int dimensions, int[] indices, float[] values) { + this.dimensions = dimensions; + this.indices = indices; + this.values = values; + } + + @Override + public int dimension() { + return dimensions; + } + + /** + * @return the zero-based positions of the components, strictly ascending; the internal + * array is returned, mutations are visible + */ + public int[] indices() { + return indices; + } + + /** + * @return the values of the components at the positions returned by {@link #indices()}; the + * internal array is returned, mutations are visible + */ + public float[] values() { + return values; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof SparseFloatVector) { + SparseFloatVector that = (SparseFloatVector) o; + return dimensions == that.dimensions + && Arrays.equals(indices, that.indices) + && Arrays.equals(values, that.values); + } + return false; + } + + @Override + public int hashCode() { + int result = dimensions; + result = 31 * result + Arrays.hashCode(indices); + result = 31 * result + Arrays.hashCode(values); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + for (int i = 0; i < indices.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(indices[i] + 1).append(':').append(values[i]); + } + return sb.append('}').append('/').append(dimensions).toString(); + } +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/Vector.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/Vector.java new file mode 100644 index 0000000000..bc81a74f6f --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/Vector.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +/** + * A vector of values, mapping the vector data types provided by some databases. + *

+ * The following implementations are provided: + *

+ */ +public interface Vector { + + /** + * @return the total number of dimensions of this vector + */ + int dimension(); +} diff --git a/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/VectorText.java b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/VectorText.java new file mode 100644 index 0000000000..bbf0179890 --- /dev/null +++ b/vertx-sql-client/src/main/java/io/vertx/sqlclient/data/VectorText.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.sqlclient.data; + +/** + * The text representation shared by the dense vector types: a bracketed, comma-separated list + * of components, e.g {@code "[0.1,0.2,0.3]"}. + */ +final class VectorText { + + private VectorText() { + // Utility class + } + + /** + * Check that the text is a bracketed list. + * + * @throws IllegalArgumentException when the text is not a bracketed list + */ + static void checkText(String text) { + String s = text.trim(); + if (s.length() < 2 || s.charAt(0) != '[' || s.charAt(s.length() - 1) != ']') { + throw new IllegalArgumentException("Invalid vector text: " + text); + } + } + + /** + * Parse the text into single precision components. + * + * @throws IllegalArgumentException when the text is malformed + */ + static float[] parseFloats(String text) { + String[] tokens = tokens(text); + float[] values = new float[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + values[i] = Float.parseFloat(tokens[i]); + } catch (NumberFormatException e) { + throw invalidComponent(tokens[i]); + } + } + return values; + } + + /** + * Parse the text into double precision components. + * + * @throws IllegalArgumentException when the text is malformed + */ + static double[] parseDoubles(String text) { + String[] tokens = tokens(text); + double[] values = new double[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + values[i] = Double.parseDouble(tokens[i]); + } catch (NumberFormatException e) { + throw invalidComponent(tokens[i]); + } + } + return values; + } + + /** + * Parse the text into byte components. + * + * @throws IllegalArgumentException when the text is malformed + */ + static byte[] parseBytes(String text) { + String[] tokens = tokens(text); + byte[] values = new byte[tokens.length]; + for (int i = 0; i < tokens.length; i++) { + try { + values[i] = Byte.parseByte(tokens[i]); + } catch (NumberFormatException e) { + throw invalidComponent(tokens[i]); + } + } + return values; + } + + private static String[] tokens(String text) { + checkText(text); + String content = text.trim(); + content = content.substring(1, content.length() - 1).trim(); + if (content.isEmpty()) { + return new String[0]; + } + String[] tokens = content.split(",", -1); + for (int i = 0; i < tokens.length; i++) { + tokens[i] = tokens[i].trim(); + } + return tokens; + } + + private static IllegalArgumentException invalidComponent(String token) { + return new IllegalArgumentException("Invalid vector component: " + token); + } + + /** + * Render single precision components. + */ + static String toString(float[] values) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < values.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(values[i]); + } + return sb.append(']').toString(); + } + + /** + * Render double precision components. + */ + static String toString(double[] values) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < values.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(values[i]); + } + return sb.append(']').toString(); + } + + /** + * Render byte components. + */ + static String toString(byte[] values) { + StringBuilder sb = new StringBuilder("["); + for (int i = 0; i < values.length; i++) { + if (i > 0) { + sb.append(','); + } + sb.append(values[i]); + } + return sb.append(']').toString(); + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/BitVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/BitVectorTest.java new file mode 100644 index 0000000000..cf329b2793 --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/BitVectorTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.BitVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class BitVectorTest { + + @Test + public void testTextRoundTrip() { + assertEquals("10110100", BitVector.create("10110100").toString()); + assertEquals("", BitVector.create("").toString()); + assertEquals("0", BitVector.create("0").toString()); + assertEquals("1", BitVector.create("1").toString()); + } + + @Test + public void testPacking() { + BitVector vector = BitVector.create("10110100"); + assertEquals(8, vector.dimension()); + assertArrayEquals(new byte[]{(byte) 0xB4}, vector.toPackedByteArray()); + assertArrayEquals(new boolean[]{true, false, true, true, false, true, false, false}, vector.toBooleanArray()); + assertEquals("10110100", vector.toString()); + } + + @Test + public void testOddBitLength() { + // 10 bits: the last byte holds two significant bits, most significant bit first + BitVector vector = BitVector.create("1011010010"); + assertEquals(10, vector.dimension()); + assertArrayEquals(new byte[]{(byte) 0xB4, (byte) 0x80}, vector.toPackedByteArray()); + assertEquals("1011010010", vector.toString()); + assertArrayEquals( + new boolean[]{true, false, true, true, false, true, false, false, true, false}, + vector.toBooleanArray()); + // boolean round trip + assertEquals(vector, BitVector.create(vector.toBooleanArray())); + } + + @Test + public void testCreateFromBooleans() { + boolean[] bits = {true, false, true, true, false, true, false, false}; + BitVector vector = BitVector.create(bits); + assertEquals(8, vector.dimension()); + assertArrayEquals(new byte[]{(byte) 0xB4}, vector.toPackedByteArray()); + assertArrayEquals(bits, vector.toBooleanArray()); + assertEquals("10110100", vector.toString()); + } + + @Test + public void testCreateFromPackedBits() { + byte[] packedBits = {(byte) 0xB4}; + BitVector vector = BitVector.create(packedBits, 8); + // the internal array is returned + assertSame(packedBits, vector.toPackedByteArray()); + assertEquals(8, vector.dimension()); + assertEquals("10110100", vector.toString()); + // odd bit length: only the significant bits are exposed + BitVector odd = BitVector.create(new byte[]{(byte) 0xB4, (byte) 0x80}, 10); + assertEquals(10, odd.dimension()); + assertEquals("1011010010", odd.toString()); + } + + @Test + public void testEqualsHashCode() { + BitVector fromText = BitVector.create("10110100"); + BitVector fromBooleans = BitVector.create(new boolean[]{true, false, true, true, false, true, false, false}); + BitVector fromPacked = BitVector.create(new byte[]{(byte) 0xB4}, 8); + assertEquals(fromText, fromBooleans); + assertEquals(fromText, fromPacked); + assertEquals(fromText.hashCode(), fromPacked.hashCode()); + assertEquals(fromText, fromText); + assertNotEquals(fromText, null); + assertNotEquals(fromText, "10110100"); + assertNotEquals(fromText, BitVector.create("10110101")); + assertNotEquals(fromText, BitVector.create("1011010")); + // the trailing padding bits are part of the value + assertNotEquals(BitVector.create("1011"), BitVector.create(new byte[]{(byte) 0xB4}, 4)); + } + + @Test + public void testMalformedInput() { + assertIllegalArgumentException(() -> BitVector.create("10a1")); + assertIllegalArgumentException(() -> BitVector.create("1011010 ")); + assertIllegalArgumentException(() -> BitVector.create("[1,0]")); + assertIllegalArgumentException(() -> BitVector.create(new byte[1], -1)); + assertIllegalArgumentException(() -> BitVector.create(new byte[2], 8)); + assertIllegalArgumentException(() -> BitVector.create(new byte[0], 1)); + try { + BitVector.create((boolean[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + BitVector.create((byte[]) null, 0); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + BitVector.create((String) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/ByteVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/ByteVectorTest.java new file mode 100644 index 0000000000..6f84575fd9 --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/ByteVectorTest.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.ByteVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class ByteVectorTest { + + @Test + public void testTextRoundTrip() { + assertEquals("[1,2,3]", ByteVector.create("[1,2,3]").toString()); + // spaces are accepted, the output is canonical + assertEquals("[1,2,3]", ByteVector.create("[ 1 , 2 , 3 ]").toString()); + assertEquals("[1,-2,127,-128]", ByteVector.create("[1,-2,127,-128]").toString()); + } + + @Test + public void testEmptyVector() { + assertEquals(0, ByteVector.create("[]").dimension()); + assertEquals("[]", ByteVector.create("[]").toString()); + assertEquals(0, ByteVector.create("[ ]").dimension()); + assertEquals(0, ByteVector.create(new byte[0]).dimension()); + assertEquals("[]", ByteVector.create(new byte[0]).toString()); + } + + @Test + public void testArrayRoundTrip() { + byte[] values = {1, 2, 3}; + ByteVector vector = ByteVector.create(values); + assertEquals(3, vector.dimension()); + // the internal array is returned + assertSame(values, vector.toByteArray()); + assertEquals("[1,2,3]", vector.toString()); + } + + @Test + public void testLazyParse() { + // create does not parse the components: a malformed component is only rejected on access + ByteVector malformed = ByteVector.create("[a,b]"); + try { + malformed.toByteArray(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + // the text is parsed once and the result is cached + ByteVector vector = ByteVector.create("[1,2,3]"); + byte[] first = vector.toByteArray(); + assertSame(first, vector.toByteArray()); + assertArrayEquals(new byte[]{1, 2, 3}, first); + } + + @Test + public void testEqualsHashCode() { + ByteVector fromText = ByteVector.create("[1,2,3]"); + ByteVector fromArray = ByteVector.create(new byte[]{1, 2, 3}); + assertEquals(fromText, fromArray); + assertEquals(fromText.hashCode(), fromArray.hashCode()); + assertEquals(fromText, fromText); + assertNotEquals(fromText, null); + assertNotEquals(fromText, "[1,2,3]"); + assertNotEquals(fromText, ByteVector.create("[1,2]")); + assertNotEquals(fromText, ByteVector.create("[1,2,4]")); + assertNotEquals(fromText, ByteVector.create("[1,2,3,4]")); + } + + @Test + public void testMalformedInput() { + assertIllegalArgumentException(() -> ByteVector.create("1,2,3")); + assertIllegalArgumentException(() -> ByteVector.create("[1,2,3")); + assertIllegalArgumentException(() -> ByteVector.create("1,2,3]")); + assertIllegalArgumentException(() -> ByteVector.create("")); + assertIllegalArgumentException(() -> ByteVector.create("[")); + // component errors surface on access (lazy parsing) + assertIllegalArgumentException(() -> ByteVector.create("[a,b]").toByteArray()); + assertIllegalArgumentException(() -> ByteVector.create("[1,bogus]").toByteArray()); + assertIllegalArgumentException(() -> ByteVector.create("[,]").toByteArray()); + // out of byte range + assertIllegalArgumentException(() -> ByteVector.create("[128]").toByteArray()); + assertIllegalArgumentException(() -> ByteVector.create("[-129]").toByteArray()); + try { + ByteVector.create((String) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + ByteVector.create((byte[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/DoubleVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/DoubleVectorTest.java new file mode 100644 index 0000000000..4ee2c4f280 --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/DoubleVectorTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.DoubleVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class DoubleVectorTest { + + @Test + public void testTextRoundTrip() { + assertEquals("[0.1,0.2,0.3]", DoubleVector.create("[0.1,0.2,0.3]").toString()); + // spaces are accepted, the output is canonical + assertEquals("[0.1,0.2,0.3]", DoubleVector.create("[ 0.1 , 0.2 , 0.3 ]").toString()); + assertEquals("[1.0,2.0,3.0]", DoubleVector.create("[1,2,3]").toString()); + assertEquals("[0.5,-0.25,42.0]", DoubleVector.create("[0.5,-0.25,42]").toString()); + } + + @Test + public void testEmptyVector() { + assertEquals(0, DoubleVector.create("[]").dimension()); + assertEquals("[]", DoubleVector.create("[]").toString()); + assertEquals(0, DoubleVector.create("[ ]").dimension()); + assertEquals(0, DoubleVector.create(new double[0]).dimension()); + assertEquals("[]", DoubleVector.create(new double[0]).toString()); + } + + @Test + public void testArrayRoundTrip() { + double[] values = {0.1, 0.2, 0.3}; + DoubleVector vector = DoubleVector.create(values); + assertEquals(3, vector.dimension()); + // the internal array is returned + assertSame(values, vector.toDoubleArray()); + assertEquals("[0.1,0.2,0.3]", vector.toString()); + } + + @Test + public void testLazyParse() { + // create does not parse the components: a malformed component is only rejected on access + DoubleVector malformed = DoubleVector.create("[a,b]"); + try { + malformed.toDoubleArray(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + // the text is parsed once and the result is cached + DoubleVector vector = DoubleVector.create("[0.1,0.2,0.3]"); + double[] first = vector.toDoubleArray(); + assertSame(first, vector.toDoubleArray()); + assertArrayEquals(new double[]{0.1, 0.2, 0.3}, first, 0.0); + } + + @Test + public void testCreateFromFloats() { + // widening + DoubleVector vector = DoubleVector.create(new float[]{0.1f, 0.2f, 0.3f}); + assertEquals(3, vector.dimension()); + assertArrayEquals(new double[]{0.1f, 0.2f, 0.3f}, vector.toDoubleArray(), 0.0); + // lossy narrowing + assertArrayEquals(new float[]{0.1f, 0.2f, 0.3f}, vector.toFloatArray(), 0.0f); + } + + @Test + public void testEqualsHashCode() { + DoubleVector fromText = DoubleVector.create("[0.1,0.2,0.3]"); + DoubleVector fromArray = DoubleVector.create(new double[]{0.1, 0.2, 0.3}); + DoubleVector fromFloats = DoubleVector.create(new float[]{0.1f, 0.2f, 0.3f}); + assertEquals(fromText, fromArray); + assertEquals(fromText.hashCode(), fromArray.hashCode()); + assertEquals(fromText, fromText); + assertNotEquals(fromText, null); + assertNotEquals(fromText, "[0.1,0.2,0.3]"); + // 0.1f widened to double is not equal to the double literal 0.1 + assertNotEquals(fromText, fromFloats); + assertNotEquals(fromText, DoubleVector.create("[0.1,0.2]")); + assertNotEquals(fromText, DoubleVector.create("[0.1,0.2,0.4]")); + assertNotEquals(fromText, DoubleVector.create("[0.1,0.2,0.3,0.4]")); + } + + @Test + public void testMalformedInput() { + assertIllegalArgumentException(() -> DoubleVector.create("0.1,0.2")); + assertIllegalArgumentException(() -> DoubleVector.create("[0.1,0.2")); + assertIllegalArgumentException(() -> DoubleVector.create("0.1,0.2]")); + assertIllegalArgumentException(() -> DoubleVector.create("")); + assertIllegalArgumentException(() -> DoubleVector.create("[")); + // component errors surface on access (lazy parsing) + assertIllegalArgumentException(() -> DoubleVector.create("[a,b]").toDoubleArray()); + assertIllegalArgumentException(() -> DoubleVector.create("[0.1,bogus]").toDoubleArray()); + assertIllegalArgumentException(() -> DoubleVector.create("[,]").toDoubleArray()); + try { + DoubleVector.create((String) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + DoubleVector.create((double[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + DoubleVector.create((float[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/FloatVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/FloatVectorTest.java new file mode 100644 index 0000000000..087d7efa97 --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/FloatVectorTest.java @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.FloatVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class FloatVectorTest { + + @Test + public void testTextRoundTrip() { + assertEquals("[0.1,0.2,0.3]", FloatVector.create("[0.1,0.2,0.3]").toString()); + // spaces are accepted, the output is canonical + assertEquals("[0.1,0.2,0.3]", FloatVector.create("[ 0.1 , 0.2 , 0.3 ]").toString()); + assertEquals("[1.0,2.0,3.0]", FloatVector.create("[1,2,3]").toString()); + assertEquals("[0.5,-0.25,42.0]", FloatVector.create("[0.5,-0.25,42]").toString()); + } + + @Test + public void testEmptyVector() { + assertEquals(0, FloatVector.create("[]").dimension()); + assertEquals("[]", FloatVector.create("[]").toString()); + assertEquals(0, FloatVector.create("[ ]").dimension()); + assertEquals(0, FloatVector.create(new float[0]).dimension()); + assertEquals("[]", FloatVector.create(new float[0]).toString()); + } + + @Test + public void testArrayRoundTrip() { + float[] values = {0.1f, 0.2f, 0.3f}; + FloatVector vector = FloatVector.create(values); + assertEquals(3, vector.dimension()); + // the internal array is returned + assertSame(values, vector.toFloatArray()); + assertEquals("[0.1,0.2,0.3]", vector.toString()); + } + + @Test + public void testLazyParse() { + // create does not parse the components: a malformed component is only rejected on access + FloatVector malformed = FloatVector.create("[a,b]"); + try { + malformed.toFloatArray(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + // the text is parsed once and the result is cached + FloatVector vector = FloatVector.create("[0.1,0.2,0.3]"); + float[] first = vector.toFloatArray(); + assertSame(first, vector.toFloatArray()); + assertArrayEquals(new float[]{0.1f, 0.2f, 0.3f}, first, 0.0f); + } + + @Test + public void testEqualsHashCode() { + FloatVector fromText = FloatVector.create("[0.1,0.2,0.3]"); + FloatVector fromArray = FloatVector.create(new float[]{0.1f, 0.2f, 0.3f}); + assertEquals(fromText, fromArray); + assertEquals(fromText.hashCode(), fromArray.hashCode()); + assertEquals(fromText, fromText); + assertNotEquals(fromText, null); + assertNotEquals(fromText, "[0.1,0.2,0.3]"); + assertNotEquals(fromText, FloatVector.create("[0.1,0.2]")); + assertNotEquals(fromText, FloatVector.create("[0.1,0.2,0.4]")); + assertNotEquals(fromText, FloatVector.create("[0.1,0.2,0.3,0.4]")); + } + + @Test + public void testMalformedInput() { + assertIllegalArgumentException(() -> FloatVector.create("0.1,0.2")); + assertIllegalArgumentException(() -> FloatVector.create("[0.1,0.2")); + assertIllegalArgumentException(() -> FloatVector.create("0.1,0.2]")); + assertIllegalArgumentException(() -> FloatVector.create("")); + assertIllegalArgumentException(() -> FloatVector.create("[")); + assertIllegalArgumentException(() -> FloatVector.create("null")); + // component errors surface on access (lazy parsing) + assertIllegalArgumentException(() -> FloatVector.create("[a,b]").toFloatArray()); + assertIllegalArgumentException(() -> FloatVector.create("[0.1,bogus]").toFloatArray()); + assertIllegalArgumentException(() -> FloatVector.create("[,]").toFloatArray()); + try { + FloatVector.create((String) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + FloatVector.create((float[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + @Test + public void testCreateFromDoubles() { + // narrowing + FloatVector vector = FloatVector.create(new double[]{0.1, 0.2, 0.3}); + assertEquals(3, vector.dimension()); + assertArrayEquals(new float[]{0.1f, 0.2f, 0.3f}, vector.toFloatArray(), 0.0f); + // widening copy + double[] doubles = vector.toDoubleArray(); + assertArrayEquals(new double[]{0.1f, 0.2f, 0.3f}, doubles, 0.0); + assertNotSame(doubles, vector.toDoubleArray()); + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/HalfFloatVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/HalfFloatVectorTest.java new file mode 100644 index 0000000000..9db76662ff --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/HalfFloatVectorTest.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.HalfFloatVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class HalfFloatVectorTest { + + @Test + public void testTextRoundTrip() { + assertEquals("[0.1,0.2,0.3]", HalfFloatVector.create("[0.1,0.2,0.3]").toString()); + // spaces are accepted, the output is canonical + assertEquals("[0.1,0.2,0.3]", HalfFloatVector.create("[ 0.1 , 0.2 , 0.3 ]").toString()); + assertEquals("[1.0,2.0,3.0]", HalfFloatVector.create("[1,2,3]").toString()); + assertEquals("[0.5,-0.25,42.0]", HalfFloatVector.create("[0.5,-0.25,42]").toString()); + } + + @Test + public void testEmptyVector() { + assertEquals(0, HalfFloatVector.create("[]").dimension()); + assertEquals("[]", HalfFloatVector.create("[]").toString()); + assertEquals(0, HalfFloatVector.create("[ ]").dimension()); + assertEquals(0, HalfFloatVector.create(new float[0]).dimension()); + assertEquals("[]", HalfFloatVector.create(new float[0]).toString()); + } + + @Test + public void testArrayRoundTrip() { + float[] values = {0.1f, 0.2f, 0.3f}; + HalfFloatVector vector = HalfFloatVector.create(values); + assertEquals(3, vector.dimension()); + // the internal array is returned + assertSame(values, vector.toFloatArray()); + assertEquals("[0.1,0.2,0.3]", vector.toString()); + } + + @Test + public void testLazyParse() { + // create does not parse the components: a malformed component is only rejected on access + HalfFloatVector malformed = HalfFloatVector.create("[a,b]"); + try { + malformed.toFloatArray(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + // the text is parsed once and the result is cached + HalfFloatVector vector = HalfFloatVector.create("[0.1,0.2,0.3]"); + float[] first = vector.toFloatArray(); + assertSame(first, vector.toFloatArray()); + assertArrayEquals(new float[]{0.1f, 0.2f, 0.3f}, first, 0.0f); + } + + @Test + public void testEqualsHashCode() { + HalfFloatVector fromText = HalfFloatVector.create("[0.1,0.2,0.3]"); + HalfFloatVector fromArray = HalfFloatVector.create(new float[]{0.1f, 0.2f, 0.3f}); + assertEquals(fromText, fromArray); + assertEquals(fromText.hashCode(), fromArray.hashCode()); + assertEquals(fromText, fromText); + assertNotEquals(fromText, null); + assertNotEquals(fromText, "[0.1,0.2,0.3]"); + assertNotEquals(fromText, HalfFloatVector.create("[0.1,0.2]")); + assertNotEquals(fromText, HalfFloatVector.create("[0.1,0.2,0.4]")); + assertNotEquals(fromText, HalfFloatVector.create("[0.1,0.2,0.3,0.4]")); + } + + @Test + public void testMalformedInput() { + assertIllegalArgumentException(() -> HalfFloatVector.create("0.1,0.2")); + assertIllegalArgumentException(() -> HalfFloatVector.create("[0.1,0.2")); + assertIllegalArgumentException(() -> HalfFloatVector.create("0.1,0.2]")); + assertIllegalArgumentException(() -> HalfFloatVector.create("")); + assertIllegalArgumentException(() -> HalfFloatVector.create("[")); + // component errors surface on access (lazy parsing) + assertIllegalArgumentException(() -> HalfFloatVector.create("[a,b]").toFloatArray()); + assertIllegalArgumentException(() -> HalfFloatVector.create("[0.1,bogus]").toFloatArray()); + assertIllegalArgumentException(() -> HalfFloatVector.create("[,]").toFloatArray()); + try { + HalfFloatVector.create((String) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + HalfFloatVector.create((float[]) null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/SparseFloatVectorTest.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/SparseFloatVectorTest.java new file mode 100644 index 0000000000..647ffa6008 --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/data/SparseFloatVectorTest.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.data; + +import io.vertx.sqlclient.data.SparseFloatVector; +import org.junit.Test; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class SparseFloatVectorTest { + + @Test + public void testAccessors() { + int[] indices = {0, 99}; + float[] values = {0.5f, -0.25f}; + SparseFloatVector vector = SparseFloatVector.create(65535, indices, values); + assertEquals(65535, vector.dimension()); + // the internal arrays are returned + assertSame(indices, vector.indices()); + assertSame(values, vector.values()); + } + + @Test + public void testToString() { + // one-based indices + SparseFloatVector vector = SparseFloatVector.create(65535, new int[]{0, 99}, new float[]{0.5f, -0.25f}); + assertEquals("{1:0.5,100:-0.25}/65535", vector.toString()); + // single entry + assertEquals("{1:0.5}/3", SparseFloatVector.create(3, new int[]{0}, new float[]{0.5f}).toString()); + // no entries + assertEquals("{}/10", SparseFloatVector.create(10, new int[0], new float[0]).toString()); + // zero-dimension vector + assertEquals("{}/0", SparseFloatVector.create(0, new int[0], new float[0]).toString()); + } + + @Test + public void testZeroValuesAreAllowed() { + // zero-valued entries are not rejected client-side, databases may reject them + SparseFloatVector vector = SparseFloatVector.create(3, new int[]{1}, new float[]{0.0f}); + assertEquals(3, vector.dimension()); + assertArrayEquals(new int[]{1}, vector.indices()); + assertArrayEquals(new float[]{0.0f}, vector.values(), 0.0f); + } + + @Test + public void testEqualsHashCode() { + SparseFloatVector vector = SparseFloatVector.create(65535, new int[]{0, 99}, new float[]{0.5f, -0.25f}); + assertEquals(vector, SparseFloatVector.create(65535, new int[]{0, 99}, new float[]{0.5f, -0.25f})); + assertEquals(vector.hashCode(), SparseFloatVector.create(65535, new int[]{0, 99}, new float[]{0.5f, -0.25f}).hashCode()); + assertEquals(vector, vector); + assertNotEquals(vector, null); + assertNotEquals(vector, "{1:0.5,100:-0.25}/65535"); + // different dimensions + assertNotEquals(vector, SparseFloatVector.create(65534, new int[]{0, 99}, new float[]{0.5f, -0.25f})); + // different indices + assertNotEquals(vector, SparseFloatVector.create(65535, new int[]{0, 98}, new float[]{0.5f, -0.25f})); + // different values + assertNotEquals(vector, SparseFloatVector.create(65535, new int[]{0, 99}, new float[]{0.5f, -0.26f})); + // different number of entries + assertNotEquals(vector, SparseFloatVector.create(65535, new int[]{0}, new float[]{0.5f})); + } + + @Test + public void testValidation() { + // negative dimensions + assertIllegalArgumentException(() -> SparseFloatVector.create(-1, new int[0], new float[0])); + // mismatching lengths + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[]{0}, new float[0])); + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[0], new float[]{0.5f})); + // out of bounds indices + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[]{-1}, new float[]{0.5f})); + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[]{10}, new float[]{0.5f})); + // not strictly ascending + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[]{1, 1}, new float[]{0.5f, 0.5f})); + assertIllegalArgumentException(() -> SparseFloatVector.create(10, new int[]{2, 1}, new float[]{0.5f, 0.5f})); + try { + SparseFloatVector.create(10, null, new float[0]); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + try { + SparseFloatVector.create(10, new int[0], null); + fail("Should throw NullPointerException"); + } catch (NullPointerException e) { + // expected + } + } + + private static void assertIllegalArgumentException(Runnable action) { + try { + action.run(); + fail("Should throw IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // expected + } + } +} diff --git a/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/tck/VectorDataTypeTestBase.java b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/tck/VectorDataTypeTestBase.java new file mode 100644 index 0000000000..65600e0e7a --- /dev/null +++ b/vertx-sql-client/src/test/java/io/vertx/tests/sqlclient/tck/VectorDataTypeTestBase.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2011-2026 Contributors to the Eclipse Foundation + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 + * which is available at https://www.apache.org/licenses/LICENSE-2.0. + * + * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 + */ + +package io.vertx.tests.sqlclient.tck; + +import io.vertx.core.Vertx; +import io.vertx.ext.unit.TestContext; +import io.vertx.sqlclient.Row; +import io.vertx.sqlclient.SqlConnection; +import io.vertx.sqlclient.Tuple; +import io.vertx.sqlclient.data.FloatVector; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; + +/** + * Base class for testing vector data types. + *

+ * Tests run against a table named {@code vertx_test_vector} with columns {@code (id, emb, notes)}, + * where the {@code emb} column holds single precision float vectors. The table must be seeded with + * a row holding the vector returned by {@link #expectedFloatVector()} and a row holding a + * {@code NULL} vector, at the ids {@link #FLOAT_VECTOR_ROW_ID} and {@link #NULL_ROW_ID}. + *

+ * The exact DDL is database-specific and defined by the subclasses. + */ +public abstract class VectorDataTypeTestBase { + + /** + * The id of the row holding the vector returned by {@link #expectedFloatVector()}. + */ + protected static final int FLOAT_VECTOR_ROW_ID = 1; + + /** + * The id of the row holding the {@code NULL} vector. + */ + protected static final int NULL_ROW_ID = 2; + + /** + * The id used by the encode tests, cleaned up after verification. + */ + protected static final int ENCODED_ROW_ID = 3; + + protected Vertx vertx; + protected Connector connector; + + protected abstract void initConnector(); + + /** + * Build a statement from the given parts, joining them with the parameter placeholders of + * the database under test. + */ + protected abstract String statement(String... parts); + + @Before + public void setUp(TestContext ctx) throws Exception { + vertx = Vertx.vertx(); + initConnector(); + } + + @After + public void tearDown(TestContext ctx) { + connector.close(); + vertx.close().onComplete(ctx.asyncAssertSuccess()); + } + + /** + * @return the components of the vector held by the row at {@link #FLOAT_VECTOR_ROW_ID} + */ + protected float[] expectedFloatVector() { + return new float[]{0.1f, 0.2f, 0.3f}; + } + + /** + * Assert the value decoded from the {@code emb} column of a {@code vertx_test_vector} row. + *

+ * The default implementation expects the value to be auto-decoded to a {@link FloatVector}; + * subclasses may override it when the database under test delivers the value in another + * representation. + */ + protected void assertDecodedFloatVector(TestContext ctx, Row row, float[] expected) { + Object value = row.getValue(0); + ctx.assertTrue(value instanceof FloatVector, "Expected FloatVector but was: " + value); + ctx.assertTrue(Arrays.equals(expected, ((FloatVector) value).toFloatArray()), + "Expected " + Arrays.toString(expected) + " but was: " + value); + } + + @Test + public void testDecodeFloatVector(TestContext ctx) { + String sql = "SELECT emb FROM vertx_test_vector WHERE id = " + FLOAT_VECTOR_ROW_ID; + connector.connect(ctx.asyncAssertSuccess(conn -> { + // text protocol + conn.query(sql).execute().onComplete(ctx.asyncAssertSuccess(textResult -> { + ctx.assertEquals(1, textResult.size()); + assertDecodedFloatVector(ctx, textResult.iterator().next(), expectedFloatVector()); + // binary protocol + conn.preparedQuery(sql).execute().onComplete(ctx.asyncAssertSuccess(binaryResult -> { + ctx.assertEquals(1, binaryResult.size()); + assertDecodedFloatVector(ctx, binaryResult.iterator().next(), expectedFloatVector()); + conn.close(); + })); + })); + })); + } + + @Test + public void testDecodeNullVector(TestContext ctx) { + connector.connect(ctx.asyncAssertSuccess(conn -> { + conn.query("SELECT emb FROM vertx_test_vector WHERE id = " + NULL_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + Row row = result.iterator().next(); + ctx.assertNull(row.getValue(0)); + conn.close(); + })); + })); + } + + @Test + public void testEncodeFloatVector(TestContext ctx) { + float[] inserted = {0.25f, -0.5f, 3.0f}; + connector.connect(ctx.asyncAssertSuccess(conn -> { + conn.preparedQuery(statement("INSERT INTO vertx_test_vector (id, emb, notes) VALUES (", ", ", ", ", ")")) + .execute(Tuple.of(ENCODED_ROW_ID, FloatVector.create(inserted), "tck")) + .onComplete(ctx.asyncAssertSuccess(insertResult -> { + ctx.assertEquals(1, insertResult.rowCount()); + conn.preparedQuery("SELECT emb FROM vertx_test_vector WHERE id = " + ENCODED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + assertDecodedFloatVector(ctx, result.iterator().next(), inserted); + conn.preparedQuery("DELETE FROM vertx_test_vector WHERE id = " + ENCODED_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(deleteResult -> { + conn.close(); + })); + })); + })); + })); + } + + @Test + public void testGetFloatVectorByClass(TestContext ctx) { + connector.connect(ctx.asyncAssertSuccess(conn -> { + conn.preparedQuery("SELECT emb FROM vertx_test_vector WHERE id = " + FLOAT_VECTOR_ROW_ID) + .execute() + .onComplete(ctx.asyncAssertSuccess(result -> { + ctx.assertEquals(1, result.size()); + Row row = result.iterator().next(); + FloatVector vector = row.get(FloatVector.class, 0); + ctx.assertNotNull(vector, "Expected a FloatVector convertible value"); + ctx.assertTrue(Arrays.equals(expectedFloatVector(), vector.toFloatArray())); + conn.close(); + })); + })); + } +}