Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions vertx-pg-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@
<PGUSER>test_user</PGUSER>
<PGPASSWORD>test_password</PGPASSWORD>
<PGSSLMODE>require</PGSSLMODE>
<PGVECTORTYPEENABLED>true</PGVECTORTYPEENABLED>
</environmentVariables>
</configuration>
</execution>
Expand Down
83 changes: 81 additions & 2 deletions vertx-pg-client/src/main/asciidoc/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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}.

Expand All @@ -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.

Expand Down Expand Up @@ -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[]`
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
50 changes: 49 additions & 1 deletion vertx-pg-client/src/main/java/examples/PgClientExamples.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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" });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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<String, String> DEFAULT_PROPERTIES;

static {
Expand All @@ -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();
Expand All @@ -149,6 +154,7 @@ public PgConnectOptions(SqlConnectOptions other) {
sslMode = opts.sslMode;
sslNegotiation = opts.sslNegotiation;
channelBinding = opts.channelBinding;
vectorTypeEnabled = opts.vectorTypeEnabled;
}
}

Expand All @@ -158,6 +164,7 @@ public PgConnectOptions(PgConnectOptions other) {
sslMode = other.sslMode;
sslNegotiation = other.sslNegotiation;
channelBinding = other.channelBinding;
vectorTypeEnabled = other.vectorTypeEnabled;
}

@Override
Expand Down Expand Up @@ -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}).
* <p>
* 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);
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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));
Expand Down
24 changes: 23 additions & 1 deletion vertx-pg-client/src/main/java/io/vertx/pgclient/impl/PgRow.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -152,6 +152,10 @@ public <T> T get(Class<T> 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) {
Expand All @@ -165,6 +169,24 @@ public <T> T get(Class<T> 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);
}
Expand Down
Loading
Loading