You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by gi...@apache.org on 2026/09/29 07:34:47 UTC
(druid) branch master updated: feat: Druid JDBC driver. (#19951)
This is an automated email from the ASF dual-hosted git repository.
gianm pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/druid.git
The following commit(s) were added to refs/heads/master by this push:
new ff97a704e21 feat: Druid JDBC driver. (#19951)
ff97a704e21 is described below
commit ff97a704e2139fbc1cb10bf2d70795aca603314d
Author: Gian Merlino <gi...@gmail.com>
AuthorDate: Tue Sep 29 00:34:40 2026 -0700
feat: Druid JDBC driver. (#19951)
This patch adds a Druid JDBC driver that uses the regular endpoint,
/druid/v2/sql/. It is recommended over the Avatica driver for a variety
of benefits, including: driver-side connection management that doesn't
require sticky load balancing, streaming results, support for SET
statements, and support for non-native SqlEngines.
In addition to the new module, there are core changes:
1) TIMESTAMP parameters to parameterized queries, when provided as strings
with zone offsets, are now correctly interpreted in the provided zone.
2) SQL now correctly treats function names in JDBC {fn ...} escapes
case-insensitively.
3) SQL now correctly handles the JDBC escape {fn now()}.
---
codestyle/spotbugs-exclude.xml | 11 +
docs/api-reference/api-reference.md | 3 +-
docs/querying/dart.md | 4 +-
docs/querying/query-context.md | 68 +-
.../sql-jdbc.md => querying/sql-jdbc-avatica.md} | 33 +-
docs/querying/sql-jdbc.md | 261 +++
docs/querying/sql.md | 12 +-
docs/tutorials/tutorial-jdbc.md | 6 +-
.../org/apache/druid/grpc/server/QueryDriver.java | 2 +-
jdbc-driver/pom.xml | 264 +++
.../java/org/apache/druid/jdbc/BooleanUtils.java | 41 +
.../org/apache/druid/jdbc/ClientProperties.java | 214 +++
.../java/org/apache/druid/jdbc/DruidArray.java | 111 ++
.../org/apache/druid/jdbc/DruidConnection.java | 645 ++++++++
.../org/apache/druid/jdbc/DruidConnectionUrl.java | 267 +++
.../apache/druid/jdbc/DruidDatabaseMetaData.java | 1650 ++++++++++++++++++
.../org/apache/druid/jdbc/DruidJdbcDriver.java | 204 +++
.../org/apache/druid/jdbc/DruidJdbcException.java | 55 +
.../DruidJdbcFeatureNotSupportedException.java | 36 +
.../apache/druid/jdbc/DruidPreparedStatement.java | 812 +++++++++
.../java/org/apache/druid/jdbc/DruidResultSet.java | 1747 ++++++++++++++++++++
.../apache/druid/jdbc/DruidResultSetMetaData.java | 265 +++
.../java/org/apache/druid/jdbc/DruidSQLState.java | 48 +
.../java/org/apache/druid/jdbc/DruidStatement.java | 613 +++++++
.../apache/druid/jdbc/DruidTimestampParser.java | 170 ++
.../java/org/apache/druid/jdbc/StringUtils.java | 52 +
.../org/apache/druid/jdbc/SuppressForbidden.java | 35 +
.../org/apache/druid/jdbc/http/ColumnMetadata.java | 137 ++
.../apache/druid/jdbc/http/DruidHttpClient.java | 69 +
.../druid/jdbc/http/DruidHttpClientImpl.java | 474 ++++++
.../druid/jdbc/http/EmptyQueryResultsIterator.java | 60 +
.../apache/druid/jdbc/http/HttpClientUtils.java | 92 ++
.../druid/jdbc/http/QueryResultsIterator.java | 39 +
.../druid/jdbc/http/QueryResultsIteratorImpl.java | 454 +++++
.../org/apache/druid/jdbc/http/SqlParameter.java | 42 +
.../org/apache/druid/jdbc/http/SqlRequest.java | 69 +
.../org/apache/druid/jdbc/sql/SetStatement.java | 28 +
.../java/org/apache/druid/jdbc/sql/SqlScanner.java | 264 +++
.../resources/META-INF/services/java.sql.Driver | 20 +
.../apache/druid/jdbc/ClientPropertiesTest.java | 61 +
.../org/apache/druid/jdbc/DruidConnectionTest.java | 239 +++
.../apache/druid/jdbc/DruidConnectionUrlTest.java | 269 +++
.../druid/jdbc/DruidDatabaseMetaDataTest.java | 514 ++++++
.../org/apache/druid/jdbc/DruidJdbcDriverTest.java | 97 ++
.../druid/jdbc/DruidParameterBindingTest.java | 363 ++++
.../druid/jdbc/DruidPreparedStatementTest.java | 263 +++
.../druid/jdbc/DruidResultSetMetaDataTest.java | 110 ++
.../org/apache/druid/jdbc/DruidResultSetTest.java | 719 ++++++++
.../DruidSetStatementPreparedStatementTest.java | 147 ++
.../apache/druid/jdbc/DruidSetStatementTest.java | 267 +++
.../org/apache/druid/jdbc/DruidStatementTest.java | 447 +++++
.../druid/jdbc/DruidTimestampParserTest.java | 82 +
.../apache/druid/jdbc/DruidTypeConversionTest.java | 196 +++
.../java/org/apache/druid/jdbc/SqlScannerTest.java | 158 ++
.../org/apache/druid/jdbc/StringUtilsTest.java | 53 +
.../jdbc/embedded/EmbeddedJdbcDriverTest.java | 741 +++++++++
.../embedded/EmbeddedSecureJdbcDriverTest.java | 234 +++
.../apache/druid/jdbc/http/ColumnMetadataTest.java | 135 ++
.../druid/jdbc/http/DruidHttpClientTest.java | 286 ++++
.../druid/jdbc/http/QueryResultsIteratorTest.java | 498 ++++++
.../apache/druid/jdbc/http/SqlParameterTest.java | 52 +
.../org/apache/druid/jdbc/http/SqlRequestTest.java | 82 +
.../druid/jdbc/http/TestQueryResultsIterator.java | 74 +
.../org/apache/druid/msq/test/MSQTestBase.java | 2 +-
pom.xml | 1 +
sql/src/main/codegen/templates/Parser.jj | 10 +-
.../org/apache/druid/sql/AbstractStatement.java | 2 +-
.../java/org/apache/druid/sql/SqlQueryPlus.java | 100 +-
.../org/apache/druid/sql/http/SqlParameter.java | 52 +-
.../java/org/apache/druid/sql/http/SqlQuery.java | 17 -
.../org/apache/druid/sql/http/SqlResource.java | 2 +-
.../druid/sql/avatica/DruidAvaticaHandlerTest.java | 21 +
.../apache/druid/sql/calcite/QueryTestRunner.java | 4 +-
website/.spelling | 6 +
website/redirects.js | 9 +-
website/sidebars.json | 11 +-
76 files changed, 15555 insertions(+), 146 deletions(-)
diff --git a/codestyle/spotbugs-exclude.xml b/codestyle/spotbugs-exclude.xml
index 464ea99a2e6..06439be53f7 100644
--- a/codestyle/spotbugs-exclude.xml
+++ b/codestyle/spotbugs-exclude.xml
@@ -98,6 +98,17 @@
</Or>
</And>
</Match>
+ <Match>
+ <!-- sqlResultSet() hands ownership of the statement to the returned ResultSet via closeOnCompletion(), and
+ closes the statement itself if no ResultSet is produced. Spotbugs cannot see through closeOnCompletion(). -->
+ <And>
+ <Or>
+ <Bug pattern="OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE" />
+ <Bug pattern="ODR_OPEN_DATABASE_RESOURCE" />
+ </Or>
+ <Class name="org.apache.druid.jdbc.DruidDatabaseMetaData" />
+ </And>
+ </Match>
<Bug pattern="AT_NONATOMIC_64BIT_PRIMITIVE"/>
<Bug pattern="AT_NONATOMIC_OPERATIONS_ON_SHARED_VARIABLE"/>
diff --git a/docs/api-reference/api-reference.md b/docs/api-reference/api-reference.md
index 60ff4034660..977731e27cf 100644
--- a/docs/api-reference/api-reference.md
+++ b/docs/api-reference/api-reference.md
@@ -57,4 +57,5 @@ Druid version. Only enable it when clients are authorized to receive this inform
* [Legacy metadata](./legacy-metadata-api.md) to retrieve datasource metadata.
## Java APIs
-* [SQL JDBC driver](./sql-jdbc.md) to connect to Druid and make Druid SQL queries using the Avatica JDBC driver.
\ No newline at end of file
+* [Druid JDBC driver](../querying/sql-jdbc.md) to connect to Druid and make Druid SQL queries over JDBC. This is the recommended JDBC driver.
+* [Avatica JDBC driver](../querying/sql-jdbc-avatica.md) to make Druid SQL queries using the Apache Calcite Avatica driver instead.
diff --git a/docs/querying/dart.md b/docs/querying/dart.md
index 772983dd908..3c245b48fcf 100644
--- a/docs/querying/dart.md
+++ b/docs/querying/dart.md
@@ -140,7 +140,7 @@ You can use any SQL query context parameters to control Dart's behavior unless o
- Use the query cache.
- Perform query prioritization or laning.
- TopN queries are always exact. Approximate TopN queries (`useApproximateTopN`) aren't supported.
-- Dart doesn't support JDBC connections. Druid ignores the `engine` context parameter when its passed through a JDBC connection.
+- Dart doesn't support the [Avatica JDBC driver](sql-jdbc-avatica.md). Druid ignores the `engine` context parameter when it's passed through an Avatica connection. Use the [Druid JDBC driver](sql-jdbc.md) instead.
- Realtime scans from the MSQ engine can't reliably read complex types. This can happen in situations such as if your data includes HLL Sketches for realtime data. Dart returns a `NullPointerException`. For more information, see [#18340](https://github.com/apache/druid/issues/18340).
- The `NilStageOutputReader` can sometimes lead to a `NoClassDefFoundError`. For more information, see [#18336](https://github.com/apache/druid/pull/18336).
-- Broadcast joins with realtime data aren't supported. If the left table of a join has realtime data and you're doing a broadcast join, you must set `sqlJoinAlgorithm` to `sortMerge`.
\ No newline at end of file
+- Broadcast joins with realtime data aren't supported. If the left table of a join has realtime data and you're doing a broadcast join, you must set `sqlJoinAlgorithm` to `sortMerge`.
diff --git a/docs/querying/query-context.md b/docs/querying/query-context.md
index 98e8b708aef..ec38bd90087 100644
--- a/docs/querying/query-context.md
+++ b/docs/querying/query-context.md
@@ -122,69 +122,20 @@ You can set multiple context parameters in a single request:
### JDBC driver API
-You can connect to Druid over JDBC and issue Druid SQL queries using the [Druid SQL JDBC driver API](../api-reference/sql-jdbc.md).
+You can connect to Druid over JDBC and issue Druid SQL queries using the [Druid JDBC driver](./sql-jdbc.md), which is
+recommended, or the [Avatica JDBC driver](./sql-jdbc-avatica.md).
This approach is useful when integrating Druid with BI tools or Java applications.
-When connecting to Druid through JDBC, you set query context parameters in a JDBC connection properties object.
-You supply the object when establishing the connection to Druid.
-The following code excerpt shows how you can configure the connection properties:
+With the Druid JDBC driver, you can set query context parameters in the connection URL, in a connection properties
+object, or with `SET` statements. For details and examples, see
+[Query context parameters](./sql-jdbc.md#query-context-parameters).
-```java
-String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/";
-
-// Set the time zone to America/Los_Angeles
-Properties connectionProperties = new Properties();
-connectionProperties.setProperty("sqlTimeZone", "America/Los_Angeles");
-
-try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
- // create and execute statements, process result sets, etc
-}
-```
-
-<details>
-<summary>View full JDBC example</summary>
-
-```java
-import java.sql.*;
-import java.util.Properties;
-
-public class JdbcDruid {
-
- public static void main(String args[]) {
-
- // Connect to /druid/v2/sql/avatica/ on your Broker.
- String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;transparent_reconnection=true";
-
- // The query you want to run.
- String query = "SELECT * FROM wikipedia WHERE user = 'BlueMoon2662'";
-
- // Set any connection context parameters you need here.
- Properties connectionProperties = new Properties();
- connectionProperties.setProperty("sqlTimeZone", "America/Los_Angeles");
-
- try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
- try (
- final Statement statement = connection.createStatement();
- final ResultSet rs = statement.executeQuery(query)
- ) {
- while (rs.next()) {
- // process result set
- Timestamp timeStamp = rs.getTimestamp("__time");
- System.out.println(timeStamp);
- }
- }
- } catch (Exception e) {
- System.out.println(e.toString());
- }
- }
-}
-```
-
-</details>
+With the Avatica JDBC driver, you must set query context parameters in a connection properties object. For an example,
+see [Avatica JDBC driver](./sql-jdbc-avatica.md).
### SET statements
-You can use the SET command to specify SQL query context parameters that modify the behavior of a Druid SQL query. Druid accepts one or more SET statements before the main SQL query. The SET command works in the both web console and the Druid SQL HTTP API.
+You can use the SET command to specify SQL query context parameters that modify the behavior of a Druid SQL query. Druid accepts one or more SET statements before the main SQL query. The SET command works in the web console, the Druid SQL HTTP API, and the [Druid JDBC driver](./sql-jdbc.md#set-statements).
In the web console, you can write your SET statements followed by your query directly. For example:
@@ -219,7 +170,8 @@ curl -X POST 'http://localhost:8888/druid/v2/sql' \
For more details on how to use the SET command in your SQL query, see [SET](sql.md#set).
:::info
-You cannot use SET statements in JDBC connections.
+You cannot use SET statements with the [Avatica JDBC driver](./sql-jdbc-avatica.md). Use the
+[Druid JDBC driver](./sql-jdbc.md#set-statements) instead.
:::
diff --git a/docs/api-reference/sql-jdbc.md b/docs/querying/sql-jdbc-avatica.md
similarity index 85%
rename from docs/api-reference/sql-jdbc.md
rename to docs/querying/sql-jdbc-avatica.md
index 771ee24e451..9f3bf473c56 100644
--- a/docs/api-reference/sql-jdbc.md
+++ b/docs/querying/sql-jdbc-avatica.md
@@ -1,7 +1,7 @@
---
-id: sql-jdbc
-title: SQL JDBC driver API
-sidebar_label: SQL JDBC driver
+id: sql-jdbc-avatica
+title: Avatica JDBC driver API
+sidebar_label: Avatica JDBC driver
---
<!--
@@ -24,11 +24,17 @@ sidebar_label: SQL JDBC driver
-->
:::info
- Apache® Druid supports two query languages: Druid SQL and [native queries](../querying/querying.md).
+ Apache® Druid supports two query languages: Druid SQL and [native queries](querying.md).
This document describes the SQL language.
:::
-You can make [Druid SQL](../querying/sql.md) queries using the [Avatica JDBC driver](https://calcite.apache.org/avatica/downloads/).
+:::info
+ We recommend the [Druid JDBC driver](sql-jdbc.md) instead of the Avatica driver described on this page.
+ The Druid JDBC driver queries the standard [SQL HTTP API](../api-reference/sql-api.md) at `/druid/v2/sql/`, so it
+ does not require connection stickiness, and is not subject to the Avatica connection and statement limits.
+:::
+
+You can make [Druid SQL](sql.md) queries using the [Avatica JDBC driver](https://calcite.apache.org/avatica/downloads/).
We recommend using Avatica JDBC driver version 1.23.0 or later. Note that starting with Avatica 1.21.0, you may need to set the [`transparent_reconnection`](https://calcite.apache.org/avatica/docs/client_reference.html#transparent_reconnection) property to `true` if you notice intermittent query failures.
Once you've downloaded the Avatica client jar, add it to your classpath.
@@ -54,7 +60,7 @@ or if a Broker is restarted.
Set `serialization` to `protobuf` if using the protobuf endpoint.
Note that as of the time of this writing, Avatica 1.23.0, the latest version, does not support passing
-[connection context parameters](../querying/sql-query-context.md) from the JDBC connection string to Druid. These context parameters
+[connection context parameters](sql-query-context.md) from the JDBC connection string to Druid. These context parameters
must be passed using a `Properties` object instead. Refer to the Java code below for an example.
Example Java code:
@@ -98,21 +104,22 @@ String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica
:::
Table metadata is available over JDBC using `connection.getMetaData()` or by querying the
-[INFORMATION_SCHEMA tables](../querying/sql-metadata-tables.md). For an example of this, see [Get the metadata for a datasource](#get-the-metadata-for-a-datasource).
+[INFORMATION_SCHEMA tables](sql-metadata-tables.md). For an example of this, see [Get the metadata for a datasource](#get-the-metadata-for-a-datasource).
## Connection stickiness
-Druid's JDBC server does not share connection state between Brokers. This means that if you're using JDBC and have
+Druid's Avatica server does not share connection state between Brokers. This means that if you're using JDBC and have
multiple Druid Brokers, you should either connect to a specific Broker or use a load balancer with sticky sessions
enabled. The Druid Router process provides connection stickiness when balancing JDBC requests, and can be used to achieve
the necessary stickiness even with a normal non-sticky load balancer. Please see the
[Router](../design/router.md) documentation for more details.
-Note that the non-JDBC [JSON over HTTP](sql-api.md#submit-a-query) API is stateless and does not require stickiness.
+Neither the [Druid JDBC driver](sql-jdbc.md) nor the non-JDBC [JSON over HTTP](../api-reference/sql-api.md#submit-a-query)
+API keeps server-side connection state, so neither requires stickiness.
## Dynamic parameters
-You can use [parameterized queries](../querying/sql.md#dynamic-parameters) in JDBC code, as in this example:
+You can use [parameterized queries](sql.md#dynamic-parameters) in JDBC code, as in this example:
```java
PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) AS cnt FROM druid.foo WHERE dim1 = ? OR dim1 = ?");
@@ -143,8 +150,6 @@ statement.executeQuery();
## Examples
-<!-- docs/tutorial-jdbc.md redirects here -->
-
The following section contains two complete samples that use the JDBC connector:
- [Get the metadata for a datasource](#get-the-metadata-for-a-datasource) shows you how to query the `INFORMATION_SCHEMA` to get metadata like column names.
@@ -168,7 +173,7 @@ Make sure you meet the following requirements before trying these examples:
### Get the metadata for a datasource
-Metadata, such as column names, is available either through the [`INFORMATION_SCHEMA`](../querying/sql-metadata-tables.md) table or through `connection.getMetaData()`. The following example uses the `INFORMATION_SCHEMA` table to retrieve and print the list of column names for the `wikipedia` datasource that you loaded during a previous tutorial.
+Metadata, such as column names, is available either through the [`INFORMATION_SCHEMA`](sql-metadata-tables.md) table or through `connection.getMetaData()`. The following example uses the `INFORMATION_SCHEMA` table to retrieve and print the list of column names for the `wikipedia` datasource that you loaded during a previous tutorial.
```java
import java.sql.*;
@@ -208,7 +213,7 @@ public class JdbcListColumns {
### Query data
-Now that you know what columns are available, you can start querying the data. The following example queries the datasource named `wikipedia` for the timestamps and comments from Japan. It also sets the [query context parameter](../querying/sql-query-context.md) `sqlTimeZone`. Optionally, you can also parameterize queries by using [dynamic parameters](#dynamic-parameters).
+Now that you know what columns are available, you can start querying the data. The following example queries the datasource named `wikipedia` for the timestamps and comments from Japan. It also sets the [query context parameter](sql-query-context.md) `sqlTimeZone`. Optionally, you can also parameterize queries by using [dynamic parameters](#dynamic-parameters).
```java
import java.sql.*;
diff --git a/docs/querying/sql-jdbc.md b/docs/querying/sql-jdbc.md
new file mode 100644
index 00000000000..defbf839bf5
--- /dev/null
+++ b/docs/querying/sql-jdbc.md
@@ -0,0 +1,261 @@
+---
+id: sql-jdbc
+title: "Druid JDBC driver"
+sidebar_label: "JDBC driver"
+---
+
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+
+<!-- docs/tutorials/tutorial-jdbc.md redirects here -->
+
+The Druid JDBC driver provides connectivity to Apache Druid using the
+[SQL HTTP API](../api-reference/sql-api.md) at `/druid/v2/sql/`. You can use it from Java code, or from any
+BI or SQL tool that accepts a third-party JDBC driver.
+
+## Install
+
+The driver is published to Maven Central as a single JAR with its dependencies bundled in:
+
+```xml
+<dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-jdbc-driver</artifactId>
+ <version>${druid.version}</version>
+</dependency>
+```
+
+The driver requires a minimum of Java 17. It is not part of the Druid distribution tarball.
+
+For a third-party tool, download the JAR from
+[Maven Central](https://repo1.maven.org/maven2/org/apache/druid/druid-jdbc-driver/) and register it with the tool.
+If the tool requires a driver class, use `org.apache.druid.jdbc.DruidJdbcDriver`.
+
+## Connection URL
+
+The driver accepts URLs of the following form:
+
+```
+jdbc:druid:https://host:port/druid/v2/sql/?param=value¶m=value
+```
+
+| Component | Description |
+|---|---|
+| Prefix | `jdbc:druid:` followed by an HTTP or HTTPS URL. |
+| Scheme | `http` or `https`. Required. |
+| Host | Hostname or IP address of a Druid Router or Broker. Required. |
+| Port | Port of the Router or Broker. Defaults to 80 for `http` and 443 for `https`. |
+| Path | Path of the SQL endpoint, normally `/druid/v2/sql/`. |
+| Parameters | Optional [driver parameters](#driver-parameters) and [query context parameters](#query-context-parameters), in standard URL query string form. URL-encode any values that contain reserved characters such as `&`, `=`, or `#`. |
+
+Credentials in the `user:password@host` form are rejected. Pass them as [driver parameters](#driver-parameters)
+instead.
+
+Some examples:
+
+```
+# Router on the default quickstart port.
+jdbc:druid:http://localhost:8888/druid/v2/sql/
+
+# HTTPS on the default port (443).
+jdbc:druid:https://druid.example.com/druid/v2/sql/
+
+# Basic authentication.
+jdbc:druid:http://localhost:8888/druid/v2/sql/?authentication=basic&user=admin&password=secret
+
+# Setting query context parameters.
+jdbc:druid:http://localhost:8888/druid/v2/sql/?timeout=60000&sqlTimeZone=Etc/UTC
+```
+
+## Connection parameters
+
+You can supply connection parameters either as a query string in the JDBC URL or connection properties. When writing
+Java code, you can specify the connection properties using `Properties` passed to `DriverManager.getConnection`.
+When the same name appears in both, the URL takes precedence.
+
+### Driver parameters
+
+The driver interprets certain connection parameters itself. All other connection parameters are sent to Druid as
+[query context parameters](#query-context-parameters).
+
+| Parameter | Description | Default |
+|---|---|---|
+| `authentication` | Authentication scheme: `basic` or `basicRaw`. See [Authentication](#authentication). Values are case-sensitive. | `basic` if `user` or `password` is set; otherwise no credentials are sent |
+| `user` | Username. Only used when `authentication` is `basic`. | None |
+| `password` | Password, or the credential token when `authentication` is `basicRaw`. | None |
+| `verifyTls` | Whether to validate the server's TLS certificate chain on HTTPS connections. | `true` |
+
+### Query context parameters
+
+Any parameter that isn't in the table above is passed to Druid as a [query context parameter](sql-query-context.md)
+on every query issued by the connection. For example, `?timeout=60000&sqlTimeZone=America/Los_Angeles` sets a 60
+second server-side query timeout and makes Druid compute time values in the `America/Los_Angeles` time zone.
+
+Query context parameters can also be supplied using [`SET` statements](#set-statements), which take precedence
+over properties supplied in the JDBC URL or connection properties.
+
+## Authentication
+
+When configured with authentication, the driver sends credentials with every request as an HTTP `Authorization` header.
+It sends no header at all when `authentication`, `user`, and `password` are all unset.
+
+`authentication=basic` performs standard HTTP basic authentication: the driver joins `user` and `password` with a
+colon and base64-encodes the result. Use this with Druid's
+[basic security](../development/extensions-core/druid-basic-security.md) extension. This is also the default scheme
+when you set `user` or `password` without setting `authentication`.
+
+`authentication=basicRaw` sends `Authorization: Basic <password>`, using the value of `password` verbatim as the
+already-encoded credential, and ignores `user`. `password` is required. Use this when you already hold an encoded
+credential or a token issued by a custom authenticator.
+
+Whenever possible, supply credentials using connection properties rather than the JDBC URL. This helps prevent them from
+being logged or stored in configuration files.
+
+## SET statements
+
+The driver accepts `SET` statements, which set [query context parameters](sql-query-context.md) for all subsequent
+queries on the same connection. `SET` statements are handled entirely within the driver and generate no requests to
+Druid.
+
+```sql
+SET timeout = 60000;
+SET sqlTimeZone = 'America/Los_Angeles';
+SET engine = 'msq-dart';
+```
+
+Values use SQL literal syntax: single quotes for strings, unquoted numbers, and `true`, `false`, `null`, or
+`unknown` in any capitalization.
+
+You can send several `SET` statements in one JDBC call, optionally followed by one regular query, separated by
+semicolons. Only one non-`SET` statement is allowed per call, and it must come last, such as:
+
+```sql
+SET timeout = 60000;
+SET sqlTimeZone = 'Etc/UTC';
+SELECT COUNT(*) FROM wikipedia
+```
+
+Setting a parameter to `NULL` undoes any earlier `SET` of that parameter on the same connection.
+The value then falls back to whatever the JDBC URL or connection properties supplied, if anything.
+
+Prepared statements cannot be used for `SET`.
+
+## Driver behavior
+
+### Connections exist only in the driver
+
+Druid does not maintain per-connection server-side state. A JDBC `Connection` is a client-side object that holds a
+URL, credentials, an HTTP client, and any context parameters set by `SET` statements. Each query is an independent
+HTTP request.
+
+This has a few practical consequences:
+
+- You do not need connection stickiness or a sticky load balancer.
+- A Broker restart does not invalidate a connection. In-flight queries fail, but later queries succeed.
+- Idle connections consume no server resources. They are not free on the client side, though: each `Connection` owns
+ an HTTP client, and therefore its own socket pool and threads. Reuse connections rather than opening one per query.
+
+`DriverManager.getConnection` does issue one `SELECT 1` query to check that the endpoint is reachable and the
+credentials work, so an unreachable host or bad credentials fails at connection time rather than at first query.
+`Connection.isValid` runs the same query.
+
+### Prepared statements are prepared at execution
+
+`Connection.prepareStatement` performs no network I/O. The driver sends the SQL and the bound parameter values
+together when you execute the statement. Druid plans the query on each execution.
+
+As a result, errors you might expect from `prepareStatement`, such as syntax errors or unknown table and column
+names, surface when the statement is first executed. Re-executing a `PreparedStatement` with new parameter values
+is not cheaper than executing a fresh `Statement`.
+
+### Statements can run concurrently
+
+Because each query is a separate HTTP request, statements created from one connection are independent and can
+execute concurrently from different threads.
+
+A single `Statement` holds at most one open `ResultSet`. Executing a statement again closes the `ResultSet` from
+its previous execution, so read one result set to completion before re-executing the statement that produced it.
+
+`Statement.close`, `Statement.isClosed`, `Statement.cancel`, `ResultSet.close`, and `ResultSet.isClosed` are safe
+to call from any thread. All other methods on a statement or result set must be called from one thread at a time.
+
+### Streaming results
+
+Rows are parsed from the HTTP response as you call `ResultSet.next`, so a large result set doesn't have to fit in
+memory. `Statement.setFetchSize` is accepted and ignored, and `getFetchSize` reports `0`; there is no batched
+fetching.
+
+Because a `ResultSet` holds an open HTTP response, it is important to close it when you're done.
+Closing a `Statement` closes its current `ResultSet`, and closing a `Connection` closes all of its statements.
+
+### Timeouts and cancellation
+
+`Statement.setQueryTimeout(seconds)` sets the Druid `timeout` context parameter, and `Statement.setMaxRows(n)` sets
+`sqlOuterLimit`. These calls override values that you set explicitly in the JDBC URL or with a `SET` statement.
+Following JDBC, `0` means "no limit", so it removes any value from those other sources rather than restoring it.
+
+Both of these are server-side limits. The only client-side limit is `Connection.setNetworkTimeout`, which bounds how
+long the driver waits for a response. It has no default and no connection parameter, so it must be set on a
+`Connection` you already hold. The connect timeout is fixed at 10 seconds and cancellation requests time out after
+5 seconds.
+
+`Statement.cancel` cancels the query on the server by issuing an HTTP `DELETE` for the query's `sqlQueryId`. The
+driver generates a fresh `sqlQueryId` per query if necessary.
+
+### Metadata
+
+`DatabaseMetaData` methods that describe schemas, tables, and columns run queries against the
+[`INFORMATION_SCHEMA` tables](sql-metadata-tables.md). You can also query those tables directly. Methods that
+describe features Druid does not have, such as stored procedures, primary and foreign keys, and indexes, return
+empty result sets.
+
+`getDatabaseProductVersion`, `getDatabaseMajorVersion`, and `getDatabaseMinorVersion` query the
+[`sys.servers` table](sql-metadata-tables.md#servers-table), which may require `sys` permissions. If that query
+is not authorized, an unknown version is reported.
+
+### Unsupported features
+
+The driver rejects the following with `SQLFeatureNotSupportedException`:
+
+- Writes. `executeUpdate`, `addBatch`, and `executeBatch` are rejected, and `ResultSet` update methods throw.
+- Transactions. Auto-commit is always on, the only supported isolation level is `TRANSACTION_NONE`, and savepoints
+ are rejected.
+- Scrollable and updatable result sets. Result sets are always `TYPE_FORWARD_ONLY` and `CONCUR_READ_ONLY`, so
+ `previous`, `absolute`, `first`, and `last` throw.
+- Stored procedures, `Blob`, `Clob`, `Ref`, `RowId`, `SQLXML`, and the stream-valued getters and setters.
+
+## Example
+
+To run a query and read the results, you can use code like the following. Note that in production usage, reusing
+the `Connection` is encouraged, because each `Connection` has its own HTTP client.
+
+```java
+final String url = "jdbc:druid:http://localhost:8888/druid/v2/sql/";
+
+try (
+ Connection connection = DriverManager.getConnection(url);
+ Statement statement = connection.createStatement();
+ ResultSet resultSet = statement.executeQuery(
+ "SELECT page, COUNT(*) AS edits FROM wikipedia GROUP BY 1 ORDER BY 2 DESC LIMIT 10")
+) {
+ while (resultSet.next()) {
+ System.out.println(resultSet.getString("page") + ": " + resultSet.getLong("edits"));
+ }
+}
+```
diff --git a/docs/querying/sql.md b/docs/querying/sql.md
index 98fd97b2411..b74c3636502 100644
--- a/docs/querying/sql.md
+++ b/docs/querying/sql.md
@@ -45,7 +45,8 @@ For more information and SQL querying options see:
For information about APIs, see:
- [Druid SQL API](../api-reference/sql-api.md) for information on the HTTP API.
-- [SQL JDBC driver API](../api-reference/sql-jdbc.md) for information about the JDBC driver API.
+- [Druid JDBC driver](./sql-jdbc.md) for information about the recommended JDBC driver.
+- [Avatica JDBC driver](./sql-jdbc-avatica.md) for information about the alternative Avatica JDBC driver.
- [SQL query context](./sql-query-context.md) for information about the query context parameters that affect SQL planning.
## Syntax
@@ -381,7 +382,7 @@ Request logs show the exact native query that will be run. Alternatively, to see
## SET
-SET statements allow you to specify SQL query context parameters that modify the behavior of a Druid SQL query. You can include one or more SET statements before the main SQL query. Druid supports using SET in the Druid SQL [JSON API](../api-reference/sql-api.md) and the [web console](../operations/web-console.md).
+SET statements allow you to specify SQL query context parameters that modify the behavior of a Druid SQL query. You can include one or more SET statements before the main SQL query. Druid supports using SET in the Druid SQL [JSON API](../api-reference/sql-api.md), the [web console](../operations/web-console.md), and the [Druid JDBC driver](./sql-jdbc.md#set-statements).
The syntax of a `SET` statement is:
@@ -398,7 +399,7 @@ SET timeout = 90000;
SELECT some_column, COUNT(*) FROM druid.foo WHERE other_column = 'foo' GROUP BY 1 ORDER BY 2 DESC
```
-SET statements only apply to the query in the same request. Subsequent requests are not affected.
+In the JSON API and the web console, SET statements only apply to the query in the same request. Subsequent requests are not affected. With the [Druid JDBC driver](./sql-jdbc.md#set-statements), they apply to all subsequent queries on the same connection.
SET statements work with SELECT, INSERT, and REPLACE queries.
@@ -426,7 +427,8 @@ written like `INTERVAL '1' HOUR`, `INTERVAL '1 02:03' DAY TO MINUTE`, `INTERVAL
Druid SQL supports dynamic parameters using question mark (`?`) syntax, where parameters are bound to `?` placeholders
at execution time. To use dynamic parameters, replace any literal in the query with a `?` character and provide a
corresponding parameter value when you execute the query. Parameters are bound to the placeholders in the order in
-which they are passed. Parameters are supported in both the [HTTP POST](../api-reference/sql-api.md) and [JDBC](../api-reference/sql-jdbc.md) APIs.
+which they are passed. Parameters are supported in the [HTTP POST](../api-reference/sql-api.md) API and by both the
+[Druid](./sql-jdbc.md) and [Avatica](./sql-jdbc-avatica.md) JDBC drivers.
Druid supports double and null values in arrays for dynamic queries.
The following example query uses the [ARRAY_CONTAINS](./sql-functions.md#array_contains) function to return `doubleArrayColumn` when the reference array `[-25.7, null, 36.85]` contains all elements of the value of `doubleArrayColumn`:
@@ -462,7 +464,7 @@ SELECT arrayColumn from druid.table where ARRAY_CONTAINS(arrayColumn, ?)
```
You can replace an IN filter with many values by dynamically passing a parameter into [SCALAR_IN_ARRAY](sql-functions.md#scalar_in_array).
-For example Java queries, see [Dynamic parameters](../api-reference/sql-jdbc.md#dynamic-parameters).
+For example Java queries, see [Dynamic parameters](./sql-jdbc-avatica.md#dynamic-parameters).
```sql
SELECT count(city) from druid.table where SCALAR_IN_ARRAY(city, ?)
diff --git a/docs/tutorials/tutorial-jdbc.md b/docs/tutorials/tutorial-jdbc.md
index e3462447af2..6eb03d81ce2 100644
--- a/docs/tutorials/tutorial-jdbc.md
+++ b/docs/tutorials/tutorial-jdbc.md
@@ -25,10 +25,10 @@ sidebar_label: JDBC connector tutorial
import BrowserOnly from '@docusaurus/BrowserOnly';
-Redirecting you to the JDBC driver API...
+Redirecting you to the Druid JDBC driver documentation...
<BrowserOnly>
{() => {
- window.location.replace("https://druid.apache.org/docs/latest/api-reference/sql-jdbc.html");
+ window.location.replace("https://druid.apache.org/docs/latest/querying/sql-jdbc");
return null;
}}
- </BrowserOnly>
\ No newline at end of file
+ </BrowserOnly>
diff --git a/extensions-contrib/grpc-query/src/main/java/org/apache/druid/grpc/server/QueryDriver.java b/extensions-contrib/grpc-query/src/main/java/org/apache/druid/grpc/server/QueryDriver.java
index acfc3cd8f86..6720fc61607 100644
--- a/extensions-contrib/grpc-query/src/main/java/org/apache/druid/grpc/server/QueryDriver.java
+++ b/extensions-contrib/grpc-query/src/main/java/org/apache/druid/grpc/server/QueryDriver.java
@@ -317,7 +317,7 @@ public class QueryDriver
.sql(request.getQuery())
.systemDefaultContext(queryConfigProvider.getContext())
.queryContext(translateContext(request))
- .sqlParameters(translateParameters(request))
+ .parameters(translateParameters(request))
.auth(authResult)
.build();
}
diff --git a/jdbc-driver/pom.xml b/jdbc-driver/pom.xml
new file mode 100644
index 00000000000..21ecf47acb1
--- /dev/null
+++ b/jdbc-driver/pom.xml
@@ -0,0 +1,264 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Licensed to the Apache Software Foundation (ASF) under one
+ ~ or more contributor license agreements. See the NOTICE file
+ ~ distributed with this work for additional information
+ ~ regarding copyright ownership. The ASF licenses this file
+ ~ to you under the Apache License, Version 2.0 (the
+ ~ "License"); you may not use this file except in compliance
+ ~ with the License. You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing,
+ ~ software distributed under the License is distributed on an
+ ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ ~ KIND, either express or implied. See the License for the
+ ~ specific language governing permissions and limitations
+ ~ under the License.
+ -->
+
+<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid</artifactId>
+ <version>39.0.0-SNAPSHOT</version>
+ </parent>
+
+ <artifactId>druid-jdbc-driver</artifactId>
+ <name>Druid JDBC Driver</name>
+ <description>Standalone JDBC Driver for Apache Druid</description>
+
+ <properties>
+ <!-- jdbc-driver is built for Java 17, so that it can be embedded in applications that run on older JVMs
+ than Druid itself requires. Only the main sources use this release; the tests are built and run with the
+ standard Druid release (maven.compiler.release), since they depend on Druid server code. -->
+ <jdbc.driver.compiler.release>17</jdbc.driver.compiler.release>
+ <surefire.rerunFailingTestsCount>0</surefire.rerunFailingTestsCount>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.findbugs</groupId>
+ <artifactId>jsr305</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Test dependencies -->
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-params</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>nl.jqno.equalsverifier</groupId>
+ <artifactId>equalsverifier</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-processing</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-processing</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-indexing-service</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-indexing-service</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-services</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-services</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-indexing-hadoop</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-server</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-server</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid</groupId>
+ <artifactId>druid-sql</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid.extensions</groupId>
+ <artifactId>druid-basic-security</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid.extensions</groupId>
+ <artifactId>simple-client-sslcontext</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.druid.extensions</groupId>
+ <artifactId>druid-testing-tools</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>default-compile</id>
+ <configuration>
+ <release>${jdbc.driver.compiler.release}</release>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <createDependencyReducedPom>true</createDependencyReducedPom>
+ <shadedArtifactAttached>false</shadedArtifactAttached>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ <exclude>META-INF/MANIFEST.MF</exclude>
+ <exclude>META-INF/versions/*/</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ <relocations>
+ <relocation>
+ <pattern>com.fasterxml.jackson</pattern>
+ <shadedPattern>org.apache.druid.shaded.jackson</shadedPattern>
+ </relocation>
+ </relocations>
+ <transformers>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <manifestEntries>
+ <Implementation-Title>${project.name}</Implementation-Title>
+ <Implementation-Version>${project.version}</Implementation-Version>
+ <Implementation-Vendor>Apache Software Foundation</Implementation-Vendor>
+ </manifestEntries>
+ </transformer>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
+ <resource>META-INF/spring.handlers</resource>
+ </transformer>
+ <transformer
+ implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
+ <resource>META-INF/spring.schemas</resource>
+ </transformer>
+ </transformers>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+</project>
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/BooleanUtils.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/BooleanUtils.java
new file mode 100644
index 00000000000..f9ccc63b722
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/BooleanUtils.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+/**
+ * Helpers for case-insensitive boolean string parsing.
+ */
+public class BooleanUtils
+{
+ private BooleanUtils()
+ {
+ // No instantiation.
+ }
+
+ public static boolean isBooleanTrue(final String s)
+ {
+ return "true".equalsIgnoreCase(s);
+ }
+
+ public static boolean isBooleanFalse(final String s)
+ {
+ return "false".equalsIgnoreCase(s);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/ClientProperties.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/ClientProperties.java
new file mode 100644
index 00000000000..def11faa644
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/ClientProperties.java
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import javax.annotation.Nullable;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * Handles the client-side JDBC connection properties that are interpreted by the driver,
+ * rather than being sent to the Druid server as query context parameters.
+ */
+public class ClientProperties
+{
+ public static final String AUTHENTICATION = "authentication";
+ public static final String USER = "user";
+ public static final String PASSWORD = "password";
+ public static final String VERIFY_TLS = "verifyTls";
+ public static final boolean DEFAULT_VERIFY_TLS = true;
+
+ /**
+ * Standard HTTP basic authentication: {@link #USER} and {@link #PASSWORD} joined by a colon, then base64-encoded.
+ */
+ public static final String AUTHENTICATION_BASIC = "basic";
+
+ /**
+ * Sends {@link #PASSWORD} verbatim as the credential, with no encoding.
+ */
+ public static final String AUTHENTICATION_BASIC_RAW = "basicRaw";
+
+ /**
+ * Set of all recognized client-side property names. All others are sent to the Druid server.
+ */
+ private static final Set<String> CLIENT_SIDE_PROPERTY_NAMES = Set.of(
+ AUTHENTICATION,
+ USER,
+ PASSWORD,
+ VERIFY_TLS
+ );
+
+ @Nullable
+ private final String authentication;
+ @Nullable
+ private final String user;
+ @Nullable
+ private final String password;
+ private final boolean verifyTls;
+
+ private ClientProperties(
+ @Nullable final String authentication,
+ @Nullable final String user,
+ @Nullable final String password,
+ final boolean verifyTls
+ )
+ {
+ this.authentication = authentication;
+ this.user = user;
+ this.password = password;
+ this.verifyTls = verifyTls;
+ }
+
+ /**
+ * Separates client-side properties from query context parameters.
+ */
+ public static SplitProperties splitProperties(final Map<String, String> allProperties) throws SQLException
+ {
+ final Map<String, String> clientProps = new HashMap<>();
+ final Map<String, String> queryContext = new HashMap<>();
+
+ for (final Map.Entry<String, String> entry : allProperties.entrySet()) {
+ final String key = entry.getKey();
+ final String value = entry.getValue();
+ if (CLIENT_SIDE_PROPERTY_NAMES.contains(key)) {
+ clientProps.put(key, value);
+ } else {
+ queryContext.put(key, value);
+ }
+ }
+
+ final ClientProperties clientProperties = new ClientProperties(
+ getAuthentication(clientProps),
+ clientProps.get(USER),
+ clientProps.get(PASSWORD),
+ getVerifyTls(clientProps)
+ );
+
+ return new SplitProperties(clientProperties, Collections.unmodifiableMap(queryContext));
+ }
+
+ @Nullable
+ public String getAuthentication()
+ {
+ return authentication;
+ }
+
+ @Nullable
+ public String getUser()
+ {
+ return user;
+ }
+
+ @Nullable
+ public String getPassword()
+ {
+ return password;
+ }
+
+ public boolean isVerifyTls()
+ {
+ return verifyTls;
+ }
+
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ final ClientProperties that = (ClientProperties) o;
+ return verifyTls == that.verifyTls
+ && Objects.equals(authentication, that.authentication)
+ && Objects.equals(user, that.user)
+ && Objects.equals(password, that.password);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(authentication, user, password, verifyTls);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "ClientProperties{" +
+ "authentication='" + authentication + '\'' +
+ ", user='" + user + '\'' +
+ ", password='[REDACTED]'" +
+ ", verifyTls=" + verifyTls +
+ '}';
+ }
+
+ /**
+ * Returns the value of {@link #AUTHENTICATION} to use. If not provided by the caller, defaults to
+ * {@link #AUTHENTICATION_BASIC} if {@link #USER} or {@link #PASSWORD} is set, or {@code null} otherwise.
+ */
+ @Nullable
+ private static String getAuthentication(final Map<String, String> clientProps)
+ {
+ final String value = clientProps.get(AUTHENTICATION);
+
+ if (value != null) {
+ return value;
+ } else if (clientProps.get(USER) != null || clientProps.get(PASSWORD) != null) {
+ return AUTHENTICATION_BASIC;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the value of {@link #VERIFY_TLS}, or {@link #DEFAULT_VERIFY_TLS} if unset.
+ *
+ * @throws SQLException if the value is not a valid boolean string
+ */
+ private static boolean getVerifyTls(final Map<String, String> clientProps) throws SQLException
+ {
+ final String value = clientProps.get(VERIFY_TLS);
+ if (value == null) {
+ return DEFAULT_VERIFY_TLS;
+ }
+
+ if (BooleanUtils.isBooleanTrue(value)) {
+ return true;
+ } else if (BooleanUtils.isBooleanFalse(value)) {
+ return false;
+ } else {
+ throw new DruidJdbcException(
+ "Invalid value[%s] for property[%s], must be 'true' or 'false'.", value, VERIFY_TLS
+ );
+ }
+ }
+
+ /**
+ * Result of separating client-side properties from query context parameters.
+ */
+ public record SplitProperties(ClientProperties clientProperties, Map<String, String> queryContext)
+ {
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidArray.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidArray.java
new file mode 100644
index 00000000000..a33ee613fad
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidArray.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.sql.Array;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Map;
+
+/**
+ * Our implementation of JDBC {@link Array}.
+ */
+public class DruidArray implements Array
+{
+ private final int baseType;
+ private final String baseTypeName;
+ private final Object[] arr;
+
+ public DruidArray(final int baseType, final String baseTypeName, final Object[] arr)
+ {
+ this.baseType = baseType;
+ this.baseTypeName = baseTypeName;
+ this.arr = arr;
+ }
+
+ @Override
+ public String getBaseTypeName()
+ {
+ return baseTypeName;
+ }
+
+ @Override
+ public int getBaseType()
+ {
+ return baseType;
+ }
+
+ @Override
+ public Object getArray()
+ {
+ return arr;
+ }
+
+ @Override
+ public Object getArray(final Map<String, Class<?>> map) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getArray with a type map is not supported for DruidArray");
+ }
+
+ @Override
+ public Object getArray(final long index, final int count)
+ {
+ final int startIndex = (int) index - 1;
+ final Object[] slice = new Object[count];
+ System.arraycopy(arr, startIndex, slice, 0, count);
+ return slice;
+ }
+
+ @Override
+ public Object getArray(final long index, final int count, final Map<String, Class<?>> map) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getArray with a type map is not supported for DruidArray");
+ }
+
+ @Override
+ public ResultSet getResultSet() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getResultSet not supported for DruidArray");
+ }
+
+ @Override
+ public ResultSet getResultSet(final Map<String, Class<?>> map) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getResultSet not supported for DruidArray");
+ }
+
+ @Override
+ public ResultSet getResultSet(final long index, final int count) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getResultSet not supported for DruidArray");
+ }
+
+ @Override
+ public ResultSet getResultSet(final long index, final int count, final Map<String, Class<?>> map) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getResultSet not supported for DruidArray");
+ }
+
+ @Override
+ public void free()
+ {
+ // Nothing to free.
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnection.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnection.java
new file mode 100644
index 00000000000..5e1776e36fb
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnection.java
@@ -0,0 +1,645 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.http.DruidHttpClient;
+import org.apache.druid.jdbc.http.QueryResultsIterator;
+import org.apache.druid.jdbc.http.SqlRequest;
+
+import javax.annotation.Nullable;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.CallableStatement;
+import java.sql.Clob;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.NClob;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLClientInfoException;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.sql.Struct;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executor;
+
+/**
+ * Our implementation of JDBC {@link Connection}. Thread-safe.
+ */
+public class DruidConnection implements Connection
+{
+ private final DruidConnectionUrl connectionUrl;
+ private final DruidHttpClient httpClient;
+ private final ObjectMapper jsonMapper;
+ private final ConcurrentHashMap<String, Object> setStatementQueryContext = new ConcurrentHashMap<>();
+
+ // Guarded by "this".
+ private final Set<DruidStatement> openStatements = new HashSet<>();
+ private volatile boolean closed; // Must acquire "this" when writing.
+
+ // Guarded by "metaDataLock".
+ private DruidDatabaseMetaData metaData;
+ private final Object metaDataLock = new Object();
+
+ public DruidConnection(
+ final DruidConnectionUrl connectionUrl,
+ final DruidHttpClient httpClient,
+ final ObjectMapper jsonMapper
+ )
+ {
+ this.connectionUrl = connectionUrl;
+ this.httpClient = httpClient;
+ this.jsonMapper = jsonMapper;
+ }
+
+ @Override
+ public Statement createStatement() throws SQLException
+ {
+ final DruidStatement statement = new DruidStatement(this);
+
+ synchronized (this) {
+ throwIfClosed();
+ openStatements.add(statement);
+ }
+
+ return statement;
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(final String sql) throws SQLException
+ {
+ final DruidPreparedStatement statement = new DruidPreparedStatement(this, sql);
+
+ synchronized (this) {
+ throwIfClosed();
+ openStatements.add(statement);
+ }
+
+ return statement;
+ }
+
+ @Override
+ public CallableStatement prepareCall(final String sql) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("CallableStatement not supported");
+ }
+
+ @Override
+ public String nativeSQL(final String sql)
+ {
+ return sql;
+ }
+
+ @Override
+ public boolean getAutoCommit()
+ {
+ return true;
+ }
+
+ @Override
+ public void setAutoCommit(final boolean autoCommit) throws SQLException
+ {
+ if (!autoCommit) {
+ throw new DruidJdbcFeatureNotSupportedException("Auto-commit cannot be disabled.");
+ }
+ }
+
+ @Override
+ public void commit()
+ {
+ // Do nothing: we are always in autocommit mode, so there cannot be an active transaction.
+ }
+
+ @Override
+ public void rollback()
+ {
+ // Do nothing: we are always in autocommit mode, so there cannot be an active transaction.
+ }
+
+ @Override
+ public DatabaseMetaData getMetaData()
+ {
+ synchronized (metaDataLock) {
+ if (metaData == null) {
+ metaData = new DruidDatabaseMetaData(this);
+ }
+ return metaData;
+ }
+ }
+
+ @Override
+ public boolean isReadOnly()
+ {
+ return true;
+ }
+
+ @Override
+ public void setReadOnly(final boolean readOnly)
+ {
+ // JDBC defines this as a hint, which we choose to ignore.
+ }
+
+ @Override
+ @Nullable
+ public String getCatalog()
+ {
+ // Druid doesn't have catalogs (only schemas and tables).
+ return null;
+ }
+
+ @Override
+ public void setCatalog(final String catalog)
+ {
+ // Druid doesn't have catalogs (only schemas and tables), ignore.
+ }
+
+ @Override
+ public int getTransactionIsolation()
+ {
+ // Transactions are not supported, return TRANSACTION_NONE.
+ return TRANSACTION_NONE;
+ }
+
+ @Override
+ public void setTransactionIsolation(final int level) throws SQLException
+ {
+ if (level != Connection.TRANSACTION_NONE) {
+ throw new DruidJdbcFeatureNotSupportedException("Only TRANSACTION_NONE is supported.");
+ }
+ }
+
+ @Override
+ @Nullable
+ public SQLWarning getWarnings()
+ {
+ // Druid's SQL protocol does not include warnings.
+ return null;
+ }
+
+ @Override
+ public void clearWarnings()
+ {
+ // Druid's SQL protocol does not include warnings, nothing to do.
+ }
+
+ @Override
+ public Statement createStatement(final int resultSetType, final int resultSetConcurrency) throws SQLException
+ {
+ if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only TYPE_FORWARD_ONLY result sets are supported");
+ }
+ if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CONCUR_READ_ONLY result sets are supported");
+ }
+ return createStatement();
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(
+ final String sql,
+ final int resultSetType,
+ final int resultSetConcurrency
+ ) throws SQLException
+ {
+ if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only TYPE_FORWARD_ONLY result sets are supported");
+ }
+ if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CONCUR_READ_ONLY result sets are supported");
+ }
+ return prepareStatement(sql);
+ }
+
+ @Override
+ public CallableStatement prepareCall(final String sql, final int resultSetType, final int resultSetConcurrency)
+ throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("CallableStatement not supported");
+ }
+
+ @Override
+ public Map<String, Class<?>> getTypeMap() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Type maps not supported");
+ }
+
+ @Override
+ public void setTypeMap(final Map<String, Class<?>> map) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Type maps not supported");
+ }
+
+ @Override
+ public int getHoldability()
+ {
+ return ResultSet.CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override
+ public void setHoldability(final int holdability) throws SQLException
+ {
+ if (holdability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CLOSE_CURSORS_AT_COMMIT is supported");
+ }
+ }
+
+ @Override
+ public Savepoint setSavepoint() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Savepoints not supported");
+ }
+
+ @Override
+ public Savepoint setSavepoint(final String name) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Savepoints not supported");
+ }
+
+ @Override
+ public void rollback(final Savepoint savepoint) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Savepoints not supported");
+ }
+
+ @Override
+ public void releaseSavepoint(final Savepoint savepoint) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Savepoints not supported");
+ }
+
+ @Override
+ public Statement createStatement(
+ final int resultSetType,
+ final int resultSetConcurrency,
+ final int resultSetHoldability
+ ) throws SQLException
+ {
+ if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only TYPE_FORWARD_ONLY result sets are supported");
+ }
+ if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CONCUR_READ_ONLY result sets are supported");
+ }
+ if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CLOSE_CURSORS_AT_COMMIT holdability is supported");
+ }
+ return createStatement();
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(
+ final String sql,
+ final int resultSetType,
+ final int resultSetConcurrency,
+ final int resultSetHoldability
+ ) throws SQLException
+ {
+ if (resultSetType != ResultSet.TYPE_FORWARD_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only TYPE_FORWARD_ONLY result sets are supported");
+ }
+ if (resultSetConcurrency != ResultSet.CONCUR_READ_ONLY) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CONCUR_READ_ONLY result sets are supported");
+ }
+ if (resultSetHoldability != ResultSet.CLOSE_CURSORS_AT_COMMIT) {
+ throw new DruidJdbcFeatureNotSupportedException("Only CLOSE_CURSORS_AT_COMMIT holdability is supported");
+ }
+ return prepareStatement(sql);
+ }
+
+ @Override
+ public CallableStatement prepareCall(
+ final String sql,
+ final int resultSetType,
+ final int resultSetConcurrency,
+ final int resultSetHoldability
+ ) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("CallableStatement not supported");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(final String sql, final int autoGeneratedKeys) throws SQLException
+ {
+ if (autoGeneratedKeys != Statement.NO_GENERATED_KEYS) {
+ throw new DruidJdbcFeatureNotSupportedException("Auto-generated keys not supported");
+ }
+ return prepareStatement(sql);
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(final String sql, final int[] columnIndexes) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Auto-generated keys not supported");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(final String sql, final String[] columnNames) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Auto-generated keys not supported");
+ }
+
+ @Override
+ public Clob createClob() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Clob creation not supported");
+ }
+
+ @Override
+ public Blob createBlob() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Blob creation not supported");
+ }
+
+ @Override
+ public NClob createNClob() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("NClob creation not supported");
+ }
+
+ @Override
+ public SQLXML createSQLXML() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("SQLXML creation not supported");
+ }
+
+ @Override
+ public boolean isValid(final int timeout) throws SQLException
+ {
+ if (timeout < 0) {
+ throw new DruidJdbcException("Timeout value must not be negative");
+ }
+
+ if (closed) {
+ return false;
+ }
+
+ try {
+ runValidationQuery(timeout);
+ return true;
+ }
+ catch (Exception e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void setClientInfo(final String name, final String value) throws SQLClientInfoException
+ {
+ throw new SQLClientInfoException();
+ }
+
+ @Override
+ @Nullable
+ public String getClientInfo(final String name)
+ {
+ return null;
+ }
+
+ @Override
+ public Properties getClientInfo()
+ {
+ return new Properties();
+ }
+
+ @Override
+ public void setClientInfo(final Properties properties) throws SQLClientInfoException
+ {
+ throw new SQLClientInfoException();
+ }
+
+ @Override
+ public Array createArrayOf(final String typeName, final Object[] elements)
+ {
+ final int baseType = switch (typeName.toUpperCase(Locale.ENGLISH)) {
+ case "INTEGER", "INT" -> Types.INTEGER;
+ case "BIGINT", "LONG" -> Types.BIGINT;
+ case "DOUBLE" -> Types.DOUBLE;
+ case "FLOAT" -> Types.FLOAT;
+ case "REAL" -> Types.REAL;
+ case "BOOLEAN" -> Types.BOOLEAN;
+ default -> Types.VARCHAR;
+ };
+ return new DruidArray(baseType, typeName, elements);
+ }
+
+ @Override
+ public Struct createStruct(final String typeName, final Object[] attributes) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Struct creation not supported");
+ }
+
+ @Override
+ @Nullable
+ public String getSchema()
+ {
+ return null;
+ }
+
+ @Override
+ public void setSchema(final String schema)
+ {
+ // Cannot set schema at the driver level, it must be specified in SQL. JDBC says drivers that do not support
+ // this call should silently ignore it.
+ }
+
+ @Override
+ public void abort(final Executor executor) throws SQLException
+ {
+ close();
+ }
+
+ @Override
+ public void setNetworkTimeout(final Executor executor, final int milliseconds) throws SQLException
+ {
+ throwIfClosed();
+ if (milliseconds < 0) {
+ throw new DruidJdbcException("networkTimeout cannot be negative");
+ }
+ httpClient.setNetworkTimeoutMillis(milliseconds);
+ }
+
+ @Override
+ public int getNetworkTimeout()
+ {
+ return httpClient.getNetworkTimeoutMillis();
+ }
+
+ @Override
+ public <T> T unwrap(final Class<T> iface) throws SQLException
+ {
+ if (iface.isAssignableFrom(getClass())) {
+ return iface.cast(this);
+ }
+ throw new DruidJdbcException("Cannot unwrap to class[%s]", iface.getName());
+ }
+
+ @Override
+ public boolean isWrapperFor(final Class<?> iface)
+ {
+ return iface.isAssignableFrom(getClass());
+ }
+
+ public DruidConnectionUrl getConnectionUrl()
+ {
+ return connectionUrl;
+ }
+
+ public DruidHttpClient getHttpClient()
+ {
+ return httpClient;
+ }
+
+ /**
+ * Returns the full query context, taking into account both {@link DruidConnectionUrl#getQueryContext()} (from the
+ * JDBC URL and properties) and {@link #setStatementQueryContext} (from {@code SET} statements issued in this
+ * connection).
+ */
+ public Map<String, Object> getQueryContext()
+ {
+ final Map<String, Object> combined = new HashMap<>(connectionUrl.getQueryContext());
+ combined.putAll(setStatementQueryContext);
+ return combined;
+ }
+
+ /**
+ * Called when a {@code SET} statement is executed. The driver intercepts these rather than sending
+ * them to the server, so they can apply to all subsequent statements issued by the connection.
+ */
+ public void addSetStatementQueryContext(final String key, @Nullable final Object value)
+ {
+ if (value == null) {
+ setStatementQueryContext.remove(key);
+ } else {
+ setStatementQueryContext.put(key, value);
+ }
+ }
+
+ /**
+ * Runs a {@code SELECT 1} validation query, blocking until it completes.
+ */
+ public void runValidationQuery(final int timeoutSeconds) throws SQLException
+ {
+ final Map<String, Object> context = getQueryContext();
+ if (timeoutSeconds > 0) {
+ context.put("timeout", (long) timeoutSeconds * 1000);
+ }
+
+ //noinspection EmptyTryBlock
+ try (final QueryResultsIterator ignored = httpClient.runQuery(SqlRequest.of("SELECT 1", context, null))) {
+ // Do nothing
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Connection validation failed: %s", e);
+ }
+ }
+
+ @Override
+ public boolean isClosed() throws SQLException
+ {
+ return closed;
+ }
+
+ @Override
+ public synchronized void close() throws SQLException
+ {
+ if (closed) {
+ return;
+ }
+
+ closed = true;
+
+ // Close all open statements. Use a snapshot to avoid ConcurrentModificationException: DruidStatement.close()
+ // calls statementClosed() which removes from openStatements.
+ Throwable e = null;
+ for (final DruidStatement statement : new ArrayList<>(openStatements)) {
+ try {
+ statement.close();
+ }
+ catch (SQLException e2) {
+ if (e == null) {
+ e = e2;
+ } else {
+ e.addSuppressed(e2);
+ }
+ }
+ }
+
+ if (httpClient != null) {
+ try {
+ httpClient.close();
+ }
+ catch (Throwable e2) {
+ if (e == null) {
+ e = e2;
+ } else {
+ e.addSuppressed(e2);
+ }
+ }
+ }
+
+ if (e instanceof SQLException) {
+ throw (SQLException) e;
+ } else if (e != null) {
+ throw new DruidJdbcException(e, "%s", e);
+ }
+ }
+
+ ObjectMapper getJsonMapper()
+ {
+ return jsonMapper;
+ }
+
+ private void throwIfClosed() throws SQLException
+ {
+ if (closed) {
+ throw new DruidJdbcException("Connection is closed");
+ }
+ }
+
+ /**
+ * Returns all connection context parameters that have been set by
+ * {@link #addSetStatementQueryContext(String, Object)}.
+ */
+ Map<String, Object> getSetStatementQueryContext()
+ {
+ return new HashMap<>(setStatementQueryContext);
+ }
+
+ /**
+ * Callback invoked by {@link DruidStatement#close()} to deregister the statement from this connection's
+ * set of open statements.
+ */
+ synchronized void onStatementClosed(final DruidStatement statement)
+ {
+ openStatements.remove(statement);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnectionUrl.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnectionUrl.java
new file mode 100644
index 00000000000..2f09facbc12
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidConnectionUrl.java
@@ -0,0 +1,267 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLDecoder;
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+
+/**
+ * Parses and validates Druid JDBC URLs.
+ */
+public class DruidConnectionUrl
+{
+ private final String scheme;
+ private final String host;
+ private final int port;
+ private final String path;
+ private final ClientProperties clientProperties;
+ private final Map<String, String> queryContext;
+
+ private DruidConnectionUrl(
+ final String scheme,
+ final String host,
+ final int port,
+ final String path,
+ final ClientProperties clientProperties,
+ final Map<String, String> queryContext
+ )
+ {
+ this.scheme = scheme;
+ this.host = host;
+ this.port = port;
+ this.path = path;
+ this.clientProperties = clientProperties;
+ this.queryContext = queryContext;
+ }
+
+ /**
+ * Creates a DruidConnectionUrl object from JDBC URL and properties.
+ *
+ * <p>The URL format is: {@code jdbc:druid:http://host:port/path?param1=value1¶m2=value2}
+ *
+ * @param url the JDBC URL string to parse, must start with "jdbc:druid:"
+ * @param connectionProperties additional connection properties that will be merged with URL parameters
+ *
+ * @return a DruidConnectionUrl object containing the parsed components
+ *
+ * @throws SQLException if the URL is invalid or cannot be parsed
+ */
+ public static DruidConnectionUrl parse(final String url, final Properties connectionProperties) throws SQLException
+ {
+ if (url == null || !url.startsWith(DruidJdbcDriver.CONNECT_STRING_PREFIX)) {
+ throw invalidUrl(StringUtils.format("Must start with[%s]", DruidJdbcDriver.CONNECT_STRING_PREFIX));
+ }
+
+ try {
+ // Remove the jdbc:druid: prefix and parse as URI
+ final String uriString = url.substring(DruidJdbcDriver.CONNECT_STRING_PREFIX.length());
+
+ final URI uri = new URI(uriString);
+
+ final String scheme = uri.getScheme();
+ if (!"http".equalsIgnoreCase(scheme) && !isHttpsScheme(scheme)) {
+ throw invalidUrl("Scheme must be 'http' or 'https'");
+ }
+
+ final String host = uri.getHost();
+ if (host == null || host.isEmpty()) {
+ throw invalidUrl("Host is required");
+ }
+
+ // Reject userinfo in the URL: credentials must come from connection properties or query parameters,
+ // not as user:password@host. We deliberately do not echo the userinfo back in the message.
+ if (uri.getUserInfo() != null) {
+ throw invalidUrl("userinfo in URL is not supported; use user/password connection properties instead");
+ }
+
+ int port = uri.getPort();
+ if (port == -1) {
+ port = isHttpsScheme(scheme) ? 443 : 80;
+ }
+
+ final Map<String, String> allProperties = new HashMap<>();
+
+ // Add JDBC connection properties.
+ if (connectionProperties != null) {
+ for (final String propertyName : connectionProperties.stringPropertyNames()) {
+ allProperties.put(propertyName, connectionProperties.getProperty(propertyName));
+ }
+ }
+
+ // Properties from URL have precedence over JDBC connection properties. Use getRawQuery(), not getQuery():
+ // the latter is already decoded, so it would decode twice and split on encoded separators.
+ allProperties.putAll(parseQueryParameters(uri.getRawQuery()));
+
+ // Separate client-side properties from query context parameters.
+ final ClientProperties.SplitProperties splitProperties = ClientProperties.splitProperties(allProperties);
+
+ return new DruidConnectionUrl(
+ scheme,
+ host,
+ port,
+ uri.getPath(),
+ splitProperties.clientProperties(),
+ splitProperties.queryContext()
+ );
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw invalidUrl(e);
+ }
+ }
+
+ public String getScheme()
+ {
+ return scheme;
+ }
+
+ public boolean isHttps()
+ {
+ return isHttpsScheme(scheme);
+ }
+
+ public String getHost()
+ {
+ return host;
+ }
+
+ public int getPort()
+ {
+ return port;
+ }
+
+ public String getPath()
+ {
+ return path;
+ }
+
+ public ClientProperties getClientProperties()
+ {
+ return clientProperties;
+ }
+
+ public Map<String, String> getQueryContext()
+ {
+ return queryContext;
+ }
+
+ public String buildHttpUrl()
+ {
+ final StringBuilder sb = new StringBuilder();
+ sb.append(scheme).append("://").append(host);
+
+ // Only include port if it's not the default port for the scheme.
+ final boolean isDefaultPort = (isHttps() && port == 443) || (!isHttps() && port == 80);
+ if (!isDefaultPort) {
+ sb.append(":").append(port);
+ }
+
+ sb.append(path);
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ final DruidConnectionUrl that = (DruidConnectionUrl) o;
+ return port == that.port
+ && Objects.equals(scheme, that.scheme)
+ && Objects.equals(host, that.host)
+ && Objects.equals(path, that.path)
+ && Objects.equals(clientProperties, that.clientProperties)
+ && Objects.equals(queryContext, that.queryContext);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(scheme, host, port, path, clientProperties, queryContext);
+ }
+
+ @Override
+ public String toString()
+ {
+ return "DruidConnectionUrl{" +
+ "scheme='" + scheme + '\'' +
+ ", host='" + host + '\'' +
+ ", port=" + port +
+ ", path='" + path + '\'' +
+ ", clientProperties=" + clientProperties +
+ ", queryContext=" + queryContext +
+ '}';
+ }
+
+ private static boolean isHttpsScheme(final String scheme)
+ {
+ return "https".equalsIgnoreCase(scheme);
+ }
+
+ private static SQLException invalidUrl(final String reason)
+ {
+ return new DruidJdbcException("Invalid JDBC URL. %s", reason);
+ }
+
+ /**
+ * Builds the error for a URL that could not be parsed. Deliberately does not include the actual URL or the
+ * exception cause, because the URL may contain credentials.
+ */
+ private static SQLException invalidUrl(final Throwable cause)
+ {
+ if (cause instanceof URISyntaxException e) {
+ return new DruidJdbcException("Invalid JDBC URL: %s at index[%s]", e.getReason(), e.getIndex());
+ } else {
+ return new DruidJdbcException("Invalid JDBC URL");
+ }
+ }
+
+ private static Map<String, String> parseQueryParameters(final String query)
+ {
+ if (query == null) {
+ return Collections.emptyMap();
+ }
+ final Map<String, String> map = new HashMap<>();
+ final String[] pairs = query.split("&");
+ for (final String pair : pairs) {
+ final int idx = pair.indexOf('=');
+ if (idx > 0) {
+ final String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8);
+ final String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8);
+ map.put(key, value);
+ } else if (!pair.isEmpty()) {
+ final String key = URLDecoder.decode(pair, StandardCharsets.UTF_8);
+ map.put(key, "");
+ }
+ }
+ return map;
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidDatabaseMetaData.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidDatabaseMetaData.java
new file mode 100644
index 00000000000..5f43bf01025
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidDatabaseMetaData.java
@@ -0,0 +1,1650 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import org.apache.druid.jdbc.http.ColumnMetadata;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.JDBCType;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.RowIdLifetime;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Our implementation of JDBC {@link DatabaseMetaData}.
+ */
+public class DruidDatabaseMetaData implements DatabaseMetaData
+{
+ private static final String DEFAULT_DATABASE_PRODUCT_VERSION = "Unknown";
+ private static final int NO_OR_UNKNOWN_LIMIT = 0;
+
+ /**
+ * Appended to each LIKE in a metadata query, matching {@link #getSearchStringEscape()}.
+ */
+ private static final String ESCAPE_CLAUSE = " ESCAPE '\\'";
+
+ /**
+ * Reserved words of Druid SQL that are not also reserved words of SQL:2003.
+ */
+ private static final String SQL_KEYWORDS =
+ "ALLOW,ARRAY_MAX_CARDINALITY,BEGIN_FRAME,BEGIN_PARTITION,BIT,CLASSIFIER,CLUSTERED,CONTAINS,CURRENT_CATALOG," +
+ "CURRENT_ROW,CURRENT_SCHEMA,DATETIME,DEFINE,DISALLOW,EMPTY,END_FRAME,END_PARTITION,EQUALS,EXPLAIN,EXTEND," +
+ "FIRST_VALUE,FRAME_ROW,FRIDAY,GROUPS,INITIAL,JSON_ARRAY,JSON_ARRAYAGG,JSON_EXISTS,JSON_OBJECT,JSON_OBJECTAGG," +
+ "JSON_QUERY,JSON_SCOPE,JSON_VALUE,LAG,LAST_VALUE,LEAD,LIKE_REGEX,LIMIT,MATCHES,MATCH_NUMBER,MATCH_RECOGNIZE," +
+ "MEASURES,MINUS,MONDAY,NEXT,NTH_VALUE,NTILE,OCCURRENCES_REGEX,OFFSET,OMIT,ONE,ORDINAL,PARTITIONED,PATTERN,PER," +
+ "PERCENT,PERIOD,PERMUTE,PORTION,POSITION_REGEX,PRECEDES,PREV,QUALIFY,RESET,RUNNING,SAFE_CAST,SAFE_OFFSET," +
+ "SAFE_ORDINAL,SATURDAY,SEEK,SHOW,SKIP,STREAM,SUBSET,SUBSTRING_REGEX,SUCCEEDS,SUNDAY,SYSTEM_TIME,THURSDAY," +
+ "TINYINT,TRANSLATE_REGEX,TRIM_ARRAY,TRUNCATE,TRY_CAST,TUESDAY,UPSERT,VALUE_OF,VARBINARY,VERSIONING,WEDNESDAY";
+
+ /**
+ * Numeric functions usable in a JDBC function escape, i.e. <code>{fn name(...)}</code>. Implemented in
+ * Druid SQL on the server side, so the driver just needs to report the correct list.
+ */
+ private static final String NUMERIC_FUNCTIONS =
+ "ABS,ACOS,ASIN,ATAN,ATAN2,CEILING,COS,COT,DEGREES,EXP,FLOOR,LOG,LOG10,MOD,PI,POWER,RADIANS,ROUND,SIN," +
+ "SQRT,TAN,TRUNCATE";
+
+ /**
+ * String functions usable in a JDBC function escape, as {@link #NUMERIC_FUNCTIONS}.
+ */
+ private static final String STRING_FUNCTIONS =
+ "CONCAT,LCASE,LEFT,LENGTH,LOCATE,LTRIM,REPEAT,REPLACE,RIGHT,RTRIM,SUBSTRING,UCASE";
+
+ /**
+ * System functions usable in a JDBC function escape, as {@link #NUMERIC_FUNCTIONS}.
+ */
+ private static final String SYSTEM_FUNCTIONS = "CONVERT,IFNULL";
+
+ /**
+ * Time and date functions usable in a JDBC function escape, as {@link #NUMERIC_FUNCTIONS}.
+ */
+ private static final String TIME_DATE_FUNCTIONS =
+ "CURDATE,DAYOFMONTH,DAYOFWEEK,DAYOFYEAR,HOUR,MINUTE,MONTH,NOW,QUARTER,SECOND,TIMESTAMPADD," +
+ "TIMESTAMPDIFF,WEEK,YEAR";
+
+ /**
+ * Columns of {@link #getImportedKeys}, {@link #getExportedKeys}, and {@link #getCrossReference}.
+ */
+ private static final List<ColumnMetadata> FOREIGN_KEY_COLUMNS = List.of(
+ new ColumnMetadata("PKTABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("PKTABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("PKTABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("PKCOLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("FKTABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("FKTABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("FKTABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("FKCOLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("KEY_SEQ", JDBCType.INTEGER),
+ new ColumnMetadata("UPDATE_RULE", JDBCType.INTEGER),
+ new ColumnMetadata("DELETE_RULE", JDBCType.INTEGER),
+ new ColumnMetadata("FK_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("PK_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DEFERRABILITY", JDBCType.INTEGER)
+ );
+
+ /**
+ * Columns of {@link #getBestRowIdentifier} and {@link #getVersionColumns}.
+ */
+ private static final List<ColumnMetadata> ROW_IDENTIFIER_COLUMNS = List.of(
+ new ColumnMetadata("SCOPE", JDBCType.INTEGER),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_SIZE", JDBCType.INTEGER),
+ new ColumnMetadata("BUFFER_LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("DECIMAL_DIGITS", JDBCType.INTEGER),
+ new ColumnMetadata("PSEUDO_COLUMN", JDBCType.INTEGER)
+ );
+
+ private final DruidConnection connection;
+ private final Object databaseProductVersionLock = new Object();
+
+ // Access guarded by databaseProductVersionLock.
+ private String databaseProductVersion;
+
+ public DruidDatabaseMetaData(final DruidConnection connection)
+ {
+ this.connection = connection;
+ }
+
+ @Override
+ public boolean allProceduresAreCallable()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean allTablesAreSelectable()
+ {
+ return true;
+ }
+
+ @Override
+ public String getURL()
+ {
+ return "jdbc:druid:" + connection.getConnectionUrl().buildHttpUrl();
+ }
+
+ @Override
+ public String getUserName()
+ {
+ final String user = connection.getConnectionUrl().getClientProperties().getUser();
+ return user != null ? user : "";
+ }
+
+ @Override
+ public boolean isReadOnly()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean nullsAreSortedHigh()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean nullsAreSortedLow()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean nullsAreSortedAtStart()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean nullsAreSortedAtEnd()
+ {
+ return false;
+ }
+
+ @Override
+ public String getDatabaseProductName()
+ {
+ return "Apache Druid";
+ }
+
+ @Override
+ public String getDatabaseProductVersion() throws SQLException
+ {
+ synchronized (databaseProductVersionLock) {
+ if (databaseProductVersion == null) {
+ databaseProductVersion = fetchDatabaseProductVersion();
+ }
+ return databaseProductVersion;
+ }
+ }
+
+ @Override
+ public String getDriverName()
+ {
+ return "Druid JDBC Driver";
+ }
+
+ @Override
+ public String getDriverVersion()
+ {
+ return DruidJdbcDriver.getVersion();
+ }
+
+ @Override
+ public int getDriverMajorVersion()
+ {
+ return DruidJdbcDriver.getStaticMajorVersion();
+ }
+
+ @Override
+ public int getDriverMinorVersion()
+ {
+ return DruidJdbcDriver.getStaticMinorVersion();
+ }
+
+ @Override
+ public boolean usesLocalFiles()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean usesLocalFilePerTable()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsMixedCaseIdentifiers()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean storesUpperCaseIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean storesLowerCaseIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean storesMixedCaseIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsMixedCaseQuotedIdentifiers()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean storesUpperCaseQuotedIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean storesLowerCaseQuotedIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean storesMixedCaseQuotedIdentifiers()
+ {
+ return false;
+ }
+
+ @Override
+ public String getIdentifierQuoteString()
+ {
+ return "\"";
+ }
+
+ @Override
+ public String getSQLKeywords()
+ {
+ return SQL_KEYWORDS;
+ }
+
+ @Override
+ public String getNumericFunctions()
+ {
+ return NUMERIC_FUNCTIONS;
+ }
+
+ @Override
+ public String getStringFunctions()
+ {
+ return STRING_FUNCTIONS;
+ }
+
+ @Override
+ public String getSystemFunctions()
+ {
+ return SYSTEM_FUNCTIONS;
+ }
+
+ @Override
+ public String getTimeDateFunctions()
+ {
+ return TIME_DATE_FUNCTIONS;
+ }
+
+ @Override
+ public String getSearchStringEscape()
+ {
+ return "\\";
+ }
+
+ @Override
+ public String getExtraNameCharacters()
+ {
+ return "";
+ }
+
+ @Override
+ public boolean supportsAlterTableWithAddColumn()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsAlterTableWithDropColumn()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsColumnAliasing()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean nullPlusNonNullIsNull()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsConvert()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsConvert(final int fromType, final int toType)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsTableCorrelationNames()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsDifferentTableCorrelationNames()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsExpressionsInOrderBy()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOrderByUnrelated()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsGroupBy()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsGroupByUnrelated()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsGroupByBeyondSelect()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsLikeEscapeClause()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsMultipleResultSets()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsMultipleTransactions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsNonNullableColumns()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsMinimumSQLGrammar()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCoreSQLGrammar()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsExtendedSQLGrammar()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsANSI92EntryLevelSQL()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsANSI92IntermediateSQL()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsANSI92FullSQL()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsIntegrityEnhancementFacility()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOuterJoins()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsFullOuterJoins()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsLimitedOuterJoins()
+ {
+ return true;
+ }
+
+ @Override
+ public String getSchemaTerm()
+ {
+ return "schema";
+ }
+
+ @Override
+ public String getProcedureTerm()
+ {
+ return "procedure";
+ }
+
+ @Override
+ public String getCatalogTerm()
+ {
+ return "catalog";
+ }
+
+ @Override
+ public boolean isCatalogAtStart()
+ {
+ return true;
+ }
+
+ @Override
+ public String getCatalogSeparator()
+ {
+ return ".";
+ }
+
+ @Override
+ public boolean supportsSchemasInDataManipulation()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSchemasInProcedureCalls()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSchemasInTableDefinitions()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSchemasInIndexDefinitions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSchemasInPrivilegeDefinitions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCatalogsInDataManipulation()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCatalogsInProcedureCalls()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCatalogsInTableDefinitions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCatalogsInIndexDefinitions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsCatalogsInPrivilegeDefinitions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsPositionedDelete()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsPositionedUpdate()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSelectForUpdate()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsStoredProcedures()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsSubqueriesInComparisons()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSubqueriesInExists()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSubqueriesInIns()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsSubqueriesInQuantifieds()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsCorrelatedSubqueries()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsUnion()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsUnionAll()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean supportsOpenCursorsAcrossCommit()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOpenCursorsAcrossRollback()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOpenStatementsAcrossCommit()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsOpenStatementsAcrossRollback()
+ {
+ return false;
+ }
+
+ @Override
+ public int getMaxBinaryLiteralLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxCharLiteralLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnsInGroupBy()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnsInIndex()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnsInOrderBy()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnsInSelect()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxColumnsInTable()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxConnections()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxCursorNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxIndexLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxSchemaNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxProcedureNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxCatalogNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxRowSize()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public boolean doesMaxRowSizeIncludeBlobs()
+ {
+ return false;
+ }
+
+ @Override
+ public int getMaxStatementLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxStatements()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxTableNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxTablesInSelect()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getMaxUserNameLength()
+ {
+ return NO_OR_UNKNOWN_LIMIT;
+ }
+
+ @Override
+ public int getDefaultTransactionIsolation()
+ {
+ return Connection.TRANSACTION_NONE;
+ }
+
+ @Override
+ public boolean supportsTransactions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsTransactionIsolationLevel(final int level)
+ {
+ return level == Connection.TRANSACTION_NONE;
+ }
+
+ @Override
+ public boolean supportsDataDefinitionAndDataManipulationTransactions()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsDataManipulationTransactionsOnly()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean dataDefinitionCausesTransactionCommit()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean dataDefinitionIgnoredInTransactions()
+ {
+ return false;
+ }
+
+ @Override
+ public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern)
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("PROCEDURE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("PROCEDURE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("PROCEDURE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("reserved1", JDBCType.VARCHAR),
+ new ColumnMetadata("reserved2", JDBCType.VARCHAR),
+ new ColumnMetadata("reserved3", JDBCType.VARCHAR),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("PROCEDURE_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("SPECIFIC_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getProcedureColumns(
+ final String catalog,
+ final String schemaPattern,
+ final String procedureNamePattern,
+ final String columnNamePattern
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("PROCEDURE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("PROCEDURE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("PROCEDURE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("PRECISION", JDBCType.INTEGER),
+ new ColumnMetadata("LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("SCALE", JDBCType.INTEGER),
+ new ColumnMetadata("RADIX", JDBCType.INTEGER),
+ new ColumnMetadata("NULLABLE", JDBCType.INTEGER),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_DEF", JDBCType.VARCHAR),
+ new ColumnMetadata("SQL_DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("SQL_DATETIME_SUB", JDBCType.INTEGER),
+ new ColumnMetadata("CHAR_OCTET_LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("ORDINAL_POSITION", JDBCType.INTEGER),
+ new ColumnMetadata("IS_NULLABLE", JDBCType.VARCHAR),
+ new ColumnMetadata("SPECIFIC_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getTables(
+ final String catalog,
+ final String schemaPattern,
+ final String tableNamePattern,
+ final String[] types
+ ) throws SQLException
+ {
+ final List<String> whereBuilder = new ArrayList<>();
+ final List<String> parameters = new ArrayList<>();
+ if (catalog != null) {
+ whereBuilder.add("TABLES.TABLE_CATALOG = ?");
+ parameters.add(catalog);
+ }
+
+ if (schemaPattern != null) {
+ whereBuilder.add("TABLES.TABLE_SCHEMA LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(schemaPattern);
+ }
+
+ if (tableNamePattern != null) {
+ whereBuilder.add("TABLES.TABLE_NAME LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(tableNamePattern);
+ }
+
+ if (types != null) {
+ if (types.length == 0) {
+ // An explicit but empty type list matches no tables.
+ whereBuilder.add("1 = 0");
+ } else {
+ whereBuilder.add(
+ "TABLES.TABLE_TYPE IN (" + String.join(", ", Collections.nCopies(types.length, "?")) + ")"
+ );
+ parameters.addAll(Arrays.asList(types));
+ }
+ }
+
+ final String where = whereBuilder.isEmpty() ? "" : "WHERE " + String.join(" AND ", whereBuilder);
+ final String sql = """
+ SELECT
+ TABLE_CATALOG AS TABLE_CAT,
+ TABLE_SCHEMA AS TABLE_SCHEM,
+ TABLE_NAME AS TABLE_NAME,
+ TABLE_TYPE AS TABLE_TYPE,
+ CAST(NULL AS VARCHAR) AS REMARKS,
+ CAST(NULL AS VARCHAR) AS TYPE_CAT,
+ CAST(NULL AS VARCHAR) AS TYPE_SCHEM,
+ CAST(NULL AS VARCHAR) AS TYPE_NAME,
+ CAST(NULL AS VARCHAR) AS SELF_REFERENCING_COL_NAME,
+ CAST(NULL AS VARCHAR) AS REF_GENERATION
+ FROM
+ INFORMATION_SCHEMA.TABLES
+ """ + where + """
+
+ ORDER BY
+ TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, TABLE_NAME
+ """;
+
+ return sqlResultSet(sql, parameters);
+ }
+
+ @Override
+ public ResultSet getSchemas() throws SQLException
+ {
+ return getSchemas(null, null);
+ }
+
+ @Override
+ public ResultSet getCatalogs() throws SQLException
+ {
+ final String sql = """
+ SELECT
+ DISTINCT CATALOG_NAME AS TABLE_CAT
+ FROM
+ INFORMATION_SCHEMA.SCHEMATA
+ ORDER BY
+ TABLE_CAT
+ """;
+
+ return sqlResultSet(sql, List.of());
+ }
+
+ @Override
+ public ResultSet getTableTypes() throws SQLException
+ {
+ final String sql = """
+ SELECT
+ DISTINCT TABLE_TYPE AS TABLE_TYPE
+ FROM
+ INFORMATION_SCHEMA.TABLES
+ ORDER BY
+ TABLE_TYPE
+ """;
+
+ return sqlResultSet(sql, List.of());
+ }
+
+ @Override
+ public ResultSet getColumns(
+ final String catalog,
+ final String schemaPattern,
+ final String tableNamePattern,
+ final String columnNamePattern
+ ) throws SQLException
+ {
+ final List<String> whereBuilder = new ArrayList<>();
+ final List<String> parameters = new ArrayList<>();
+ if (catalog != null) {
+ whereBuilder.add("COLUMNS.TABLE_CATALOG = ?");
+ parameters.add(catalog);
+ }
+
+ if (schemaPattern != null) {
+ whereBuilder.add("COLUMNS.TABLE_SCHEMA LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(schemaPattern);
+ }
+
+ if (tableNamePattern != null) {
+ whereBuilder.add("COLUMNS.TABLE_NAME LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(tableNamePattern);
+ }
+
+ if (columnNamePattern != null) {
+ whereBuilder.add("COLUMNS.COLUMN_NAME LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(columnNamePattern);
+ }
+
+ final String where = whereBuilder.isEmpty() ? "" : "WHERE " + String.join(" AND ", whereBuilder);
+ final String sql = """
+ SELECT
+ TABLE_CATALOG AS TABLE_CAT,
+ TABLE_SCHEMA AS TABLE_SCHEM,
+ TABLE_NAME AS TABLE_NAME,
+ COLUMN_NAME AS COLUMN_NAME,
+ CAST(JDBC_TYPE AS INTEGER) AS DATA_TYPE,
+ DATA_TYPE AS TYPE_NAME,
+ COALESCE(CAST(CHARACTER_MAXIMUM_LENGTH AS INTEGER), CAST(NUMERIC_PRECISION AS INTEGER)) AS COLUMN_SIZE,
+ -1 AS BUFFER_LENGTH,
+ CAST(NUMERIC_SCALE AS INTEGER) AS DECIMAL_DIGITS,
+ CAST(NUMERIC_PRECISION_RADIX AS INTEGER) AS NUM_PREC_RADIX,
+ CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS NULLABLE,
+ CAST(NULL AS VARCHAR) AS REMARKS,
+ COLUMN_DEFAULT AS COLUMN_DEF,
+ -1 AS SQL_DATA_TYPE,
+ -1 AS SQL_DATETIME_SUB,
+ -1 AS CHAR_OCTET_LENGTH,
+ CAST(ORDINAL_POSITION AS INTEGER) AS ORDINAL_POSITION,
+ IS_NULLABLE AS IS_NULLABLE,
+ CAST(NULL AS VARCHAR) AS SCOPE_CATALOG,
+ CAST(NULL AS VARCHAR) AS SCOPE_SCHEMA,
+ CAST(NULL AS VARCHAR) AS SCOPE_TABLE,
+ -1 AS SOURCE_DATA_TYPE,
+ 'NO' AS IS_AUTOINCREMENT,
+ 'NO' AS IS_GENERATEDCOLUMN
+ FROM
+ INFORMATION_SCHEMA.COLUMNS
+ """ + where + """
+
+ ORDER BY
+ TABLE_CAT, TABLE_SCHEM, TABLE_NAME, ORDINAL_POSITION
+ """;
+
+ return sqlResultSet(sql, parameters);
+ }
+
+ @Override
+ public ResultSet getColumnPrivileges(
+ final String catalog,
+ final String schema,
+ final String table,
+ final String columnNamePattern
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("GRANTOR", JDBCType.VARCHAR),
+ new ColumnMetadata("GRANTEE", JDBCType.VARCHAR),
+ new ColumnMetadata("PRIVILEGE", JDBCType.VARCHAR),
+ new ColumnMetadata("IS_GRANTABLE", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getTablePrivileges(final String catalog, final String schemaPattern, final String tableNamePattern)
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("GRANTOR", JDBCType.VARCHAR),
+ new ColumnMetadata("GRANTEE", JDBCType.VARCHAR),
+ new ColumnMetadata("PRIVILEGE", JDBCType.VARCHAR),
+ new ColumnMetadata("IS_GRANTABLE", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getBestRowIdentifier(
+ final String catalog,
+ final String schema,
+ final String table,
+ final int scope,
+ final boolean nullable
+ )
+ {
+ return DruidResultSet.createEmpty(ROW_IDENTIFIER_COLUMNS);
+ }
+
+ @Override
+ public ResultSet getVersionColumns(final String catalog, final String schema, final String table)
+ {
+ return DruidResultSet.createEmpty(ROW_IDENTIFIER_COLUMNS);
+ }
+
+ @Override
+ public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table)
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("KEY_SEQ", JDBCType.INTEGER),
+ new ColumnMetadata("PK_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getImportedKeys(final String catalog, final String schema, final String table)
+ {
+ return DruidResultSet.createEmpty(FOREIGN_KEY_COLUMNS);
+ }
+
+ @Override
+ public ResultSet getExportedKeys(final String catalog, final String schema, final String table)
+ {
+ return DruidResultSet.createEmpty(FOREIGN_KEY_COLUMNS);
+ }
+
+ @Override
+ public ResultSet getCrossReference(
+ final String parentCatalog,
+ final String parentSchema,
+ final String parentTable,
+ final String foreignCatalog,
+ final String foreignSchema,
+ final String foreignTable
+ )
+ {
+ return DruidResultSet.createEmpty(FOREIGN_KEY_COLUMNS);
+ }
+
+ @Override
+ public ResultSet getTypeInfo()
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("PRECISION", JDBCType.INTEGER),
+ new ColumnMetadata("LITERAL_PREFIX", JDBCType.VARCHAR),
+ new ColumnMetadata("LITERAL_SUFFIX", JDBCType.VARCHAR),
+ new ColumnMetadata("CREATE_PARAMS", JDBCType.VARCHAR),
+ new ColumnMetadata("NULLABLE", JDBCType.INTEGER),
+ new ColumnMetadata("CASE_SENSITIVE", JDBCType.BOOLEAN),
+ new ColumnMetadata("SEARCHABLE", JDBCType.INTEGER),
+ new ColumnMetadata("UNSIGNED_ATTRIBUTE", JDBCType.BOOLEAN),
+ new ColumnMetadata("FIXED_PREC_SCALE", JDBCType.BOOLEAN),
+ new ColumnMetadata("AUTO_INCREMENT", JDBCType.BOOLEAN),
+ new ColumnMetadata("LOCAL_TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("MINIMUM_SCALE", JDBCType.INTEGER),
+ new ColumnMetadata("MAXIMUM_SCALE", JDBCType.INTEGER),
+ new ColumnMetadata("SQL_DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("SQL_DATETIME_SUB", JDBCType.INTEGER),
+ new ColumnMetadata("NUM_PREC_RADIX", JDBCType.INTEGER)
+ ));
+ }
+
+ @Override
+ public ResultSet getIndexInfo(
+ final String catalog,
+ final String schema,
+ final String table,
+ final boolean unique,
+ final boolean approximate
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("NON_UNIQUE", JDBCType.BOOLEAN),
+ new ColumnMetadata("INDEX_QUALIFIER", JDBCType.VARCHAR),
+ new ColumnMetadata("INDEX_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("ORDINAL_POSITION", JDBCType.INTEGER),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("ASC_OR_DESC", JDBCType.VARCHAR),
+ new ColumnMetadata("CARDINALITY", JDBCType.BIGINT),
+ new ColumnMetadata("PAGES", JDBCType.BIGINT),
+ new ColumnMetadata("FILTER_CONDITION", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public boolean supportsResultSetType(final int type)
+ {
+ return type == ResultSet.TYPE_FORWARD_ONLY;
+ }
+
+ @Override
+ public boolean supportsResultSetConcurrency(final int type, final int concurrency)
+ {
+ return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY;
+ }
+
+ @Override
+ public boolean ownUpdatesAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean ownDeletesAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean ownInsertsAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean othersUpdatesAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean othersDeletesAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean othersInsertsAreVisible(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean updatesAreDetected(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean deletesAreDetected(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean insertsAreDetected(final int type)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsBatchUpdates()
+ {
+ return false;
+ }
+
+ @Override
+ public ResultSet getUDTs(
+ final String catalog,
+ final String schemaPattern,
+ final String typeNamePattern,
+ final int[] types
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TYPE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("CLASS_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("BASE_TYPE", JDBCType.INTEGER)
+ ));
+ }
+
+ @Override
+ public Connection getConnection()
+ {
+ return connection;
+ }
+
+ @Override
+ public boolean supportsSavepoints()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsNamedParameters()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsMultipleOpenResults()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsGetGeneratedKeys()
+ {
+ return false;
+ }
+
+ @Override
+ public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern)
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TYPE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("SUPERTYPE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("SUPERTYPE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("SUPERTYPE_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getSuperTables(final String catalog, final String schemaPattern, final String tableNamePattern)
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("SUPERTABLE_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getAttributes(
+ final String catalog,
+ final String schemaPattern,
+ final String typeNamePattern,
+ final String attributeNamePattern
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TYPE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("ATTR_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("ATTR_TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("ATTR_SIZE", JDBCType.INTEGER),
+ new ColumnMetadata("DECIMAL_DIGITS", JDBCType.INTEGER),
+ new ColumnMetadata("NUM_PREC_RADIX", JDBCType.INTEGER),
+ new ColumnMetadata("NULLABLE", JDBCType.INTEGER),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("ATTR_DEF", JDBCType.VARCHAR),
+ new ColumnMetadata("SQL_DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("SQL_DATETIME_SUB", JDBCType.INTEGER),
+ new ColumnMetadata("CHAR_OCTET_LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("ORDINAL_POSITION", JDBCType.INTEGER),
+ new ColumnMetadata("IS_NULLABLE", JDBCType.VARCHAR),
+ new ColumnMetadata("SCOPE_CATALOG", JDBCType.VARCHAR),
+ new ColumnMetadata("SCOPE_SCHEMA", JDBCType.VARCHAR),
+ new ColumnMetadata("SCOPE_TABLE", JDBCType.VARCHAR),
+ new ColumnMetadata("SOURCE_DATA_TYPE", JDBCType.INTEGER)
+ ));
+ }
+
+ @Override
+ public boolean supportsResultSetHoldability(final int holdability)
+ {
+ return holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override
+ public int getResultSetHoldability()
+ {
+ return ResultSet.CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override
+ public int getDatabaseMajorVersion() throws SQLException
+ {
+ return parseVersionPart(0);
+ }
+
+ @Override
+ public int getDatabaseMinorVersion() throws SQLException
+ {
+ return parseVersionPart(1);
+ }
+
+ @Override
+ public int getJDBCMajorVersion()
+ {
+ return 4;
+ }
+
+ @Override
+ public int getJDBCMinorVersion()
+ {
+ return 2;
+ }
+
+ @Override
+ public int getSQLStateType()
+ {
+ return DatabaseMetaData.sqlStateSQL99;
+ }
+
+ @Override
+ public boolean locatorsUpdateCopy()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean supportsStatementPooling()
+ {
+ return false;
+ }
+
+ @Override
+ public RowIdLifetime getRowIdLifetime()
+ {
+ return RowIdLifetime.ROWID_UNSUPPORTED;
+ }
+
+ @Override
+ public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException
+ {
+ final List<String> whereBuilder = new ArrayList<>();
+ final List<String> parameters = new ArrayList<>();
+ if (catalog != null) {
+ whereBuilder.add("SCHEMATA.CATALOG_NAME = ?");
+ parameters.add(catalog);
+ }
+
+ if (schemaPattern != null) {
+ whereBuilder.add("SCHEMATA.SCHEMA_NAME LIKE ?" + ESCAPE_CLAUSE);
+ parameters.add(schemaPattern);
+ }
+
+ final String where = whereBuilder.isEmpty() ? "" : "WHERE " + String.join(" AND ", whereBuilder);
+ final String sql = """
+ SELECT
+ SCHEMA_NAME AS TABLE_SCHEM,
+ CATALOG_NAME AS TABLE_CATALOG
+ FROM
+ INFORMATION_SCHEMA.SCHEMATA
+ """ + where + """
+
+ ORDER BY
+ TABLE_CATALOG, TABLE_SCHEM
+ """;
+
+ return sqlResultSet(sql, parameters);
+ }
+
+ @Override
+ public boolean supportsStoredFunctionsUsingCallSyntax()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean autoCommitFailureClosesAllResultSets()
+ {
+ return false;
+ }
+
+ @Override
+ public ResultSet getClientInfoProperties()
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("MAX_LEN", JDBCType.INTEGER),
+ new ColumnMetadata("DEFAULT_VALUE", JDBCType.VARCHAR),
+ new ColumnMetadata("DESCRIPTION", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getFunctions(final String catalog, final String schemaPattern, final String functionNamePattern)
+
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("FUNCTION_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("FUNCTION_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("FUNCTION_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("FUNCTION_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("SPECIFIC_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getFunctionColumns(
+ final String catalog,
+ final String schemaPattern,
+ final String functionNamePattern,
+ final String columnNamePattern
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("FUNCTION_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("FUNCTION_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("FUNCTION_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("TYPE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("PRECISION", JDBCType.INTEGER),
+ new ColumnMetadata("LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("SCALE", JDBCType.INTEGER),
+ new ColumnMetadata("RADIX", JDBCType.INTEGER),
+ new ColumnMetadata("NULLABLE", JDBCType.INTEGER),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("CHAR_OCTET_LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("ORDINAL_POSITION", JDBCType.INTEGER),
+ new ColumnMetadata("IS_NULLABLE", JDBCType.VARCHAR),
+ new ColumnMetadata("SPECIFIC_NAME", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public ResultSet getPseudoColumns(
+ final String catalog,
+ final String schemaPattern,
+ final String tableNamePattern,
+ final String columnNamePattern
+ )
+ {
+ return DruidResultSet.createEmpty(List.of(
+ new ColumnMetadata("TABLE_CAT", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_SCHEM", JDBCType.VARCHAR),
+ new ColumnMetadata("TABLE_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("COLUMN_NAME", JDBCType.VARCHAR),
+ new ColumnMetadata("DATA_TYPE", JDBCType.INTEGER),
+ new ColumnMetadata("COLUMN_SIZE", JDBCType.INTEGER),
+ new ColumnMetadata("DECIMAL_DIGITS", JDBCType.INTEGER),
+ new ColumnMetadata("NUM_PREC_RADIX", JDBCType.INTEGER),
+ new ColumnMetadata("COLUMN_USAGE", JDBCType.VARCHAR),
+ new ColumnMetadata("REMARKS", JDBCType.VARCHAR),
+ new ColumnMetadata("CHAR_OCTET_LENGTH", JDBCType.INTEGER),
+ new ColumnMetadata("IS_NULLABLE", JDBCType.VARCHAR)
+ ));
+ }
+
+ @Override
+ public boolean generatedKeyAlwaysReturned()
+ {
+ return false;
+ }
+
+ @Override
+ public <T> T unwrap(final Class<T> iface) throws SQLException
+ {
+ if (iface.isAssignableFrom(getClass())) {
+ return iface.cast(this);
+ }
+ throw new DruidJdbcException("Cannot unwrap to class[%s]", iface.getName());
+ }
+
+ @Override
+ public boolean isWrapperFor(final Class<?> iface)
+ {
+ return iface.isAssignableFrom(getClass());
+ }
+
+ /**
+ * Issue a query to the server and return the response as a ResultSet.
+ */
+ private ResultSet sqlResultSet(final String sql, final List<String> parameters) throws SQLException
+ {
+ final PreparedStatement statement = connection.prepareStatement(sql);
+ statement.closeOnCompletion();
+ try {
+ for (int i = 0; i < parameters.size(); i++) {
+ statement.setString(i + 1, parameters.get(i));
+ }
+ return statement.executeQuery();
+ }
+ catch (Throwable e) {
+ // No ResultSet was produced, so closeOnCompletion() will never fire.
+ try {
+ statement.close();
+ }
+ catch (Throwable e2) {
+ e.addSuppressed(e2);
+ }
+ throw new DruidJdbcException(e, "Failed to execute metadata query");
+ }
+ }
+
+ /**
+ * Parses the dot-separated segment at the given index from {@link #getDatabaseProductVersion()}, returning 0 if it
+ * is missing or not numeric.
+ */
+ private int parseVersionPart(final int index) throws SQLException
+ {
+ final String[] parts = getDatabaseProductVersion().split("\\.");
+ if (index >= parts.length) {
+ return 0;
+ }
+ try {
+ return Integer.parseInt(parts[index]);
+ }
+ catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * Reads the server version from {@code sys.servers}, or returns {@link #DEFAULT_DATABASE_PRODUCT_VERSION} if it
+ * cannot be read.
+ */
+ private String fetchDatabaseProductVersion() throws SQLException
+ {
+ try (final Statement stmt = connection.createStatement()) {
+ try (final ResultSet rs = stmt.executeQuery("SELECT \"version\" FROM sys.servers LIMIT 1")) {
+ if (rs.next()) {
+ final String version = rs.getString(1);
+ if (version != null && !version.isEmpty()) {
+ return version;
+ }
+ }
+ }
+ }
+ catch (SQLException e) {
+ if (DruidSQLState.InvalidAuthorizationSpecification.getSqlState().equals(e.getSQLState())) {
+ // Fall through to return the default version if the query to sys.servers is forbidden.
+ } else {
+ throw e;
+ }
+ }
+ return DEFAULT_DATABASE_PRODUCT_VERSION;
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcDriver.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcDriver.java
new file mode 100644
index 00000000000..c5445d91e6d
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcDriver.java
@@ -0,0 +1,204 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.http.DruidHttpClient;
+import org.apache.druid.jdbc.http.DruidHttpClientImpl;
+
+import javax.annotation.Nullable;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.util.Properties;
+import java.util.logging.Logger;
+
+public class DruidJdbcDriver implements Driver
+{
+ public static final String CONNECT_STRING_PREFIX = "jdbc:druid:";
+
+ /**
+ * Fallback version string used when the implementation version cannot be read from the JAR manifest.
+ * This is an arbitrary recent-ish Druid version and carries no special meaning.
+ */
+ public static final String FALLBACK_VERSION = "36.0.0";
+
+ private static final String VERSION;
+ private static final int MAJOR_VERSION;
+ private static final int MINOR_VERSION;
+
+ static {
+ final String implVersion = DruidJdbcDriver.class.getPackage().getImplementationVersion();
+ VERSION = implVersion != null ? implVersion : FALLBACK_VERSION;
+ MAJOR_VERSION = parseMajorVersion(VERSION);
+ MINOR_VERSION = parseMinorVersion(VERSION);
+
+ try {
+ DriverManager.registerDriver(new DruidJdbcDriver());
+ }
+ catch (SQLException e) {
+ throw new RuntimeException("Failed to register Druid JDBC driver", e);
+ }
+ }
+
+ public static String getVersion()
+ {
+ return VERSION;
+ }
+
+ public static int getStaticMajorVersion()
+ {
+ return MAJOR_VERSION;
+ }
+
+ public static int getStaticMinorVersion()
+ {
+ return MINOR_VERSION;
+ }
+
+ @Override
+ @Nullable
+ public Connection connect(final String url, final Properties info) throws SQLException
+ {
+ if (!acceptsURL(url)) {
+ return null;
+ }
+
+ final DruidConnectionUrl connectionUrl = DruidConnectionUrl.parse(url, info);
+ final ObjectMapper jsonMapper = new ObjectMapper();
+ final DruidHttpClient httpClient = new DruidHttpClientImpl(connectionUrl, jsonMapper);
+ final DruidConnection connection = new DruidConnection(connectionUrl, httpClient, jsonMapper);
+ return validateOrClose(connection);
+ }
+
+ @Override
+ public boolean acceptsURL(final String url)
+ {
+ return url != null && url.startsWith(CONNECT_STRING_PREFIX);
+ }
+
+ @Override
+ public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info)
+ {
+ return new DriverPropertyInfo[0];
+ }
+
+ @Override
+ public int getMajorVersion()
+ {
+ return MAJOR_VERSION;
+ }
+
+ @Override
+ public int getMinorVersion()
+ {
+ return MINOR_VERSION;
+ }
+
+ @Override
+ public boolean jdbcCompliant()
+ {
+ return false;
+ }
+
+ @Override
+ public Logger getParentLogger()
+ {
+ return Logger.getLogger(getClass().getPackageName());
+ }
+
+ /**
+ * Parses the major version (first dot-separated segment) from a version string.
+ * For example, "38.0.0-SNAPSHOT" returns 38. Returns 0 if the version string
+ * cannot be parsed.
+ */
+ static int parseMajorVersion(final String version)
+ {
+ final String segment = firstSegment(version);
+ try {
+ return Integer.parseInt(segment);
+ }
+ catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * Parses the minor version (second dot-separated segment) from a version string.
+ * For example, "38.0.0-SNAPSHOT" returns 0. Returns 0 if the version string has
+ * no second segment or cannot be parsed.
+ */
+ static int parseMinorVersion(final String version)
+ {
+ final int firstDot = version.indexOf('.');
+ if (firstDot < 0 || firstDot == version.length() - 1) {
+ return 0;
+ }
+
+ final String rest = version.substring(firstDot + 1);
+ final String segment = firstSegment(rest);
+ try {
+ return Integer.parseInt(segment);
+ }
+ catch (NumberFormatException e) {
+ return 0;
+ }
+ }
+
+ /**
+ * Runs the connection validation query and returns the connection if it succeeds. Otherwise, closes
+ * the connection.
+ */
+ static Connection validateOrClose(final DruidConnection connection) throws SQLException
+ {
+ try {
+ connection.runValidationQuery(0);
+ return connection;
+ }
+ catch (Throwable e) {
+ try {
+ connection.close();
+ }
+ catch (Throwable e2) {
+ e.addSuppressed(e2);
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Returns the portion of a version string up to the first '.' or '-', whichever comes first.
+ */
+ private static String firstSegment(final String s)
+ {
+ int end = s.length();
+ final int dot = s.indexOf('.');
+ if (dot >= 0) {
+ end = dot;
+ }
+ final int dash = s.indexOf('-');
+ if (dash >= 0 && dash < end) {
+ end = dash;
+ }
+ return s.substring(0, end);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcException.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcException.java
new file mode 100644
index 00000000000..98418163668
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcException.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.sql.SQLException;
+
+/**
+ * Subclass of {@link SQLException} that is designed to simplify instantiation, using format strings and values
+ * of {@link DruidSQLState}. It is not guaranteed that *all* exceptions thrown by the Druid JDBC driver are
+ * instances of this class.
+ */
+public class DruidJdbcException extends SQLException
+{
+ public DruidJdbcException(final String formatText, final Object... arguments)
+ {
+ super(StringUtils.format(formatText, arguments));
+ }
+
+ public DruidJdbcException(final Throwable cause, final String formatText, final Object... arguments)
+ {
+ super(StringUtils.format(formatText, arguments), cause);
+ }
+
+ public DruidJdbcException(final DruidSQLState sqlState, final String formatText, final Object... arguments)
+ {
+ super(StringUtils.format(formatText, arguments), sqlState.getSqlState());
+ }
+
+ public DruidJdbcException(
+ final Throwable cause,
+ final DruidSQLState sqlState,
+ final String formatText,
+ final Object... arguments
+ )
+ {
+ super(StringUtils.format(formatText, arguments), sqlState.getSqlState(), cause);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcFeatureNotSupportedException.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcFeatureNotSupportedException.java
new file mode 100644
index 00000000000..35a399aaa10
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidJdbcFeatureNotSupportedException.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.sql.SQLFeatureNotSupportedException;
+
+/**
+ * Subclass of {@link SQLFeatureNotSupportedException} that is designed to simplify instantiation, using format
+ * strings and values of {@link DruidSQLState}. This is the counterpart to {@link DruidJdbcException} and should be
+ * thrown wherever the Druid JDBC driver does not support an optional JDBC feature, so that callers (connection pools,
+ * ORMs, and other tooling) can distinguish "feature absent" from a genuine error via the standard exception type.
+ */
+public class DruidJdbcFeatureNotSupportedException extends SQLFeatureNotSupportedException
+{
+ public DruidJdbcFeatureNotSupportedException(final String formatText, final Object... arguments)
+ {
+ super(StringUtils.format(formatText, arguments), DruidSQLState.FeatureUnsupported.getSqlState());
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidPreparedStatement.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidPreparedStatement.java
new file mode 100644
index 00000000000..cabf5a0cce7
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidPreparedStatement.java
@@ -0,0 +1,812 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import org.apache.druid.jdbc.http.QueryResultsIterator;
+import org.apache.druid.jdbc.http.SqlParameter;
+import org.apache.druid.jdbc.http.SqlRequest;
+import org.apache.druid.jdbc.sql.SqlScanner;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.net.URL;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Date;
+import java.sql.JDBCType;
+import java.sql.NClob;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.Ref;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.RowId;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.TimeZone;
+import java.util.UUID;
+
+/**
+ * Our implementation of JDBC {@link PreparedStatement}.
+ *
+ * <p><b>Thread safety:</b> same contract as {@link DruidStatement}.
+ */
+public class DruidPreparedStatement extends DruidStatement implements PreparedStatement
+{
+ /**
+ * ISO-8601 date formatter ({@code yyyy-MM-dd}), no timezone included.
+ */
+ private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
+
+ /**
+ * ISO-8601 time formatter ({@code HH:mm:ss[.SSS]}), no timezone included.
+ */
+ private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ISO_LOCAL_TIME;
+
+ /**
+ * ISO-8601 timestamp formatter for instants in UTC ({@code yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}).
+ */
+ private static final DateTimeFormatter TIMESTAMP_UTC_FORMATTER =
+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH).withZone(ZoneId.of("UTC"));
+
+ /**
+ * ISO-8601 zoneless timestamp formatter ({@code yyyy-MM-dd'T'HH:mm:ss[.SSS]}).
+ */
+ private static final DateTimeFormatter TIMESTAMP_ZONELESS_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
+
+ /**
+ * Typed NULL used to stand in for an unbound parameter in {@link #getMetaData()}.
+ */
+ private static final SqlParameter UNBOUND_PARAMETER_PLACEHOLDER =
+ new SqlParameter(JDBCType.NULL.getName(), null);
+
+ private final SqlScanner sqlScanner;
+ private final Map<Integer, SqlParameter> parameters = new HashMap<>();
+ private ResultSetMetaData cachedMetaData;
+
+ public DruidPreparedStatement(final DruidConnection connection, final String sql) throws SQLException
+ {
+ super(connection);
+ this.sqlScanner = SqlScanner.scan(sql);
+ }
+
+ @Override
+ public ResultSet executeQuery() throws SQLException
+ {
+ throwIfClosed();
+
+ final String sql = preparedSqlStatement();
+
+ // Check that all expected parameters are set.
+ final List<SqlParameter> parameterList = new ArrayList<>();
+ for (int i = 1; i <= sqlScanner.getParameterCount(); i++) {
+ final SqlParameter param = parameters.get(i);
+ if (param == null) {
+ throw new DruidJdbcException("Parameter[%s] must be bound", i);
+ }
+ parameterList.add(param);
+ }
+
+ return executeSql(sql, parameterList);
+ }
+
+ /**
+ * Returns the SQL statement to send to the server, validating that there is exactly one and that it is not a
+ * {@code SET} statement. Shared by {@link #executeQuery()} and {@link #getMetaData()}.
+ */
+ private String preparedSqlStatement() throws SQLException
+ {
+ if (!sqlScanner.getSetStatements().isEmpty()) {
+ throw new DruidJdbcException("Cannot prepare SET statements");
+ }
+
+ final String sql = sqlScanner.getSqlStatement();
+ if (sql == null) {
+ throw new DruidJdbcException("No SQL statement to execute");
+ }
+
+ return sql;
+ }
+
+ @Override
+ public int executeUpdate() throws SQLException
+ {
+ throwIfClosed();
+ throw new DruidJdbcFeatureNotSupportedException("Update operations are not supported");
+ }
+
+ @Override
+ public ResultSet executeQuery(final String sql) throws SQLException
+ {
+ throw cannotUseSqlArgument("executeQuery");
+ }
+
+ @Override
+ public int executeUpdate(final String sql) throws SQLException
+ {
+ throw cannotUseSqlArgument("executeUpdate");
+ }
+
+ @Override
+ public boolean execute(final String sql) throws SQLException
+ {
+ throw cannotUseSqlArgument("execute");
+ }
+
+ @Override
+ public void addBatch(final String sql) throws SQLException
+ {
+ throw cannotUseSqlArgument("addBatch");
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException
+ {
+ throw cannotUseSqlArgument("executeUpdate");
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException
+ {
+ throw cannotUseSqlArgument("executeUpdate");
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final String[] columnNames) throws SQLException
+ {
+ throw cannotUseSqlArgument("executeUpdate");
+ }
+
+ @Override
+ public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException
+ {
+ throw cannotUseSqlArgument("execute");
+ }
+
+ @Override
+ public boolean execute(final String sql, final int[] columnIndexes) throws SQLException
+ {
+ throw cannotUseSqlArgument("execute");
+ }
+
+ @Override
+ public boolean execute(final String sql, final String[] columnNames) throws SQLException
+ {
+ throw cannotUseSqlArgument("execute");
+ }
+
+ @Override
+ public void setNull(final int parameterIndex, final int sqlType) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ final String typeName;
+ try {
+ typeName = JDBCType.valueOf(sqlType).getName();
+ }
+ catch (IllegalArgumentException e) {
+ throw new DruidJdbcException(e, "Unsupported SQL type[%s]", sqlType);
+ }
+ parameters.put(parameterIndex, new SqlParameter(typeName, null));
+ }
+
+ @Override
+ public void setBoolean(final int parameterIndex, final boolean x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.BOOLEAN.getName(), x));
+ }
+
+ @Override
+ public void setByte(final int parameterIndex, final byte x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.TINYINT.getName(), x));
+ }
+
+ @Override
+ public void setShort(final int parameterIndex, final short x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.SMALLINT.getName(), x));
+ }
+
+ @Override
+ public void setInt(final int parameterIndex, final int x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.INTEGER.getName(), x));
+ }
+
+ @Override
+ public void setLong(final int parameterIndex, final long x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.BIGINT.getName(), x));
+ }
+
+ @Override
+ public void setFloat(final int parameterIndex, final float x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.REAL.getName(), x));
+ }
+
+ @Override
+ public void setDouble(final int parameterIndex, final double x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.DOUBLE.getName(), x));
+ }
+
+ @Override
+ public void setBigDecimal(final int parameterIndex, final BigDecimal x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.DECIMAL.getName(), x));
+ }
+
+ @Override
+ public void setString(final int parameterIndex, final String x) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.VARCHAR.getName(), x));
+ }
+
+ @Override
+ public void setBytes(final int parameterIndex, final byte[] x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBytes not supported");
+ }
+
+ @Override
+ public void setDate(final int parameterIndex, final Date x) throws SQLException
+ {
+ setDate(parameterIndex, x, null);
+ }
+
+ @Override
+ public void setTime(final int parameterIndex, final Time x) throws SQLException
+ {
+ throw timeNotSupported("setTime");
+ }
+
+ @Override
+ public void setTimestamp(final int parameterIndex, final Timestamp x) throws SQLException
+ {
+ setTimestamp(parameterIndex, x, null);
+ }
+
+ @Override
+ public void setAsciiStream(final int parameterIndex, final InputStream x, final int length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setAsciiStream not supported");
+ }
+
+ @Override
+ public void setUnicodeStream(final int parameterIndex, final InputStream x, final int length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setUnicodeStream not supported");
+ }
+
+ @Override
+ public void setBinaryStream(final int parameterIndex, final InputStream x, final int length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBinaryStream not supported");
+ }
+
+ @Override
+ public void clearParameters()
+ {
+ parameters.clear();
+ }
+
+ @Override
+ public void setObject(final int parameterIndex, final Object x, final int targetSqlType) throws SQLException
+ {
+ setObject(parameterIndex, x, targetSqlType, -1);
+ }
+
+ @Override
+ public void setObject(final int parameterIndex, final Object obj) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ if (obj == null) {
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.VARCHAR.getName(), null));
+ } else if (obj instanceof String s) {
+ setString(parameterIndex, s);
+ } else if (obj instanceof Integer i) {
+ setInt(parameterIndex, i);
+ } else if (obj instanceof Long l) {
+ setLong(parameterIndex, l);
+ } else if (obj instanceof Double d) {
+ setDouble(parameterIndex, d);
+ } else if (obj instanceof Float f) {
+ setFloat(parameterIndex, f);
+ } else if (obj instanceof Short sh) {
+ setShort(parameterIndex, sh);
+ } else if (obj instanceof Byte b) {
+ setByte(parameterIndex, b);
+ } else if (obj instanceof Boolean b) {
+ setBoolean(parameterIndex, b);
+ } else if (obj instanceof BigDecimal bd) {
+ setBigDecimal(parameterIndex, bd);
+ } else if (obj instanceof Timestamp ts) {
+ setTimestamp(parameterIndex, ts);
+ } else if (obj instanceof Date d) {
+ setDate(parameterIndex, d);
+ } else if (obj instanceof Time || obj instanceof LocalTime) {
+ throw timeNotSupported("setObject");
+ } else if (obj instanceof LocalDate) {
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.DATE.getName(), serializeParameterValue(obj)));
+ } else if (obj instanceof LocalDateTime ||
+ obj instanceof OffsetDateTime ||
+ obj instanceof ZonedDateTime ||
+ obj instanceof Instant) {
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.TIMESTAMP.getName(), serializeParameterValue(obj)));
+ } else if (obj instanceof UUID) {
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.VARCHAR.getName(), serializeParameterValue(obj)));
+ } else {
+ throw new DruidJdbcFeatureNotSupportedException(
+ "setObject does not support type[%s] (parameter[%s])", obj.getClass().getName(), parameterIndex
+ );
+ }
+ }
+
+ @Override
+ public boolean execute() throws SQLException
+ {
+ //noinspection resource: caller is expected to call getCurrentResultSet()
+ executeQuery();
+ return true;
+ }
+
+ @Override
+ public void addBatch() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Batch operations not supported");
+ }
+
+ @Override
+ public void setCharacterStream(final int parameterIndex, final Reader reader, final int length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setCharacterStream not supported");
+ }
+
+ @Override
+ public void setRef(final int parameterIndex, final Ref x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setRef not supported");
+ }
+
+ @Override
+ public void setBlob(final int parameterIndex, final Blob x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBlob not supported");
+ }
+
+ @Override
+ public void setClob(final int parameterIndex, final Clob x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setClob not supported");
+ }
+
+ @Override
+ public void setArray(final int parameterIndex, final Array x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setArray not supported");
+ }
+
+ @Override
+ public ResultSetMetaData getMetaData() throws SQLException
+ {
+ throwIfClosed();
+
+ if (cachedMetaData != null) {
+ return cachedMetaData;
+ }
+
+ final String sql = preparedSqlStatement();
+
+ try {
+ final Map<String, Object> queryContext = newQueryContext();
+ queryContext.put("sqlOuterLimit", 0);
+
+ // Fill unbound parameters (getMetaData does not require all parameters to be bound).
+ final List<SqlParameter> parameterList = new ArrayList<>();
+ for (int i = 1; i <= sqlScanner.getParameterCount(); i++) {
+ parameterList.add(parameters.getOrDefault(i, UNBOUND_PARAMETER_PLACEHOLDER));
+ }
+
+ final SqlRequest request = SqlRequest.of(sql, queryContext, parameterList);
+ try (final QueryResultsIterator results = getHttpClient().runQuery(request)) {
+ cachedMetaData = new DruidResultSetMetaData(results.getColumns());
+ return cachedMetaData;
+ }
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Failed to get metadata: %s", e);
+ }
+ }
+
+ @Override
+ public void setDate(final int parameterIndex, final Date x, final Calendar cal) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ final String value;
+ if (x == null) {
+ value = null;
+ } else {
+ final TimeZone tz = cal != null ? cal.getTimeZone() : TimeZone.getDefault();
+ final LocalDate ld = Instant.ofEpochMilli(x.getTime()).atZone(tz.toZoneId()).toLocalDate();
+ value = DATE_FORMATTER.format(ld);
+ }
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.DATE.getName(), value));
+ }
+
+ @Override
+ public void setTime(final int parameterIndex, final Time x, final Calendar cal) throws SQLException
+ {
+ throw timeNotSupported("setTime");
+ }
+
+ @Override
+ public void setTimestamp(final int parameterIndex, final Timestamp x, final Calendar cal) throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+ final Object value;
+ if (x == null) {
+ value = null;
+ } else {
+ value = serializeParameterValue(Instant.ofEpochMilli(x.getTime()));
+ }
+ parameters.put(parameterIndex, new SqlParameter(JDBCType.TIMESTAMP.getName(), value));
+ }
+
+ @Override
+ public void setNull(final int parameterIndex, final int sqlType, final String typeName) throws SQLException
+ {
+ setNull(parameterIndex, sqlType);
+ }
+
+ @Override
+ public void setURL(final int parameterIndex, final URL x) throws SQLException
+ {
+ setString(parameterIndex, x != null ? x.toString() : null);
+ }
+
+ @Override
+ public ParameterMetaData getParameterMetaData() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getParameterMetaData not supported");
+ }
+
+ @Override
+ public void setRowId(final int parameterIndex, final RowId x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setRowId not supported");
+ }
+
+ @Override
+ public void setNString(final int parameterIndex, final String value) throws SQLException
+ {
+ setString(parameterIndex, value);
+ }
+
+ @Override
+ public void setNCharacterStream(final int parameterIndex, final Reader value, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setNCharacterStream not supported");
+ }
+
+ @Override
+ public void setNClob(final int parameterIndex, final NClob value) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setNClob not supported");
+ }
+
+ @Override
+ public void setClob(final int parameterIndex, final Reader reader, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setClob not supported");
+ }
+
+ @Override
+ public void setBlob(final int parameterIndex, final InputStream inputStream, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBlob not supported");
+ }
+
+ @Override
+ public void setNClob(final int parameterIndex, final Reader reader, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setNClob not supported");
+ }
+
+ @Override
+ public void setSQLXML(final int parameterIndex, final SQLXML xmlObject) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setSQLXML not supported");
+ }
+
+ @Override
+ public void setObject(final int parameterIndex, final Object x, final int targetSqlType, final int scaleOrLength)
+ throws SQLException
+ {
+ checkParameterIndex(parameterIndex);
+
+ final JDBCType jdbcType;
+ try {
+ jdbcType = JDBCType.valueOf(targetSqlType);
+ }
+ catch (IllegalArgumentException e) {
+ throw new DruidJdbcException(e, "Unsupported SQL type[%s]", targetSqlType);
+ }
+
+ if (jdbcType == JDBCType.TIME || jdbcType == JDBCType.TIME_WITH_TIMEZONE) {
+ throw timeNotSupported("setObject");
+ }
+
+ if (x == null || jdbcType == JDBCType.NULL) {
+ setNull(parameterIndex, targetSqlType);
+ return;
+ }
+
+ try {
+ switch (jdbcType) {
+ case BIT, BOOLEAN -> setBoolean(parameterIndex, castToBoolean(x));
+ case TINYINT -> setByte(parameterIndex, castToNumber(x).byteValue());
+ case SMALLINT -> setShort(parameterIndex, castToNumber(x).shortValue());
+ case INTEGER -> setInt(parameterIndex, castToNumber(x).intValue());
+ case BIGINT -> setLong(parameterIndex, castToNumber(x).longValue());
+ case REAL -> setFloat(parameterIndex, castToNumber(x).floatValue());
+ case FLOAT, DOUBLE -> setDouble(parameterIndex, castToNumber(x).doubleValue());
+ case DECIMAL, NUMERIC -> setBigDecimal(parameterIndex, castToBigDecimal(x, scaleOrLength));
+ case CHAR, VARCHAR, LONGVARCHAR, NCHAR, NVARCHAR, LONGNVARCHAR ->
+ setString(parameterIndex, String.valueOf(serializeParameterValue(x)));
+ case DATE -> setDate(
+ parameterIndex,
+ x instanceof String s ? Date.valueOf(s) : new Date(castToMillis(x))
+ );
+ case TIMESTAMP, TIMESTAMP_WITH_TIMEZONE -> setTimestamp(
+ parameterIndex,
+ x instanceof String s ? Timestamp.valueOf(s) : new Timestamp(castToMillis(x))
+ );
+
+ // Let the value's own class pick the wire type, as Avatica does for JAVA_OBJECT.
+ case JAVA_OBJECT, OTHER -> setObject(parameterIndex, x);
+
+ default -> throw new DruidJdbcFeatureNotSupportedException(
+ "setObject does not support SQL type[%s] (parameter[%s])", jdbcType.getName(), parameterIndex
+ );
+ }
+ }
+ catch (IllegalArgumentException e) {
+ throw new DruidJdbcException(
+ e,
+ DruidSQLState.InvalidParameterType,
+ "Cannot convert an instance of[%s] to type[%s] (parameter[%s])",
+ x.getClass().getName(),
+ jdbcType.getName(),
+ parameterIndex
+ );
+ }
+ }
+
+ @Override
+ public void setAsciiStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setAsciiStream not supported");
+ }
+
+ @Override
+ public void setBinaryStream(final int parameterIndex, final InputStream x, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBinaryStream not supported");
+ }
+
+ @Override
+ public void setCharacterStream(final int parameterIndex, final Reader reader, final long length) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setCharacterStream not supported");
+ }
+
+ @Override
+ public void setAsciiStream(final int parameterIndex, final InputStream x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setAsciiStream not supported");
+ }
+
+ @Override
+ public void setBinaryStream(final int parameterIndex, final InputStream x) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBinaryStream not supported");
+ }
+
+ @Override
+ public void setCharacterStream(final int parameterIndex, final Reader reader) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setCharacterStream not supported");
+ }
+
+ @Override
+ public void setNCharacterStream(final int parameterIndex, final Reader value) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setNCharacterStream not supported");
+ }
+
+ @Override
+ public void setClob(final int parameterIndex, final Reader reader) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setClob not supported");
+ }
+
+ @Override
+ public void setBlob(final int parameterIndex, final InputStream inputStream) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setBlob not supported");
+ }
+
+ @Override
+ public void setNClob(final int parameterIndex, final Reader reader) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("setNClob not supported");
+ }
+
+ private void checkParameterIndex(final int parameterIndex) throws SQLException
+ {
+ throwIfClosed();
+
+ if (parameterIndex < 1) {
+ throw new DruidJdbcException("Parameter index must be >= 1, got: %s", parameterIndex);
+ }
+
+ final int expectedParameters = sqlScanner.getParameterCount();
+ if (parameterIndex > expectedParameters) {
+ throw new DruidJdbcException(
+ "Parameter index %s is out of range; expected %s parameter(s)",
+ parameterIndex,
+ expectedParameters
+ );
+ }
+ }
+
+ private static DruidJdbcException cannotUseSqlArgument(final String method)
+ {
+ return new DruidJdbcException("%s with a SQL argument cannot be called on a PreparedStatement", method);
+ }
+
+ /**
+ * Thrown by the {@code setTime} methods, and by the {@code setObject} overloads that would bind a SQL TIME.
+ */
+ private static DruidJdbcFeatureNotSupportedException timeNotSupported(final String method)
+ {
+ return new DruidJdbcFeatureNotSupportedException("%s not supported: Druid SQL has no TIME type.", method);
+ }
+
+ /**
+ * Converts a bound value to a boolean.
+ */
+ private static boolean castToBoolean(final Object in)
+ {
+ if (in instanceof Boolean b) {
+ return b;
+ } else if (in instanceof String s) {
+ if (BooleanUtils.isBooleanTrue(s)) {
+ return true;
+ } else if (BooleanUtils.isBooleanFalse(s)) {
+ return false;
+ }
+ }
+
+ throw new IllegalArgumentException("not a boolean");
+ }
+
+ /**
+ * Converts a bound value to a {@link Number}.
+ */
+ private static Number castToNumber(final Object in)
+ {
+ if (in instanceof Number n) {
+ return n;
+ } else {
+ return new BigDecimal(String.valueOf(in));
+ }
+ }
+
+ /**
+ * Converts a bound value to a {@link BigDecimal}, rounded to {@code scale} when it is nonnegative.
+ */
+ private static BigDecimal castToBigDecimal(final Object in, final int scale)
+ {
+ final Number number = castToNumber(in);
+ final BigDecimal value = number instanceof BigDecimal bd ? bd : new BigDecimal(number.toString());
+ return scale >= 0 ? value.setScale(scale, RoundingMode.HALF_UP) : value;
+ }
+
+ /**
+ * Converts a non-string bound value to epoch milliseconds, for the {@code DATE} and {@code TIMESTAMP} targets.
+ * Local values are resolved in the JVM default time zone, matching the {@code setDate} and {@code setTimestamp}
+ * overloads that take no {@link Calendar}.
+ */
+ private static long castToMillis(final Object in)
+ {
+ if (in instanceof java.util.Date d) {
+ return d.getTime();
+ } else if (in instanceof Instant i) {
+ return i.toEpochMilli();
+ } else if (in instanceof OffsetDateTime odt) {
+ return odt.toInstant().toEpochMilli();
+ } else if (in instanceof ZonedDateTime zdt) {
+ return zdt.toInstant().toEpochMilli();
+ } else if (in instanceof LocalDateTime ldt) {
+ return Timestamp.valueOf(ldt).getTime();
+ } else if (in instanceof LocalDate ld) {
+ return Date.valueOf(ld).getTime();
+ } else {
+ return castToNumber(in).longValue();
+ }
+ }
+
+ /**
+ * Converts a bound value to its JSON-serializable representation.
+ */
+ private static Object serializeParameterValue(final Object obj)
+ {
+ if (obj instanceof LocalDate) {
+ return DATE_FORMATTER.format((LocalDate) obj);
+ } else if (obj instanceof LocalTime) {
+ return TIME_FORMATTER.format((LocalTime) obj);
+ } else if (obj instanceof LocalDateTime) {
+ return TIMESTAMP_ZONELESS_FORMATTER.format((LocalDateTime) obj);
+ } else if (obj instanceof OffsetDateTime) {
+ return TIMESTAMP_UTC_FORMATTER.format(((OffsetDateTime) obj).toInstant());
+ } else if (obj instanceof ZonedDateTime) {
+ return TIMESTAMP_UTC_FORMATTER.format(((ZonedDateTime) obj).toInstant());
+ } else if (obj instanceof Instant) {
+ return TIMESTAMP_UTC_FORMATTER.format((Instant) obj);
+ } else if (obj instanceof UUID) {
+ return obj.toString();
+ } else {
+ return obj;
+ }
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSet.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSet.java
new file mode 100644
index 00000000000..21f5dd2b296
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSet.java
@@ -0,0 +1,1747 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.http.ColumnMetadata;
+import org.apache.druid.jdbc.http.EmptyQueryResultsIterator;
+import org.apache.druid.jdbc.http.QueryResultsIterator;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.net.URL;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Date;
+import java.sql.JDBCType;
+import java.sql.NClob;
+import java.sql.Ref;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.RowId;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Statement;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.ZoneId;
+import java.util.Base64;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.TimeZone;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Our implementation of JDBC {@link ResultSet}. Forward-only and read-only. Must be closed in order to
+ * release the underlying HTTP response.
+ *
+ * <p><b>Thread safety:</b> {@link #close()} and {@link #isClosed()} are safe to call from any
+ * thread. All other methods are not.
+ */
+public class DruidResultSet implements ResultSet
+{
+ private final QueryResultsIterator resultsIterator;
+
+ @Nullable
+ private final DruidStatement statement;
+
+ /**
+ * Used by {@link #coerceToString(Object)} to write list-valued columns as JSON.
+ */
+ @Nullable
+ private final ObjectMapper jsonMapper;
+
+ /**
+ * Whether this resultset is closed. Set by {@link #close()}.
+ */
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+
+ /**
+ * Lowercased column name to 1-based column index, for {@link #findColumn(String)}. Built on first use, since
+ * many callers only ever access columns by index.
+ */
+ @Nullable
+ private Map<String, Integer> columnIndexByLowercaseName;
+
+ /**
+ * Zero-based index of the current row; -1 before the first call to {@link #next()}.
+ */
+ private int currentRowIndex = -1;
+
+ /**
+ * Values of the current row, or null when positioned before the first row or after the last row.
+ */
+ @Nullable
+ private Object[] currentRow;
+
+ /**
+ * Whether the most recently read column value was null. Set by {@link #getCurrentRowValue(int)} and returned
+ * by {@link #wasNull()}.
+ */
+ private boolean lastValueWasNull;
+
+ public DruidResultSet(
+ final QueryResultsIterator resultsIterator,
+ @Nullable final DruidStatement statement,
+ @Nullable final ObjectMapper jsonMapper
+ )
+ {
+ this.resultsIterator = Objects.requireNonNull(resultsIterator, "resultsIterator");
+ this.statement = statement;
+ this.jsonMapper = jsonMapper;
+ }
+
+ /**
+ * Create an empty resultset with the provided columns.
+ */
+ public static ResultSet createEmpty(final List<ColumnMetadata> columns)
+ {
+ return new DruidResultSet(
+ new EmptyQueryResultsIterator(columns),
+ null, // No DruidStatement to close, null is OK
+ null // No ObjectMapper needed for empty results
+ );
+ }
+
+ @Override
+ public boolean next() throws SQLException
+ {
+ throwIfClosed();
+
+ if (resultsIterator.hasNext()) {
+ currentRow = resultsIterator.next();
+ currentRowIndex++;
+ return true;
+ } else {
+ currentRow = null;
+ return false;
+ }
+ }
+
+ @Override
+ public void close() throws SQLException
+ {
+ if (!closed.compareAndSet(false, true)) {
+ return;
+ }
+ try {
+ resultsIterator.close();
+ }
+ catch (IOException e) {
+ throw new DruidJdbcException(e, "Failed to close results iterator");
+ }
+ finally {
+ if (statement != null) {
+ statement.onResultSetClosed(this);
+ }
+ }
+ }
+
+ @Override
+ public boolean wasNull() throws SQLException
+ {
+ throwIfClosed();
+ return lastValueWasNull;
+ }
+
+ @Override
+ @Nullable
+ public String getString(final int columnIndex) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return coerceToString(value);
+ }
+
+ @Override
+ public boolean getBoolean(final int columnIndex) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return false;
+ }
+ return toBoolean(value, columnIndex);
+ }
+
+ @Override
+ public byte getByte(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "byte");
+ return value == null ? 0 : (byte) value.longValue();
+ }
+
+ @Override
+ public short getShort(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "short");
+ return value == null ? 0 : (short) value.longValue();
+ }
+
+ @Override
+ public int getInt(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "int");
+ return value == null ? 0 : (int) value.longValue();
+ }
+
+ @Override
+ public long getLong(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "long");
+ return value == null ? 0 : value.longValue();
+ }
+
+ @Override
+ public float getFloat(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "float");
+ return value == null ? 0 : (float) value.doubleValue();
+ }
+
+ @Override
+ public double getDouble(final int columnIndex) throws SQLException
+ {
+ final Number value = getNumericValue(columnIndex, "double");
+ return value == null ? 0 : value.doubleValue();
+ }
+
+ @Override
+ @Nullable
+ public BigDecimal getBigDecimal(final int columnIndex, final int scale) throws SQLException
+ {
+ final BigDecimal value = getBigDecimal(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return value.setScale(scale, RoundingMode.HALF_UP);
+ }
+
+ @Override
+ @Nullable
+ public byte[] getBytes(final int columnIndex) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return toBytes(value, columnIndex);
+ }
+
+ @Override
+ @Nullable
+ public Date getDate(final int columnIndex) throws SQLException
+ {
+ return getDate(columnIndex, null);
+ }
+
+ @Override
+ @Nullable
+ public Time getTime(final int columnIndex) throws SQLException
+ {
+ return getTime(columnIndex, null);
+ }
+
+ @Override
+ @Nullable
+ public Timestamp getTimestamp(final int columnIndex) throws SQLException
+ {
+ return getTimestamp(columnIndex, null);
+ }
+
+ @Override
+ public InputStream getAsciiStream(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getAsciiStream not supported");
+ }
+
+ @Override
+ public InputStream getUnicodeStream(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getUnicodeStream not supported");
+ }
+
+ @Override
+ public InputStream getBinaryStream(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getBinaryStream not supported");
+ }
+
+ @Override
+ public String getString(final String columnLabel) throws SQLException
+ {
+ return getString(findColumn(columnLabel));
+ }
+
+ @Override
+ public boolean getBoolean(final String columnLabel) throws SQLException
+ {
+ return getBoolean(findColumn(columnLabel));
+ }
+
+ @Override
+ public byte getByte(final String columnLabel) throws SQLException
+ {
+ return getByte(findColumn(columnLabel));
+ }
+
+ @Override
+ public short getShort(final String columnLabel) throws SQLException
+ {
+ return getShort(findColumn(columnLabel));
+ }
+
+ @Override
+ public int getInt(final String columnLabel) throws SQLException
+ {
+ return getInt(findColumn(columnLabel));
+ }
+
+ @Override
+ public long getLong(final String columnLabel) throws SQLException
+ {
+ return getLong(findColumn(columnLabel));
+ }
+
+ @Override
+ public float getFloat(final String columnLabel) throws SQLException
+ {
+ return getFloat(findColumn(columnLabel));
+ }
+
+ @Override
+ public double getDouble(final String columnLabel) throws SQLException
+ {
+ return getDouble(findColumn(columnLabel));
+ }
+
+ @Override
+ public BigDecimal getBigDecimal(final String columnLabel, final int scale) throws SQLException
+ {
+ return getBigDecimal(findColumn(columnLabel), scale);
+ }
+
+ @Override
+ public byte[] getBytes(final String columnLabel) throws SQLException
+ {
+ return getBytes(findColumn(columnLabel));
+ }
+
+ @Override
+ @Nullable
+ public Date getDate(final String columnLabel) throws SQLException
+ {
+ return getDate(findColumn(columnLabel));
+ }
+
+ @Override
+ @Nullable
+ public Time getTime(final String columnLabel) throws SQLException
+ {
+ return getTime(findColumn(columnLabel));
+ }
+
+ @Override
+ @Nullable
+ public Timestamp getTimestamp(final String columnLabel) throws SQLException
+ {
+ return getTimestamp(findColumn(columnLabel));
+ }
+
+ @Override
+ public InputStream getAsciiStream(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getAsciiStream not supported");
+ }
+
+ @Override
+ public InputStream getUnicodeStream(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getUnicodeStream not supported");
+ }
+
+ @Override
+ public InputStream getBinaryStream(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getBinaryStream not supported");
+ }
+
+ @Override
+ @Nullable
+ public SQLWarning getWarnings() throws SQLException
+ {
+ throwIfClosed();
+ return null;
+ }
+
+ @Override
+ public void clearWarnings() throws SQLException
+ {
+ throwIfClosed();
+ }
+
+ @Override
+ public String getCursorName() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("Cursors not supported");
+ }
+
+ @Override
+ public ResultSetMetaData getMetaData() throws SQLException
+ {
+ throwIfClosed();
+ return new DruidResultSetMetaData(resultsIterator.getColumns());
+ }
+
+ @Override
+ public Object getObject(final int columnIndex) throws SQLException
+ {
+ return coerceForGetObject(getCurrentRowValue(columnIndex), columnIndex);
+ }
+
+ @Override
+ public Object getObject(final String columnLabel) throws SQLException
+ {
+ return getObject(findColumn(columnLabel));
+ }
+
+ @Override
+ public int findColumn(final String columnLabel) throws SQLException
+ {
+ throwIfClosed();
+
+ if (columnIndexByLowercaseName == null) {
+ // Per the java.sql.ResultSet javadoc: "Column names used as input to getter methods are case insensitive.
+ // When a getter method is called with a column name and several columns have the same name, the value of
+ // the first matching column will be returned." Hence putIfAbsent.
+ final List<ColumnMetadata> columns = resultsIterator.getColumns();
+ final Map<String, Integer> map = new HashMap<>();
+ for (int i = 0; i < columns.size(); i++) {
+ map.putIfAbsent(columns.get(i).name().toLowerCase(Locale.ENGLISH), i + 1); // JDBC columns are 1-based
+ }
+ columnIndexByLowercaseName = map;
+ }
+
+ final Integer columnIndex = columnIndexByLowercaseName.get(columnLabel.toLowerCase(Locale.ENGLISH));
+ if (columnIndex == null) {
+ throw new DruidJdbcException("Column not found: %s", columnLabel);
+ }
+ return columnIndex;
+ }
+
+ @Override
+ public Reader getCharacterStream(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getCharacterStream not supported");
+ }
+
+ @Override
+ public Reader getCharacterStream(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getCharacterStream not supported");
+ }
+
+ @Override
+ @Nullable
+ public BigDecimal getBigDecimal(final int columnIndex) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return toBigDecimal(value, columnIndex);
+ }
+
+ @Override
+ public BigDecimal getBigDecimal(final String columnLabel) throws SQLException
+ {
+ return getBigDecimal(findColumn(columnLabel));
+ }
+
+ @Override
+ public boolean isBeforeFirst() throws SQLException
+ {
+ throwIfClosed();
+ return currentRowIndex < 0 && resultsIterator.hasNext();
+ }
+
+ @Override
+ public boolean isAfterLast() throws SQLException
+ {
+ throwIfClosed();
+ // True only once next() has returned false, which is when it clears currentRow.
+ return currentRowIndex >= 0 && currentRow == null;
+ }
+
+ @Override
+ public boolean isFirst() throws SQLException
+ {
+ throwIfClosed();
+ return currentRow != null && currentRowIndex == 0;
+ }
+
+ @Override
+ public boolean isLast() throws SQLException
+ {
+ throwIfClosed();
+ // Requires a lookahead, which for a streaming iterator may block until the next row arrives. It does not
+ // consume the row: hasNext() is idempotent.
+ return currentRow != null && !resultsIterator.hasNext();
+ }
+
+ @Override
+ public void beforeFirst() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("beforeFirst not supported");
+ }
+
+ @Override
+ public void afterLast() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("afterLast not supported");
+ }
+
+ @Override
+ public boolean first() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("first not supported");
+ }
+
+ @Override
+ public boolean last() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("last not supported");
+ }
+
+ @Override
+ public int getRow() throws SQLException
+ {
+ throwIfClosed();
+ if (currentRow == null) {
+ return 0;
+ } else {
+ return currentRowIndex + 1; // JDBC rows are 1-based
+ }
+ }
+
+ @Override
+ public boolean absolute(final int row) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("absolute not supported");
+ }
+
+ @Override
+ public boolean relative(final int rows) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("relative not supported");
+ }
+
+ @Override
+ public boolean previous() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("previous not supported");
+ }
+
+ @Override
+ public int getFetchDirection() throws SQLException
+ {
+ return ResultSet.FETCH_FORWARD;
+ }
+
+ @Override
+ public void setFetchDirection(final int direction) throws SQLException
+ {
+ if (direction != ResultSet.FETCH_FORWARD) {
+ throw new DruidJdbcFeatureNotSupportedException("Only FETCH_FORWARD is supported");
+ }
+ }
+
+ @Override
+ public int getFetchSize() throws SQLException
+ {
+ return 0;
+ }
+
+ @Override
+ public void setFetchSize(final int rows) throws SQLException
+ {
+ // Ignore fetch size
+ }
+
+ @Override
+ public int getType() throws SQLException
+ {
+ return ResultSet.TYPE_FORWARD_ONLY;
+ }
+
+ @Override
+ public int getConcurrency() throws SQLException
+ {
+ return ResultSet.CONCUR_READ_ONLY;
+ }
+
+ @Override
+ public boolean rowUpdated() throws SQLException
+ {
+ return false;
+ }
+
+ @Override
+ public boolean rowInserted() throws SQLException
+ {
+ return false;
+ }
+
+ @Override
+ public boolean rowDeleted() throws SQLException
+ {
+ return false;
+ }
+
+ // Update methods - all throw exceptions since ResultSet is read-only
+ @Override
+ public void updateNull(final int columnIndex) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBoolean(final int columnIndex, final boolean x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateByte(final int columnIndex, final byte x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateShort(final int columnIndex, final short x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateInt(final int columnIndex, final int x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateLong(final int columnIndex, final long x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateFloat(final int columnIndex, final float x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateDouble(final int columnIndex, final double x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBigDecimal(final int columnIndex, final BigDecimal x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateString(final int columnIndex, final String x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBytes(final int columnIndex, final byte[] x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateDate(final int columnIndex, final Date x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateTime(final int columnIndex, final Time x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateTimestamp(final int columnIndex, final Timestamp x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final int columnIndex, final InputStream x, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final int columnIndex, final InputStream x, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final int columnIndex, final Reader x, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateObject(final int columnIndex, final Object x, final int scaleOrLength) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateObject(final int columnIndex, final Object x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ // String-based update methods
+ @Override
+ public void updateNull(final String columnLabel) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBoolean(final String columnLabel, final boolean x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateByte(final String columnLabel, final byte x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateShort(final String columnLabel, final short x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateInt(final String columnLabel, final int x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateLong(final String columnLabel, final long x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateFloat(final String columnLabel, final float x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateDouble(final String columnLabel, final double x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBigDecimal(final String columnLabel, final BigDecimal x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateString(final String columnLabel, final String x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBytes(final String columnLabel, final byte[] x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateDate(final String columnLabel, final Date x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateTime(final String columnLabel, final Time x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateTimestamp(final String columnLabel, final Timestamp x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final String columnLabel, final InputStream x, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final String columnLabel, final InputStream x, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final String columnLabel, final Reader reader, final int length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateObject(final String columnLabel, final Object x, final int scaleOrLength) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateObject(final String columnLabel, final Object x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void insertRow() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateRow() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void deleteRow() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void refreshRow() throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("refreshRow not supported");
+ }
+
+ @Override
+ public void cancelRowUpdates() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void moveToInsertRow() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void moveToCurrentRow() throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ @Nullable
+ public Statement getStatement() throws SQLException
+ {
+ throwIfClosed();
+ return statement;
+ }
+
+ @Override
+ public Object getObject(final int columnIndex, final Map<String, Class<?>> map) throws SQLException
+ {
+ return getObject(columnIndex);
+ }
+
+ @Override
+ public Ref getRef(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getRef not supported");
+ }
+
+ @Override
+ public Blob getBlob(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getBlob not supported");
+ }
+
+ @Override
+ public Clob getClob(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getClob not supported");
+ }
+
+ @Override
+ @Nullable
+ public Array getArray(final int columnIndex) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return coerceToArray(value, columnIndex);
+ }
+
+ @Override
+ public Object getObject(final String columnLabel, final Map<String, Class<?>> map) throws SQLException
+ {
+ return getObject(columnLabel);
+ }
+
+ @Override
+ public Ref getRef(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getRef not supported");
+ }
+
+ @Override
+ public Blob getBlob(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getBlob not supported");
+ }
+
+ @Override
+ public Clob getClob(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getClob not supported");
+ }
+
+ @Override
+ public Array getArray(final String columnLabel) throws SQLException
+ {
+ return getArray(findColumn(columnLabel));
+ }
+
+ @Override
+ @Nullable
+ public Date getDate(final int columnIndex, @Nullable final Calendar cal) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+
+ if (value instanceof Date date) {
+ // A DATE column: re-anchor the stored day, rather than truncating an instant.
+ if (cal == null) {
+ return date;
+ } else {
+ return new Date(date.toLocalDate().atStartOfDay(zoneOf(cal)).toInstant().toEpochMilli());
+ }
+ } else {
+ return toDate(toEpochMillis(value, columnIndex, "Date"), zoneOf(cal));
+ }
+ }
+
+ @Override
+ @Nullable
+ public Date getDate(final String columnLabel, @Nullable final Calendar cal) throws SQLException
+ {
+ return getDate(findColumn(columnLabel), cal);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>As in {@link #getDate(int, Calendar)}, {@code cal} does not affect which instant the value denotes,
+ * but does select the time zone whose reading of that instant's time of day is returned. The returned
+ * value places that time of day on 1970-01-01, as {@link Time} requires. This is the inverse of
+ * {@link DruidPreparedStatement#setTime(int, Time, Calendar)}, which reads the time of day off a
+ * {@link Time} in {@code cal}'s time zone.
+ */
+ @Override
+ @Nullable
+ public Time getTime(final int columnIndex, @Nullable final Calendar cal) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return toTime(toEpochMillis(value, columnIndex, "Time"), zoneOf(cal));
+ }
+
+ @Override
+ @Nullable
+ public Time getTime(final String columnLabel, @Nullable final Calendar cal) throws SQLException
+ {
+ return getTime(findColumn(columnLabel), cal);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * <p>The {@code cal} argument is ignored: Druid's JSON results carry an explicit UTC offset on every temporal
+ * value, so the value already denotes a single instant and there is nothing for {@code cal} to resolve.
+ */
+ @Override
+ @Nullable
+ public Timestamp getTimestamp(final int columnIndex, @Nullable final Calendar cal) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+
+ // Return an existing Timestamp as-is to preserve sub-millisecond nanos, which getTime() would drop.
+ if (value instanceof Timestamp t) {
+ return t;
+ }
+ return new Timestamp(toEpochMillis(value, columnIndex, "Timestamp"));
+ }
+
+ @Override
+ @Nullable
+ public Timestamp getTimestamp(final String columnLabel, @Nullable final Calendar cal) throws SQLException
+ {
+ return getTimestamp(findColumn(columnLabel), cal);
+ }
+
+ @Override
+ public URL getURL(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getURL not supported");
+ }
+
+ @Override
+ public URL getURL(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getURL not supported");
+ }
+
+ @Override
+ public void updateRef(final int columnIndex, final Ref x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateRef(final String columnLabel, final Ref x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final int columnIndex, final Blob x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final String columnLabel, final Blob x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final int columnIndex, final Clob x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final String columnLabel, final Clob x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateArray(final int columnIndex, final Array x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateArray(final String columnLabel, final Array x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public RowId getRowId(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getRowId not supported");
+ }
+
+ @Override
+ public RowId getRowId(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getRowId not supported");
+ }
+
+ @Override
+ public void updateRowId(final int columnIndex, final RowId x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateRowId(final String columnLabel, final RowId x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public int getHoldability()
+ {
+ return ResultSet.CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override
+ public boolean isClosed() throws SQLException
+ {
+ return closed.get();
+ }
+
+ @Override
+ public void updateNString(final int columnIndex, final String nString) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNString(final String columnLabel, final String nString) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final int columnIndex, final NClob nClob) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final String columnLabel, final NClob nClob) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public NClob getNClob(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getNClob not supported");
+ }
+
+ @Override
+ public NClob getNClob(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getNClob not supported");
+ }
+
+ @Override
+ public SQLXML getSQLXML(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getSQLXML not supported");
+ }
+
+ @Override
+ public SQLXML getSQLXML(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getSQLXML not supported");
+ }
+
+ @Override
+ public void updateSQLXML(final int columnIndex, final SQLXML xmlObject) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateSQLXML(final String columnLabel, final SQLXML xmlObject) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public String getNString(final int columnIndex) throws SQLException
+ {
+ return getString(columnIndex);
+ }
+
+ @Override
+ public String getNString(final String columnLabel) throws SQLException
+ {
+ return getString(columnLabel);
+ }
+
+ @Override
+ public Reader getNCharacterStream(final int columnIndex) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getNCharacterStream not supported");
+ }
+
+ @Override
+ public Reader getNCharacterStream(final String columnLabel) throws SQLException
+ {
+ throw new DruidJdbcFeatureNotSupportedException("getNCharacterStream not supported");
+ }
+
+ @Override
+ public void updateNCharacterStream(final int columnIndex, final Reader x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNCharacterStream(final String columnLabel, final Reader reader, final long length)
+ throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final int columnIndex, final InputStream x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final int columnIndex, final InputStream x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final int columnIndex, final Reader x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final String columnLabel, final InputStream x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final String columnLabel, final InputStream x, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final String columnLabel, final Reader reader, final long length)
+ throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final int columnIndex, final InputStream inputStream, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final String columnLabel, final InputStream inputStream, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final int columnIndex, final Reader reader, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final String columnLabel, final Reader reader, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final int columnIndex, final Reader reader, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final String columnLabel, final Reader reader, final long length) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNCharacterStream(final int columnIndex, final Reader x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNCharacterStream(final String columnLabel, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final int columnIndex, final InputStream x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final int columnIndex, final InputStream x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final int columnIndex, final Reader x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateAsciiStream(final String columnLabel, final InputStream x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBinaryStream(final String columnLabel, final InputStream x) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateCharacterStream(final String columnLabel, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final int columnIndex, final InputStream inputStream) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateBlob(final String columnLabel, final InputStream inputStream) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final int columnIndex, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateClob(final String columnLabel, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final int columnIndex, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ public void updateNClob(final String columnLabel, final Reader reader) throws SQLException
+ {
+ throw updatesNotSupported();
+ }
+
+ @Override
+ @Nullable
+ @SuppressWarnings("unchecked")
+ public <T> T getObject(final int columnIndex, final Class<T> type) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+
+ final Object coercedValue = coerceForGetObject(value, columnIndex);
+ if (type.isInstance(coercedValue)) {
+ return (T) coercedValue;
+ }
+
+ // From this point on, we know the value is non-null.
+ if (type == String.class) {
+ return (T) coerceToString(value);
+ }
+ if (type == Long.class) {
+ return (T) Long.valueOf(toNumber(value, columnIndex, "long").longValue());
+ }
+ if (type == Integer.class) {
+ return (T) Integer.valueOf((int) toNumber(value, columnIndex, "int").longValue());
+ }
+ if (type == Double.class) {
+ return (T) Double.valueOf(toNumber(value, columnIndex, "double").doubleValue());
+ }
+ if (type == Float.class) {
+ return (T) Float.valueOf((float) toNumber(value, columnIndex, "float").doubleValue());
+ }
+ if (type == Short.class) {
+ return (T) Short.valueOf((short) toNumber(value, columnIndex, "short").longValue());
+ }
+ if (type == Byte.class) {
+ return (T) Byte.valueOf((byte) toNumber(value, columnIndex, "byte").longValue());
+ }
+ if (type == Boolean.class) {
+ return (T) Boolean.valueOf(toBoolean(value, columnIndex));
+ }
+ if (type == BigDecimal.class) {
+ return (T) toBigDecimal(value, columnIndex);
+ }
+ if (type == Timestamp.class) {
+ return (T) new Timestamp(toEpochMillis(value, columnIndex, "Timestamp"));
+ }
+ if (type == Date.class) {
+ // No Calendar parameter on this method, so normalize in the default time zone, like getDate(int).
+ return (T) toDate(toEpochMillis(value, columnIndex, "Date"), zoneOf(null));
+ }
+ if (type == Time.class) {
+ return (T) toTime(toEpochMillis(value, columnIndex, "Time"), zoneOf(null));
+ }
+ if (type == byte[].class) {
+ return (T) toBytes(value, columnIndex);
+ }
+
+ throw new DruidJdbcException(
+ "Cannot convert column %s of type %s to requested type %s",
+ columnIndex,
+ value.getClass().getName(),
+ type.getName()
+ );
+ }
+
+ @Override
+ public <T> T getObject(final String columnLabel, final Class<T> type) throws SQLException
+ {
+ return getObject(findColumn(columnLabel), type);
+ }
+
+ @Override
+ public <T> T unwrap(final Class<T> iface) throws SQLException
+ {
+ if (iface.isAssignableFrom(getClass())) {
+ return iface.cast(this);
+ }
+ throw new DruidJdbcException("Cannot unwrap to class[%s]", iface.getName());
+ }
+
+ @Override
+ public boolean isWrapperFor(final Class<?> iface)
+ {
+ return iface.isAssignableFrom(getClass());
+ }
+
+ private void throwIfClosed() throws SQLException
+ {
+ if (closed.get()) {
+ throw new DruidJdbcException("ResultSet is closed");
+ }
+ }
+
+ private void validateRowPosition() throws SQLException
+ {
+ if (currentRow == null) {
+ throw new DruidJdbcException("No current row. Call next() first.");
+ }
+ }
+
+ private void validateColumnIndex(final int columnIndex) throws SQLException
+ {
+ final int columnCount = resultsIterator.getColumns().size();
+ if (columnIndex < 1 || columnIndex > columnCount) {
+ throw new DruidJdbcException("Invalid column index[%s]. Valid range[1-%s]", columnIndex, columnCount);
+ }
+ }
+
+ /**
+ * Returns the value of a column of the current row, and updates {@link #lastValueWasNull} so that
+ * {@link #wasNull()} reflects this read.
+ */
+ @Nullable
+ private Object getCurrentRowValue(final int columnIndex) throws SQLException
+ {
+ throwIfClosed();
+ validateRowPosition();
+ validateColumnIndex(columnIndex);
+
+ final Object value = currentRow[columnIndex - 1]; // JDBC columns are 1-based
+ lastValueWasNull = value == null;
+ return value;
+ }
+
+ /**
+ * Reads a column value for the numeric getters, which narrow the result with a cast: values too large for the
+ * narrower type wrap around rather than throwing.
+ *
+ * @return the column value, or null if the column value is null
+ */
+ @Nullable
+ private Number getNumericValue(final int columnIndex, final String targetLabel) throws SQLException
+ {
+ final Object value = getCurrentRowValue(columnIndex);
+ if (value == null) {
+ return null;
+ }
+ return toNumber(value, columnIndex, targetLabel);
+ }
+
+ /**
+ * Coerces VARCHAR and ARRAY column value to the Java type that the {@code getObject} getters return for the
+ * column's SQL type, which is the type {@link DruidResultSetMetaData#getColumnClassName(int)} reports. Values that
+ * {@link QueryResultsIterator} already read as the right type are returned as-is.
+ */
+ @Nullable
+ private Object coerceForGetObject(@Nullable final Object value, final int columnIndex) throws SQLException
+ {
+ if (value == null) {
+ return null;
+ }
+
+ return switch (resultsIterator.getColumns().get(columnIndex - 1).jdbcType()) {
+ case Types.VARCHAR, Types.CHAR -> coerceToString(value);
+ case Types.ARRAY -> coerceToArray(value, columnIndex);
+ default -> value;
+ };
+ }
+
+ /**
+ * Converts a non-null column value to a string. Lists, which Druid uses for arrays and for multi-value
+ * dimensions, are written as JSON rather than using {@link Object#toString()}, so that the result is
+ * unambiguous and matches how Druid stringifies these values server-side.
+ */
+ private String coerceToString(final Object value) throws SQLException
+ {
+ if (value instanceof List || value instanceof Map) {
+ try {
+ return jsonMapper.writeValueAsString(value);
+ }
+ catch (JsonProcessingException e) {
+ throw new DruidJdbcException(e, "Cannot convert value of type[%s] to String", value.getClass().getName());
+ }
+ }
+
+ return value.toString();
+ }
+
+ /**
+ * Converts a non-null column value to an {@link Array}, for {@link #getArray(int)} and for {@code getObject}.
+ */
+ private Array coerceToArray(final Object value, final int columnIndex) throws SQLException
+ {
+ if (value instanceof List<?> list) {
+ final JDBCType elementType = resultsIterator.getColumns().get(columnIndex - 1).arrayElementType();
+ return new DruidArray(elementType.getVendorTypeNumber(), elementType.getName(), list.toArray());
+ }
+ throw cannotConvert(columnIndex, value, "Array");
+ }
+
+ /**
+ * Converts a non-null column value for the numeric getters. Strings are not parsed; only {@link Number}
+ * is accepted.
+ *
+ * @param targetLabel target type name used in error messages, e.g. {@code "int"}
+ */
+ private static Number toNumber(final Object value, final int columnIndex, final String targetLabel)
+ throws SQLException
+ {
+ if (value instanceof Number n) {
+ return n;
+ }
+ throw cannotConvert(columnIndex, value, targetLabel);
+ }
+
+ /**
+ * Converts a non-null column value for {@link #getBoolean(int)}. Accepts {@link Boolean}, {@link Number}
+ * (nonzero is true), and the string forms that {@link BooleanUtils} recognizes plus {@code "1"}.
+ */
+ private static boolean toBoolean(final Object value, final int columnIndex) throws SQLException
+ {
+ if (value instanceof Boolean b) {
+ return b;
+ }
+ if (value instanceof Number n) {
+ return n.intValue() != 0;
+ }
+ if (value instanceof String str) {
+ return BooleanUtils.isBooleanTrue(str) || "1".equals(str);
+ }
+ throw cannotConvert(columnIndex, value, "boolean");
+ }
+
+ /**
+ * Converts a non-null column value for {@link #getBigDecimal(int)}.
+ */
+ private static BigDecimal toBigDecimal(final Object value, final int columnIndex) throws SQLException
+ {
+ if (value instanceof BigDecimal bd) {
+ return bd;
+ }
+ if (value instanceof Number) {
+ return new BigDecimal(value.toString());
+ }
+ throw cannotConvert(columnIndex, value, "BigDecimal");
+ }
+
+ /**
+ * Converts a non-null column value for {@link #getBytes(int)}.
+ */
+ private static byte[] toBytes(final Object value, final int columnIndex) throws SQLException
+ {
+ if (value instanceof byte[] bytes) {
+ return bytes;
+ }
+ if (value instanceof String str) {
+ // Druid's SQL JSON response encodes VARBINARY and COMPLEX column values as base64 strings
+ // (Jackson's default binary serialization).
+ try {
+ return Base64.getDecoder().decode(str);
+ }
+ catch (IllegalArgumentException e) {
+ throw new DruidJdbcException(e, "Cannot convert column %s value to bytes: not valid base64", columnIndex);
+ }
+ }
+ throw cannotConvert(columnIndex, value, "bytes");
+ }
+
+ /**
+ * Converts an already-materialized, non-null column value to epoch milliseconds, for the
+ * {@code getDate}/{@code getTime}/{@code getTimestamp} getters. Numbers are treated as epoch millis.
+ *
+ * @param targetLabel JDBC type name used in error messages, e.g. {@code "Date"}
+ */
+ private static long toEpochMillis(final Object value, final int columnIndex, final String targetLabel)
+ throws SQLException
+ {
+ if (value instanceof java.util.Date d) {
+ return d.getTime();
+ }
+ if (value instanceof Number n) {
+ return n.longValue();
+ }
+ if (value instanceof String str) {
+ try {
+ return DruidTimestampParser.parse(str).getTime();
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Cannot convert '%s' to %s", value, targetLabel);
+ }
+ }
+ throw cannotConvert(columnIndex, value, targetLabel);
+ }
+
+ /**
+ * The time zone in which the {@code getDate} and {@code getTime} getters normalize their result. This is
+ * {@code cal}'s time zone, or the JVM default time zone when {@code cal} is null, as the JDBC spec requires
+ * of the getters that take no {@link Calendar}.
+ */
+ private static ZoneId zoneOf(@Nullable final Calendar cal)
+ {
+ return cal != null ? cal.getTimeZone().toZoneId() : TimeZone.getDefault().toZoneId();
+ }
+
+ /**
+ * Converts epoch milliseconds to a {@link Date}, truncated to midnight of the calendar day that
+ * {@code epochMillis} falls on in {@code zone}. {@link Date} requires this: its contract is that the
+ * time-of-day fields of the wrapped millisecond value read as zero in the time zone the value is used with.
+ */
+ private static Date toDate(final long epochMillis, final ZoneId zone)
+ {
+ final LocalDate localDate = Instant.ofEpochMilli(epochMillis).atZone(zone).toLocalDate();
+ return new Date(localDate.atStartOfDay(zone).toInstant().toEpochMilli());
+ }
+
+ /**
+ * Converts epoch milliseconds to a {@link Time} holding the time of day that {@code epochMillis} falls on in
+ * {@code zone}, placed on 1970-01-01. {@link Time} requires this: its contract is that the date fields of the
+ * wrapped millisecond value read as the epoch day in the time zone the value is used with.
+ */
+ private static Time toTime(final long epochMillis, final ZoneId zone)
+ {
+ final LocalTime localTime = Instant.ofEpochMilli(epochMillis).atZone(zone).toLocalTime();
+ return new Time(localTime.atDate(LocalDate.EPOCH).atZone(zone).toInstant().toEpochMilli());
+ }
+
+ private static DruidJdbcException cannotConvert(
+ final int columnIndex,
+ final Object value,
+ final String targetLabel
+ )
+ {
+ return new DruidJdbcException(
+ "Cannot convert column %s of type %s to %s", columnIndex, value.getClass().getSimpleName(), targetLabel
+ );
+ }
+
+ /**
+ * Thrown by the {@code updateXxx} and other cursor-mutating methods, since this resultset is read-only.
+ */
+ private static DruidJdbcFeatureNotSupportedException updatesNotSupported()
+ {
+ return new DruidJdbcFeatureNotSupportedException("Updates not supported");
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSetMetaData.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSetMetaData.java
new file mode 100644
index 00000000000..5e1639e80af
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidResultSetMetaData.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import org.apache.druid.jdbc.http.ColumnMetadata;
+
+import java.math.BigDecimal;
+import java.sql.Array;
+import java.sql.Date;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.util.List;
+
+/**
+ * Our implementation of JDBC {@link ResultSetMetaData}.
+ */
+public class DruidResultSetMetaData implements ResultSetMetaData
+{
+ private final List<ColumnMetadata> columns;
+
+ public DruidResultSetMetaData(final List<ColumnMetadata> columns)
+ {
+ this.columns = columns;
+ }
+
+ @Override
+ public int getColumnCount()
+ {
+ return columns.size();
+ }
+
+ @Override
+ public boolean isAutoIncrement(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return false;
+ }
+
+ @Override
+ public boolean isCaseSensitive(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return getSqlType(column) == Types.VARCHAR || getSqlType(column) == Types.CHAR;
+ }
+
+ @Override
+ public boolean isSearchable(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return true;
+ }
+
+ @Override
+ public boolean isCurrency(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return false;
+ }
+
+ @Override
+ public int isNullable(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // We can't tell from ColumnMetadata if a result column is nullable, so report all as nullable to be safe.
+ return ResultSetMetaData.columnNullable;
+ }
+
+ @Override
+ public boolean isSigned(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // All numeric types are signed.
+ final int sqlType = getSqlType(column);
+ return sqlType == Types.TINYINT || sqlType == Types.SMALLINT ||
+ sqlType == Types.INTEGER || sqlType == Types.BIGINT ||
+ sqlType == Types.REAL || sqlType == Types.FLOAT ||
+ sqlType == Types.DOUBLE || sqlType == Types.DECIMAL ||
+ sqlType == Types.NUMERIC;
+ }
+
+ @Override
+ public int getColumnDisplaySize(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Some reasonable guesses at display size.
+ return switch (getSqlType(column)) {
+ case Types.TINYINT -> 4;
+ case Types.SMALLINT -> 6;
+ case Types.INTEGER -> 11;
+ case Types.BIGINT -> 20;
+ case Types.REAL, Types.FLOAT -> 15;
+ case Types.DOUBLE -> 25;
+ case Types.TIMESTAMP -> 29;
+ case Types.DATE -> 10;
+ case Types.TIME -> 8;
+ default -> 512;
+ };
+ }
+
+ @Override
+ public String getColumnLabel(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return columns.get(column - 1).name();
+ }
+
+ @Override
+ public String getColumnName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return columns.get(column - 1).name();
+ }
+
+ @Override
+ public String getSchemaName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Druid SQL API does not return schema name.
+ return "";
+ }
+
+ @Override
+ public int getPrecision(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Druid SQL API does not return precision information.
+ return 0;
+ }
+
+ @Override
+ public int getScale(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Druid SQL API does not return scale information.
+ return 0;
+ }
+
+ @Override
+ public String getTableName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Druid SQL API does not return table name.
+ return "";
+ }
+
+ @Override
+ public String getCatalogName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ // Druid SQL API does not return catalog name.
+ return "";
+ }
+
+ @Override
+ public int getColumnType(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return columns.get(column - 1).jdbcType();
+ }
+
+ @Override
+ public String getColumnTypeName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return columns.get(column - 1).type().getName();
+ }
+
+ @Override
+ public boolean isReadOnly(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return true;
+ }
+
+ @Override
+ public boolean isWritable(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return false;
+ }
+
+ @Override
+ public boolean isDefinitelyWritable(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return false;
+ }
+
+ @Override
+ public String getColumnClassName(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+
+ return switch (getSqlType(column)) {
+ case Types.BIT, Types.TINYINT, Types.SMALLINT, Types.INTEGER -> Integer.class.getName();
+ case Types.DECIMAL, Types.NUMERIC -> BigDecimal.class.getName();
+ case Types.BIGINT -> Long.class.getName();
+ case Types.REAL -> Float.class.getName();
+ case Types.FLOAT, Types.DOUBLE -> Double.class.getName();
+ case Types.BOOLEAN -> Boolean.class.getName();
+ case Types.TIMESTAMP -> Timestamp.class.getName();
+ case Types.DATE -> Date.class.getName();
+ case Types.TIME -> Time.class.getName();
+ case Types.VARCHAR, Types.CHAR -> String.class.getName();
+ case Types.ARRAY -> Array.class.getName();
+ default -> Object.class.getName();
+ };
+ }
+
+ @Override
+ public <T> T unwrap(final Class<T> iface) throws SQLException
+ {
+ if (iface.isAssignableFrom(getClass())) {
+ return iface.cast(this);
+ }
+ throw new DruidJdbcException("Cannot unwrap to class[%s]", iface.getName());
+ }
+
+ @Override
+ public boolean isWrapperFor(final Class<?> iface)
+ {
+ return iface.isAssignableFrom(getClass());
+ }
+
+ private void validateColumnIndex(final int columnIndex) throws SQLException
+ {
+ if (columnIndex < 1 || columnIndex > columns.size()) {
+ throw new DruidJdbcException("Invalid column index[%s]. Valid range[1-%s]", columnIndex, columns.size());
+ }
+ }
+
+ private int getSqlType(final int column) throws SQLException
+ {
+ validateColumnIndex(column);
+ return columns.get(column - 1).jdbcType();
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidSQLState.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidSQLState.java
new file mode 100644
index 00000000000..4549ae8aaca
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidSQLState.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.sql.SQLException;
+
+/**
+ * Possible SQLState values for {@link DruidJdbcException}.
+ *
+ * @see SQLException#getSQLState()
+ */
+public enum DruidSQLState
+{
+ ConnectionUnableToConnect("08001"),
+ ConnectionDoesNotExist("08003"),
+ InvalidParameterType("07006"),
+ InvalidAuthorizationSpecification("28000"),
+ FeatureUnsupported("0A000");
+
+ private final String sqlState;
+
+ DruidSQLState(final String sqlState)
+ {
+ this.sqlState = sqlState;
+ }
+
+ public String getSqlState()
+ {
+ return sqlState;
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidStatement.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidStatement.java
new file mode 100644
index 00000000000..a338f44a910
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidStatement.java
@@ -0,0 +1,613 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import org.apache.druid.jdbc.http.DruidHttpClient;
+import org.apache.druid.jdbc.http.QueryResultsIterator;
+import org.apache.druid.jdbc.http.SqlParameter;
+import org.apache.druid.jdbc.http.SqlRequest;
+import org.apache.druid.jdbc.sql.SetStatement;
+import org.apache.druid.jdbc.sql.SqlScanner;
+
+import javax.annotation.Nullable;
+import java.sql.BatchUpdateException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Our implementation of JDBC {@link Statement}. Executes queries using Druid's SQL endpoint.
+ *
+ * <p>SET statements are intercepted in the driver so they may apply to future statements in the same connection.
+ * This is necessary because JDBC connections are a purely driver-side concept: the server is connectionless.
+ *
+ * <p><b>Thread safety:</b> {@link #close()}, {@link #isClosed()}, and {@link #cancel()} are safe to
+ * call from any thread. All other methods are not.
+ */
+public class DruidStatement implements Statement
+{
+ private final DruidConnection connection;
+ private final DruidHttpClient httpClient;
+
+ /**
+ * The sqlQueryId of the currently-outstanding query. Used by {@link #cancel()}.
+ */
+ private final AtomicReference<String> currentSqlQueryId = new AtomicReference<>();
+
+ /**
+ * Whether this statement is closed. Set by {@link #close()}.
+ */
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+
+ /**
+ * Row limit set by {@link #setMaxRows(int)}, or null if unset. Applied to query context by
+ * {@link #applyMaxRows(Map)}.
+ */
+ @Nullable
+ private Integer maxRows;
+
+ /**
+ * Timeout set by {@link #setQueryTimeout(int)}, or null if unset. Applied to query context by
+ * {@link #applyQueryTimeout(Map)}.
+ */
+ @Nullable
+ private Integer queryTimeoutSeconds;
+
+ /**
+ * Flag set by {@link #closeOnCompletion()}. If set, this statement is closed when the associated result set
+ * is closed.
+ */
+ private volatile boolean closeOnCompletion;
+
+ /**
+ * Reference to the currently associated result set.
+ */
+ private volatile ResultSet currentResultSet;
+
+ public DruidStatement(final DruidConnection connection)
+ {
+ this.connection = connection;
+ this.httpClient = connection.getHttpClient();
+ }
+
+ @Override
+ public ResultSet executeQuery(final String sql) throws SQLException
+ {
+ if (execute(sql)) {
+ return currentResultSet;
+ } else {
+ throw new DruidJdbcException("Query did not return a result set");
+ }
+ }
+
+ @Override
+ public int executeUpdate(final String sql) throws SQLException
+ {
+ throwIfClosed();
+ throw new DruidJdbcFeatureNotSupportedException("executeUpdate not supported");
+ }
+
+ @Override
+ public void close() throws SQLException
+ {
+ if (closed.compareAndSet(false, true)) {
+ try {
+ closeCurrentResultSet();
+ }
+ finally {
+ connection.onStatementClosed(this);
+ }
+ }
+ }
+
+ @Override
+ public int getMaxFieldSize() throws SQLException
+ {
+ throwIfClosed();
+ return 0; // No limit
+ }
+
+ @Override
+ public void setMaxFieldSize(final int max) throws SQLException
+ {
+ throwIfClosed();
+
+ // Validated, but then ignored.
+ if (max < 0) {
+ throw new DruidJdbcException("maxFieldSize cannot be negative");
+ }
+ }
+
+ @Override
+ public int getMaxRows() throws SQLException
+ {
+ throwIfClosed();
+ return maxRows != null ? maxRows : 0;
+ }
+
+ @Override
+ public void setMaxRows(final int max) throws SQLException
+ {
+ throwIfClosed();
+ if (max < 0) {
+ throw new DruidJdbcException("maxRows cannot be negative");
+ }
+ this.maxRows = max;
+ }
+
+ @Override
+ public void setEscapeProcessing(final boolean enable)
+ {
+ // Driver does not implement escape processing, so there's nothing to disable. Druid SQL implements some
+ // escape processing server side, like {fn ...} and {ts ...}, which are not controlled here.
+ }
+
+ @Override
+ public int getQueryTimeout() throws SQLException
+ {
+ throwIfClosed();
+ return queryTimeoutSeconds != null ? queryTimeoutSeconds : 0;
+ }
+
+ @Override
+ public void setQueryTimeout(final int seconds) throws SQLException
+ {
+ throwIfClosed();
+ if (seconds < 0) {
+ throw new DruidJdbcException("queryTimeout cannot be negative");
+ }
+ this.queryTimeoutSeconds = seconds;
+ }
+
+ @Override
+ public void cancel() throws SQLException
+ {
+ throwIfClosed();
+
+ final String sqlQueryId = currentSqlQueryId.getAndSet(null);
+ if (sqlQueryId != null) {
+ try {
+ httpClient.cancelQuery(sqlQueryId);
+ }
+ catch (SQLException e) {
+ throw new DruidJdbcException(e, "Failed to cancel query[%s]", sqlQueryId);
+ }
+ }
+ }
+
+ @Override
+ @Nullable
+ public SQLWarning getWarnings() throws SQLException
+ {
+ throwIfClosed();
+ return null;
+ }
+
+ @Override
+ public void clearWarnings() throws SQLException
+ {
+ throwIfClosed();
+ }
+
+ @Override
+ public void setCursorName(final String name) throws SQLException
+ {
+ throwIfClosed();
+ throw new DruidJdbcFeatureNotSupportedException("Named cursors not supported");
+ }
+
+ @Override
+ public boolean execute(final String sql) throws SQLException
+ {
+ throwIfClosed();
+
+ final SqlScanner sqlScanner = SqlScanner.scan(sql);
+ closeCurrentResultSet();
+
+ // Handle SET statements in the driver.
+ for (final SetStatement setStatement : sqlScanner.getSetStatements()) {
+ connection.addSetStatementQueryContext(setStatement.key(), setStatement.value());
+ }
+
+ final String sqlStatement = sqlScanner.getSqlStatement();
+ if (sqlStatement == null) {
+ return false;
+ }
+
+ executeSql(sqlStatement, List.of());
+ return true;
+ }
+
+ /**
+ * Runs a query, installs the result as the current result set, and returns it. Shared by {@link #execute(String)}
+ * and {@link DruidPreparedStatement#executeQuery()}.
+ */
+ protected ResultSet executeSql(final String sql, final List<SqlParameter> parameters) throws SQLException
+ {
+ try {
+ closeCurrentResultSet();
+
+ final Map<String, Object> queryContext = newQueryContext();
+ currentSqlQueryId.set((String) queryContext.get("sqlQueryId"));
+
+ final QueryResultsIterator results = httpClient.runQuery(SqlRequest.of(sql, queryContext, parameters));
+ final ResultSet resultSet = new DruidResultSet(results, this, connection.getJsonMapper());
+
+ currentResultSet = resultSet;
+ if (closed.get()) {
+ resultSet.close();
+ throw new DruidJdbcException("Statement is closed");
+ }
+
+ return resultSet;
+ }
+ catch (Throwable e) {
+ currentSqlQueryId.set(null);
+
+ if (e instanceof SQLException) {
+ throw e;
+ } else {
+ throw new DruidJdbcException(e, "Failed to execute query: %s", e);
+ }
+ }
+ }
+
+ @Override
+ public ResultSet getResultSet() throws SQLException
+ {
+ throwIfClosed();
+ return currentResultSet;
+ }
+
+ @Override
+ public int getUpdateCount() throws SQLException
+ {
+ throwIfClosed();
+ return -1; // No update count for read-only operations
+ }
+
+ @Override
+ public boolean getMoreResults() throws SQLException
+ {
+ throwIfClosed();
+ closeCurrentResultSet();
+ return false; // Only one result set per query
+ }
+
+ @Override
+ public int getFetchDirection() throws SQLException
+ {
+ throwIfClosed();
+ return ResultSet.FETCH_FORWARD;
+ }
+
+ @Override
+ public void setFetchDirection(final int direction) throws SQLException
+ {
+ throwIfClosed();
+ if (direction != ResultSet.FETCH_FORWARD) {
+ throw new DruidJdbcFeatureNotSupportedException("Only FETCH_FORWARD is supported");
+ }
+ }
+
+ @Override
+ public int getFetchSize() throws SQLException
+ {
+ throwIfClosed();
+
+ // We don't use fetch size, so report zero (see setFetchSize).
+ return 0;
+ }
+
+ @Override
+ public void setFetchSize(final int rows) throws SQLException
+ {
+ throwIfClosed();
+
+ // No-op, other than validating that "rows" is nonnegative. We fetch rows as a stream, not in batches.
+ if (rows < 0) {
+ throw new DruidJdbcException("fetchSize cannot be negative");
+ }
+ }
+
+ @Override
+ public int getResultSetConcurrency() throws SQLException
+ {
+ throwIfClosed();
+ return ResultSet.CONCUR_READ_ONLY;
+ }
+
+ @Override
+ public int getResultSetType() throws SQLException
+ {
+ throwIfClosed();
+ return ResultSet.TYPE_FORWARD_ONLY;
+ }
+
+ @Override
+ public void addBatch(final String sql) throws SQLException
+ {
+ // Nothing to do, executeBatch() always throws.
+ }
+
+ @Override
+ public void clearBatch()
+ {
+ // Nothing to do, executeBatch() always throws.
+ }
+
+ @Override
+ public int[] executeBatch() throws SQLException
+ {
+ throwIfClosed();
+
+ // Per interface docs, batch statements that produce ResultSets must raise BatchUpdateException.
+ // This driver currently only accepts SELECT statements, so we reject batches upfront.
+ clearBatch();
+ throw new BatchUpdateException(
+ "Druid does not support batched updates",
+ DruidSQLState.FeatureUnsupported.getSqlState(),
+ 0,
+ new int[0]
+ );
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException
+ {
+ throwIfClosed();
+ return connection;
+ }
+
+ @Override
+ public boolean getMoreResults(final int current) throws SQLException
+ {
+ throwIfClosed();
+
+ if (current == Statement.CLOSE_CURRENT_RESULT || current == Statement.CLOSE_ALL_RESULTS) {
+ closeCurrentResultSet();
+ }
+
+ // Only one result set per query
+ return false;
+ }
+
+ @Override
+ public ResultSet getGeneratedKeys() throws SQLException
+ {
+ throwIfClosed();
+ throw new DruidJdbcFeatureNotSupportedException("Generated keys not supported");
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException
+ {
+ return executeUpdate(sql);
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException
+ {
+ return executeUpdate(sql);
+ }
+
+ @Override
+ public int executeUpdate(final String sql, final String[] columnNames) throws SQLException
+ {
+ return executeUpdate(sql);
+ }
+
+ @Override
+ public boolean execute(final String sql, final int autoGeneratedKeys) throws SQLException
+ {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(final String sql, final int[] columnIndexes) throws SQLException
+ {
+ return execute(sql);
+ }
+
+ @Override
+ public boolean execute(final String sql, final String[] columnNames) throws SQLException
+ {
+ return execute(sql);
+ }
+
+ @Override
+ public int getResultSetHoldability() throws SQLException
+ {
+ throwIfClosed();
+ return ResultSet.CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override
+ public boolean isClosed() throws SQLException
+ {
+ return closed.get();
+ }
+
+ @Override
+ public boolean isPoolable() throws SQLException
+ {
+ throwIfClosed();
+ return false;
+ }
+
+ @Override
+ public void setPoolable(final boolean poolable) throws SQLException
+ {
+ throwIfClosed();
+ }
+
+ @Override
+ public void closeOnCompletion() throws SQLException
+ {
+ throwIfClosed();
+ this.closeOnCompletion = true;
+ }
+
+ @Override
+ public boolean isCloseOnCompletion() throws SQLException
+ {
+ throwIfClosed();
+ return closeOnCompletion;
+ }
+
+ /**
+ * Callback invoked by a {@link DruidResultSet} when it is closed. Clears the current result set state and,
+ * if {@link #closeOnCompletion} is set, closes this statement as required by the JDBC contract.
+ */
+ void onResultSetClosed(final ResultSet resultSet) throws SQLException
+ {
+ //noinspection ObjectEquality
+ if (resultSet == currentResultSet) {
+ currentResultSet = null;
+ currentSqlQueryId.set(null);
+ }
+ if (closeOnCompletion && !closed.get()) {
+ close();
+ }
+ }
+
+ @Override
+ public <T> T unwrap(final Class<T> iface) throws SQLException
+ {
+ if (iface.isAssignableFrom(getClass())) {
+ return iface.cast(this);
+ }
+ throw new DruidJdbcException("Cannot unwrap to class[%s]", iface.getName());
+ }
+
+ @Override
+ public boolean isWrapperFor(final Class<?> iface)
+ {
+ return iface.isAssignableFrom(getClass());
+ }
+
+ protected void throwIfClosed() throws SQLException
+ {
+ if (closed.get()) {
+ throw new DruidJdbcException("Statement is closed");
+ }
+ if (connection.isClosed()) {
+ throw new DruidJdbcException("Connection is closed");
+ }
+ }
+
+ private void closeCurrentResultSet() throws SQLException
+ {
+ final boolean wasCloseOnCompletion = closeOnCompletion;
+
+ if (currentResultSet != null && !currentResultSet.isClosed()) {
+ // Clear closeOnCompletion if set, since this method is used for driver-initiated result set closes.
+ // Close-on-completion only applies to user-initiated result set closes.
+ closeOnCompletion = false;
+ try {
+ currentResultSet.close();
+ }
+ finally {
+ // Restore closeOnCompletion, if it was set.
+ closeOnCompletion = wasCloseOnCompletion;
+ currentResultSet = null;
+ }
+ }
+ // Clear the query ID when result set is closed
+ currentSqlQueryId.set(null);
+ }
+
+ /**
+ * Builds the query context for a query issued by this statement: the connection's context (from the JDBC URL,
+ * connection properties, and {@code SET} statements), plus the per-statement settings from
+ * {@link #setQueryTimeout(int)} and {@link #setMaxRows(int)}, plus a resolved {@code sqlQueryId}.
+ *
+ * <p>This does not make the query cancelable; only {@link #executeSql} does that, by saving the resolved
+ * {@code sqlQueryId} as {@link #currentSqlQueryId}.
+ */
+ protected Map<String, Object> newQueryContext()
+ {
+ final Map<String, Object> queryContext = new HashMap<>(connection.getQueryContext());
+ applyQueryTimeout(queryContext);
+ applyMaxRows(queryContext);
+ computeSqlQueryId(queryContext);
+ return queryContext;
+ }
+
+ /**
+ * Applies {@link #queryTimeoutSeconds} to the query context as the "timeout" key (in milliseconds). Per JDBC,
+ * an explicit zero means "no limit", and therefore removes any value supplied by the URL or a SET statement.
+ */
+ private void applyQueryTimeout(final Map<String, Object> queryContext)
+ {
+ if (queryTimeoutSeconds != null) {
+ if (queryTimeoutSeconds > 0) {
+ queryContext.put("timeout", (long) queryTimeoutSeconds * 1000);
+ } else {
+ queryContext.remove("timeout");
+ }
+ }
+ }
+
+ /**
+ * Applies {@link #maxRows} to the query context using "sqlOuterLimit". Zero is handled as in
+ * {@link #applyQueryTimeout(Map)}.
+ */
+ private void applyMaxRows(final Map<String, Object> queryContext)
+ {
+ if (maxRows != null) {
+ if (maxRows > 0) {
+ queryContext.put("sqlOuterLimit", maxRows);
+ } else {
+ queryContext.remove("sqlOuterLimit");
+ }
+ }
+ }
+
+ protected DruidHttpClient getHttpClient()
+ {
+ return httpClient;
+ }
+
+ /**
+ * Sets sqlQueryId to a random UUID if it is not already set in the context.
+ */
+ private static void computeSqlQueryId(final Map<String, Object> queryContext)
+ {
+ queryContext.compute(
+ "sqlQueryId",
+ (ignored, existingId) -> {
+ if (existingId instanceof String) {
+ return existingId;
+ } else {
+ return UUID.randomUUID().toString();
+ }
+ }
+ );
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidTimestampParser.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidTimestampParser.java
new file mode 100644
index 00000000000..4dfaa4d001a
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/DruidTimestampParser.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.format.DateTimeParseException;
+import java.time.temporal.TemporalAccessor;
+import java.util.Locale;
+
+/**
+ * Utility class for parsing timestamp, date, and time strings into {@link Timestamp}.
+ */
+public class DruidTimestampParser
+{
+ /**
+ * Flexible formatter that accepts ISO8601 and SQL formatted dates, with and without timezones.
+ */
+ private static final DateTimeFormatter TIMESTAMP_FORMATTER =
+ new DateTimeFormatterBuilder()
+ .parseCaseInsensitive()
+ .optionalStart()
+ .append(DateTimeFormatter.ISO_LOCAL_DATE)
+ .optionalStart().appendLiteral('T').optionalEnd()
+ .optionalStart().appendLiteral(' ').optionalEnd()
+ .optionalEnd()
+ .optionalStart()
+ .append(DateTimeFormatter.ISO_LOCAL_TIME)
+ .optionalEnd()
+ .optionalStart()
+ .appendOffsetId()
+ .optionalEnd()
+ .toFormatter(Locale.ENGLISH);
+
+ private DruidTimestampParser()
+ {
+ // No instantiation.
+ }
+
+ /**
+ * Parse a timestamp, date, or time string into a {@link Timestamp}.
+ *
+ * <p>Supported formats:</p>
+ * <ul>
+ * <li>ISO 8601 instant with offset or Z suffix (e.g. "2025-01-15T12:30:45.000Z", "2025-01-15T12:30:45+05:30")</li>
+ * <li>ISO local date-time with T separator (e.g. "2025-01-15T12:30:45") -- interpreted as UTC</li>
+ * <li>Date-time with space separator (e.g. "2025-06-01 10:30:45.123") -- interpreted as UTC</li>
+ * <li>Bare date (e.g. "2025-01-15") -- interpreted as midnight UTC</li>
+ * <li>Bare time (e.g. "14:30:15") -- interpreted as that time on epoch day, UTC</li>
+ * <li>Epoch milliseconds as a numeric string (e.g. "1715000000000")</li>
+ * </ul>
+ *
+ * @param str the string to parse
+ * @return a {@link Timestamp} representing the parsed value
+ * @throws IllegalArgumentException if str is null or blank
+ * @throws ParseException if the string cannot be parsed as any supported format
+ */
+ public static Timestamp parse(final String str) throws ParseException
+ {
+ if (str == null || str.isBlank()) {
+ throw new IllegalArgumentException("Timestamp string cannot be null or blank");
+ }
+
+ try {
+ final TemporalAccessor parsed = TIMESTAMP_FORMATTER.parseBest(
+ str,
+ OffsetDateTime::from,
+ LocalDateTime::from,
+ LocalDate::from,
+ LocalTime::from
+ );
+
+ final Instant instant;
+ if (parsed instanceof OffsetDateTime offsetDateTime) {
+ instant = offsetDateTime.toInstant();
+ } else if (parsed instanceof LocalDateTime localDateTime) {
+ instant = localDateTime.toInstant(ZoneOffset.UTC);
+ } else if (parsed instanceof LocalDate localDate) {
+ instant = localDate.atStartOfDay(ZoneOffset.UTC).toInstant();
+ } else if (parsed instanceof LocalTime localTime) {
+ instant = localTime.atDate(LocalDate.EPOCH).toInstant(ZoneOffset.UTC);
+ } else {
+ // Not expecting to reach here.
+ throw new IllegalStateException("Unexpected parsed class: " + parsed.getClass());
+ }
+
+ return Timestamp.from(instant);
+ }
+ catch (DateTimeParseException ignored) {
+ // Not a string timestamp; fall through to checking for milliseconds.
+ }
+
+ try {
+ // Epoch milliseconds as a numeric string (e.g. "1715000000000").
+ return new Timestamp(Long.parseLong(str));
+ }
+ catch (NumberFormatException e) {
+ throw new ParseException(StringUtils.format("Cannot parse timestamp string: %s", str), 0);
+ }
+ }
+
+ /**
+ * Parse a date or timestamp string and return the calendar date it names, taking the date fields as written,
+ * ignoring the timezone information in the string.
+ *
+ * @param str the string to parse
+ * @return the calendar date named by {@code str}
+ * @throws IllegalArgumentException if str is null or blank
+ * @throws ParseException if the string cannot be parsed as any supported format
+ */
+ public static LocalDate parseLocalDate(final String str) throws ParseException
+ {
+ if (str == null || str.isBlank()) {
+ throw new IllegalArgumentException("Date string cannot be null or blank");
+ }
+
+ try {
+ final TemporalAccessor parsed = TIMESTAMP_FORMATTER.parseBest(
+ str,
+ OffsetDateTime::from,
+ LocalDateTime::from,
+ LocalDate::from
+ );
+
+ if (parsed instanceof OffsetDateTime offsetDateTime) {
+ return offsetDateTime.toLocalDate();
+ } else if (parsed instanceof LocalDateTime localDateTime) {
+ return localDateTime.toLocalDate();
+ } else if (parsed instanceof LocalDate localDate) {
+ return localDate;
+ }
+ }
+ catch (DateTimeParseException ignored) {
+ // Not a string date; fall through to checking for milliseconds.
+ }
+
+ try {
+ // Epoch milliseconds. There is no offset to go by, so read the date in UTC.
+ return Instant.ofEpochMilli(Long.parseLong(str)).atZone(ZoneOffset.UTC).toLocalDate();
+ }
+ catch (NumberFormatException e) {
+ throw new ParseException(StringUtils.format("Cannot parse date string: %s", str), 0);
+ }
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/StringUtils.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/StringUtils.java
new file mode 100644
index 00000000000..a44d8711057
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/StringUtils.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.util.Locale;
+
+/**
+ * Small string helpers. This driver deliberately avoids depending on other Druid modules, so it
+ * carries its own minimal utilities rather than reusing {@code org.apache.druid.java.util.common.StringUtils}.
+ */
+public class StringUtils
+{
+ private StringUtils()
+ {
+ // No instantiation.
+ }
+
+ /**
+ * Formats a string using {@link Locale#ENGLISH}, so results do not depend on the JVM default
+ * locale. Prefer this (and format strings generally) over string concatenation for messages.
+ */
+ public static String format(final String format, final Object... args)
+ {
+ return String.format(Locale.ENGLISH, format, args);
+ }
+
+ /**
+ * Equivalent to {@link String#replace(CharSequence, CharSequence)}.
+ */
+ @SuppressForbidden(reason = "String#replace")
+ public static String replace(final String source, final String target, final String replacement)
+ {
+ return source.replace(target, replacement);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/SuppressForbidden.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/SuppressForbidden.java
new file mode 100644
index 00000000000..f6ec2d3a9ed
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/SuppressForbidden.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Marks a method that deliberately calls an API listed in {@code codestyle/druid-forbidden-apis.txt}.
+ */
+@Retention(RetentionPolicy.CLASS)
+@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.TYPE})
+@interface SuppressForbidden
+{
+ String reason();
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/ColumnMetadata.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/ColumnMetadata.java
new file mode 100644
index 00000000000..846e9a25c8e
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/ColumnMetadata.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import javax.annotation.Nullable;
+import java.sql.JDBCType;
+import java.sql.Types;
+import java.util.Objects;
+
+/**
+ * Represents metadata about a result column, loaded from the {@code sqlTypesHeader} and the native
+ * {@code typesHeader}.
+ *
+ * @param name name of the column
+ * @param type JDBC column type
+ * @param nativeType native Druid type string, e.g. {@code STRING} or {@code ARRAY<LONG>}. Null when the server sends
+ * no native type for the column, which it does for SQL types that have no Druid equivalent.
+ */
+public record ColumnMetadata(String name, JDBCType type, @Nullable String nativeType)
+{
+ public ColumnMetadata
+ {
+ Objects.requireNonNull(name, "name");
+ Objects.requireNonNull(type, "type");
+ }
+
+ /**
+ * Convenience constructor for a column without an explicit native type (e.g. synthesized metadata result
+ * sets); the Druid native type is derived from the JDBC type.
+ */
+ public ColumnMetadata(final String name, final JDBCType type)
+ {
+ this(name, type, nativeTypeForJdbcType(type));
+ }
+
+ /**
+ * The Druid native type of the elements of {@code nativeType}, when a value of that type is read as an array.
+ */
+ @Nullable
+ public static String arrayElementNativeType(@Nullable final String nativeType)
+ {
+ if (nativeType == null) {
+ return null;
+ } else if (nativeType.startsWith("ARRAY<") && nativeType.endsWith(">")) {
+ return nativeType.substring("ARRAY<".length(), nativeType.length() - 1).trim();
+ } else {
+ return nativeType;
+ }
+ }
+
+ /**
+ * The JDBC {@link Types} code for a Druid native type, such as {@link Types#BIGINT} for {@code LONG}.
+ */
+ public static int jdbcTypeForNativeType(@Nullable final String nativeType)
+ {
+ return typeForNativeType(nativeType).getVendorTypeNumber();
+ }
+
+ /**
+ * The {@link JDBCType} for a Druid native type, such as {@link JDBCType#BIGINT} for {@code LONG}. An unknown or
+ * absent native type maps to {@link JDBCType#OTHER}.
+ */
+ public static JDBCType typeForNativeType(@Nullable final String nativeType)
+ {
+ if (nativeType == null) {
+ return JDBCType.OTHER;
+ }
+
+ return switch (nativeType) {
+ case "LONG" -> JDBCType.BIGINT;
+ case "STRING" -> JDBCType.VARCHAR;
+ case "DOUBLE" -> JDBCType.DOUBLE;
+ case "FLOAT" -> JDBCType.FLOAT;
+ default -> nativeType.startsWith("ARRAY") ? JDBCType.ARRAY : JDBCType.OTHER;
+ };
+ }
+
+ /**
+ * The Druid native type name for a {@link JDBCType}, following Druid's SQL-to-native type mapping.
+ *
+ * @throws IllegalArgumentException if there is no Druid native type for {@code type}
+ */
+ public static String nativeTypeForJdbcType(final JDBCType type)
+ {
+ return switch (type) {
+ case VARCHAR, CHAR -> "STRING";
+ case BIGINT, INTEGER, SMALLINT, TINYINT, BOOLEAN, TIMESTAMP, DATE -> "LONG";
+ case FLOAT, REAL -> "FLOAT";
+ case DOUBLE -> "DOUBLE";
+ default -> throw new IllegalArgumentException("No Druid type mapping for JDBC type[" + type + "]");
+ };
+ }
+
+ /**
+ * The JDBC {@link Types} code for this column, derived from {@link #type()}, e.g.
+ * {@link Types#VARCHAR}.
+ */
+ public int jdbcType()
+ {
+ return type.getVendorTypeNumber();
+ }
+
+ /**
+ * The JDBC {@link Types} code for the elements of this column, when it is read as an array by
+ * {@code ResultSet#getArray}. Derived from {@link #nativeType()}.
+ */
+ public int arrayElementJdbcType()
+ {
+ return arrayElementType().getVendorTypeNumber();
+ }
+
+ /**
+ * The {@link JDBCType} of the elements of this column, when it is read as an array by
+ * {@code ResultSet#getArray}. Derived from {@link #nativeType()}.
+ */
+ public JDBCType arrayElementType()
+ {
+ return typeForNativeType(arrayElementNativeType(nativeType));
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClient.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClient.java
new file mode 100644
index 00000000000..0c0887afa44
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClient.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import java.sql.SQLException;
+
+/**
+ * HTTP client for Druid SQL.
+ */
+public interface DruidHttpClient extends AutoCloseable
+{
+ /**
+ * Run a SQL query.
+ *
+ * @throws SQLException if the query execution fails prior to returning any results
+ */
+ QueryResultsIterator runQuery(SqlRequest request) throws SQLException;
+
+ /**
+ * Cancels a running SQL query.
+ *
+ * @throws SQLException if the cancellation request fails
+ */
+ void cancelQuery(String sqlQueryId) throws SQLException;
+
+ /**
+ * Returns the URL for this client, like {@code https://example.com:9088/druid/v2/sql/}.
+ */
+ String getUrl();
+
+ /**
+ * Returns the per-request network timeout in milliseconds, or zero if none is set.
+ */
+ int getNetworkTimeoutMillis();
+
+ /**
+ * Sets the per-request network timeout, in milliseconds, applied to HTTP requests started after this call.
+ * Zero means no client-side request timeout.
+ */
+ void setNetworkTimeoutMillis(int networkTimeoutMillis);
+
+ /**
+ * Returns whether the client is closed.
+ */
+ boolean isClosed();
+
+ /**
+ * Closes the HTTP client and releases resources. Aborts any in-flight requests.
+ */
+ @Override
+ void close();
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClientImpl.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClientImpl.java
new file mode 100644
index 00000000000..a4c9101a5fd
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/DruidHttpClientImpl.java
@@ -0,0 +1,474 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.ClientProperties;
+import org.apache.druid.jdbc.DruidConnectionUrl;
+import org.apache.druid.jdbc.DruidJdbcException;
+import org.apache.druid.jdbc.DruidSQLState;
+import org.apache.druid.jdbc.StringUtils;
+
+import javax.annotation.Nullable;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.InputStream;
+import java.net.ConnectException;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.net.UnknownHostException;
+import java.net.http.HttpClient;
+import java.net.http.HttpHeaders;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.sql.SQLException;
+import java.time.Duration;
+import java.util.Base64;
+import java.util.Locale;
+
+/**
+ * Production implementation of {@link DruidHttpClient}, using the JDK {@link HttpClient}.
+ */
+public class DruidHttpClientImpl implements DruidHttpClient
+{
+ private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(10);
+ private static final Duration CANCELLATION_TIMEOUT = Duration.ofSeconds(5);
+ private static final String CTX_SQL_QUERY_ID = "sqlQueryId";
+ private static final String CONTENT_TYPE_JSON = "application/json";
+
+ private final HttpClient httpClient;
+ private final ObjectMapper jsonMapper;
+ private final String httpUrl;
+ private final ClientProperties clientProperties;
+
+ private volatile int networkTimeoutMillis;
+ private volatile boolean closed;
+
+ public DruidHttpClientImpl(
+ final DruidConnectionUrl connectionUrl,
+ final ObjectMapper jsonMapper
+ ) throws SQLException
+ {
+ this.httpUrl = connectionUrl.buildHttpUrl();
+ this.clientProperties = connectionUrl.getClientProperties();
+
+ final HttpClient.Builder clientBuilder =
+ HttpClient.newBuilder()
+ .connectTimeout(DEFAULT_CONNECT_TIMEOUT)
+ .followRedirects(HttpClient.Redirect.NEVER);
+
+ if (connectionUrl.isHttps() && !clientProperties.isVerifyTls()) {
+ try {
+ final SSLContext sslContext = createTrustAllSslContext();
+ clientBuilder.sslContext(sslContext);
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Failed to configure TLS context: %s", e);
+ }
+ }
+
+ this.httpClient = clientBuilder.build();
+ this.jsonMapper = jsonMapper;
+ }
+
+ @Override
+ public QueryResultsIterator runQuery(final SqlRequest request) throws SQLException
+ {
+ throwIfClosed();
+
+ try {
+ final byte[] requestJson = jsonMapper.writeValueAsBytes(request);
+ final HttpRequest.Builder requestBuilder =
+ createRequestBuilder(URI.create(httpUrl))
+ .header("Content-Type", CONTENT_TYPE_JSON)
+ .POST(HttpRequest.BodyPublishers.ofByteArray(requestJson));
+
+ final String sqlQueryId = sqlQueryIdOf(request);
+ final HttpResponse<InputStream> response = executeQueryRequest(requestBuilder);
+ try {
+ return new QueryResultsIteratorImpl(response.body(), jsonMapper, sqlQueryId);
+ }
+ catch (Throwable e) {
+ try {
+ response.body().close();
+ }
+ catch (Throwable e2) {
+ e.addSuppressed(e2);
+ }
+ throw e;
+ }
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Failed to execute SQL query: %s", e);
+ }
+ }
+
+ @Override
+ public void cancelQuery(final String sqlQueryId) throws SQLException
+ {
+ throwIfClosed();
+
+ if (sqlQueryId == null || sqlQueryId.isEmpty()) {
+ throw new DruidJdbcException("sqlQueryId cannot be null or empty");
+ }
+
+ try {
+ final String cancellationUrl =
+ (httpUrl.endsWith("/") ? httpUrl.substring(0, httpUrl.length() - 1) : httpUrl)
+ + "/"
+ + encodePathComponent(sqlQueryId);
+
+ final HttpRequest.Builder requestBuilder =
+ createRequestBuilder(URI.create(cancellationUrl))
+ .DELETE()
+ .timeout(CANCELLATION_TIMEOUT);
+
+ final HttpRequest request = requestBuilder.build();
+ final HttpResponse<Void> response = httpClient.send(request, HttpResponse.BodyHandlers.discarding());
+
+ // Consider 404 or 2xx a success, any other return code a failure.
+ final int statusCode = response.statusCode();
+ if (!(statusCode >= 200 && statusCode < 300) && statusCode != 404) {
+ throw new DruidJdbcException(
+ "Failed to cancel sqlQueryId[%s]: Received HTTP %s", sqlQueryId, statusCode);
+ }
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Failed to cancel sqlQueryId[%s]: %s", sqlQueryId, e);
+ }
+ }
+
+ @Override
+ public String getUrl()
+ {
+ return httpUrl;
+ }
+
+ @Override
+ public int getNetworkTimeoutMillis()
+ {
+ return networkTimeoutMillis;
+ }
+
+ @Override
+ public void setNetworkTimeoutMillis(final int networkTimeoutMillis)
+ {
+ this.networkTimeoutMillis = networkTimeoutMillis;
+ }
+
+ @Override
+ public boolean isClosed()
+ {
+ return closed;
+ }
+
+ @Override
+ public void close()
+ {
+ try {
+ HttpClientUtils.close(httpClient);
+ }
+ catch (RuntimeException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ finally {
+ closed = true;
+ }
+ }
+
+ /**
+ * Executes an HTTP request, returning the response as a stream if it succeeds. Throws an error for non-successful
+ * HTTP codes.
+ *
+ * @throws SQLException if the HTTP request fails
+ */
+ private HttpResponse<InputStream> executeQueryRequest(final HttpRequest.Builder requestBuilder) throws SQLException
+ {
+ throwIfClosed();
+
+ try {
+ // Apply network timeout, if set, to the HTTP connection.
+ final int networkTimeoutMillisToUse = networkTimeoutMillis;
+ if (networkTimeoutMillisToUse > 0) {
+ requestBuilder.timeout(Duration.ofMillis(networkTimeoutMillisToUse));
+ }
+
+ final HttpRequest request = requestBuilder.build();
+ final HttpResponse<InputStream> response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
+
+ if (response.statusCode() >= 300) {
+ // Handle errors. 3xx counts as an error (in addition to 4xx and 5xx), since we do not follow redirects.
+ try (InputStream inputStream = response.body()) {
+ final String errorBody = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
+ throw toSQLException(response.statusCode(), response.headers(), errorBody);
+ }
+ } else {
+ return response;
+ }
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new DruidJdbcException(e, "Failed to execute query against[%s]: interrupted: %s", httpUrl, e);
+ }
+ catch (ConnectException | UnknownHostException e) {
+ throw new DruidJdbcException(
+ e,
+ DruidSQLState.ConnectionUnableToConnect,
+ "Failed to connect to[%s]: %s",
+ httpUrl,
+ e
+ );
+ }
+ catch (Exception e) {
+ throw new DruidJdbcException(e, "Failed to execute query against[%s]: %s", httpUrl, e);
+ }
+ }
+
+ /**
+ * Creates an HTTP request builder with authentication headers added.
+ */
+ private HttpRequest.Builder createRequestBuilder(final URI uri) throws SQLException
+ {
+ throwIfClosed();
+
+ final HttpRequest.Builder builder = HttpRequest.newBuilder().uri(uri).header("Accept", CONTENT_TYPE_JSON);
+
+ if (clientProperties.getAuthentication() != null) {
+ final String authentication = clientProperties.getAuthentication();
+
+ if (ClientProperties.AUTHENTICATION_BASIC.equals(authentication)) {
+ final String user = clientProperties.getUser();
+ final String password = clientProperties.getPassword();
+ final String credentials = (user == null ? "" : user) + ":" + (password == null ? "" : password);
+ final String encodedCredentials =
+ Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
+
+ builder.header("Authorization", "Basic " + encodedCredentials);
+ } else if (ClientProperties.AUTHENTICATION_BASIC_RAW.equals(authentication)) {
+ final String password = clientProperties.getPassword();
+
+ if (password == null || password.isEmpty()) {
+ throw new DruidJdbcException("Password is required for basicRaw authentication");
+ }
+
+ builder.header("Authorization", "Basic " + password);
+ } else {
+ throw new DruidJdbcException("Unsupported authentication method: %s", authentication);
+ }
+ }
+
+ return builder;
+ }
+
+ SQLException toSQLException(final int statusCode, final HttpHeaders headers, @Nullable final String body)
+ {
+ if (statusCode >= 300 && statusCode < 400) {
+ return new DruidJdbcException(
+ "HTTP %s redirect from[%s] to[%s]: connect to the redirect target directly",
+ statusCode,
+ httpUrl,
+ headers.firstValue("location").orElse("none")
+ );
+ }
+
+ // Check if the response is JSON, try to parse the error response if so.
+ String formattedError = null;
+
+ if (body != null && !body.isEmpty() && isJsonContentType(headers)) {
+ try {
+ final ErrorResponse errorResponse = jsonMapper.readValue(body, ErrorResponse.class);
+ formattedError = errorResponse.asFullErrorMessage();
+ }
+ catch (Exception ignored) {
+ // Fall back to default error message.
+ }
+ }
+
+ if (formattedError == null) {
+ formattedError = chopBody(body);
+ }
+
+ if (statusCode == 401 || statusCode == 403) {
+ return new DruidJdbcException(
+ DruidSQLState.InvalidAuthorizationSpecification,
+ "HTTP %s error from[%s]: %s",
+ statusCode,
+ httpUrl,
+ formattedError
+ );
+ } else {
+ return new DruidJdbcException("HTTP %s error from[%s]: %s", statusCode, httpUrl, formattedError);
+ }
+ }
+
+ private void throwIfClosed() throws SQLException
+ {
+ if (closed) {
+ throw new DruidJdbcException(DruidSQLState.ConnectionDoesNotExist, "HTTP client is closed");
+ }
+ }
+
+ /**
+ * Returns the sqlQueryId from a request's query context, or null if it has none. Normally set by the statement
+ * that built the request, both for cancellation and so errors can name the query.
+ */
+ @Nullable
+ private static String sqlQueryIdOf(final SqlRequest request)
+ {
+ final Object sqlQueryId = request.context().get(CTX_SQL_QUERY_ID);
+ return sqlQueryId == null ? null : String.valueOf(sqlQueryId);
+ }
+
+ /**
+ * Chops a string to 1000 chars or less. Meant for inclusion in error messages.
+ */
+ private static String chopBody(@Nullable final String body)
+ {
+ final int maxChars = 1000;
+
+ if (body == null || body.isEmpty()) {
+ return "no body";
+ } else if (body.length() > maxChars) {
+ return StringUtils.format("first 1K chars of body: %s", body.substring(0, maxChars));
+ } else {
+ return StringUtils.format("body: %s", body);
+ }
+ }
+
+ /**
+ * Encodes a URL path component.
+ */
+ @Nullable
+ private static String encodePathComponent(@Nullable String s)
+ {
+ if (s == null) {
+ return null;
+ }
+
+ return StringUtils.replace(URLEncoder.encode(s, StandardCharsets.UTF_8), "+", "%20");
+ }
+
+ /**
+ * Creates an SSL context that trusts all certificates without verification.
+ * This is only used when {@link ClientProperties#isVerifyTls()} is explicitly disabled.
+ */
+ private static SSLContext createTrustAllSslContext() throws Exception
+ {
+ final TrustManager[] trustAllCerts = new TrustManager[]{
+ new X509TrustManager()
+ {
+ @Override
+ public X509Certificate[] getAcceptedIssuers()
+ {
+ return new X509Certificate[0];
+ }
+
+ @Override
+ public void checkClientTrusted(final X509Certificate[] certs, final String authType)
+ {
+ // Accept all client certificates
+ }
+
+ @Override
+ public void checkServerTrusted(final X509Certificate[] certs, final String authType)
+ {
+ // Accept all server certificates
+ }
+ }
+ };
+
+ final SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, trustAllCerts, new SecureRandom());
+ return sslContext;
+ }
+
+ /**
+ * Checks if the HTTP response content type is JSON.
+ */
+ private static boolean isJsonContentType(final HttpHeaders headers)
+ {
+ return headers.firstValue("content-type")
+ .map(contentType -> contentType.toLowerCase(Locale.ENGLISH).contains(CONTENT_TYPE_JSON))
+ .orElse(false);
+ }
+
+ /**
+ * Models an error response from the Druid SQL API.
+ *
+ * @param error well-defined error code
+ * @param errorMessage message with additional details about the error
+ * @param errorClass class of exception that caused this error
+ * @param host host on which the error occurred
+ */
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ public record ErrorResponse(
+ @JsonProperty("error") String error,
+ @JsonProperty("errorMessage") String errorMessage,
+ @JsonProperty("errorClass") String errorClass,
+ @JsonProperty("host") String host
+ )
+ {
+ @Nullable
+ public String asFullErrorMessage()
+ {
+ if (error == null) {
+ return null;
+ }
+
+ final StringBuilder errorBuilder = new StringBuilder();
+ errorBuilder.append(error);
+
+ // Add host if available
+ if (host != null) {
+ errorBuilder.append(" from[").append(host).append("]");
+ }
+
+ // Add error class if available
+ if (errorClass != null) {
+ errorBuilder.append(": ").append(errorClass);
+ }
+
+ // Add error message if available
+ if (errorMessage != null) {
+ errorBuilder.append(": ").append(errorMessage);
+ }
+
+ return errorBuilder.toString();
+ }
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/EmptyQueryResultsIterator.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/EmptyQueryResultsIterator.java
new file mode 100644
index 00000000000..a8dd75deb3f
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/EmptyQueryResultsIterator.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import java.util.List;
+import java.util.NoSuchElementException;
+
+/**
+ * Implementation of {@link QueryResultsIterator} for empty result sets generated by the driver itself.
+ */
+public class EmptyQueryResultsIterator implements QueryResultsIterator
+{
+ private final List<ColumnMetadata> columns;
+
+ public EmptyQueryResultsIterator(final List<ColumnMetadata> columns)
+ {
+ this.columns = columns;
+ }
+
+ @Override
+ public boolean hasNext()
+ {
+ return false;
+ }
+
+ @Override
+ public Object[] next()
+ {
+ throw new NoSuchElementException();
+ }
+
+ @Override
+ public List<ColumnMetadata> getColumns()
+ {
+ return columns;
+ }
+
+ @Override
+ public void close()
+ {
+ // Nothing to do.
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/HttpClientUtils.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/HttpClientUtils.java
new file mode 100644
index 00000000000..9751e9d5446
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/HttpClientUtils.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import javax.annotation.Nullable;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.http.HttpClient;
+
+/**
+ * Utility class for closing {@link HttpClient}. Necessary because this driver is built for Java 17, where clients
+ * cannot be closed, but we still want to properly close them on Java 21+ (where they are AutoCloseable).
+ */
+public class HttpClientUtils
+{
+ @Nullable
+ private static final Method HTTP_CLIENT_CLOSE = findHttpClientMethod("close");
+
+ @Nullable
+ private static final Method HTTP_CLIENT_SHUTDOWN_NOW = findHttpClientMethod("shutdownNow");
+
+ private HttpClientUtils()
+ {
+ // No instantiation.
+ }
+
+ /**
+ * Shuts down a client immediately, if possible. On Java 17, where these methods on {@link HttpClient} do not exist,
+ * this is a no-op.
+ */
+ public static void close(final HttpClient httpClient) throws IOException
+ {
+ invokeIfPresent(HTTP_CLIENT_SHUTDOWN_NOW, httpClient);
+ invokeIfPresent(HTTP_CLIENT_CLOSE, httpClient);
+ }
+
+ private static void invokeIfPresent(@Nullable final Method method, final HttpClient httpClient) throws IOException
+ {
+ if (method != null) {
+ try {
+ method.invoke(httpClient);
+ }
+ catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ catch (InvocationTargetException e) {
+ final Throwable cause = e.getCause();
+ if (cause instanceof IOException ioe) {
+ throw ioe;
+ } else if (cause instanceof RuntimeException re) {
+ throw re;
+ } else if (cause instanceof Error error) {
+ throw error;
+ } else {
+ throw new RuntimeException(cause);
+ }
+ }
+ }
+ }
+
+ /**
+ * Returns the named no-arg {@link HttpClient} method if the current JVM has it, or null if it does not.
+ */
+ @Nullable
+ private static Method findHttpClientMethod(final String name)
+ {
+ try {
+ return HttpClient.class.getMethod(name);
+ }
+ catch (NoSuchMethodException e) {
+ return null;
+ }
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIterator.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIterator.java
new file mode 100644
index 00000000000..83a11a4ce04
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIterator.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import java.io.Closeable;
+import java.sql.SQLException;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Streaming iterator for SQL query results in "array" format. Closeable and must be closed when done.
+ * Does not implement {@link Iterator}, so we can throw {@link SQLException} from {@link #hasNext()}
+ * and {@link #next}.
+ */
+public interface QueryResultsIterator extends Closeable
+{
+ boolean hasNext() throws SQLException;
+
+ Object[] next() throws SQLException;
+
+ List<ColumnMetadata> getColumns();
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIteratorImpl.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIteratorImpl.java
new file mode 100644
index 00000000000..28412fe6735
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/QueryResultsIteratorImpl.java
@@ -0,0 +1,454 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.core.io.JsonEOFException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.DruidJdbcException;
+import org.apache.druid.jdbc.DruidTimestampParser;
+import org.apache.druid.jdbc.StringUtils;
+
+import javax.annotation.Nullable;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Date;
+import java.sql.JDBCType;
+import java.sql.SQLException;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NoSuchElementException;
+
+public class QueryResultsIteratorImpl implements QueryResultsIterator
+{
+ private final JsonParser jsonParser;
+ private final InputStream responseStream;
+ private final List<ColumnMetadata> columns;
+
+ /**
+ * sqlQueryId of the query these results belong to, if known.
+ */
+ @Nullable
+ private final String sqlQueryId;
+
+ /**
+ * Written by {@link #close()}, which may run on a different thread than the one doing the reading.
+ */
+ private volatile boolean closed = false;
+
+ private boolean reachedEnd = false;
+
+ /**
+ * True when {@link #hasNext()} has advanced the parser to a START_ARRAY token for a data row
+ * that has not yet been consumed by {@link #next()}. Used to make {@link #hasNext()} idempotent.
+ */
+ private boolean peekedRow = false;
+
+ /**
+ * Number of data rows returned by {@link #next()} so far.
+ */
+ private long rowsRead;
+
+ public QueryResultsIteratorImpl(
+ final InputStream responseStream,
+ final ObjectMapper objectMapper,
+ @Nullable final String sqlQueryId
+ ) throws SQLException
+ {
+ this.sqlQueryId = sqlQueryId;
+ this.responseStream = responseStream;
+
+ try {
+ final JsonFactory jsonFactory = objectMapper.getFactory();
+ this.jsonParser = jsonFactory.createParser(responseStream);
+ this.columns = new ArrayList<>();
+ initialize();
+ }
+ catch (SQLException e) {
+ throw e;
+ }
+ catch (Exception e) {
+ throw readError(e, "Failed to create streaming iterator");
+ }
+ }
+
+ @Override
+ public boolean hasNext() throws SQLException
+ {
+ if (closed) {
+ throw new DruidJdbcException("Result iterator has been closed");
+ }
+
+ if (reachedEnd) {
+ return false;
+ }
+
+ if (peekedRow) {
+ // Already advanced to a START_ARRAY for the next data row; don't advance again.
+ return true;
+ }
+
+ try {
+ final JsonToken nextToken = jsonParser.nextToken();
+ if (nextToken == JsonToken.END_ARRAY) {
+ // We've reached the end of the main array.
+ reachedEnd = true;
+ return false;
+ } else if (nextToken == JsonToken.START_ARRAY) {
+ // Start of a new data row.
+ peekedRow = true;
+ return true;
+ } else {
+ throw new DruidJdbcException("Expected array or end of array, got[%s]", nextToken);
+ }
+ }
+ catch (SQLException e) {
+ reachedEnd = true;
+ throw e;
+ }
+ catch (Exception e) {
+ reachedEnd = true;
+ throw readError(e, "Error reading query results");
+ }
+ }
+
+ @Override
+ public Object[] next() throws SQLException
+ {
+ if (closed) {
+ throw new DruidJdbcException("Result iterator has been closed");
+ }
+
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+
+ try {
+ peekedRow = false;
+ return readDataRow();
+ }
+ catch (IOException e) {
+ throw readError(e, "Failed to read next row");
+ }
+ }
+
+ @Override
+ public List<ColumnMetadata> getColumns()
+ {
+ return columns;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ closed = true;
+ responseStream.close();
+ }
+
+ private void initialize() throws IOException, SQLException
+ {
+ // Expect the response to start with an array.
+ final JsonToken firstToken = jsonParser.nextToken();
+ if (firstToken == null) {
+ throw truncatedResponse(null, 0, sqlQueryId);
+ } else if (firstToken != JsonToken.START_ARRAY) {
+ throw new DruidJdbcException("Expected array response format");
+ }
+
+ // Read and parse the header (column names) row.
+ final List<String> headerRow;
+ if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
+ throw new DruidJdbcException("Response missing header row");
+ } else {
+ headerRow = readMetadataRow();
+ }
+
+ // Read and parse the typesHeader row.
+ if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
+ throw new DruidJdbcException("Response missing typesHeader row");
+ }
+ final List<String> nativeTypesRow = readMetadataRow();
+
+ // Read and parse the sqlTypesHeader row.
+ if (jsonParser.nextToken() != JsonToken.START_ARRAY) {
+ throw new DruidJdbcException("Response missing sqlTypesHeader row");
+ }
+ final List<String> sqlTypesRow = readMetadataRow();
+
+ if (headerRow.size() != sqlTypesRow.size()) {
+ throw new DruidJdbcException("header and sqlTypesHeader must have same number of columns");
+ }
+
+ if (nativeTypesRow.size() != sqlTypesRow.size()) {
+ throw new DruidJdbcException("typesHeader and sqlTypesHeader must have same number of columns");
+ }
+
+ // Build column metadata.
+ for (int i = 0; i < headerRow.size(); i++) {
+ final JDBCType type = JDBCType.valueOf(sqlTypesRow.get(i));
+ columns.add(new ColumnMetadata(headerRow.get(i), type, nativeTypesRow.get(i)));
+ }
+ }
+
+ /**
+ * Reads a metadata row (e.g. header, sqlTypesHeader) from the stream. Advances to the {@link JsonToken#END_ARRAY}
+ * at the end of the row.
+ */
+ private List<String> readMetadataRow() throws IOException
+ {
+ final List<String> row = new ArrayList<>();
+ JsonToken token;
+ while ((token = jsonParser.nextToken()) != JsonToken.END_ARRAY) {
+ if (token == JsonToken.VALUE_STRING) {
+ row.add(jsonParser.getValueAsString());
+ } else if (token == JsonToken.VALUE_NULL) {
+ row.add(null);
+ } else {
+ row.add(jsonParser.getValueAsString());
+ }
+ }
+ return row;
+ }
+
+ /**
+ * Reads a data row from the stream. Coerces objects to the expected Java types using
+ * {@link #readDataObject(String, String, int)}. Advances to the {@link JsonToken#END_ARRAY} at the end of the row.
+ */
+ private Object[] readDataRow() throws IOException, SQLException
+ {
+ final Object[] row = new Object[columns.size()];
+ int columnIndex = 0;
+ while ((jsonParser.nextToken()) != JsonToken.END_ARRAY) {
+ if (columnIndex >= columns.size()) {
+ throw new DruidJdbcException("Data row too long");
+ }
+
+ final ColumnMetadata column = columns.get(columnIndex);
+ final Object value = readDataObject(column.name(), column.nativeType(), column.jdbcType());
+ row[columnIndex++] = value;
+ }
+
+ if (columnIndex != columns.size()) {
+ throw new DruidJdbcException("Data row too short");
+ }
+
+ rowsRead++;
+ return row;
+ }
+
+ /**
+ * Reads a data object from the stream. If the data object consists of multiple tokens, this advances to the
+ * final token.
+ *
+ * @param columnName name of the column, used in error messages
+ * @param nativeType Druid native type of the value, used to type the elements if the value is an array
+ * @param jdbcType SQL type that determines the Java type of the returned value. This is the column's own declared
+ * type for a top-level value, or the element type for a value nested inside an array.
+ *
+ * @throws DruidJdbcException if the value cannot be read as the declared type
+ */
+ @Nullable
+ private Object readDataObject(
+ final String columnName,
+ @Nullable final String nativeType,
+ final int jdbcType
+ ) throws IOException, SQLException
+ {
+ final JsonToken token = jsonParser.currentToken();
+ if (token == JsonToken.VALUE_NULL) {
+ return null;
+ }
+
+ // Handle nested values: read JSON arrays into Lists, and JSON objects into Maps.
+ if (token == JsonToken.START_ARRAY) {
+ return readJsonArray(columnName, ColumnMetadata.arrayElementNativeType(nativeType));
+ } else if (token == JsonToken.START_OBJECT) {
+ return jsonParser.readValueAs(Object.class);
+ }
+
+ // About to read a primitive value. Finish the token now, so a truncation is reported as a truncation rather
+ // than cannot-coerce.
+ jsonParser.finishToken();
+
+ try {
+ switch (jdbcType) {
+ case Types.BIT:
+ case Types.TINYINT:
+ case Types.SMALLINT:
+ case Types.INTEGER:
+ return jsonParser.getIntValue();
+
+ case Types.BIGINT:
+ return jsonParser.getLongValue();
+
+ case Types.REAL:
+ return (float) jsonParser.getDoubleValue();
+
+ case Types.FLOAT:
+ case Types.DOUBLE:
+ return jsonParser.getDoubleValue();
+
+ case Types.DECIMAL:
+ case Types.NUMERIC:
+ return jsonParser.getDecimalValue();
+
+ case Types.BOOLEAN:
+ return jsonParser.getValueAsBoolean();
+
+ case Types.TIMESTAMP:
+ if (token == JsonToken.VALUE_NUMBER_INT) {
+ return new Timestamp(jsonParser.getLongValue());
+ } else {
+ return DruidTimestampParser.parse(jsonParser.getValueAsString());
+ }
+
+ case Types.DATE:
+ // Keep the calendar day the server floored the value to, rather than the instant, so that the day does
+ // not shift when the JVM default time zone differs from the session time zone. See
+ // DruidTimestampParser#parseLocalDate.
+ return Date.valueOf(DruidTimestampParser.parseLocalDate(jsonParser.getValueAsString()));
+
+ case Types.TIME:
+ if (token == JsonToken.VALUE_NUMBER_INT) {
+ return new Time(jsonParser.getLongValue());
+ } else {
+ return new Time(DruidTimestampParser.parse(jsonParser.getValueAsString()).getTime());
+ }
+
+ case Types.VARCHAR:
+ case Types.CHAR:
+ return jsonParser.getValueAsString();
+
+ default:
+ break;
+ }
+ }
+ catch (Exception e) {
+ throw cannotCoerce(columnName, jdbcType, e);
+ }
+
+ // Other type: let Jackson choose the representation.
+ return jsonParser.readValueAs(Object.class);
+ }
+
+ /**
+ * Returns the exception to throw when a value from the server cannot be read as its column's declared SQL type.
+ */
+ private DruidJdbcException cannotCoerce(
+ final String columnName,
+ final int sqlType,
+ @Nullable final Throwable cause
+ ) throws IOException
+ {
+ final String format = "Cannot read value[%s] of column[%s] as declared type[%s]";
+ final String valueText = jsonParser.getText();
+ final JDBCType jdbcType = JDBCType.valueOf(sqlType);
+ if (cause == null) {
+ return new DruidJdbcException(format, valueText, columnName, jdbcType);
+ } else {
+ return new DruidJdbcException(cause, format, valueText, columnName, jdbcType);
+ }
+ }
+
+ /**
+ * Reads a data array from the stream. Advances to the {@link JsonToken#END_ARRAY} at the end of the data array.
+ *
+ * @param columnName name of the column, used in error messages
+ * @param elementNativeType Druid native type of the elements of this array
+ */
+ private List<Object> readJsonArray(
+ final String columnName,
+ @Nullable final String elementNativeType
+ ) throws IOException, SQLException
+ {
+ final int elementJdbcType = ColumnMetadata.jdbcTypeForNativeType(elementNativeType);
+ final List<Object> retVal = new ArrayList<>();
+ while ((jsonParser.nextToken()) != JsonToken.END_ARRAY) {
+ retVal.add(readDataObject(columnName, elementNativeType, elementJdbcType));
+ }
+ return retVal;
+ }
+
+ /**
+ * Returns the exception to throw when reading the response stream failed. The single place that decides whether
+ * a read failure was the server cutting us off, or something else.
+ *
+ * @param e the exception that reading threw
+ * @param what what the driver was doing, used as the message prefix for a failure that is not a truncation
+ */
+ private DruidJdbcException readError(final Throwable e, final String what)
+ {
+ if (isResponseTruncated(e)) {
+ return truncatedResponse(e, rowsRead, sqlQueryId);
+ } else {
+ return new DruidJdbcException(e, "%s: %s", what, e);
+ }
+ }
+
+ /**
+ * Returns whether an exception thrown while reading the response stream means the response body ended before
+ * the server finished writing it.
+ */
+ private static boolean isResponseTruncated(@Nullable final Throwable e)
+ {
+ Throwable t = e;
+ while (t != null) {
+ if (t instanceof JsonEOFException || t instanceof EOFException) {
+ return true;
+ } else {
+ t = t.getCause();
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns the exception to throw when the response was truncated.
+ *
+ * @param cause the exception that revealed the truncation, if there was one
+ * @param rowsRead number of rows successfully delivered before the response was cut off
+ * @param sqlQueryId sqlQueryId to point the user at in the server's logs, if known
+ */
+ private static DruidJdbcException truncatedResponse(
+ @Nullable final Throwable cause,
+ final long rowsRead,
+ @Nullable final String sqlQueryId
+ )
+ {
+ final String format =
+ "Truncated response after[%,d] rows: the server may have cut off the response because the query hit an "
+ + "error or timed out. Check the Druid broker logs for %s.";
+ final String logHint =
+ sqlQueryId == null ? "details" : StringUtils.format("sqlQueryId[%s]", sqlQueryId);
+
+ if (cause == null) {
+ return new DruidJdbcException(format, rowsRead, logHint);
+ } else {
+ return new DruidJdbcException(cause, format, rowsRead, logHint);
+ }
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlParameter.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlParameter.java
new file mode 100644
index 00000000000..4b1c7db99a4
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlParameter.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import javax.annotation.Nullable;
+import java.util.Objects;
+
+/**
+ * Represents a SQL parameter for parameterized queries.
+ *
+ * @param type SQL type name for the parameter, like {@code BOOLEAN} or {@code VARCHAR}
+ * @param value value for the parameter
+ */
+public record SqlParameter(
+ @JsonProperty("type") String type,
+ @JsonProperty("value") @Nullable Object value
+)
+{
+ public SqlParameter
+ {
+ Objects.requireNonNull(type, "type");
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlRequest.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlRequest.java
new file mode 100644
index 00000000000..7f94d66785b
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/http/SqlRequest.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.http;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import javax.annotation.Nullable;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Represents a SQL query request to be sent to Druid. Same model as the {@code SqlQuery} class, but we don't use that
+ * here because the druid-jdbc-driver module wants to have minimal dependencies.
+ */
+public record SqlRequest(
+ @JsonProperty("query") String query,
+ @JsonProperty("resultFormat") String resultFormat,
+ @JsonProperty("header") @JsonInclude(JsonInclude.Include.NON_DEFAULT) boolean header,
+ @JsonProperty("typesHeader") @JsonInclude(JsonInclude.Include.NON_DEFAULT) boolean typesHeader,
+ @JsonProperty("sqlTypesHeader") @JsonInclude(JsonInclude.Include.NON_DEFAULT) boolean sqlTypesHeader,
+ @JsonProperty("context") @JsonInclude(JsonInclude.Include.NON_EMPTY) Map<String, Object> context,
+ @JsonProperty("parameters") @JsonInclude(JsonInclude.Include.NON_EMPTY) List<SqlParameter> parameters
+)
+{
+ public SqlRequest
+ {
+ Objects.requireNonNull(query, "query");
+ resultFormat = resultFormat != null ? resultFormat : "array";
+ context = context != null ? new HashMap<>(context) : new HashMap<>();
+ parameters = parameters != null ? parameters : List.of();
+ }
+
+ /**
+ * Creates a request in the form this driver always uses: "array" result format with all headers requested.
+ */
+ public static SqlRequest of(
+ final String query,
+ @Nullable final Map<String, Object> context,
+ @Nullable final List<SqlParameter> parameters
+ )
+ {
+ final Map<String, Object> mergedContext = context != null ? new HashMap<>(context) : new HashMap<>();
+
+ // Need sqlStringifyArrays: false to properly read arrays.
+ mergedContext.put("sqlStringifyArrays", false);
+
+ return new SqlRequest(query, null, true, true, true, mergedContext, parameters);
+ }
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SetStatement.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SetStatement.java
new file mode 100644
index 00000000000..ec3368eba23
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SetStatement.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.sql;
+
+/**
+ * Representation of a SET statement, which for JDBC are handled in the driver due to the server being connectionless.
+ * Returned by {@link SqlScanner#getSetStatements()}.
+ */
+public record SetStatement(String key, Object value)
+{
+}
diff --git a/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SqlScanner.java b/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SqlScanner.java
new file mode 100644
index 00000000000..fe2f3f24f78
--- /dev/null
+++ b/jdbc-driver/src/main/java/org/apache/druid/jdbc/sql/SqlScanner.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc.sql;
+
+import org.apache.druid.jdbc.BooleanUtils;
+import org.apache.druid.jdbc.DruidJdbcException;
+import org.apache.druid.jdbc.StringUtils;
+
+import javax.annotation.Nullable;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Lightweight SQL scanner that splits statements on semicolons, picks out {@code SET} statements, and counts
+ * parameter placeholders ({@code ?}).
+ */
+public class SqlScanner
+{
+ private static final Pattern PATTERN_SET_STATEMENT = Pattern.compile(
+ "^\\s*SET\\s+(\\w+)\\s*=\\s*(.*?)\\s*$|^\\s*SET\\b.*",
+ Pattern.DOTALL | Pattern.CASE_INSENSITIVE
+ );
+ private final List<SetStatement> setStatements;
+ @Nullable
+ private final String sqlStatement;
+ private final int sqlStatementParameterCount;
+
+ private SqlScanner(
+ final List<SetStatement> setStatements,
+ @Nullable final String sqlStatement,
+ final int sqlStatementParameterCount
+ )
+ {
+ this.setStatements = setStatements;
+ this.sqlStatement = sqlStatement;
+ this.sqlStatementParameterCount = sqlStatementParameterCount;
+ }
+
+ /**
+ * Scans some SQL, which may potentially be multi-statement.
+ */
+ public static SqlScanner scan(final String sql) throws SQLException
+ {
+ if (sql == null || sql.isEmpty()) {
+ return new SqlScanner(List.of(), null, 0);
+ }
+
+ final List<ScannedStatement> statements = new ArrayList<>();
+ final StringBuilder current = new StringBuilder();
+ int currentStart = 0;
+ int parameterCount = 0;
+
+ boolean inStringLiteral = false;
+ boolean inDoubleQuotedIdentifier = false;
+ boolean inLineComment = false;
+ boolean inBlockComment = false;
+
+ for (int i = 0; i < sql.length(); i++) {
+ final char c = sql.charAt(i);
+ final char next = (i + 1 < sql.length()) ? sql.charAt(i + 1) : '\0';
+
+ if (inStringLiteral) {
+ current.append(c);
+ if (c == '\'' && next == '\'') {
+ // Escaped single quote
+ current.append(next);
+ i++;
+ } else if (c == '\'') {
+ inStringLiteral = false;
+ }
+ } else if (inDoubleQuotedIdentifier) {
+ current.append(c);
+ if (c == '"' && next == '"') {
+ // Escaped double quote
+ current.append(next);
+ i++;
+ } else if (c == '"') {
+ inDoubleQuotedIdentifier = false;
+ }
+ } else if (inLineComment) {
+ if (c == '\n' || c == '\r') {
+ inLineComment = false;
+ current.append(c);
+ }
+ // else skip
+ } else if (inBlockComment) {
+ if (c == '*' && next == '/') {
+ inBlockComment = false;
+ i++;
+ // Leave a space behind, so the tokens on either side of the comment stay separate.
+ current.append(' ');
+ }
+ // else skip
+ } else {
+ // Normal code
+ if (c == '\'') {
+ inStringLiteral = true;
+ current.append(c);
+ } else if (c == '"') {
+ inDoubleQuotedIdentifier = true;
+ current.append(c);
+ } else if ((c == '-' && next == '-') || (c == '/' && next == '/')) {
+ inLineComment = true;
+ i++;
+ } else if (c == '/' && next == '*') {
+ inBlockComment = true;
+ i++;
+ } else if (c == ';') {
+ statements.add(new ScannedStatement(sql.substring(currentStart, i), current.toString()));
+ current.setLength(0);
+ currentStart = i + 1;
+ } else if (c == '?') {
+ parameterCount++;
+ current.append(c);
+ } else {
+ current.append(c);
+ }
+ }
+ }
+
+ // Reject SQL that ends with an unterminated string literal, identifier, or block comment.
+ if (inStringLiteral) {
+ throw new DruidJdbcException("Unterminated string literal");
+ } else if (inDoubleQuotedIdentifier) {
+ throw new DruidJdbcException("Unterminated quoted identifier");
+ } else if (inBlockComment) {
+ throw new DruidJdbcException("Unterminated block comment");
+ }
+
+ // Add trailing statement if non-empty.
+ if (!current.isEmpty()) {
+ statements.add(new ScannedStatement(sql.substring(currentStart), current.toString()));
+ }
+
+ // Split statements into setStatements and sqlStatement.
+ final List<SetStatement> setStatements = new ArrayList<>();
+ String sqlStatement = null;
+
+ for (final ScannedStatement statement : statements) {
+ if (statement.withoutComments().isBlank()) {
+ continue;
+ }
+
+ if (sqlStatement != null) {
+ throw new DruidJdbcException("Cannot execute more than one regular (non-SET) statement");
+ }
+
+ final Matcher m = PATTERN_SET_STATEMENT.matcher(statement.withoutComments());
+ if (!m.matches()) {
+ sqlStatement = statement.text();
+ } else if (m.group(1) == null) {
+ throw new DruidJdbcException("SET syntax invalid: %s", statement.withoutComments().trim());
+ } else {
+ setStatements.add(new SetStatement(m.group(1), parseSetValue(m.group(2))));
+ }
+ }
+
+ return new SqlScanner(setStatements, sqlStatement, parameterCount);
+ }
+
+ /**
+ * Returns the {@code SET} statements found in the SQL, in the order they appeared.
+ */
+ public List<SetStatement> getSetStatements()
+ {
+ return setStatements;
+ }
+
+ /**
+ * Returns a non-SET statement that was found, as written. There can be at most one. Returns null if there is none.
+ */
+ @Nullable
+ public String getSqlStatement()
+ {
+ return sqlStatement;
+ }
+
+ /**
+ * Returns the number of {@code ?} parameter placeholders in the {@link #getSqlStatement()}.
+ */
+ public int getParameterCount()
+ {
+ return sqlStatementParameterCount;
+ }
+
+ @Nullable
+ private static Object parseSetValue(final String valueStr) throws SQLException
+ {
+ if (valueStr.isEmpty()) {
+ throw new DruidJdbcException("SET value missing");
+ }
+
+ // Handle SQL string literals (single quotes only).
+ if (valueStr.startsWith("'") && valueStr.endsWith("'")) {
+ if (valueStr.length() < 2) {
+ throw new DruidJdbcException("SET value invalid: %s", valueStr);
+ }
+ // Handle escaped single quotes within the string
+ final String content = valueStr.substring(1, valueStr.length() - 1);
+ return StringUtils.replace(content, "''", "'");
+ }
+
+ // Handle NULL literal.
+ if ("null".equalsIgnoreCase(valueStr) || "unknown".equalsIgnoreCase(valueStr)) {
+ return null;
+ }
+
+ // Handle plain booleans.
+ if (BooleanUtils.isBooleanTrue(valueStr)) {
+ return Boolean.TRUE;
+ }
+
+ if (BooleanUtils.isBooleanFalse(valueStr)) {
+ return Boolean.FALSE;
+ }
+
+ // Handle plain longs.
+ try {
+ return Long.parseLong(valueStr);
+ }
+ catch (NumberFormatException e) {
+ // Continue.
+ }
+
+ // Handle plain doubles.
+ try {
+ return Double.parseDouble(valueStr);
+ }
+ catch (NumberFormatException e) {
+ // Continue.
+ }
+
+ throw new DruidJdbcException("SET value invalid: %s", valueStr);
+ }
+
+ /**
+ * One statement found by {@link #scan}. {@link #text} is the statement as written, which is what we send to Druid.
+ * {@link #withoutComments} has comments elided, and is only used to recognize {@code SET} statements, which lets
+ * comments appear anywhere within one.
+ */
+ private record ScannedStatement(String text, String withoutComments)
+ {
+ }
+}
diff --git a/jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver b/jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver
new file mode 100644
index 00000000000..c0c697525af
--- /dev/null
+++ b/jdbc-driver/src/main/resources/META-INF/services/java.sql.Driver
@@ -0,0 +1,20 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+org.apache.druid.jdbc.DruidJdbcDriver
diff --git a/jdbc-driver/src/test/java/org/apache/druid/jdbc/ClientPropertiesTest.java b/jdbc-driver/src/test/java/org/apache/druid/jdbc/ClientPropertiesTest.java
new file mode 100644
index 00000000000..f35d72b0282
--- /dev/null
+++ b/jdbc-driver/src/test/java/org/apache/druid/jdbc/ClientPropertiesTest.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.sql.SQLException;
+import java.util.Map;
+
+public class ClientPropertiesTest
+{
+ @Test
+ public void testEqualsAndHashCode()
+ {
+ EqualsVerifier.forClass(ClientProperties.class)
+ .usingGetClass()
+ .verify();
+ }
+
+ @Test
+ public void testAuthenticationDefaultsToBasicWithUserAndPassword() throws SQLException
+ {
+ Assertions.assertEquals(
+ ClientProperties.AUTHENTICATION_BASIC,
+ clientPropertiesOf(Map.of("user", "admin", "password", "secret")).getAuthentication()
+ );
+ }
+
+ @Test
+ public void testExplicitAuthenticationOverridesDefault() throws SQLException
+ {
+ Assertions.assertEquals(
+ ClientProperties.AUTHENTICATION_BASIC_RAW,
+ clientPropertiesOf(Map.of("authentication", "basicRaw", "password", "token")).getAuthentication()
+ );
+ }
+
+ private static ClientProperties clientPropertiesOf(final Map<String, String> allProperties) throws SQLException
+ {
+ return ClientProperties.splitProperties(allProperties).clientProperties();
+ }
+}
diff --git a/jdbc-driver/src/test/java/org/apache/druid/jdbc/DruidConnectionTest.java b/jdbc-driver/src/test/java/org/apache/druid/jdbc/DruidConnectionTest.java
new file mode 100644
index 00000000000..d1e37f83e49
--- /dev/null
+++ b/jdbc-driver/src/test/java/org/apache/druid/jdbc/DruidConnectionTest.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.jdbc;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.druid.jdbc.http.ColumnMetadata;
+import org.apache.druid.jdbc.http.DruidHttpClient;
+import org.apache.druid.jdbc.http.SqlRequest;
+import org.apache.druid.jdbc.http.TestQueryResultsIterator;
+import org.hamcrest.MatcherAssert;
+import org.hamcrest.Matchers;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.sql.Array;
+import java.sql.Connection;
+import java.sql.JDBCType;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.util.List;
+import java.util.Properties;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.lenient;
+import static org.mockito.Mockito.verify;
+
+@ExtendWith(MockitoExtension.class)
+public class DruidConnectionTest
+{
+ private static final String DEFAULT_URL = "jdbc:druid:http://localhost:8888/druid/v2/sql/";
+ private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
+
+ @Mock
+ private DruidHttpClient mockHttpClient;
+
+ @BeforeEach
+ public void setUp() throws SQLException
+ {
+ lenient().when(mockHttpClient.runQuery(any())).thenAnswer(
+ invocation -> new TestQueryResultsIterator(
+ List.of(new ColumnMetadata("EXPR$0", JDBCType.INTEGER)),
+ List.<Object[]>of(new Object[]{1})
+ )
+ );
+ }
+
+ private DruidConnection newConnection() throws SQLException
+ {
... 6601 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org