/r2dbc-mssql

R2DBC Driver for Microsoft SQL Server using TDS (Tabular Data Stream) Protocol

Primary LanguageJavaApache License 2.0Apache-2.0

Reactive Relational Database Connectivity Microsoft SQL Server Implementation Java CI with Maven Maven Central

This project contains the Microsoft SQL Server 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:

  • Complies with R2DBC 0.9
  • Login with username/password with temporary SSL encryption
  • Full SSL encryption support (for e.g. Azure usage).
  • Transaction Control
  • Simple execution of SQL batches (direct and cursored execution)
  • Execution of parametrized statements (direct and cursored execution)
  • Extensive type support (including TEXT, VARCHAR(MAX), IMAGE, VARBINARY(MAX) and national variants, see below for exceptions)
  • Execution of stored procedures

Next steps:

  • Add support for TVP and UDTs

Code of Conduct

This project is governed by the R2DBC Code of Conduct. By participating, you are expected to uphold this code of conduct. Please report unacceptable behavior to info@r2dbc.io.

Getting Started

Here is a quick teaser of how to use R2DBC MSSQL in Java:

URL Connection Factory Discovery

ConnectionFactory connectionFactory = ConnectionFactories.get("r2dbc:mssql://<host>:1433/<database>");

Publisher<? extends Connection> connectionPublisher = connectionFactory.create();

Programmatic Connection Factory Discovery

ConnectionFactoryOptions options = builder()
    .option(DRIVER, "sqlserver")
    .option(HOST, "…")
    .option(PORT, …)  // optional, defaults to 1433
    .option(USER, "…")
    .option(PASSWORD, "…")
    .option(DATABASE, "…") // optional
    .option(SSL, true) // optional, defaults to false
    .option(Option.valueOf("applicationName"), "…") // optional
    .option(Option.valueOf("preferCursoredExecution"), true/false) // optional
    .option(Option.valueOf("connectionId"), new UUID(…)) // optional
    .build();

ConnectionFactory connectionFactory = ConnectionFactories.get(options);

Publisher<? extends Connection> connectionPublisher = connectionFactory.create();

// Alternative: Creating a Mono using Project Reactor
Mono<Connection> connectionMono = Mono.from(connectionFactory.create());

Supported ConnectionFactory Discovery Options

Option Description
ssl Whether to use transport-level encryption for the entire SQL server traffic.
driver Must be sqlserver.
host Server hostname to connect to.
port Server port to connect to. Defaults to 1433. (Optional)
username Login username.
password Login password.
database Initial database to select. Defaults to SQL Server user profile settings. (Optional)
applicationName Name of the application. Defaults to driver name and version. (Optional)
connectionId Connection Id for tracing purposes. Defaults to a random Id. (Optional)
connectTimeout Connection Id for tracing purposes. Defaults to 30 seconds. (Optional)
hostNameInCertificate Expected hostname in SSL certificate. Supports wildcards (e.g. *.database.windows.net). (Optional)
lockWaitTimeout Lock wait timeout using SET LOCK_TIMEOUT …. (Optional)
preferCursoredExecution Whether to prefer cursors or direct execution for queries. Uses by default direct. Cursors require more round-trips but are more backpressure-friendly. Defaults to direct execution. Can be boolean or a Predicate<String> accepting the SQL query. _(
Optional)_
sendStringParametersAsUnicode Configure whether to send character data as unicode (NVARCHAR, NCHAR, NTEXT) or whether to use the database encoding, defaults to true. If disabled, CharSequence data is sent using the database-specific collation such as ASCII/MBCS instead of Unicode.
sslTunnel Enables SSL tunnel usage when using a SSL tunnel or SSL terminator in front of SQL Server. Accepts Function<SslContextBuilder, SslContextBuilder> to customize the SSL tunnel settings. SSL tunneling is not related to SQL Server's built-in SSL support. (Optional)
sslContextBuilderCustomizer SSL Context customizer to configure SQL Server's built-in SSL support (Function<SslContextBuilder, SslContextBuilder>) (Optional)
tcpKeepAlive Enable/disable TCP KeepAlive. Disabled by default. (Optional)
tcpNoDelay Enable/disable TCP NoDelay. Enabled by default. (Optional)
trustServerCertificate Fully trust the server certificate bypassing X.509 certificate validation. Disabled by default. (Optional)
trustStoreType Type of the TrustStore. Defaults to KeyStore.getDefaultType(). (Optional)
trustStore Path to the certificate TrustStore file. (Optional)
trustStorePassword Password used to check the integrity of the TrustStore data. (Optional)

Programmatic Configuration

MssqlConnectionConfiguration configuration = MssqlConnectionConfiguration.builder()
    .host("…")
    .username("…")
    .password("…")
    .database("…")
    .preferCursoredExecution(…)
    .build();

MssqlConnectionFactory factory = new MssqlConnectionFactory(configuration);

Mono<MssqlConnection> connectionMono = factory.create();

Microsoft SQL Server uses named parameters that are prefixed with @. The following SQL statement makes use of parameters:

INSERT INTO person (id, first_name, last_name) VALUES(@id, @firstname, @lastname)

