- Notifications
You must be signed in to change notification settings - Fork36
R2DBC Driver for Microsoft SQL Server using TDS (Tabular Data Stream) Protocol
License
r2dbc/r2dbc-mssql
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This project contains theMicrosoft SQL Server implementation of theR2DBC 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 1.0
- 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
This project is governed by theR2DBC Code of Conduct. By participating, you are expected to uphold this code of conduct. Pleasereport unacceptable behavior toinfo@r2dbc.io.
Here is a quick teaser of how to use R2DBC MSSQL in Java:
URL Connection Factory Discovery
ConnectionFactoryconnectionFactory =ConnectionFactories.get("r2dbc:mssql://<host>:1433/<database>");Publisher<?extendsConnection>connectionPublisher =connectionFactory.create();
Programmatic Connection Factory Discovery
ConnectionFactoryOptionsoptions =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"),newUUID(…))// optional .build();ConnectionFactoryconnectionFactory =ConnectionFactories.get(options);Publisher<?extendsConnection>connectionPublisher =connectionFactory.create();// Alternative: Creating a Mono using Project ReactorMono<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 besqlserver . |
host | Server hostname to connect to. |
port | Server port to connect to. Defaults to1433 .(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 usingSET 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 beboolean or aPredicate<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 totrue . 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. AcceptsFunction<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 toKeyStore.getDefaultType() .(Optional) |
trustStore | Path to the certificate TrustStore file.(Optional) |
trustStorePassword | Password used to check the integrity of the TrustStore data.(Optional) |
Programmatic Configuration
MssqlConnectionConfigurationconfiguration =MssqlConnectionConfiguration.builder() .host("…") .username("…") .password("…") .database("…") .preferCursoredExecution(…) .build();MssqlConnectionFactoryfactory =newMssqlConnectionFactory(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.
Artifacts can be found onMaven 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>
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:
MssqlConnectionconnection= …;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
This reference table shows the type mapping betweenMicrosoft SQL Server and Java data types:
Types inbold indicate the native (default) Java type.
Note: BLOB (image
,binary
,varbinary
andvarbinary(max)
) and CLOB (text
,ntext
,varchar(max)
andnvarchar(max)
)values are fully materialized in the client before decoding. Make sure to account for proper memory sizing.
If SL4J is on the classpath, it will be used. Otherwise, there are two possible fallbacks: Console orjava.util.logging.Logger
). By default, the Console fallback is used. To use the JDK loggers, set thereactor.logging.fallback
System property toJDK
.
Logging facilities:
- Driver Logging (
io.r2dbc.mssql
) - Query Logging (
io.r2dbc.mssql.QUERY
onDEBUG
level) - Transport Logging (
io.r2dbc.mssql.client
)DEBUG
enablesMessage
exchange loggingTRACE
enables traffic logging
Having trouble with R2DBC? We'd love to help!
- Check thespec documentation, andJavadoc.
- If you are upgrading, check out thechangelog for "new and noteworthy" features.
- Ask a question - we monitorstackoverflow.com for questions tagged with
r2dbc
. You can also chat with the communityonGitter. - Report bugs with R2DBC MSSQL atgithub.com/r2dbc/r2dbc-mssql/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 theissue 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.
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 themaven wrapper. You also need JDK 1.8 and Docker to run integration tests.
$ ./mvnw clean install
If you want to build with the regularmvn
command, you will needMaven v3.6.0 or above.
Also seeCONTRIBUTING.adoc if you wish to submit pull requests. Commits requireSigned-off-by
(git commit -s
) to ensureDeveloper Certificate of Origin.
Running the JMH benchmarks builds and runs the benchmarks without running tests.
$ ./mvnw clean install -Pjmh
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 therelease-0.x
branch. This push will trigger a Maven staging build (seebuild-and-deploy-to-maven-central.sh
).
R2DBC MSSQL is Open Source software released under theApache 2.0 license.
About
R2DBC Driver for Microsoft SQL Server using TDS (Tabular Data Stream) Protocol
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Contributors13
Uh oh!
There was an error while loading.Please reload this page.