pgjdbc_r2dbc-postgresql
Языки
- Java99,7%
- Shell0,3%
PostgreSQL R2DBC Driver

This project contains the PostgreSQL implementation of the R2DBC SPI. This implementation is not intended to be used directly, but rather to be used as the backing implementation for a humane client library to delegate to.
This driver provides the following features:
- Implements R2DBC 1.0
- Login with username/password (MD5, SASL/SCRAM) or implicit trust
- Supports credential rotation by providing
orSupplier<String>Publisher<String> - SCRAM authentication
- Unix Domain Socket transport
- Connection Fail-over supporting multiple hosts
- TLS
- Explicit transactions
- Notifications
- Logical Decode
- Binary data transfer
- Execution of prepared statements with bindings
- Execution of batch statements without bindings
- Read and write support for a majority of data types (see Data Type Mapping for details)
- Fetching of
usingREFCURSORio.r2dbc.postgresql.api.RefCursor - Extension points to register
s to handle additional PostgreSQL data typesCodec
Next steps:
- Multi-dimensional arrays
Code of Conduct
This project is governed by the Code of Conduct. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to r2dbc@googlegroups.com.
Getting Started
Here is a quick teaser of how to use R2DBC PostgreSQL in Java:
URL Connection Factory Discovery
Programmatic Connection Factory Discovery
Supported ConnectionFactory Discovery Options
| Option | Description |
|---|---|
| Enables SSL usage (). |
| Must be . |
| Protocol specifier. Empty to use single-host operations. Supported: for multi-server failover operations. (Optional) |
| Server hostname to connect to. May contain a comma-separated list of hosts with ports when using the protocol. |
| Server port to connect to. Defaults to . (Optional) |
| Unix Domain Socket path to connect to as alternative to TCP. (Optional) |
| Login username. Can be a plain , , or . |
| Login password. Can be a plain , , or . (Optional when using TLS Certificate authentication) |
| Database to select. (Optional) |
| The name of the application connecting to the database. Defaults to . (Optional) |
| Whether to auto-detect and register s from the class path. Defaults to . (Optional) |
| Enable compatibility mode for cursored fetching. Required when using newer pgpool versions. Defaults to . (Optional) |
| Log level for error responses. Any of , , , or Defaults to . (Optional) |
| Collection of to provide additional extensions when creating a connection factory. Defaults to empty. (Optional) |
| The default number of rows to return when fetching results. Defaults to for unlimited. (Optional) |
| Whether to force binary transfer. Defaults to . (Optional) |
| Host status recheck time when using multi-server operations. Defaults to . (Optional) |
| Whether to shuffle the list of given hostnames before connect when using multi-server operations. Defaults to . (Optional) |
| TCP/Socket LoopResources (depends on the endpoint connection type). (Optional) |
| Lock wait timeout. (Optional) |
| Log level for error responses. Any of , , , or Defaults to . (Optional) |
| Configure whether codecs should prefer attached data buffers. The default is , meaning that codecs will copy data from the input buffer into a byte array. Enabling attached buffers requires consumption of values such as to avoid memory leaks. |
| Determine the number of queries that are cached in each connection. The default is , meaning there's no limit. The value of disables the cache. Any other value specifies the cache size. |
| A of connection parameters. These are applied to each database connection created by the . Useful for setting generic PostgreSQL connection parameters. (Optional) |
| The search path to set. (Optional) |
| SSL mode to use, see enum. Supported values: , , , , , , . (Optional) |
| Path to SSL CA certificate in PEM format. Can be also a resource path. (Optional) |
| Path to SSL key for TLS authentication in PEM format. Can be also a resource path. (Optional) |
| Path to SSL certificate for TLS authentication in PEM format. Can be also a resource path. (Optional) |
| Key password to decrypt SSL key. (Optional) |
| implementation. (Optional) |
| Enable/disable SNI to send the configured name during the SSL handshake. Defaults to . (Optional) |
| Statement timeout. (Optional) |
| Type of server to use when using multi-host operations. Supported values: , , , . Defaults to . (Optional) |
| Enable/disable TCP NoDelay. Enabled by default. (Optional) |
| Enable/disable TCP KeepAlive. Disabled by default. (Optional) |
| Configure the session timezone to control conversion of local temporal representations. Defaults to (Optional) |
Programmatic Configuration
PostgreSQL uses index parameters that are prefixed with . The following SQL statement makes use of parameters:
Parameters are referenced using the same identifiers when binding these:
Binding also allowed positional index (zero-based) references. The parameter index is derived from the parameter discovery order when parsing the query.
Maven configuration
Artifacts can be found on Maven Central.
If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.
Connection Fail-over
To support simple connection fail-over it is possible to define multiple endpoints (host and port pairs) in the connection url separated by commas. The driver will try once to connect to each of them
in order until the connection succeeds. If none succeeds a normal connection exception is thrown. Make sure to specify the protocol.
The syntax for the connection url is:
r2dbc:postgresql:failover://user:foo@host1:5433,host2:5432,host3
For example an application can create two connection pools. One data source is for writes, another for reads. The write pool limits connections only to a primary node:
r2dbc:postgresql:failover://user:foo@host1:5433,host2:5432,host3?targetServerType=primary.
Cursors
R2DBC Postgres supports both, the simple and extended message flow.
Cursored fetching is activated by configuring a . Postgres cursors are valid for the duration of a transaction. R2DBC can use cursors in auto-commit mode ( and ) to not
require an explicit transaction (). Newer pgpool versions don't support this feature. To work around this limitation, either use explicit transactions when configuring a fetch
size or enable compatibility mode. Compatibility mode avoids cursors in auto-commit mode ( with no limit + ). Cursors in a transaction use (with fetch size as limit) +
as message flow.
Listen/Notify
Listen and Notify provide a simple form of signal or inter-process communication mechanism for processes accessing the same PostgreSQL database. For Listen/Notify, two actors are involved: The sender (notify) and the receiver (listen). The following example uses two connections to illustrate how they work together:
Upon subscription, the first connection enters listen mode and publishes incoming s as . The second connection broadcasts a notification to the channel upon
subscription.
Transaction Definitions
Postgres supports additional options when starting a transaction. In particular, the following options can be specified:
- Isolation Level (
) (reset after the transaction to previous value)isolationLevel - Transaction Mutability (
)readOnly - Deferrable Mode (
)deferrable
These options can be specified upon transaction begin to start the transaction and apply options in a single command roundtrip:
See also: https://www.postgresql.org/docs/current/sql-begin.html
JSON/JSONB support
PostgreSQL supports JSON by storing values in / columns. These values can be consumed and written using the regular R2DBC SPI and by using driver-specific extensions with
the type.
You can choose from two approaches:
- Native JSONB encoding using the
wrapper type.Json - Using scalar types.
The difference between the type and scalar types is that values are written encoded as to the database.
and types are represented as respective and require casting () when used with parameterized statements.
The following code shows and cases for JSON interaction:
Write JSON
Consume JSON
Write JSON using casting
Consume JSON as scalar type
The following types are supported for JSON exchange:
- io.r2dbc.postgresql.codec.Json
(must be released after usage to avoid memory leaks)ByteBuf- ByteBuffer
- byte[]
- String
(must be closed after usage to avoid memory leaks)InputStream
CITEXT support
CITEXT is a built-in extension to support case-insensitive columns. By default, the driver sends all string values as that cannot be used directly with (without casting or converting values in your SQL).
If you cast input, then you can send parameters to the server without further customization of the driver:
If you want to send individual -values in a CITEXT-compatible way, then use :
If you do not have control over the created SQL or you want to send all values in a CITEXT-compatible way, then you can customize the driver configuration by registering a to send values with the OID to let Postgres infer the value type from the provided values:
You can register also the as so that it gets auto-detected during creation.
Cursors
The driver can consume cursors that were created by PL/pgSQL as .
Cursors are represented as objects. Cursors obtained from can be used to fetch the cursor directly.
Since cursors are stateful, they must be closed once they are no longer in use.
Logical Decode
PostgreSQL allows replication streaming and decoding persistent changes to a database's tables into useful chunks of data. In PostgreSQL, logical decoding is implemented by decoding the contents of the write-ahead log, which describe changes on a storage level, into an application-specific form such as a stream of tuples or SQL statements.
Consuming the replication stream is a four-step process:
- Obtain a replication connection via
.PostgresqlConnectionFactory.replication() - Create a replication slot (physical/logical).
- Initiate replication using the replication slot.
- Once the replication stream is set up, you can consume and map the binary data using
.ReplicationStream.map(…)
On application shutdown, the .
Note that a connection is busy once the replication is active and a connection can have at most one active replication stream.
Postgres Enum Types
Applications may make use of Postgres enumerated types by using to map custom types to Java types.
requires the Postgres OID and the Java to map enum values to the Postgres protocol and to materialize Enum instances from Postgres results.
You can configure a through for one or more enumeration type mappings. Make sure to use different Java enum types otherwise the driver is not able to distinguish between Postgres OIDs.
Example:
SQL:
Java Model:
Codec Registration:
When available, the driver registers also an array variant of the codec.
Data Type Mapping
This reference table shows the type mapping between PostgreSQL and Java data types:
Types in bold indicate the native (default) Java type.
Support for the following single-dimensional arrays (read and write):
Extension mechanism
This driver accepts the following extensions:
to contributeCodecRegistrars for PostgreSQL ObjectIDs.Codec
Extensions can be registered programmatically using or discovered using Java's mechanism (from ).
The driver ships with built-in dynamic codecs (e.g. , PostGIS ) that are registered during the connection handshake depending on their availability while connecting. Note that Postgres extensions registered after a connection was established require a reconnect to initialize the codec.
Logging
If SL4J is on the classpath, it will be used. Otherwise, there are two possible fallbacks: Console or ). By default, the Console fallback is used. To use the JDK loggers, set the System property to .
Logging facilities:
- Driver Logging (
)io.r2dbc.postgresql - Query Logging (
onio.r2dbc.postgresql.QUERYlevel)DEBUG - Parameters' values Logging (
onio.r2dbc.postgresql.PARAMlevel)DEBUG - Transport Logging (
)io.r2dbc.postgresql.clientenablesDEBUGexchange loggingMessageenables traffic loggingTRACE
Logging that is associated with a connection reports the logical connection id () which is a driver-local connection counter and the Postgres Process Id () once the connection handshake finishes.
Getting Help
Having trouble with R2DBC? We'd love to help!
- Check the spec documentation, and Javadoc.
- If you are upgrading, check out the changelog for "new and noteworthy" features.
- Ask a question - we monitor stackoverflow.com for questions
tagged with
. You can also chat with the community on Gitter.r2dbc - Report bugs with R2DBC PostgreSQL at github.com/pgjdbc/r2dbc-postgresql/issues.
Reporting Issues
R2DBC uses GitHub as issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:
- Before you log a bug, please search the issue tracker to see if someone has already reported the problem.
- If the issue doesn't already exist, create a new issue.
- Please provide as much information as possible with the issue report, we like to know the version of R2DBC PostgreSQL that you are using and JVM version.
- If you need to paste code, or include a stack trace use Markdown ``` escapes before and after your text.
- If possible try to create a test-case or project that replicates the issue. Attach a link to your code or a compressed file containing your code.
Building from Source
You don't need to build from source to use R2DBC PostgreSQL (binaries in Maven Central), but if you want to try out the latest and greatest, R2DBC PostgreSQL can be easily built with the maven wrapper. You also need JDK 1.8 and Docker to run integration tests.
If you want to build with the regular command, you will need Maven v3.5.0 or above.
Also see CONTRIBUTING.adoc if you wish to submit pull requests.
Running JMH Benchmarks
Running the JMH benchmarks builds and runs the benchmarks without running tests.
License
This project is released under version 2.0 of the Apache License.