Parameters are referenced without the @ prefix when binding these:

connection.createStatement("INSERT INTO person (id, first_name, last_name) VALUES(@id, @firstname, @lastname)")
            .bind("id", 1)
            .bind("firstname", "Walter")
            .bind("lastname", "White")
            .execute()

Binding also allows 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.

<dependency>
  <groupId>io.r2dbc</groupId>
  <artifactId>r2dbc-mssql</artifactId>
  <version>${version}</version>
</dependency>

If you'd rather like the latest snapshots of the upcoming major version, use our Maven snapshot repository and declare the appropriate dependency version.

<dependency>
  <groupId>io.r2dbc</groupId>
  <artifactId>r2dbc-mssql</artifactId>
  <version>${version}.BUILD-SNAPSHOT</version>
</dependency>

<repository>
<id>sonatype-nexus-snapshots</id>
<name>Sonatype OSS Snapshot Repository</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>

Transaction Definitions

SQL Server supports additional options when starting a transaction. In particular, the following options can be specified:

  • Isolation Level (isolationLevel) (reset after the transaction to previous value)
  • Transaction Name (name)
  • Transaction Log Mark (mark)
  • Lock Wait Timeout (lockWaitTimeout) (reset after the transaction to -1)

These options can be specified upon transaction begin to start the transaction and apply options in a single command roundtrip:

MssqlConnection connection= …;

        connection.beginTransaction(MssqlTransactionDefinition.from(IsolationLevel.READ_UNCOMMITTED)
        .name("my-transaction").mark("tx-log-mark")
        .lockTimeout(Duration.ofMinutes(1)));

See also: https://docs.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql

Data Type Mapping

This reference table shows the type mapping between Microsoft SQL Server and Java data types:

Microsoft SQL Server Type Java Data Type
bit Boolean, Byte, Short, Integer, Long, BigDecimal, BigInteger
tinyint Byte, Boolean, Short, Integer, Long, BigDecimal, BigInteger
smallint Short, Boolean, Byte, Integer, Long, BigDecimal, BigInteger
int Integer, Boolean, Byte, Short, Long, BigDecimal, BigInteger
bigint Long, Boolean, Byte, Short, Integer, BigDecimal, BigInteger
real Float, Double
float Double, Float
decimal BigDecimal, BigInteger
numeric BigDecimal, BigInteger
uniqueidentifier UUID, String
smalldatetime LocalDateTime
datetime LocalDateTime
datetime2 LocalDateTime
date LocalDate
time LocalTime
datetimeoffset OffsetDateTime, ZonedDateTime
timestamp byte[]
smallmoney BigDecimal
money BigDecimal
char String, Clob
varchar String, Clob
varcharmax String, Clob
nchar String, Clob
nvarchar String, Clob
nvarcharmax String, Clob
text String, Clob
ntext String, Clob
image ByteBuffer, byte[], Blob
binary ByteBuffer, byte[], Blob
varbinary ByteBuffer, byte[], Blob
varbinarymax ByteBuffer, byte[], Blob
sql_variant Not yet supported.
xml Not yet supported.
udt Not yet supported.
geometry Not yet supported.
geography Not yet supported.

Types in bold indicate the native (default) Java type.

Note: BLOB (image, binary, varbinary and varbinary(max)) and CLOB (text, ntext, varchar(max) and nvarchar(max)) values are fully materialized in the client before decoding. Make sure to account for proper memory sizing.

Logging

If SL4J is on the classpath, it will be used. Otherwise, there are two possible fallbacks: Console or java.util.logging.Logger). By default, the Console fallback is used. To use the JDK loggers, set the reactor.logging.fallback System property to JDK.

Logging facilities:

  • Driver Logging (io.r2dbc.mssql)
  • Query Logging (io.r2dbc.mssql.QUERY on DEBUG level)
  • Transport Logging (io.r2dbc.mssql.client)
    • DEBUG enables Message exchange logging
    • TRACE enables traffic logging

Getting Help

Having trouble with R2DBC? We'd love to help!

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 MSSQL 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 MSSQL (binaries in Maven Central), but if you want to try out the latest and greatest, R2DBC MSSQL can be easily built with the maven wrapper. You also need JDK 1.8 and Docker to run integration tests.

 $ ./mvnw clean install

If you want to build with the regular mvn command, you will need Maven v3.5.0 or above.

Also see CONTRIBUTING.adoc if you wish to submit pull requests. Commits require Signed-off-by (git commit -s) to ensure Developer Certificate of Origin.

Running JMH Benchmarks

Running the JMH benchmarks builds and runs the benchmarks without running tests.

 $ ./mvnw clean install -Pjmh

Staging to Maven Central

To stage a release to Maven Central, you need to create a release tag (release version) that contains the desired state and version numbers (mvn versions:set versions:commit -q -o -DgenerateBackupPoms=false -DnewVersion=x.y.z.(RELEASE|Mnnn|RCnnn) and force-push it to the release-0.x branch. This push will trigger a Maven staging build (see build-and-deploy-to-maven-central.sh).

License

R2DBC MSSQL is Open Source software released under the Apache 2.0 license.