diff --git a/client-v2/src/main/java/com/clickhouse/client/api/Client.java b/client-v2/src/main/java/com/clickhouse/client/api/Client.java index f7dc49519..b0930a6ae 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/Client.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/Client.java @@ -89,6 +89,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -1992,13 +1993,6 @@ public CompletableFuture query(String sqlQuery, Map parser expects @@ -2011,6 +2005,58 @@ public CompletableFuture query(String sqlQuery, Map httpClientHelper.createRequest(endpoint, requestSettings.getAllSettings(), sqlQuery), + null); + } + + /** + * Sends a SQL request whose body is written directly to the HTTP output stream through {@link DataStreamWriter}. + * Use this when the SQL request body is large (for example a batched {@code INSERT ... VALUES} statement) to avoid + * building the full SQL text as one {@link String} in memory. + * + * @param sqlWriter writer that emits the UTF-8 SQL request body + * @param settings query operation settings (optional) + * @return {@code CompletableFuture} - a promise to query response + */ + public CompletableFuture queryStream(DataStreamWriter sqlWriter, QuerySettings settings) { + return queryStream(null, sqlWriter, settings); + } + + /** + * Sends a SQL request whose body is written directly to the HTTP output stream through {@link DataStreamWriter}. + * + * @param queryDescription optional short SQL template or description for diagnostics and spans + * @param sqlWriter writer that emits the UTF-8 SQL request body + * @param settings query operation settings (optional) + * @return {@code CompletableFuture} - a promise to query response + */ + public CompletableFuture queryStream(String queryDescription, DataStreamWriter sqlWriter, QuerySettings settings) { + Objects.requireNonNull(sqlWriter, "sqlWriter cannot be null"); + if (settings == null) { + settings = new QuerySettings(); + } + final QuerySettings requestSettings = new QuerySettings(buildRequestSettings(settings.getAllSettings())); + + return queryInternal(queryDescription, requestSettings, + endpoint -> httpClientHelper.createRequest(endpoint, requestSettings.getAllSettings(), out -> { + sqlWriter.onOutput(out); + out.close(); + }), + sqlWriter); + } + + private CompletableFuture queryInternal(String sqlForSpan, + QuerySettings requestSettings, + Function requestFactory, + DataStreamWriter retryCallback) { + applyFormatSpecificSettings(requestSettings); + ClientStatisticsHolder clientStats = new ClientStatisticsHolder(); + // Origin of the duration of a failed operation. Taken where the client starts OP_DURATION, which is + // the duration reported for a successful operation, so that both outcomes measure the same work. + final long operationStartNanos = System.nanoTime(); + clientStats.start(ClientMetrics.OP_DURATION); + if (requestSettings.getQueryId() == null && queryIdGenerator != null) { requestSettings.setQueryId(queryIdGenerator.get()); } @@ -2019,7 +2065,7 @@ public CompletableFuture query(String sqlQuery, Map responseSupplier = () -> { long startTime = System.nanoTime(); // Selecting some node @@ -2029,7 +2075,7 @@ public CompletableFuture query(String sqlQuery, Map query(String sqlQuery, Map'` for cluster-wide cancellation. - Batch execution: Supports batched statements and prepared-statement batches, including multi-row rewrite for eligible `INSERT ... VALUES` statements. -- Prepared statements: Supports `?` parameters through client-side SQL rendering and validates that all parameters are bound before execution. +- Prepared statements: Supports `?` parameters through client-side SQL rendering and validates that all parameters are bound before execution. When `WriterStatementImpl` is not selected, `StreamingPreparedStatementImpl` is enabled by default (`jdbc_streaming_prepared_statement=true`): it uses `FastSqlBatchWriter` and `SqlParameterBinder` to stream UTF-8 SQL bytes through `Client.queryStream(...)` (and fixed-size byte chunks for batches) without constructing a full SQL string in memory. Set `jdbc_streaming_prepared_statement=false` to use the legacy `PreparedStatementImpl` string-building path. - SQL parsing and classification: Classifies SQL to distinguish queries, updates, inserts, `USE`, and role-changing statements, with selectable parser backends. - JDBC escape processing: Translates supported JDBC escape syntax for dates, timestamps, and functions before execution. Escape sequences are only recognized outside of quoted text, so string literals and quoted identifiers — including inlined parameter values that contain `{fn `, `{d '...'}`, or `{ts '...'}` — are passed through unchanged. - Result set streaming: Streams result sets from ClickHouse binary formats and `FORMAT JSONEachRow`, enforces max-row limits, and manages result-set lifecycle correctly. diff --git a/docs/source-map.md b/docs/source-map.md index 39ac30945..101eefb75 100644 --- a/docs/source-map.md +++ b/docs/source-map.md @@ -72,7 +72,7 @@ parser areas (v1 and v2) also have a detail label: `jdbc-metadata` and `sql-pars `ClientException`, `ServerException`, `ClickHouseException`, `ClientFaultCause`, `DataTransferException`; jdbc `SqlExceptionUtils` (v1); data `ClickHouseChecker`. - **JDBC insert** — `jdbc-v2/.../jdbc/` `PreparedStatementImpl`, - `WriterStatementImpl`. v1: `clickhouse-jdbc/.../jdbc/ClickHousePreparedStatement`. + `StreamingPreparedStatementImpl`, `WriterStatementImpl`. v1: `clickhouse-jdbc/.../jdbc/ClickHousePreparedStatement`. - **JDBC read** — `jdbc-v2/.../jdbc/` `ResultSetImpl`, `StatementImpl`. v1: `ClickHouseResultSet`, `ClickHouseStatement`. - **JDBC metadata** — `jdbc-v2/.../jdbc/metadata/` (`DatabaseMetaDataImpl`, diff --git a/history/latest/3523.md b/history/latest/3523.md new file mode 100644 index 000000000..e755a8bca --- /dev/null +++ b/history/latest/3523.md @@ -0,0 +1,11 @@ +- **[client-v2]** Added `Client#queryStream(DataStreamWriter, QuerySettings)` and + `Client#queryStream(String, DataStreamWriter, QuerySettings)` to stream a UTF-8 SQL request body directly to the HTTP + output stream instead of assembling the full SQL text as one `String` in memory. + (https://github.com/ClickHouse/clickhouse-java/issues/3523) +- **[jdbc-v2]** Reduced memory allocations and improved throughput for large parameterized SQL queries and + `INSERT ... VALUES (...)` batches (for example, batches with SQL functions where `beta.row_binary_for_simple_insert` + cannot be used). `Connection#prepareStatement` now returns `StreamingPreparedStatementImpl` by default + (`jdbc_streaming_prepared_statement=true`), which writes parameters directly as UTF-8 bytes to the HTTP request + stream or fixed-size 64 KB batch chunks instead of building and copying intermediate `StringBuilder` and `String` + buffers. Set `jdbc_streaming_prepared_statement=false` to revert to the legacy `PreparedStatementImpl` string path. + (https://github.com/ClickHouse/clickhouse-java/issues/3523) diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java index 35542a0ec..89df1347d 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/ConnectionImpl.java @@ -479,6 +479,9 @@ public PreparedStatement prepareStatement(String sql, int resultSetType, int res return new WriterStatementImpl(this, sql, tableSchema, parsedStatement); } } + if (config.isFlagSet(DriverProperties.STREAMING_PREPARED_STATEMENT)) { + return new StreamingPreparedStatementImpl(this, sql, parsedStatement); + } return new PreparedStatementImpl(this, sql, parsedStatement); } diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java index 8bbcfd10b..eaf23299f 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java @@ -221,6 +221,15 @@ public enum DriverProperties { + "array level. Set to false to return the innermost type that is not an array.") MULTI_DIMENSIONAL_ARRAY_ELEMENT_TYPE("jdbc_multi_dimensional_array_element_type", String.valueOf(Boolean.TRUE)), + /** + * Uses the streaming {@link java.sql.PreparedStatement} implementation ({@link StreamingPreparedStatementImpl}) for + * parameterized SQL statements instead of building full SQL strings in memory. + * Default: true + */ + @ConfigDescription("Uses the streaming PreparedStatement implementation for parameterized queries and writes, " + + "serializing parameters directly to UTF-8 bytes instead of building large SQL strings in memory.") + STREAMING_PREPARED_STATEMENT("jdbc_streaming_prepared_statement", String.valueOf(Boolean.TRUE)), + ; diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/PreparedStatementImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/PreparedStatementImpl.java index 7bf67034a..2bb36232b 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/PreparedStatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/PreparedStatementImpl.java @@ -70,20 +70,25 @@ public class PreparedStatementImpl extends StatementImpl implements PreparedStat protected final Calendar defaultCalendar; - private final String originalSql; + protected final String originalSql; private final String[] values; // temp value holder (set can be called > once) private final List batchValues; // composed value statements - private final ParsedPreparedStatement parsedPreparedStatement; + protected final ParsedPreparedStatement parsedPreparedStatement; private final boolean insertStmtWithValues; private final String valueListTmpl; private final int[] paramPositionsInDataClause; - private final int argCount; + protected final int argCount; private final ParameterMetaData parameterMetaData; private ResultSetMetaData resultSetMetaData = null; public PreparedStatementImpl(ConnectionImpl connection, String sql, ParsedPreparedStatement parsedStatement) throws SQLException { + this(connection, sql, parsedStatement, true); + } + + protected PreparedStatementImpl(ConnectionImpl connection, String sql, ParsedPreparedStatement parsedStatement, + boolean allocateLegacyBuffers) throws SQLException { super(connection); this.isPoolable = true; // PreparedStatement is poolable by default this.originalSql = sql; @@ -91,8 +96,18 @@ public PreparedStatementImpl(ConnectionImpl connection, String sql, ParsedPrepar this.argCount = parsedStatement.getArgCount(); this.defaultCalendar = connection.defaultCalendar; + this.parameterMetaData = new ParameterMetaDataImpl(this.argCount); + + if (!allocateLegacyBuffers) { + this.values = null; + this.paramPositionsInDataClause = new int[0]; + this.batchValues = Collections.emptyList(); + this.valueListTmpl = ""; + this.insertStmtWithValues = false; + return; + } + this.values = new String[argCount]; - this.parameterMetaData = new ParameterMetaDataImpl(this.values.length); int valueListStartPos = parsedStatement.getAssignValuesListStartPosition(); int valueListStopPos = parsedStatement.getAssignValuesListStopPosition(); @@ -156,6 +171,14 @@ public int executeUpdate() throws SQLException { return (int) super.executeUpdateImpl(buildSQL(), localSettings); } + protected void setParameterValue(int parameterIndex, Object x) throws SQLException { + setParameterValue(parameterIndex, x, null); + } + + protected void setParameterValue(int parameterIndex, Object x, Long length) throws SQLException { + values[parameterIndex - 1] = encodeObject(x, length); + } + @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { ensureOpen(); @@ -165,61 +188,61 @@ public void setNull(int parameterIndex, int sqlType) throws SQLException { @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setShort(int parameterIndex, short x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setInt(int parameterIndex, int x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setLong(int parameterIndex, long x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setString(int parameterIndex, String x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override @@ -246,7 +269,7 @@ public void setAsciiStream(int parameterIndex, InputStream x, int length) throws @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x, (long) length); + setParameterValue(parameterIndex, x, (long) length); } @Override @@ -270,7 +293,7 @@ public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQ ensureOpen(); isValidForTargetType(x, targetSqlType); - values[parameterIndex-1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override @@ -278,7 +301,7 @@ public void setObject(int parameterIndex, Object x, int targetSqlType, int scale ensureOpen(); isValidForTargetType(x, targetSqlType); - values[parameterIndex-1] = encodeObject(x, (long) scaleOrLength); + setParameterValue(parameterIndex, x, (long) scaleOrLength); } @Override @@ -286,20 +309,20 @@ public void setObject(int parameterIndex, Object x, SQLType targetSqlType) throw ensureOpen(); isValidForTargetType(x, targetSqlType.getVendorTypeNumber()); - values[parameterIndex-1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setObject(int parameterIndex, Object x, SQLType targetSqlType, int scaleOrLength) throws SQLException { ensureOpen(); isValidForTargetType(x, targetSqlType.getVendorTypeNumber()); - values[parameterIndex-1] = encodeObject(x, (long) scaleOrLength); + setParameterValue(parameterIndex, x, (long) scaleOrLength); } @Override public void setObject(int parameterIndex, Object x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override @@ -399,19 +422,19 @@ public void setRef(int parameterIndex, Ref x) throws SQLException { @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setClob(int parameterIndex, Clob x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setArray(int parameterIndex, Array x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override @@ -484,33 +507,33 @@ public static String replaceQuestionMarks(String sql, final String replacement) public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { ensureOpen(); TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone(); - values[parameterIndex - 1] = encodeObject(DataTypeUtils.toLocalDate(x, tz)); + setParameterValue(parameterIndex, DataTypeUtils.toLocalDate(x, tz)); } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { ensureOpen(); TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone(); - values[parameterIndex - 1] = encodeObject(DataTypeUtils.toLocalTime(x, tz)); + setParameterValue(parameterIndex, DataTypeUtils.toLocalTime(x, tz)); } @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { ensureOpen(); TimeZone tz = (cal == null ? defaultCalendar : cal).getTimeZone(); - values[parameterIndex - 1] = encodeObject(DataTypeUtils.toZonedDateTime(x, tz)); + setParameterValue(parameterIndex, DataTypeUtils.toZonedDateTime(x, tz)); } @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(null); + setParameterValue(parameterIndex, null); } @Override public void setURL(int parameterIndex, URL x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } /** @@ -537,103 +560,103 @@ public void setRowId(int parameterIndex, RowId x) throws SQLException { @Override public void setNString(int parameterIndex, String x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setNCharacterStream(int parameterIndex, Reader x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x, length); + setParameterValue(parameterIndex, x, length); } @Override public void setNClob(int parameterIndex, NClob x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setClob(int parameterIndex, Reader x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setBlob(int parameterIndex, InputStream x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setNClob(int parameterIndex, Reader x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setSQLXML(int parameterIndex, SQLXML x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x, length); + setParameterValue(parameterIndex, x, length); } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x, length); + setParameterValue(parameterIndex, x, length); } @Override public void setCharacterStream(int parameterIndex, Reader x, long length) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x, length); + setParameterValue(parameterIndex, x, length); } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setCharacterStream(int parameterIndex, Reader x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setNCharacterStream(int parameterIndex, Reader x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setClob(int parameterIndex, Reader x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setBlob(int parameterIndex, InputStream x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override public void setNClob(int parameterIndex, Reader x) throws SQLException { ensureOpen(); - values[parameterIndex - 1] = encodeObject(x); + setParameterValue(parameterIndex, x); } @Override @@ -752,7 +775,7 @@ public final int executeUpdate(String sql, String[] columnNames) throws SQLExcep "executeUpdate(String, String[]) cannot be called in PreparedStatement or CallableStatement!", ExceptionUtils.SQL_STATE_WRONG_OBJECT_TYPE); } - private String encodeObject(Object x) throws SQLException { + protected String encodeObject(Object x) throws SQLException { return encodeObject(x, null); } @@ -761,7 +784,7 @@ private String encodeObject(Object x) throws SQLException { private static final char O_BRACKET = '['; private static final char C_BRACKET = ']'; - private String encodeObject(Object x, Long length) throws SQLException { + protected String encodeObject(Object x, Long length) throws SQLException { try { if (x == null) { return "NULL"; diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java index 4ceb9da88..a8d3c18ca 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java @@ -1,6 +1,7 @@ package com.clickhouse.jdbc; import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.client.api.DataStreamWriter; import com.clickhouse.client.api.ServerException; import com.clickhouse.client.api.data_formats.ClickHouseFormatReader; import com.clickhouse.client.api.data_formats.JSONEachRowFormatReader; @@ -23,6 +24,7 @@ import java.util.Deque; import java.util.List; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -91,6 +93,10 @@ protected void ensureOpen() throws SQLException { } } + protected boolean isEscapeProcessingEnabled() { + return escapeProcessingEnabled; + } + private String parseJdbcEscapeSyntax(String sql) { if (escapeProcessingEnabled) { sql = escapedSQLToNative(sql); @@ -288,6 +294,23 @@ protected String setLastQueryID(String queryId) { protected ResultSetImpl executeQueryImpl(String sql, QuerySettings settings) throws SQLException { ensureOpen(); + String nativeSql = parseJdbcEscapeSyntax(sql); + return executeQueryInternal(nativeSql, settings, + mergedSettings -> connection.getClient().query(nativeSql, mergedSettings)); + } + + protected ResultSetImpl executeQueryStreamImpl(String sqlTemplate, DataStreamWriter writer, QuerySettings settings) throws SQLException { + return executeQueryInternal(sqlTemplate, settings, + mergedSettings -> connection.getClient().queryStream(sqlTemplate, writer, mergedSettings)); + } + + private interface QueryFutureSupplier { + CompletableFuture execute(QuerySettings mergedSettings) throws SQLException; + } + + private ResultSetImpl executeQueryInternal(String sqlForState, QuerySettings settings, + QueryFutureSupplier queryExecutor) throws SQLException { + ensureOpen(); // Closing before trying to do next request. Otherwise, deadlock because previous connection will not be // release before this one completes. @@ -300,16 +323,15 @@ protected ResultSetImpl executeQueryImpl(String sql, QuerySettings settings) thr this.closed = false; } - QuerySettings mergedSettings = QuerySettings.merge(settings, new QuerySettings()); + QuerySettings mergedSettings = QuerySettings.merge(settings, new QuerySettings()); mergedSettings.setQueryId(setLastQueryID(mergedSettings.getQueryId())); QueryResponse response = null; try { - lastStatementSql = parseJdbcEscapeSyntax(sql); - LOG.trace("SQL Query: {}", lastStatementSql); // this is not secure for create statements because of passwords + lastStatementSql = sqlForState; if (queryTimeout == 0) { - response = connection.getClient().query(lastStatementSql, mergedSettings).get(); + response = queryExecutor.execute(mergedSettings).get(); } else { - response = connection.getClient().query(lastStatementSql, mergedSettings).get(queryTimeout, TimeUnit.SECONDS); + response = queryExecutor.execute(mergedSettings).get(queryTimeout, TimeUnit.SECONDS); } ClickHouseFormatReader reader; @@ -420,6 +442,31 @@ protected long executeUpdateImpl(String sql, QuerySettings settings) throws SQLE return updateCount; } + protected long executeUpdateStreamImpl(String sqlTemplate, DataStreamWriter writer, QuerySettings settings) throws SQLException { + ensureOpen(); + + if (resultSetAutoClose) { + closeCurrentResultSet(); + } + + QuerySettings mergedSettings = QuerySettings.merge(connection.getDefaultQuerySettings(), settings); + mergedSettings.setQueryId(setLastQueryID(mergedSettings.getQueryId())); + lastStatementSql = sqlTemplate; + long updateCount = 0; + try (QueryResponse response = queryTimeout == 0 + ? connection.getClient().queryStream(lastStatementSql, writer, mergedSettings).get() + : connection.getClient().queryStream(lastStatementSql, writer, mergedSettings).get(queryTimeout, TimeUnit.SECONDS)) { + updateCount = Math.max(0L, response.getWrittenRows()); + lastQueryId = response.getQueryId(); + } catch (Exception e) { + handleSocketTimeoutException(e); + throwOnExecutionTimeout(e, mergedSettings.getQueryId()); + throw ExceptionUtils.toSqlState(e); + } + + return updateCount; + } + private void postUpdateActions() throws SQLException { if (parsedStatement.getUseDatabase() != null) { this.localSettings.setDatabase(parsedStatement.getUseDatabase()); diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/StreamingPreparedStatementImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StreamingPreparedStatementImpl.java new file mode 100644 index 000000000..79d4529dc --- /dev/null +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StreamingPreparedStatementImpl.java @@ -0,0 +1,457 @@ +package com.clickhouse.jdbc; + +import com.clickhouse.jdbc.internal.ExceptionUtils; +import com.clickhouse.jdbc.internal.ParsedPreparedStatement; +import com.clickhouse.jdbc.internal.fastwriter.FastSqlBatchWriter; +import com.clickhouse.jdbc.internal.fastwriter.SqlParameterBinder; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.TimeZone; +import java.util.UUID; + +/** + * Streaming {@link PreparedStatement} implementation backed by {@link FastSqlBatchWriter} and + * {@link SqlParameterBinder}. + *

+ * Common parameter types are bound directly without boxing or intermediate {@link String} allocations and + * written as UTF-8 bytes directly to the HTTP request stream (for single executions) or fixed-size byte chunks + * (for batches). Complex JDBC types (arrays, tuples, maps, streams, etc.) reuse + * {@link PreparedStatementImpl#encodeObject(Object, Long)} so SQL rendering stays consistent with the legacy path. + */ +public class StreamingPreparedStatementImpl extends PreparedStatementImpl implements PreparedStatement { + + private static final int STREAM_BUFFER_SIZE = 64 * 1024; + private static final long MAX_SAFE_EPOCH_SECONDS = (Long.MAX_VALUE - 999_999_999L) / 1_000_000_000L; + private static final long MIN_SAFE_EPOCH_SECONDS = Long.MIN_VALUE / 1_000_000_000L; + + private final FastSqlBatchWriter rawWriter; + private final FastSqlBatchWriter escapedWriter; + + private final SqlParameterBinder binder; + private final boolean[] paramSet; + private TimeZone cachedTimeZone; + private ZoneId cachedZoneId; + + private FastSqlBatchWriter batchWriter; + private ChunkedByteBuffer batchBuffer; + private int batchRowCount; + private List statementBatch; + + public StreamingPreparedStatementImpl(ConnectionImpl connection, String sql, + ParsedPreparedStatement parsedStatement) throws SQLException { + super(connection, sql, parsedStatement, false); + + this.rawWriter = new FastSqlBatchWriter(originalSql, parsedStatement); + + // JDBC escape syntax (e.g. {d '...'}, {ts '...'}, {fn ...}) can rewrite the SQL text, + // shifting both the VALUES (...) bounds and every '?' offset — and can even turn a + // non-batchable raw statement into a valid single-group INSERT ... VALUES (...) or vice versa. + // Re-parse the translated SQL so escapedWriter owns a CompiledTemplate with exact bounds, + // offsets, and batchability when escape processing is enabled. + FastSqlBatchWriter escaped = this.rawWriter; + if (originalSql.indexOf('{') >= 0) { + String escapedSql = escapedSQLToNative(originalSql); + if (!escapedSql.equals(originalSql)) { + ParsedPreparedStatement escapedParsed = connection.getSqlParser().parsePreparedStatement(escapedSql); + escaped = new FastSqlBatchWriter(escapedSql, escapedParsed); + } + } + this.escapedWriter = escaped; + + this.binder = new SqlParameterBinder(argCount); + this.paramSet = new boolean[argCount]; + } + + // Selected per execution rather than at construction because JDBC allows callers to toggle + // Statement#setEscapeProcessing(boolean) after prepareStatement(sql) returns. + private FastSqlBatchWriter activeWriter() { + return isEscapeProcessingEnabled() ? escapedWriter : rawWriter; + } + + private int checkParamIndex(int parameterIndex) throws SQLException { + int idx = parameterIndex - 1; + if (idx < 0 || idx >= argCount) { + throw new SQLException("Parameter index out of range: " + parameterIndex + + " (expected 1.." + argCount + ")", ExceptionUtils.SQL_STATE_CLIENT_ERROR); + } + return idx; + } + + private void ensureAllParametersSet() throws SQLException { + for (int i = 0; i < argCount; i++) { + if (!paramSet[i]) { + throw new SQLException("Parameter at position '" + (i + 1) + "' is not set"); + } + } + } + + private ZoneId getDefaultZoneId() { + TimeZone tz = defaultCalendar.getTimeZone(); + if (cachedZoneId == null || !tz.equals(cachedTimeZone)) { + cachedTimeZone = tz; + cachedZoneId = tz.toZoneId(); + } + return cachedZoneId; + } + + private void bindEpochNanos(int idx, long epochSeconds, int nano, Object fallbackObject) throws SQLException { + if (epochSeconds >= MIN_SAFE_EPOCH_SECONDS && epochSeconds <= MAX_SAFE_EPOCH_SECONDS) { + binder.setUnixTimestamp64Nano(idx, epochSeconds * 1_000_000_000L + nano); + } else { + binder.setRawSql(idx, encodeObject(fallbackObject)); + } + paramSet[idx] = true; + } + + private void bindObject(int idx, Object x, Long length) throws SQLException { + if (x == null) { + binder.setNull(idx); + } else if (x instanceof String) { + binder.setCharSequence(idx, (String) x); + } else if (x instanceof Integer) { + binder.setInt(idx, ((Integer) x).intValue()); + } else if (x instanceof Long) { + binder.setLong(idx, ((Long) x).longValue()); + } else if (x instanceof Boolean) { + binder.setInt(idx, ((Boolean) x).booleanValue() ? 1 : 0); + } else if (x instanceof Double) { + binder.setDouble(idx, ((Double) x).doubleValue()); + } else if (x instanceof Float) { + binder.setFloat(idx, ((Float) x).floatValue()); + } else if (x instanceof Short) { + binder.setInt(idx, ((Short) x).shortValue()); + } else if (x instanceof Byte) { + binder.setInt(idx, ((Byte) x).byteValue()); + } else if (x instanceof LocalDate) { + binder.setLocalDate(idx, (LocalDate) x); + } else if (x instanceof Date) { + binder.setLocalDate(idx, ((Date) x).toLocalDate()); + } else if (x instanceof Timestamp) { + binder.setLocalDateTime(idx, ((Timestamp) x).toLocalDateTime()); + } else if (x instanceof LocalDateTime) { + LocalDateTime ldt = (LocalDateTime) x; + long epochSeconds = ldt.toEpochSecond(getDefaultZoneId().getRules().getOffset(ldt)); + bindEpochNanos(idx, epochSeconds, ldt.getNano(), ldt); + return; + } else if (x instanceof Instant) { + Instant instant = (Instant) x; + bindEpochNanos(idx, instant.getEpochSecond(), instant.getNano(), instant); + return; + } else if (x instanceof OffsetDateTime) { + Instant instant = ((OffsetDateTime) x).toInstant(); + bindEpochNanos(idx, instant.getEpochSecond(), instant.getNano(), instant); + return; + } else if (x instanceof ZonedDateTime) { + Instant instant = ((ZonedDateTime) x).toInstant(); + bindEpochNanos(idx, instant.getEpochSecond(), instant.getNano(), instant); + return; + } else if (x instanceof UUID) { + binder.setObject(idx, x); + } else { + binder.setRawSql(idx, encodeObject(x, length)); + } + paramSet[idx] = true; + } + + private void writeSingleStatement(OutputStream out, FastSqlBatchWriter writer) throws IOException { + BufferedOutputStream buffered = new BufferedOutputStream(out, STREAM_BUFFER_SIZE); + writer.writeStatement(buffered, binder); + buffered.flush(); + } + + @Override + public ResultSet executeQuery() throws SQLException { + ensureOpen(); + ensureAllParametersSet(); + currentUpdateCount = -1; + final FastSqlBatchWriter writer = activeWriter(); + currentResultSet = executeQueryStreamImpl(originalSql, + out -> writeSingleStatement(out, writer), localSettings); + if (currentResultSet == null) { + throw new SQLException("executeQuery() requires a ResultSet; use execute() for statements that do not produce one.", + ExceptionUtils.SQL_STATE_CLIENT_ERROR); + } + return currentResultSet; + } + + @Override + public int executeUpdate() throws SQLException { + return (int) executeLargeUpdate(); + } + + @Override + public long executeLargeUpdate() throws SQLException { + ensureOpen(); + ensureAllParametersSet(); + final FastSqlBatchWriter writer = activeWriter(); + return executeUpdateStreamImpl(originalSql, + out -> writeSingleStatement(out, writer), localSettings); + } + + @Override + public boolean execute() throws SQLException { + ensureOpen(); + ensureAllParametersSet(); + currentUpdateCount = -1; + final FastSqlBatchWriter writer = activeWriter(); + if (parsedPreparedStatement.isHasResultSet()) { + currentResultSet = executeQueryStreamImpl(originalSql, + out -> writeSingleStatement(out, writer), localSettings); + return currentResultSet != null; + } else { + currentUpdateCount = executeUpdateStreamImpl(originalSql, + out -> writeSingleStatement(out, writer), localSettings); + return false; + } + } + + @Override + public void addBatch() throws SQLException { + ensureOpen(); + ensureAllParametersSet(); + FastSqlBatchWriter writer = activeWriter(); + try { + if (writer.isInsertValuesBatchable()) { + if (batchBuffer == null) { + batchBuffer = new ChunkedByteBuffer(); + } + if (batchRowCount == 0) { + batchWriter = writer; + } else { + batchBuffer.write(','); + } + writer.writeRow(batchBuffer, binder); + batchRowCount++; + } else { + if (statementBatch == null) { + statementBatch = new ArrayList<>(); + } + ChunkedByteBuffer entry = new ChunkedByteBuffer(); + writer.writeStatement(entry, binder); + statementBatch.add(entry); + } + } catch (IOException e) { + throw new SQLException("Error buffering batch row", ExceptionUtils.SQL_STATE_SQL_ERROR, e); + } + } + + @Override + public void clearBatch() throws SQLException { + super.clearBatch(); + batchWriter = null; + if (batchBuffer != null) { + batchBuffer.reset(); + } + batchRowCount = 0; + if (statementBatch != null) { + statementBatch.clear(); + } + } + + @Override + public int[] executeBatch() throws SQLException { + long[] large = executeLargeBatch(); + int[] results = new int[large.length]; + for (int i = 0; i < large.length; i++) { + results[i] = (int) large[i]; + } + return results; + } + + @Override + public long[] executeLargeBatch() throws SQLException { + ensureOpen(); + if (batchRowCount > 0) { + int rowCount = batchRowCount; + long updateCount = executeBatchStream(); + long[] results = new long[rowCount]; + Arrays.fill(results, updateCount == rowCount ? 1L : Statement.SUCCESS_NO_INFO); + clearBatch(); + return results; + } + if (statementBatch == null || statementBatch.isEmpty()) { + return new long[0]; + } + long[] results = new long[statementBatch.size()]; + for (int i = 0; i < statementBatch.size(); i++) { + final ChunkedByteBuffer entry = statementBatch.get(i); + results[i] = executeUpdateStreamImpl(originalSql, entry::writeTo, localSettings); + } + clearBatch(); + return results; + } + + private long executeBatchStream() throws SQLException { + final FastSqlBatchWriter writer = batchWriter != null ? batchWriter : activeWriter(); + final ChunkedByteBuffer buffer = batchBuffer; + return executeUpdateStreamImpl(originalSql, out -> { + writer.writePrefix(out); + buffer.writeTo(out); + writer.writeSuffix(out); + }, localSettings); + } + + @Override + public void clearParameters() throws SQLException { + ensureOpen(); + binder.reset(); + Arrays.fill(paramSet, false); + } + + @Override + public void close() throws SQLException { + super.close(); + batchWriter = null; + batchBuffer = null; + batchRowCount = 0; + statementBatch = null; + binder.reset(); + Arrays.fill(paramSet, false); + } + + @Override + protected void setParameterValue(int parameterIndex, Object x, Long length) throws SQLException { + bindObject(checkParamIndex(parameterIndex), x, length); + } + + @Override + public void setBoolean(int parameterIndex, boolean x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setInt(idx, x ? 1 : 0); + paramSet[idx] = true; + } + + @Override + public void setByte(int parameterIndex, byte x) throws SQLException { + setInt(parameterIndex, x); + } + + @Override + public void setShort(int parameterIndex, short x) throws SQLException { + setInt(parameterIndex, x); + } + + @Override + public void setInt(int parameterIndex, int x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setInt(idx, x); + paramSet[idx] = true; + } + + @Override + public void setLong(int parameterIndex, long x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setLong(idx, x); + paramSet[idx] = true; + } + + @Override + public void setFloat(int parameterIndex, float x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setFloat(idx, x); + paramSet[idx] = true; + } + + @Override + public void setDouble(int parameterIndex, double x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setDouble(idx, x); + paramSet[idx] = true; + } + + @Override + public void setString(int parameterIndex, String x) throws SQLException { + ensureOpen(); + int idx = checkParamIndex(parameterIndex); + binder.setCharSequence(idx, x); + paramSet[idx] = true; + } + + /** + * Fixed-chunk {@link OutputStream} for batch row buffering without array-resizing copies. + */ + private static final class ChunkedByteBuffer extends OutputStream { + private static final int CHUNK_SIZE = 64 * 1024; + private final List chunks = new ArrayList<>(); + private byte[] current; + private int pos; + + ChunkedByteBuffer() { + this.current = new byte[CHUNK_SIZE]; + this.chunks.add(this.current); + } + + @Override + public void write(int b) { + if (pos == current.length) { + nextChunk(); + } + current[pos++] = (byte) b; + } + + @Override + public void write(byte[] b, int off, int len) { + int remaining = len; + int srcPos = off; + while (remaining > 0) { + int space = current.length - pos; + if (space == 0) { + nextChunk(); + space = current.length; + } + int toCopy = Math.min(space, remaining); + System.arraycopy(b, srcPos, current, pos, toCopy); + pos += toCopy; + srcPos += toCopy; + remaining -= toCopy; + } + } + + private void nextChunk() { + current = new byte[CHUNK_SIZE]; + chunks.add(current); + pos = 0; + } + + void writeTo(OutputStream out) throws IOException { + int lastIdx = chunks.size() - 1; + for (int i = 0; i < lastIdx; i++) { + byte[] chunk = chunks.get(i); + out.write(chunk, 0, chunk.length); + } + if (pos > 0) { + out.write(chunks.get(lastIdx), 0, pos); + } + } + + void reset() { + byte[] first = chunks.get(0); + chunks.clear(); + chunks.add(first); + current = first; + pos = 0; + } + } +} diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java index c452f0db6..dae7afc3d 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/SqlParserFacade.java @@ -606,7 +606,7 @@ public void enterViewParam(ClickHouseParser.ViewParamContext ctx) { } } - private static void parseParameters(String originalQuery, ParsedPreparedStatement stmt) { + public static void parseParameters(String originalQuery, ParsedPreparedStatement stmt) { int len = originalQuery.length(); for (int i = 0; i < len; i++) { char ch = originalQuery.charAt(i); diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriter.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriter.java new file mode 100644 index 000000000..10c5c8986 --- /dev/null +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriter.java @@ -0,0 +1,463 @@ +package com.clickhouse.jdbc.internal.fastwriter; + +import com.clickhouse.jdbc.internal.ParsedPreparedStatement; +import com.clickhouse.jdbc.internal.SqlParserFacade; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Objects; + +/** + * Near-zero-allocation SQL row writer that compiles a parameterized SQL template into pre-encoded UTF-8 + * byte segments once at construction time and streams bound row values directly to an {@link OutputStream}. + *

+ * Parameter placeholder positions are determined using {@link SqlParserFacade#parseParameters(String, ParsedPreparedStatement)}, + * matching {@link com.clickhouse.jdbc.PreparedStatementImpl} so quoted literals, comments, heredocs, and + * ternary expressions are handled consistently. + *

+ * The compiled template ({@code staticParts}) is immutable and can be shared across threads via + * {@link #newWriter()}, while each writer instance holds a reusable per-instance numeric scratch buffer + * and must be confined to a single thread. + *

+ * Callers should wrap unbuffered target streams (such as {@code FileOutputStream} or socket streams) in a + * {@link java.io.BufferedOutputStream} (32 KB to 64 KB recommended). + */ +public final class FastSqlBatchWriter { + + private static final byte[] EMPTY_BYTES = new byte[0]; + private static final byte[] NULL_BYTES = {'N', 'U', 'L', 'L'}; + private static final byte[] TRUE_BYTES = {'T', 'R', 'U', 'E'}; + private static final byte[] FALSE_BYTES = {'F', 'A', 'L', 'S', 'E'}; + private static final byte[] LONG_MIN_VALUE_BYTES = { + '-', '9', '2', '2', '3', '3', '7', '2', '0', '3', '6', '8', '5', '4', '7', '7', '5', '8', '0', '8' + }; + private static final byte[] FROM_UNIX_TS_64_NANO_PREFIX = { + 'f', 'r', 'o', 'm', 'U', 'n', 'i', 'x', 'T', 'i', 'm', 'e', 's', 't', 'a', 'm', 'p', '6', '4', 'N', 'a', 'n', 'o', '(' + }; + + /** + * Immutable pre-encoded UTF-8 SQL template owned by {@link FastSqlBatchWriter}. + * Can be safely shared across threads via {@link FastSqlBatchWriter#newWriter()}. + */ + public static final class CompiledTemplate { + private final boolean insertValuesBatchable; + private final byte[] prefix; + private final byte[][] staticParts; + private final byte[] suffix; + + private CompiledTemplate(boolean insertValuesBatchable, byte[] prefix, byte[][] staticParts, byte[] suffix) { + this.insertValuesBatchable = insertValuesBatchable; + this.prefix = prefix; + this.staticParts = staticParts; + this.suffix = suffix; + } + + public static CompiledTemplate compile(String sql, ParsedPreparedStatement parsed) { + Objects.requireNonNull(sql, "sql must not be null"); + Objects.requireNonNull(parsed, "parsed must not be null"); + int count = parsed.getArgCount(); + int[] positions = parsed.getParamPositions(); + if (isSingleGroupInsertValues(parsed)) { + int startPos = parsed.getAssignValuesListStartPosition(); + int stopPos = parsed.getAssignValuesListStopPosition(); + String prefix = sql.substring(0, startPos); + String valueList = sql.substring(startPos, stopPos + 1); + String suffix = stopPos + 1 < sql.length() ? sql.substring(stopPos + 1) : ""; + + int[] relPositions = new int[count]; + for (int i = 0; i < count; i++) { + relPositions[i] = positions[i] - startPos; + } + return new CompiledTemplate( + true, + prefix.isEmpty() ? EMPTY_BYTES : prefix.getBytes(StandardCharsets.UTF_8), + compileParts(valueList, relPositions, count), + suffix.isEmpty() ? EMPTY_BYTES : suffix.getBytes(StandardCharsets.UTF_8)); + } + return new CompiledTemplate(false, EMPTY_BYTES, compileParts(sql, positions, count), EMPTY_BYTES); + } + + public static CompiledTemplate compileRow(String sqlTemplate, int[] paramPositions, int argCount) { + Objects.requireNonNull(sqlTemplate, "sqlTemplate must not be null"); + Objects.requireNonNull(paramPositions, "paramPositions must not be null"); + if (argCount < 0 || argCount > paramPositions.length) { + throw new IllegalArgumentException("Invalid argCount: " + argCount); + } + return new CompiledTemplate(false, EMPTY_BYTES, compileParts(sqlTemplate, paramPositions, argCount), EMPTY_BYTES); + } + + public boolean isInsertValuesBatchable() { + return insertValuesBatchable; + } + + public int getParameterCount() { + return staticParts.length - 1; + } + + private static boolean isSingleGroupInsertValues(ParsedPreparedStatement parsedStatement) { + if (!parsedStatement.isInsert() || parsedStatement.isInsertWithSelect() + || parsedStatement.isHasResultSet() || parsedStatement.getAssignValuesGroups() != 1) { + return false; + } + int startPos = parsedStatement.getAssignValuesListStartPosition(); + int stopPos = parsedStatement.getAssignValuesListStopPosition(); + if (startPos < 0 || stopPos <= startPos) { + return false; + } + int[] positions = parsedStatement.getParamPositions(); + for (int i = 0; i < parsedStatement.getArgCount(); i++) { + if (positions[i] < startPos || positions[i] > stopPos) { + return false; + } + } + return true; + } + + private static byte[][] compileParts(String sqlTemplate, int[] paramPositions, int argCount) { + byte[][] parts = new byte[argCount + 1][]; + int start = 0; + for (int i = 0; i < argCount; i++) { + int qIdx = paramPositions[i]; + if (qIdx < start || qIdx >= sqlTemplate.length()) { + throw new IllegalArgumentException( + "Invalid parameter position " + qIdx + " at index " + i + + " for template of length " + sqlTemplate.length()); + } + parts[i] = sqlTemplate.substring(start, qIdx).getBytes(StandardCharsets.UTF_8); + start = qIdx + 1; + } + parts[argCount] = sqlTemplate.substring(start).getBytes(StandardCharsets.UTF_8); + return parts; + } + } + + private final CompiledTemplate template; + private final byte[][] staticParts; + private final byte[] numScratch = new byte[32]; + + public FastSqlBatchWriter(String sqlTemplate) { + Objects.requireNonNull(sqlTemplate, "sqlTemplate must not be null"); + ParsedPreparedStatement parsed = new ParsedPreparedStatement(); + SqlParserFacade.parseParameters(sqlTemplate, parsed); + this.template = CompiledTemplate.compileRow(sqlTemplate, parsed.getParamPositions(), parsed.getArgCount()); + this.staticParts = this.template.staticParts; + } + + public FastSqlBatchWriter(String sqlTemplate, ParsedPreparedStatement parsedStatement) { + this(CompiledTemplate.compile(sqlTemplate, parsedStatement)); + } + + public FastSqlBatchWriter(String sqlTemplate, int[] paramPositions, int argCount) { + this(CompiledTemplate.compileRow(sqlTemplate, paramPositions, argCount)); + } + + private FastSqlBatchWriter(CompiledTemplate template) { + this.template = Objects.requireNonNull(template, "template must not be null"); + this.staticParts = template.staticParts; + } + + public static FastSqlBatchWriter of(CompiledTemplate template) { + return new FastSqlBatchWriter(template); + } + + /** + * Creates a new writer instance sharing this instance's immutable compiled UTF-8 template with its own + * thread-confined scratch buffer. + * + * @return new {@link FastSqlBatchWriter} sharing the compiled template + */ + public FastSqlBatchWriter newWriter() { + return new FastSqlBatchWriter(this.template); + } + + public CompiledTemplate getTemplate() { + return template; + } + + public boolean isInsertValuesBatchable() { + return template.insertValuesBatchable; + } + + public void writePrefix(OutputStream out) throws IOException { + if (template.prefix.length > 0) { + out.write(template.prefix); + } + } + + public void writeSuffix(OutputStream out) throws IOException { + if (template.suffix.length > 0) { + out.write(template.suffix); + } + } + + public void writeStatement(OutputStream out, SqlParameterBinder binder) throws IOException { + writePrefix(out); + writeRow(out, binder); + writeSuffix(out); + } + + public int getParameterCount() { + return staticParts.length - 1; + } + + public SqlParameterBinder newBinder() { + return new SqlParameterBinder(getParameterCount()); + } + + void validateParameterCount(int actual) { + int expected = staticParts.length - 1; + if (actual != expected) { + throw new IllegalArgumentException( + "Parameter count mismatch: expected " + expected + ", got " + actual); + } + } + + public void writeRow(OutputStream out, Object... params) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + validateParameterCount(params == null ? 0 : params.length); + int expected = staticParts.length - 1; + for (int i = 0; i < expected; i++) { + out.write(staticParts[i]); + writeObjectParam(out, params[i]); + } + out.write(staticParts[expected]); + } + + public void writeRow(OutputStream out, SqlParameterBinder binder) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + validateParameterCount(binder == null ? 0 : binder.size()); + int expected = staticParts.length - 1; + for (int i = 0; i < expected; i++) { + out.write(staticParts[i]); + switch (binder.typeAt(i)) { + case SqlParameterBinder.TYPE_NULL: + out.write(NULL_BYTES); + break; + case SqlParameterBinder.TYPE_BOOLEAN: + out.write(binder.booleanAt(i) ? TRUE_BYTES : FALSE_BYTES); + break; + case SqlParameterBinder.TYPE_LONG: + writeLongAscii(out, binder.longAt(i)); + break; + case SqlParameterBinder.TYPE_FLOAT: + writeAsciiUnquoted(out, Float.toString(binder.floatAt(i))); + break; + case SqlParameterBinder.TYPE_DOUBLE: + writeAsciiUnquoted(out, Double.toString(binder.doubleAt(i))); + break; + case SqlParameterBinder.TYPE_CHAR_SEQUENCE: + writeEscapedCharSequence(out, (CharSequence) binder.refAt(i)); + break; + case SqlParameterBinder.TYPE_LOCAL_DATE: + writeLocalDate(out, (LocalDate) binder.refAt(i)); + break; + case SqlParameterBinder.TYPE_LOCAL_DATE_TIME: + writeLocalDateTime(out, (LocalDateTime) binder.refAt(i)); + break; + case SqlParameterBinder.TYPE_RAW_SQL: + writeRawUtf8(out, (CharSequence) binder.refAt(i)); + break; + case SqlParameterBinder.TYPE_UNIX_TIMESTAMP_64_NANO: + out.write(FROM_UNIX_TS_64_NANO_PREFIX); + writeLongAscii(out, binder.longAt(i)); + out.write(')'); + break; + case SqlParameterBinder.TYPE_OBJECT: + writeEscapedCharSequence(out, binder.refAt(i).toString()); + break; + default: + throw new IllegalStateException("Unknown parameter type: " + binder.typeAt(i)); + } + } + out.write(staticParts[expected]); + } + + public void writeRow(OutputStream out, long p1, CharSequence p2, boolean p3) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + validateParameterCount(3); + out.write(staticParts[0]); + writeLongAscii(out, p1); + out.write(staticParts[1]); + if (p2 == null) { + out.write(NULL_BYTES); + } else { + writeEscapedCharSequence(out, p2); + } + out.write(staticParts[2]); + out.write(p3 ? TRUE_BYTES : FALSE_BYTES); + out.write(staticParts[3]); + } + + private void writeObjectParam(OutputStream out, Object value) throws IOException { + if (value == null) { + out.write(NULL_BYTES); + } else if (value instanceof CharSequence) { + writeEscapedCharSequence(out, (CharSequence) value); + } else if (value instanceof Integer) { + writeLongAscii(out, ((Integer) value).intValue()); + } else if (value instanceof Long) { + writeLongAscii(out, ((Long) value).longValue()); + } else if (value instanceof Boolean) { + out.write(((Boolean) value).booleanValue() ? TRUE_BYTES : FALSE_BYTES); + } else if (value instanceof Double) { + writeAsciiUnquoted(out, Double.toString(((Double) value).doubleValue())); + } else if (value instanceof Float) { + writeAsciiUnquoted(out, Float.toString(((Float) value).floatValue())); + } else if (value instanceof Short) { + writeLongAscii(out, ((Short) value).shortValue()); + } else if (value instanceof Byte) { + writeLongAscii(out, ((Byte) value).byteValue()); + } else if (value instanceof LocalDateTime) { + writeLocalDateTime(out, (LocalDateTime) value); + } else if (value instanceof LocalDate) { + writeLocalDate(out, (LocalDate) value); + } else { + writeEscapedCharSequence(out, value.toString()); + } + } + + private static void writeAsciiUnquoted(OutputStream out, String ascii) throws IOException { + for (int i = 0, len = ascii.length(); i < len; i++) { + out.write(ascii.charAt(i)); + } + } + + private void writeLocalDate(OutputStream out, LocalDate date) throws IOException { + int year = date.getYear(); + if (year < 0 || year > 9999) { + writeEscapedCharSequence(out, date.toString()); + return; + } + byte[] s = numScratch; + s[0] = '\''; + writeFourDigits(s, 1, year); + s[5] = '-'; + writeTwoDigits(s, 6, date.getMonthValue()); + s[8] = '-'; + writeTwoDigits(s, 9, date.getDayOfMonth()); + s[11] = '\''; + out.write(s, 0, 12); + } + + private void writeLocalDateTime(OutputStream out, LocalDateTime dt) throws IOException { + int year = dt.getYear(); + if (year < 0 || year > 9999) { + writeEscapedCharSequence(out, dt.toString()); + return; + } + byte[] s = numScratch; + s[0] = '\''; + writeFourDigits(s, 1, year); + s[5] = '-'; + writeTwoDigits(s, 6, dt.getMonthValue()); + s[8] = '-'; + writeTwoDigits(s, 9, dt.getDayOfMonth()); + s[11] = ' '; + writeTwoDigits(s, 12, dt.getHour()); + s[14] = ':'; + writeTwoDigits(s, 15, dt.getMinute()); + s[17] = ':'; + writeTwoDigits(s, 18, dt.getSecond()); + int pos = 20; + int nano = dt.getNano(); + if (nano != 0) { + s[pos++] = '.'; + int end = pos + 9; + int n = nano; + for (int p = end - 1; p >= pos; p--) { + s[p] = (byte) ('0' + (n % 10)); + n /= 10; + } + while (end > pos && s[end - 1] == '0') { + end--; + } + pos = end; + } + s[pos++] = '\''; + out.write(s, 0, pos); + } + + private static void writeFourDigits(byte[] buf, int offset, int value) { + buf[offset] = (byte) ('0' + (value / 1000)); + buf[offset + 1] = (byte) ('0' + ((value / 100) % 10)); + buf[offset + 2] = (byte) ('0' + ((value / 10) % 10)); + buf[offset + 3] = (byte) ('0' + (value % 10)); + } + + private static void writeTwoDigits(byte[] buf, int offset, int value) { + buf[offset] = (byte) ('0' + (value / 10)); + buf[offset + 1] = (byte) ('0' + (value % 10)); + } + + void writeLongAscii(OutputStream out, long value) throws IOException { + if (value == 0L) { + out.write('0'); + return; + } + if (value == Long.MIN_VALUE) { + out.write(LONG_MIN_VALUE_BYTES); + return; + } + boolean negative = value < 0L; + if (negative) { + value = -value; + } + int pos = numScratch.length; + while (value > 0L) { + numScratch[--pos] = (byte) ('0' + (value % 10L)); + value /= 10L; + } + if (negative) { + numScratch[--pos] = '-'; + } + out.write(numScratch, pos, numScratch.length - pos); + } + + static void writeEscapedCharSequence(OutputStream out, CharSequence seq) throws IOException { + out.write('\''); + writeUtf8(out, seq, true); + out.write('\''); + } + + static void writeRawUtf8(OutputStream out, CharSequence seq) throws IOException { + writeUtf8(out, seq, false); + } + + private static void writeUtf8(OutputStream out, CharSequence seq, boolean escapeSqlString) throws IOException { + final int len = seq.length(); + for (int i = 0; i < len; i++) { + char c = seq.charAt(i); + if (escapeSqlString && (c == '\'' || c == '\\')) { + out.write('\\'); + out.write(c); + } else if (c < 0x80) { + out.write(c); + } else { + int cp = Character.codePointAt(seq, i); + if (cp < 0x800) { + out.write(0xC0 | (cp >> 6)); + out.write(0x80 | (cp & 0x3F)); + } else if (cp < 0x10000) { + if (Character.isSurrogate(c)) { + out.write('?'); + } else { + out.write(0xE0 | (cp >> 12)); + out.write(0x80 | ((cp >> 6) & 0x3F)); + out.write(0x80 | (cp & 0x3F)); + } + } else { + out.write(0xF0 | (cp >> 18)); + out.write(0x80 | ((cp >> 12) & 0x3F)); + out.write(0x80 | ((cp >> 6) & 0x3F)); + out.write(0x80 | (cp & 0x3F)); + if (Character.isHighSurrogate(c) && i + 1 < len) { + i++; + } + } + } + } + } +} diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/MultiRowSqlBatchWriter.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/MultiRowSqlBatchWriter.java new file mode 100644 index 000000000..72db5b867 --- /dev/null +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/MultiRowSqlBatchWriter.java @@ -0,0 +1,130 @@ +package com.clickhouse.jdbc.internal.fastwriter; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +/** + * Multi-row {@code INSERT ... VALUES (...), (...)} batch writer built on top of {@link FastSqlBatchWriter}. + *

+ * Pre-encodes {@code header}, {@code rowDelimiter}, {@code footer}, and {@code rowTemplate} to UTF-8 bytes once + * at initialization. Call {@link #beginBatch(OutputStream)}, one or more {@code writeRow(...)} overloads, and + * {@link #endBatch(OutputStream)}. + *

+ * Immutable pre-encoded templates can be shared across threads via {@link #newWriter()}; each writer instance + * maintains its own batch state and scratch buffer and must be confined to a single thread. + */ +public final class MultiRowSqlBatchWriter { + + private static final byte[] EMPTY_BYTES = new byte[0]; + + private final byte[] headerBytes; + private final byte[] delimiterBytes; + private final byte[] footerBytes; + private final FastSqlBatchWriter rowWriter; + + private boolean batchOpen; + private int rowCount; + + public MultiRowSqlBatchWriter(String header, String rowTemplate, String rowDelimiter, String footer) { + Objects.requireNonNull(header, "header must not be null"); + Objects.requireNonNull(rowTemplate, "rowTemplate must not be null"); + Objects.requireNonNull(rowDelimiter, "rowDelimiter must not be null"); + this.headerBytes = header.isEmpty() ? EMPTY_BYTES : header.getBytes(StandardCharsets.UTF_8); + this.delimiterBytes = rowDelimiter.isEmpty() ? EMPTY_BYTES : rowDelimiter.getBytes(StandardCharsets.UTF_8); + this.footerBytes = (footer == null || footer.isEmpty()) ? EMPTY_BYTES : footer.getBytes(StandardCharsets.UTF_8); + this.rowWriter = new FastSqlBatchWriter(rowTemplate); + } + + private MultiRowSqlBatchWriter(byte[] headerBytes, byte[] delimiterBytes, byte[] footerBytes, + FastSqlBatchWriter rowWriter) { + this.headerBytes = headerBytes; + this.delimiterBytes = delimiterBytes; + this.footerBytes = footerBytes; + this.rowWriter = rowWriter; + } + + /** + * Creates a new multi-row writer sharing the immutable compiled UTF-8 templates with independent batch state + * and numeric scratch buffer. + * + * @return new {@link MultiRowSqlBatchWriter} sharing the compiled templates + */ + public MultiRowSqlBatchWriter newWriter() { + return new MultiRowSqlBatchWriter(headerBytes, delimiterBytes, footerBytes, rowWriter.newWriter()); + } + + public int getParameterCount() { + return rowWriter.getParameterCount(); + } + + public int getRowCount() { + return rowCount; + } + + public SqlParameterBinder newBinder() { + return rowWriter.newBinder(); + } + + public void beginBatch(OutputStream out) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + if (batchOpen) { + throw new IllegalStateException("Batch is already open; call endBatch() before starting a new batch"); + } + if (headerBytes.length > 0) { + out.write(headerBytes); + } + batchOpen = true; + rowCount = 0; + } + + public void writeRow(OutputStream out, Object... params) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + ensureBatchOpen(); + rowWriter.validateParameterCount(params == null ? 0 : params.length); + if (rowCount > 0 && delimiterBytes.length > 0) { + out.write(delimiterBytes); + } + rowWriter.writeRow(out, params); + rowCount++; + } + + public void writeRow(OutputStream out, SqlParameterBinder binder) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + ensureBatchOpen(); + rowWriter.validateParameterCount(binder == null ? 0 : binder.size()); + if (rowCount > 0 && delimiterBytes.length > 0) { + out.write(delimiterBytes); + } + rowWriter.writeRow(out, binder); + rowCount++; + } + + public void writeRow(OutputStream out, long p1, CharSequence p2, boolean p3) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + ensureBatchOpen(); + rowWriter.validateParameterCount(3); + if (rowCount > 0 && delimiterBytes.length > 0) { + out.write(delimiterBytes); + } + rowWriter.writeRow(out, p1, p2, p3); + rowCount++; + } + + public void endBatch(OutputStream out) throws IOException { + Objects.requireNonNull(out, "out must not be null"); + ensureBatchOpen(); + if (footerBytes.length > 0) { + out.write(footerBytes); + } + batchOpen = false; + rowCount = 0; + } + + private void ensureBatchOpen() { + if (!batchOpen) { + throw new IllegalStateException("Batch is not open; call beginBatch() first"); + } + } +} diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/SqlParameterBinder.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/SqlParameterBinder.java new file mode 100644 index 000000000..85679e521 --- /dev/null +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/fastwriter/SqlParameterBinder.java @@ -0,0 +1,200 @@ +package com.clickhouse.jdbc.internal.fastwriter; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Arrays; + +/** + * Reusable, mutable row parameter binder for {@link FastSqlBatchWriter} and {@link MultiRowSqlBatchWriter} + * that stores primitive values without boxing and avoids varargs {@code Object[]} allocations. + *

+ * Instances are stateful and not thread-safe; confine each instance to a single thread and reuse it across rows. + */ +public final class SqlParameterBinder { + + static final byte TYPE_NULL = 0; + static final byte TYPE_BOOLEAN = 1; + static final byte TYPE_LONG = 2; + static final byte TYPE_FLOAT = 3; + static final byte TYPE_DOUBLE = 4; + static final byte TYPE_CHAR_SEQUENCE = 5; + static final byte TYPE_LOCAL_DATE = 6; + static final byte TYPE_LOCAL_DATE_TIME = 7; + static final byte TYPE_OBJECT = 8; + static final byte TYPE_RAW_SQL = 9; + static final byte TYPE_UNIX_TIMESTAMP_64_NANO = 10; + + private final byte[] types; + private final long[] longValues; + private final Object[] refValues; + + public SqlParameterBinder(int parameterCount) { + if (parameterCount < 0) { + throw new IllegalArgumentException("parameterCount must be >= 0: " + parameterCount); + } + this.types = new byte[parameterCount]; + this.longValues = new long[parameterCount]; + this.refValues = new Object[parameterCount]; + } + + public int size() { + return types.length; + } + + public SqlParameterBinder setNull(int index) { + types[index] = TYPE_NULL; + refValues[index] = null; + return this; + } + + public SqlParameterBinder setBoolean(int index, boolean value) { + types[index] = TYPE_BOOLEAN; + longValues[index] = value ? 1L : 0L; + refValues[index] = null; + return this; + } + + public SqlParameterBinder setInt(int index, int value) { + types[index] = TYPE_LONG; + longValues[index] = value; + refValues[index] = null; + return this; + } + + public SqlParameterBinder setLong(int index, long value) { + types[index] = TYPE_LONG; + longValues[index] = value; + refValues[index] = null; + return this; + } + + public SqlParameterBinder setFloat(int index, float value) { + types[index] = TYPE_FLOAT; + longValues[index] = Float.floatToRawIntBits(value); + refValues[index] = null; + return this; + } + + public SqlParameterBinder setDouble(int index, double value) { + types[index] = TYPE_DOUBLE; + longValues[index] = Double.doubleToRawLongBits(value); + refValues[index] = null; + return this; + } + + public SqlParameterBinder setLocalDate(int index, LocalDate value) { + if (value == null) { + return setNull(index); + } + types[index] = TYPE_LOCAL_DATE; + refValues[index] = value; + return this; + } + + public SqlParameterBinder setLocalDateTime(int index, LocalDateTime value) { + if (value == null) { + return setNull(index); + } + types[index] = TYPE_LOCAL_DATE_TIME; + refValues[index] = value; + return this; + } + + public SqlParameterBinder setRawSql(int index, CharSequence rawSql) { + if (rawSql == null) { + return setNull(index); + } + types[index] = TYPE_RAW_SQL; + refValues[index] = rawSql; + return this; + } + + public SqlParameterBinder setUnixTimestamp64Nano(int index, long epochNanos) { + types[index] = TYPE_UNIX_TIMESTAMP_64_NANO; + longValues[index] = epochNanos; + refValues[index] = null; + return this; + } + + public SqlParameterBinder setString(int index, CharSequence value) { + return setCharSequence(index, value); + } + + public SqlParameterBinder setCharSequence(int index, CharSequence value) { + if (value == null) { + return setNull(index); + } + types[index] = TYPE_CHAR_SEQUENCE; + refValues[index] = value; + return this; + } + + public SqlParameterBinder setObject(int index, Object value) { + if (value == null) { + return setNull(index); + } + if (value instanceof CharSequence) { + return setCharSequence(index, (CharSequence) value); + } + if (value instanceof Long) { + return setLong(index, ((Long) value).longValue()); + } + if (value instanceof Integer) { + return setInt(index, ((Integer) value).intValue()); + } + if (value instanceof Boolean) { + return setBoolean(index, ((Boolean) value).booleanValue()); + } + if (value instanceof Double) { + return setDouble(index, ((Double) value).doubleValue()); + } + if (value instanceof Float) { + return setFloat(index, ((Float) value).floatValue()); + } + if (value instanceof Short) { + return setLong(index, ((Short) value).shortValue()); + } + if (value instanceof Byte) { + return setLong(index, ((Byte) value).byteValue()); + } + if (value instanceof LocalDateTime) { + return setLocalDateTime(index, (LocalDateTime) value); + } + if (value instanceof LocalDate) { + return setLocalDate(index, (LocalDate) value); + } + types[index] = TYPE_OBJECT; + refValues[index] = value; + return this; + } + + public SqlParameterBinder reset() { + Arrays.fill(types, TYPE_NULL); + Arrays.fill(refValues, null); + return this; + } + + byte typeAt(int index) { + return types[index]; + } + + long longAt(int index) { + return longValues[index]; + } + + float floatAt(int index) { + return Float.intBitsToFloat((int) longValues[index]); + } + + double doubleAt(int index) { + return Double.longBitsToDouble(longValues[index]); + } + + boolean booleanAt(int index) { + return longValues[index] != 0L; + } + + Object refAt(int index) { + return refValues[index]; + } +} diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/AbstractPreparedStatementTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/AbstractPreparedStatementTest.java new file mode 100644 index 000000000..0d2ba6ee4 --- /dev/null +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/AbstractPreparedStatementTest.java @@ -0,0 +1,2780 @@ +package com.clickhouse.jdbc; + +import com.clickhouse.client.api.Client; +import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.client.api.DataTypeUtils; +import com.clickhouse.client.api.internal.ServerSettings; +import com.clickhouse.client.api.query.QueryResponse; +import com.clickhouse.client.api.query.QuerySettings; +import com.clickhouse.client.testdata.DataTypeGenerator; +import com.clickhouse.client.testdata.GenerateTestDataSet; +import com.clickhouse.client.testdata.GenerateTestDataSet.DataSetEntry; +import com.clickhouse.client.testdata.TestDataSet; +import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; +import com.clickhouse.data.ClickHouseFormat; +import com.clickhouse.data.ClickHouseVersion; +import com.clickhouse.data.Tuple; +import com.clickhouse.jdbc.internal.JdbcUtils; +import com.clickhouse.jdbc.internal.SqlParserFacade; +import org.apache.commons.lang3.RandomStringUtils; +import org.testng.Assert; +import org.testng.SkipException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.sql.Array; +import java.sql.Connection; +import java.sql.Date; +import java.sql.JDBCType; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.SQLType; +import java.sql.Statement; +import java.sql.Timestamp; +import java.sql.Types; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Random; +import java.util.Set; +import java.util.StringJoiner; +import java.util.TimeZone; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertThrows; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.expectThrows; +import static org.testng.Assert.fail; + +/** + * Shared integration test suite for {@link PreparedStatement} implementations. + */ +@Test(groups = {"integration"}) +public abstract class AbstractPreparedStatementTest extends JdbcIntegrationTest { + + private static final Instant MAX_UNIX_NANO_INSTANT = Instant.ofEpochSecond(0, Long.MAX_VALUE); + private static final Pattern TIME_DATASET_TYPE = Pattern.compile("(^|[(, ])Time(64)?\\b"); + + private static final String KNOWN_ISSUE_TIME_FRACTIONAL_SECONDS = + "Time: Duration is encoded with 9 fractional digits, which ClickHouse Time rejects"; + private static final String KNOWN_ISSUE_DATETIME64_OVERFLOW = + "DateTime64: fromUnixTimestamp64Nano(Int64) overflows timestamps after 2262-04-11T23:47:16.854775807Z"; + + private final Set testedCatalogTypes = ConcurrentHashMap.newKeySet(); + private final Set matchedCatalogKnownIssues = ConcurrentHashMap.newKeySet(); + + protected void configureConnectionProperties(Properties properties) { + } + + protected abstract Class expectedPreparedStatementClass(); + + protected abstract String tablePrefix(); + + @Override + public Connection getJdbcConnection(Properties properties) throws SQLException { + Properties merged = new Properties(); + configureConnectionProperties(merged); + if (properties != null) { + merged.putAll(properties); + } + return super.getJdbcConnection(merged); + } + + protected Connection getDefaultJdbcConnection(Properties properties) throws SQLException { + return super.getJdbcConnection(properties); + } + + @DataProvider + protected Object[][] catalogDataSetEntries() { + return GenerateTestDataSet.readDataSetIndex().stream() + .filter(DataSetEntry::isStorable) + .map(entry -> new Object[]{entry}) + .toArray(Object[][]::new); + } + + @Test(dataProvider = "catalogDataSetEntries", groups = {"integration"}) + public void testInsertCatalogDataSet(DataSetEntry entry) throws Exception { + if (TIME_DATASET_TYPE.matcher(entry.getType()).find() + && ClickHouseVersion.of(getServerVersion()).check("(,25.5]")) { + throw new SkipException("Time and Time64 types require ClickHouse 25.6+"); + } + + DataTypeGenerator generator = GenerateTestDataSet.parseType(entry.getType()); + TestDataSet dataSet = TestDataSet.of(generator); + String expectedTsv = readResourceAsLatin1("/datasets/" + entry.getName() + ".tsv"); + ClickHouseColumn valueCol = ClickHouseColumn.of("value", entry.getClickHouseType()); + String table = tablePrefix() + "cat_" + entry.getName(); + + Properties props = new Properties(); + props.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "false"); + props.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + for (Map.Entry setting : dataSet.getRequiredSettings().entrySet()) { + props.setProperty(DriverProperties.serverSetting(setting.getKey()), setting.getValue()); + } + + String insertSql = "INSERT INTO " + table + " (`id`, `value`) VALUES (?, ?)"; + + try (Connection conn = getJdbcConnection(props); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute(dataSet.getCreateTableSql(table, null, isCluster())); + try { + try (PreparedStatement ps = conn.prepareStatement(insertSql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + for (Object[] row : dataSet.getRows()) { + ps.setInt(1, ((Integer) row[0]).intValue()); + ps.setObject(2, adaptDataSetValue(conn, row[1], valueCol)); + ps.addBatch(); + } + int[] batchResult = ps.executeBatch(); + assertEquals(batchResult.length, dataSet.getRows().size()); + } catch (SQLException e) { + if ("Time".equals(entry.getType()) + && e.getMessage() != null + && e.getMessage().contains("Cannot parse string") + && e.getMessage().contains("as Time")) { + matchedCatalogKnownIssues.add(KNOWN_ISSUE_TIME_FRACTIONAL_SECONDS); + testedCatalogTypes.add(entry.getType()); + return; + } + throw e; + } + + Client client = conn.unwrap(ConnectionImpl.class).getClient(); + String actualTsv = readTableAsTsv(client, table, dataSet.getRequiredSettings()); + assertCatalogTsvRowsEqual(entry.getType(), dataSet.getRows(), expectedTsv, actualTsv); + testedCatalogTypes.add(entry.getType()); + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + @Test(groups = {"integration"}, dependsOnMethods = "testInsertCatalogDataSet", alwaysRun = true) + public void testCatalogKnownIssuesAreCurrent() { + if (!testedCatalogTypes.containsAll(GenerateTestDataSet.getStorableTypes())) { + throw new SkipException("Not all catalog datasets were executed"); + } + List resolved = new ArrayList<>(); + for (String issue : Arrays.asList(KNOWN_ISSUE_TIME_FRACTIONAL_SECONDS, KNOWN_ISSUE_DATETIME64_OVERFLOW)) { + if (!matchedCatalogKnownIssues.contains(issue)) { + resolved.add(issue); + } + } + assertTrue(resolved.isEmpty(), + "Known issues no longer reproduce; remove them from AbstractPreparedStatementTest:\n " + + String.join("\n ", resolved)); + } + + @Test(groups = {"integration"}) + public void testInsertMultiColumnDataSet() throws Exception { + TestDataSet dataSet = TestDataSet.builder() + .column("c_int8", GenerateTestDataSet.parseType("Int8")) + .column("c_int16", GenerateTestDataSet.parseType("Int16")) + .column("c_int32", GenerateTestDataSet.parseType("Int32")) + .column("c_int64", GenerateTestDataSet.parseType("Int64")) + .column("c_float32", GenerateTestDataSet.parseType("Float32")) + .column("c_dec", GenerateTestDataSet.parseType("Decimal(18, 6)")) + .column("c_bool", GenerateTestDataSet.parseType("Bool")) + .column("c_str", GenerateTestDataSet.parseType("String")) + .column("c_bin", GenerateTestDataSet.parseType("BinaryString")) + .column("c_null_str", GenerateTestDataSet.parseType("Nullable(String)")) + .column("c_date", GenerateTestDataSet.parseType("Date")) + .column("c_dt", GenerateTestDataSet.parseType("DateTime('America/New_York')")) + .column("c_dt64", GenerateTestDataSet.parseType("DateTime64(9, 'Asia/Kolkata')")) + .column("c_uuid", GenerateTestDataSet.parseType("UUID")) + .column("c_ipv6", GenerateTestDataSet.parseType("IPv6")) + .column("c_enum", GenerateTestDataSet.parseType("Enum16")) + .column("c_arr", GenerateTestDataSet.parseType("Array(Nullable(String))")) + .column("c_tup", GenerateTestDataSet.parseType("Tuple(a Int64, b Nullable(String), c Array(UInt8))")) + .column("c_map", GenerateTestDataSet.parseType("Map(String, Int32)")) + .column("c_tail", GenerateTestDataSet.parseType("Float64")) + .build(); + + List valueCols = new ArrayList<>(); + StringJoiner colNames = new StringJoiner(", "); + StringJoiner placeholders = new StringJoiner(", "); + colNames.add("`id`"); + placeholders.add("?"); + for (Map.Entry col : dataSet.getColumns().entrySet()) { + valueCols.add(ClickHouseColumn.of(col.getKey(), col.getValue().getType())); + colNames.add("`" + col.getKey() + "`"); + placeholders.add("?"); + } + + String table = tablePrefix() + "cat_multi_col"; + Properties props = new Properties(); + props.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "false"); + props.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + for (Map.Entry setting : dataSet.getRequiredSettings().entrySet()) { + props.setProperty(DriverProperties.serverSetting(setting.getKey()), setting.getValue()); + } + + String insertSql = "INSERT INTO " + table + " (" + colNames + ") VALUES (" + placeholders + ")"; + List rows = dataSet.getRows(); + int batchSplit = Math.max(1, rows.size() - 5); + + try (Connection conn = getJdbcConnection(props); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute(dataSet.getCreateTableSql(table, null, isCluster())); + try { + try (PreparedStatement ps = conn.prepareStatement(insertSql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + for (int r = 0; r < batchSplit; r++) { + Object[] row = rows.get(r); + ps.setInt(1, ((Integer) row[0]).intValue()); + for (int c = 0; c < valueCols.size(); c++) { + setTypedParameter(conn, ps, c + 2, row[c + 1], valueCols.get(c)); + } + ps.addBatch(); + } + int[] batchResult = ps.executeBatch(); + assertEquals(batchResult.length, batchSplit); + + for (int r = batchSplit; r < rows.size(); r++) { + Object[] row = rows.get(r); + ps.setInt(1, ((Integer) row[0]).intValue()); + for (int c = 0; c < valueCols.size(); c++) { + setTypedParameter(conn, ps, c + 2, row[c + 1], valueCols.get(c)); + } + assertEquals(ps.executeUpdate(), 1); + } + } + + Client client = conn.unwrap(ConnectionImpl.class).getClient(); + String actualTsv = readTableAsTsv(client, table, dataSet.getRequiredSettings()); + assertTsvRowsEqual("multi-column dataset", dataSet.getTsv(), actualTsv); + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + private static void setTypedParameter(Connection conn, PreparedStatement ps, int index, + Object value, ClickHouseColumn column) throws SQLException { + Object adapted = adaptDataSetValue(conn, value, column); + if (adapted == null) { + ps.setNull(index, Types.OTHER); + } else if (adapted instanceof Boolean) { + ps.setBoolean(index, ((Boolean) adapted).booleanValue()); + } else if (adapted instanceof Byte) { + ps.setByte(index, ((Byte) adapted).byteValue()); + } else if (adapted instanceof Short) { + ps.setShort(index, ((Short) adapted).shortValue()); + } else if (adapted instanceof Integer) { + ps.setInt(index, ((Integer) adapted).intValue()); + } else if (adapted instanceof Long) { + ps.setLong(index, ((Long) adapted).longValue()); + } else if (adapted instanceof Float) { + ps.setFloat(index, ((Float) adapted).floatValue()); + } else if (adapted instanceof Double) { + ps.setDouble(index, ((Double) adapted).doubleValue()); + } else if (adapted instanceof java.math.BigDecimal) { + ps.setBigDecimal(index, (java.math.BigDecimal) adapted); + } else if (adapted instanceof String) { + ps.setString(index, (String) adapted); + } else if (adapted instanceof byte[]) { + ps.setBytes(index, (byte[]) adapted); + } else if (adapted instanceof Array) { + ps.setArray(index, (Array) adapted); + } else { + ps.setObject(index, adapted); + } + } + + private static String readResourceAsLatin1(String resourcePath) throws Exception { + try (InputStream in = GenerateTestDataSet.class.getResourceAsStream(resourcePath)) { + assertNotNull(in, "Missing dataset resource: " + resourcePath); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + return new String(out.toByteArray(), StandardCharsets.ISO_8859_1); + } + } + + private static Object adaptDataSetValue(Connection conn, Object value, ClickHouseColumn column) + throws SQLException { + if (value == null) { + return null; + } + ClickHouseDataType type = column.getDataType(); + if (type == ClickHouseDataType.Point && value instanceof double[]) { + double[] p = (double[]) value; + return new Tuple(p[0], p[1]); + } + if ((type == ClickHouseDataType.Ring || type == ClickHouseDataType.LineString) + && value instanceof double[][]) { + return conn.createArrayOf("Array(Point)", box2d((double[][]) value)); + } + if ((type == ClickHouseDataType.Polygon || type == ClickHouseDataType.MultiLineString) + && value instanceof double[][][]) { + return conn.createArrayOf("Array(Array(Point))", box3d((double[][][]) value)); + } + if (type == ClickHouseDataType.MultiPolygon && value instanceof double[][][][]) { + return conn.createArrayOf("Array(Array(Array(Point)))", box4d((double[][][][]) value)); + } + if (type == ClickHouseDataType.Nested && value instanceof List) { + List rows = (List) value; + List nestedCols = column.getNestedColumns(); + List adapted = new ArrayList<>(rows.size()); + for (Object item : rows) { + List fields = (List) item; + Object[] elements = new Object[fields.size()]; + for (int i = 0; i < fields.size(); i++) { + elements[i] = i < nestedCols.size() + ? adaptDataSetValue(conn, fields.get(i), nestedCols.get(i)) + : fields.get(i); + } + adapted.add(new Tuple(elements)); + } + return adapted; + } + if (type == ClickHouseDataType.Tuple && value instanceof List) { + List list = (List) value; + List nested = column.getNestedColumns(); + Object[] elements = new Object[list.size()]; + for (int i = 0; i < list.size(); i++) { + elements[i] = i < nested.size() + ? adaptDataSetValue(conn, list.get(i), nested.get(i)) + : list.get(i); + } + return new Tuple(elements); + } + if (type == ClickHouseDataType.Array && value instanceof List && !column.getNestedColumns().isEmpty()) { + ClickHouseColumn elemCol = column.getNestedColumns().get(0); + List list = (List) value; + List adapted = new ArrayList<>(list.size()); + for (Object el : list) { + adapted.add(adaptDataSetValue(conn, el, elemCol)); + } + return adapted; + } + if (type == ClickHouseDataType.Map && value instanceof Map && column.getNestedColumns().size() == 2) { + ClickHouseColumn keyCol = column.getNestedColumns().get(0); + ClickHouseColumn valCol = column.getNestedColumns().get(1); + Map adapted = new LinkedHashMap<>(); + for (Map.Entry entry : ((Map) value).entrySet()) { + adapted.put( + adaptDataSetValue(conn, entry.getKey(), keyCol), + adaptDataSetValue(conn, entry.getValue(), valCol)); + } + return adapted; + } + return value; + } + + private static Double[][] box2d(double[][] value) { + Double[][] result = new Double[value.length][]; + for (int i = 0; i < value.length; i++) { + result[i] = new Double[value[i].length]; + for (int j = 0; j < value[i].length; j++) { + result[i][j] = value[i][j]; + } + } + return result; + } + + private static Double[][][] box3d(double[][][] value) { + Double[][][] result = new Double[value.length][][]; + for (int i = 0; i < value.length; i++) { + result[i] = box2d(value[i]); + } + return result; + } + + private static Double[][][][] box4d(double[][][][] value) { + Double[][][][] result = new Double[value.length][][][]; + for (int i = 0; i < value.length; i++) { + result[i] = box3d(value[i]); + } + return result; + } + + private static String readTableAsTsv(Client client, String table, Map settings) throws Exception { + QuerySettings querySettings = new QuerySettings().setFormat(ClickHouseFormat.TabSeparated); + settings.forEach(querySettings::serverSetting); + try (QueryResponse response = client.query("SELECT * FROM " + table + " ORDER BY id", querySettings) + .get(60, TimeUnit.SECONDS); + InputStream in = response.getInputStream()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[8192]; + int n; + while ((n = in.read(buf)) >= 0) { + out.write(buf, 0, n); + } + return new String(out.toByteArray(), StandardCharsets.ISO_8859_1); + } + } + + private void assertCatalogTsvRowsEqual(String typeName, List rows, + String expectedTsv, String actualTsv) { + if (expectedTsv.equals(actualTsv)) { + return; + } + String[] expectedLines = expectedTsv.split("\n", -1); + String[] actualLines = actualTsv.split("\n", -1); + assertEquals(actualLines.length, expectedLines.length, typeName + ": row count mismatch"); + for (int i = 0; i < expectedLines.length; i++) { + if (!actualLines[i].equals(expectedLines[i])) { + if (i < rows.size() && rows.get(i)[1] instanceof ZonedDateTime + && ((ZonedDateTime) rows.get(i)[1]).toInstant().isAfter(MAX_UNIX_NANO_INSTANT)) { + matchedCatalogKnownIssues.add(KNOWN_ISSUE_DATETIME64_OVERFLOW); + continue; + } + assertEquals(actualLines[i], expectedLines[i], typeName + ": mismatch at row " + i); + } + } + } + + private static void assertTsvRowsEqual(String suiteName, String expectedTsv, String actualTsv) { + if (expectedTsv.equals(actualTsv)) { + return; + } + String[] expectedLines = expectedTsv.split("\n", -1); + String[] actualLines = actualTsv.split("\n", -1); + assertEquals(actualLines.length, expectedLines.length, suiteName + ": row count mismatch"); + for (int i = 0; i < expectedLines.length; i++) { + assertEquals(actualLines[i], expectedLines[i], suiteName + ": mismatch at row " + i); + } + } + + @Test(groups = {"integration"}) + public void testInsertWithFunctionsAndExpressions() throws Exception { + String table = tablePrefix() + "functions"; + Properties props = new Properties(); + props.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + + try (Connection conn = getJdbcConnection(props); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute("CREATE TABLE " + table + + " (id Int32, ts DateTime, abs_v Int32, upper_s String, expr_v Int64, tail Float64) ORDER BY id"); + try { + String sql = "INSERT INTO " + table + + " (id, ts, abs_v, upper_s, expr_v, tail) VALUES (?, now(), abs(?), upper(?), ? + 100, ?)"; + + try (PreparedStatement ps = conn.prepareStatement(sql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + + ps.setInt(1, 1); + ps.setInt(2, -42); + ps.setString(3, "single'row\\test"); + ps.setLong(4, 10L); + ps.setDouble(5, 1.25d); + assertEquals(ps.executeUpdate(), 1); + + ps.setInt(1, 2); + ps.setInt(2, -7); + ps.setString(3, "largeUpdate"); + ps.setLong(4, 20L); + ps.setDouble(5, 2.5d); + assertEquals(ps.executeLargeUpdate(), 1L); + + ps.setInt(1, 3); + ps.setInt(2, -9); + ps.setString(3, "executeCall"); + ps.setLong(4, 30L); + ps.setDouble(5, 3.75d); + assertFalse(ps.execute()); + assertEquals(ps.getUpdateCount(), 1); + + for (int i = 4; i <= 8; i++) { + ps.setInt(1, i); + ps.setInt(2, -i * 10); + ps.setString(3, "batch_" + i); + ps.setLong(4, i * 100L); + ps.setDouble(5, i + 0.5d); + ps.addBatch(); + } + int[] batchRes = ps.executeBatch(); + assertEquals(batchRes.length, 5); + for (int r : batchRes) { + assertEquals(r, 1); + } + + ps.setInt(1, 9); + ps.setInt(2, -99); + ps.setString(3, "largeBatch"); + ps.setLong(4, 900L); + ps.setDouble(5, 9.5d); + ps.addBatch(); + long[] largeBatchRes = ps.executeLargeBatch(); + assertEquals(largeBatchRes, new long[]{1L}); + } + + String literalSql = "INSERT INTO " + table + + " (id, ts, abs_v, upper_s, expr_v, tail) VALUES (10, now(), abs(-100), upper('lit'), 1000 + 100, 10.5)"; + try (PreparedStatement ps = conn.prepareStatement(literalSql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + assertEquals(ps.executeUpdate(), 1); + } + + try (ResultSet rs = st.executeQuery("SELECT id, ts, abs_v, upper_s, expr_v, tail FROM " + table + " ORDER BY id")) { + int rowCount = 0; + while (rs.next()) { + rowCount++; + int id = rs.getInt(1); + assertEquals(id, rowCount); + assertNotNull(rs.getTimestamp(2)); + if (id == 1) { + assertEquals(rs.getInt(3), 42); + assertEquals(rs.getString(4), "SINGLE'ROW\\TEST"); + assertEquals(rs.getLong(5), 110L); + assertEquals(rs.getDouble(6), 1.25d); + } else if (id == 2) { + assertEquals(rs.getInt(3), 7); + assertEquals(rs.getString(4), "LARGEUPDATE"); + assertEquals(rs.getLong(5), 120L); + assertEquals(rs.getDouble(6), 2.5d); + } else if (id == 3) { + assertEquals(rs.getInt(3), 9); + assertEquals(rs.getString(4), "EXECUTECALL"); + assertEquals(rs.getLong(5), 130L); + assertEquals(rs.getDouble(6), 3.75d); + } else if (id <= 8) { + assertEquals(rs.getInt(3), id * 10); + assertEquals(rs.getString(4), "BATCH_" + id); + assertEquals(rs.getLong(5), id * 100L + 100L); + assertEquals(rs.getDouble(6), id + 0.5d); + } else if (id == 9) { + assertEquals(rs.getInt(3), 99); + assertEquals(rs.getString(4), "LARGEBATCH"); + assertEquals(rs.getLong(5), 1000L); + assertEquals(rs.getDouble(6), 9.5d); + } else { + assertEquals(rs.getInt(3), 100); + assertEquals(rs.getString(4), "LIT"); + assertEquals(rs.getLong(5), 1100L); + assertEquals(rs.getDouble(6), 10.5d); + } + } + assertEquals(rowCount, 10); + } + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + @DataProvider + protected Object[][] testBatchInsertTextStatement_dp() { + return new Object[][]{ + {"INSERT INTO \n `%s` \nVALUES (?, ?, ?, ?)"}, + {" INSERT INTO %s (ts, v1, v2, v3) VALUES (?, ?, ?, ?)"}, + }; + } + + @Test(dataProvider = "testBatchInsertTextStatement_dp", groups = {"integration"}) + public void testBatchInsertTextStatement(String sql) throws Exception { + String table = tablePrefix() + "batch_text"; + long seed = System.currentTimeMillis(); + Random rnd = new Random(seed); + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE TABLE IF NOT EXISTS " + table + + " ( ts DateTime DEFAULT now(), v1 Int32, v2 Float32, v3 Int32) ORDER BY ()"); + } + + final int nBatches = 10; + try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { + Assert.assertEquals(stmt.getClass(), expectedPreparedStatementClass()); + for (int bI = 0; bI < nBatches; bI++) { + stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS))); + stmt.setInt(2, rnd.nextInt()); + stmt.setFloat(3, rnd.nextFloat()); + stmt.setInt(4, rnd.nextInt()); + stmt.addBatch(); + } + + int[] result = stmt.executeBatch(); + for (int r : result) { + Assert.assertEquals(r, 1); + } + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) { + int count = 0; + while (rs.next()) { + assertNotNull(rs.getTimestamp(1)); + assertTrue(rs.getInt(2) != 0); + assertTrue(rs.getFloat(3) != 0.0f); + assertTrue(rs.getInt(4) != 0); + count++; + } + assertEquals(count, nBatches); + + stmt.execute("TRUNCATE " + table); + } + } + } + + @DataProvider + protected Object[][] batchInsertReuseProvider() { + return new Object[][]{ + {"batch_novalues_reuse", "INSERT INTO %s (v1, v2) VALUES (?, ?)", false}, + {"batch_values_reuse", "INSERT INTO %s (v1, v2) VALUES (1, ?)", true}, + }; + } + + @Test(dataProvider = "batchInsertReuseProvider", groups = {"integration"}) + public void testBatchInsertReuse(String tableSuffix, String sql, boolean fixedFirstColumn) throws Exception { + String table = tablePrefix() + tableSuffix; + Random rnd = new Random(System.currentTimeMillis()); + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + stmt.execute("CREATE TABLE " + table + " (v1 Int32, v2 Int32) ORDER BY tuple()"); + } + + final int nBatches = 10; + try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { + Assert.assertEquals(stmt.getClass(), expectedPreparedStatementClass()); + stmt.setString(1, "invalid"); + if (!fixedFirstColumn) { + stmt.setInt(2, rnd.nextInt()); + } + stmt.addBatch(); + assertThrows(SQLException.class, stmt::executeBatch); + assertThrows(SQLException.class, stmt::executeBatch); + stmt.clearBatch(); + + for (int step = 0; step < 2; step++) { + for (int bI = 0; bI < (nBatches >> 1); bI++) { + stmt.setInt(1, rnd.nextInt()); + if (!fixedFirstColumn) { + stmt.setInt(2, rnd.nextInt()); + } + stmt.addBatch(); + } + + int[] result = stmt.executeBatch(); + for (int r : result) { + Assert.assertEquals(r, 1); + } + } + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) { + int count = 0; + while (rs.next()) { + if (fixedFirstColumn) { + assertEquals(rs.getInt(1), 1); + } else { + assertTrue(rs.getInt(1) != 0); + } + assertTrue(rs.getInt(2) != 0); + count++; + } + assertEquals(count, nBatches); + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + } + + @DataProvider + protected Object[][] compressionModesDataProvider() { + return new Object[][]{ + {false, false}, + {true, false}, + {true, true}, + }; + } + + @Test(dataProvider = "compressionModesDataProvider", groups = {"integration"}) + public void testLargeBatchAndCompression(boolean compressClientRequest, + boolean useHttpCompression) throws Exception { + String table = tablePrefix() + "large_" + compressClientRequest + "_" + useHttpCompression; + Properties props = new Properties(); + props.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + props.setProperty(ClientConfigProperties.COMPRESS_CLIENT_REQUEST.getKey(), String.valueOf(compressClientRequest)); + props.setProperty(ClientConfigProperties.USE_HTTP_COMPRESSION.getKey(), String.valueOf(useHttpCompression)); + + final int firstBatchSize = 5_000; + final int secondBatchSize = 100; + final String padding = "payload_'\\UTF8_тест_01234567890123456789012345678901234567890123456789"; + + try (Connection conn = getJdbcConnection(props); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute("CREATE TABLE " + table + + " (id Int32, label String, payload String, computed Int64, tail Float64) ORDER BY id"); + try { + String sql = "INSERT INTO " + table + + " (id, label, payload, computed, tail) VALUES (?, upper(?), ?, ? * 2, ?)"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + + for (int i = 0; i < firstBatchSize; i++) { + ps.setInt(1, i); + ps.setString(2, "row_" + i); + ps.setString(3, padding + "_" + i); + ps.setLong(4, i); + ps.setDouble(5, i + 0.25d); + ps.addBatch(); + } + int[] res1 = ps.executeBatch(); + assertEquals(res1.length, firstBatchSize); + for (int r : res1) { + assertEquals(r, 1); + } + + for (int i = firstBatchSize; i < firstBatchSize + secondBatchSize; i++) { + ps.setInt(1, i); + ps.setString(2, "row_" + i); + ps.setString(3, padding + "_" + i); + ps.setLong(4, i); + ps.setDouble(5, i + 0.25d); + ps.addBatch(); + } + int[] res2 = ps.executeBatch(); + assertEquals(res2.length, secondBatchSize); + } + + int totalRows = firstBatchSize + secondBatchSize; + long expectedSum = (long) totalRows * (totalRows - 1); + try (ResultSet rs = st.executeQuery( + "SELECT count(), sum(computed), min(id), max(id) FROM " + table)) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), totalRows); + assertEquals(rs.getLong(2), expectedSum); + assertEquals(rs.getInt(3), 0); + assertEquals(rs.getInt(4), totalRows - 1); + } + + try (ResultSet rs = st.executeQuery( + "SELECT id, label, payload, computed, tail FROM " + table + + " WHERE id IN (0, 2500, " + (totalRows - 1) + ") ORDER BY id")) { + int[] ids = {0, 2500, totalRows - 1}; + for (int id : ids) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), id); + assertEquals(rs.getString(2), "ROW_" + id); + assertEquals(rs.getString(3), padding + "_" + id); + assertEquals(rs.getLong(4), id * 2L); + assertEquals(rs.getDouble(5), id + 0.25d); + } + assertFalse(rs.next()); + } + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + @Test(groups = {"integration"}) + public void testEscapeProcessingAndTrailingSemicolon() throws Exception { + String table = tablePrefix() + "escape"; + Properties props = new Properties(); + props.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + + try (Connection conn = getJdbcConnection(props); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute("CREATE TABLE " + table + + " (id Int32, val Int32, d Date, text String, tail Float64) ORDER BY id"); + try { + String sql = "INSERT INTO " + table + + " (id, val, d, text, tail) VALUES (?, abs(?), '2025-01-15', ?, ?);"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + + ps.setInt(1, 1); + ps.setInt(2, -15); + ps.setString(3, "{fn abs(-99)} literal"); + ps.setDouble(4, 1.5d); + assertEquals(ps.executeUpdate(), 1); + + ps.setInt(1, 2); + ps.setInt(2, -25); + ps.setString(3, "{d '2000-01-01'} literal"); + ps.setDouble(4, 2.5d); + ps.addBatch(); + assertEquals(ps.executeBatch(), new int[]{1}); + } + + String noEscapeSql = "INSERT INTO " + table + + " (id, val, d, text, tail) VALUES (?, abs(?), '2025-02-20', ?, ?)"; + try (PreparedStatement ps = conn.prepareStatement(noEscapeSql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + ps.setEscapeProcessing(false); + ps.setInt(1, 3); + ps.setInt(2, -35); + ps.setString(3, "{fn raw}"); + ps.setDouble(4, 3.5d); + assertEquals(ps.executeUpdate(), 1); + } + + String escapedSql = "INSERT INTO " + table + + " (id, val, d, text, tail) VALUES (?, {fn abs(?)}, {d '2025-03-25'}, ?, ?)"; + try (PreparedStatement ps = conn.prepareStatement(escapedSql)) { + ps.setInt(1, 4); + ps.setInt(2, -45); + ps.setString(3, "escaped"); + ps.setDouble(4, 4.5d); + assertEquals(ps.executeUpdate(), 1); + } + + try (ResultSet rs = st.executeQuery("SELECT id, val, d, text, tail FROM " + table + " ORDER BY id")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + assertEquals(rs.getInt(2), 15); + assertEquals(rs.getObject(3, LocalDate.class), LocalDate.of(2025, 1, 15)); + assertEquals(rs.getString(4), "{fn abs(-99)} literal"); + assertEquals(rs.getDouble(5), 1.5d); + + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 2); + assertEquals(rs.getInt(2), 25); + assertEquals(rs.getObject(3, LocalDate.class), LocalDate.of(2025, 1, 15)); + assertEquals(rs.getString(4), "{d '2000-01-01'} literal"); + assertEquals(rs.getDouble(5), 2.5d); + + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 3); + assertEquals(rs.getInt(2), 35); + assertEquals(rs.getObject(3, LocalDate.class), LocalDate.of(2025, 2, 20)); + assertEquals(rs.getString(4), "{fn raw}"); + assertEquals(rs.getDouble(5), 3.5d); + + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 4); + assertEquals(rs.getInt(2), 45); + assertEquals(rs.getObject(3, LocalDate.class), LocalDate.of(2025, 3, 25)); + assertEquals(rs.getString(4), "escaped"); + assertEquals(rs.getDouble(5), 4.5d); + + assertFalse(rs.next()); + } + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + @Test(groups = {"integration"}) + public void testInsertNegativePaths() throws Exception { + String table = tablePrefix() + "negative"; + try (Connection conn = getJdbcConnection(); + Statement st = conn.createStatement()) { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + st.execute("CREATE TABLE " + table + " (id Int32, val Int32) ORDER BY id"); + try { + String sql = "INSERT INTO " + table + " (id, val) VALUES (?, abs(?))"; + try (PreparedStatement ps = conn.prepareStatement(sql)) { + assertEquals(ps.getClass(), expectedPreparedStatementClass()); + + ps.setInt(1, 1); + assertThrows(SQLException.class, ps::executeUpdate); + + ps.setInt(2, -10); + ps.clearParameters(); + assertThrows(SQLException.class, ps::executeUpdate); + + ps.setInt(1, 1); + ps.setInt(2, -10); + assertThrows(SQLException.class, ps::executeQuery); + } + + PreparedStatement closedPs = conn.prepareStatement(sql); + closedPs.close(); + assertThrows(SQLException.class, () -> closedPs.setInt(1, 1)); + assertThrows(SQLException.class, closedPs::addBatch); + assertThrows(SQLException.class, closedPs::executeBatch); + assertThrows(SQLException.class, closedPs::executeUpdate); + } finally { + st.execute("DROP TABLE IF EXISTS " + table + " SYNC"); + } + } + } + + @Test(groups = { "integration" }) + public void testSetNull() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setNull(1, Types.INTEGER); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertNull(rs.getObject(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetBoolean() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setBoolean(1, true); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertTrue(rs.getBoolean(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetByte() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setByte(1, (byte) 1); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals((byte) 1, rs.getByte(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetShort() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setShort(1, (short) 1); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals((short) 1, rs.getShort(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetInt() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setInt(1, 1); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1, rs.getInt(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetLong() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setLong(1, 1L); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1L, rs.getLong(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetFloat() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setFloat(1, 1.0f); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1.0f, rs.getFloat(1), 0.0f); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetDouble() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setDouble(1, 1.0); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(1.0, rs.getDouble(1), 0.0); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetString() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setString(1, "test"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals("test", rs.getString(1)); + assertFalse(rs.next()); + } + } + } + } + + @DataProvider(name = "specialCharacterStrings") + Object[][] specialCharacterStrings() { + return new Object[][] { + {"plain value"}, + {"tab\tinside"}, + {"newline\ninside"}, + {"C:\\temp"}, + {"quote'inside"}, + {"mixed\t'quote'\nand\\backslash"}, + {"unicode é中😀"}, + }; + } + + @Test(groups = { "integration" }, dataProvider = "specialCharacterStrings") + public void testSetStringWithSpecialCharacters(String value) throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setString(1, value); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), value); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetBytes() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setBytes(1, new byte[] { 1, 2, 3 }); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getBytes(1), new byte[] { 1, 2, 3 }); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetDate() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT toDate(?)")) { + stmt.setDate(1, java.sql.Date.valueOf("2021-01-01"), new GregorianCalendar(TimeZone.getTimeZone("UTC"))); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-01")); + assertFalse(rs.next()); + } + + stmt.setDate(1, java.sql.Date.valueOf("2021-01-02")); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-02")); + assertFalse(rs.next()); + } + + stmt.setObject(1, java.sql.Date.valueOf("2021-01-02")); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-02")); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }, enabled = false) + public void testSetTime() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT toTime(?)")) { + stmt.setTime(1, java.sql.Time.valueOf("12:34:56"), new GregorianCalendar(TimeZone.getTimeZone("UTC"))); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getTime(1).toString(), "12:34:56"); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testSetTimestamp() throws Exception { + final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT toDateTime64(?, 3)")) { + Timestamp tsToWrite = java.sql.Timestamp.valueOf("2021-01-01 01:34:56.456"); + ZonedDateTime tsSeenInCalendarTz = ZonedDateTime.ofInstant(tsToWrite.toInstant(), calendar.getTimeZone().toZoneId()); + stmt.setTimestamp(1, tsToWrite, calendar); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + + assertEquals(rs.getObject(1, ZonedDateTime.class), tsSeenInCalendarTz); + Timestamp dbTimestamp = rs.getTimestamp(1, calendar); + assertEquals(dbTimestamp.toInstant(), tsSeenInCalendarTz.toInstant()); + assertFalse(rs.next()); + } + } + + String localTimezone = TimeZone.getDefault().getID(); + try (PreparedStatement stmt = conn.prepareStatement("SELECT toDateTime64(?, 3, ?)")) { + LocalDateTime localTs = LocalDateTime.parse("2021-01-01T01:34:56").withNano((int) TimeUnit.MILLISECONDS.toNanos(456)); + stmt.setObject(1, localTs); + stmt.setString(2, localTimezone); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + + assertEquals(rs.getObject(1, LocalDateTime.class), localTs); + Timestamp dbTimestamp = rs.getTimestamp(1); + + assertEquals(dbTimestamp.getTime(), localTs.toInstant(ZoneId.systemDefault().getRules().getOffset(localTs)).toEpochMilli()); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testBigDecimal() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setBigDecimal(1, java.math.BigDecimal.valueOf(1.0)); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(java.math.BigDecimal.valueOf(1.0), rs.getBigDecimal(1)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testPrimitiveArrays() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setObject(1, new String[][] {new String[]{"a"}, new String[]{"b"}, new String[]{"c"}}); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + Array a1 = rs.getArray(1); + assertNotNull(a1); + assertEquals(Arrays.deepToString((Object[]) a1.getArray()), "[[a], [b], [c]]"); + Array a2 = rs.getObject(1, Array.class); + assertNotNull(a2); + assertEquals(Arrays.deepToString((Object[]) a2.getArray()), "[[a], [b], [c]]"); + Array a3 = rs.getObject(1) instanceof Array ? (Array) rs.getObject(1) : null; + assertNotNull(a3); + assertEquals(Arrays.deepToString((Object[]) a3.getArray()), "[[a], [b], [c]]"); + assertFalse(rs.next()); + } + } + + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setObject(1, new Object[] {1, 2, 3}); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + Array a1 = rs.getArray(1); + assertNotNull(a1); + assertEquals(Arrays.deepToString((Object[]) a1.getArray()), "[1, 2, 3]"); + } + } + } + } + + @Test + public void testTuple() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { + stmt.setObject(1, new Tuple("a", 1)); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(Arrays.asList(rs.getObject(1, Object[].class)).toString(), "[a, 1]"); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testSetAsciiStream() throws Exception { + final String value = "Some long string with '' to check quote escaping"; + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { + stmt.setAsciiStream(1, new ByteArrayInputStream(value.getBytes())); + stmt.setAsciiStream(2, new ByteArrayInputStream(value.getBytes()), 10); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), value); + assertEquals(rs.getString(2), value.subSequence(0, 10)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testSetUnicodeStream() throws Exception { + final String value = "Some long string with '' to check quote escaping"; + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { + stmt.setUnicodeStream(1, new ByteArrayInputStream(value.getBytes()), value.length()); + stmt.setUnicodeStream(2, new ByteArrayInputStream(value.getBytes()), 10); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), value); + assertEquals(rs.getString(2), value.subSequence(0, 10)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testSetBinaryStream() throws Exception { + final String value = "Some long string with '' to check quote escaping"; + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { + stmt.setBinaryStream(1, new ByteArrayInputStream(value.getBytes())); + stmt.setBinaryStream(2, new ByteArrayInputStream(value.getBytes()), 10); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), value); + assertEquals(rs.getString(2), value.subSequence(0, 10)); + assertFalse(rs.next()); + } + } + } + } + + @Test + public void testSetNCharacterStream() throws Exception { + final String value = "Some long string with '' to check quote escaping"; + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { + stmt.setNCharacterStream(1, new InputStreamReader(new ByteArrayInputStream(value.getBytes()))); + stmt.setNCharacterStream(2, new InputStreamReader(new ByteArrayInputStream(value.getBytes())), 10); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), value); + assertEquals(rs.getString(2), value.subSequence(0, 10)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testEscapeStrings() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT FALSE OR ? = 'test', ?")) { + stmt.setString(1, "test\\' OR 1 = 1 --"); + stmt.setString(2, "test\\\\' OR 1 = 1 --"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "false"); + assertEquals(rs.getString(2), "test\\\\' OR 1 = 1 --"); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = { "integration" }) + public void testTernaryOperator() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT ( TRUE ? 1 : 0) as val1, ? as val2")) { + stmt.setString(1, "test\\' OR 1 = 1 --"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString("val1"), "1"); + assertEquals(rs.getString(2), "test\\' OR 1 = 1 --"); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = "integration") + void testWithClause() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("with data as (SELECT number FROM numbers(100)) select * from data ")) { + stmt.execute(); + ResultSet rs = stmt.getResultSet(); + int count = 0; + while (rs.next()) { + count++; + } + assertEquals(count, 100); + } + } + } + + @Test(groups = "integration") + void testWithClauseWithParams() throws Exception { + final String table = tablePrefix() + "with_stmt"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (v1 String) ORDER BY ()"); + stmt.execute("INSERT INTO " + table + " VALUES ('A'), ('B')"); + } + final Timestamp target_time = Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); + try (PreparedStatement stmt = conn.prepareStatement("WITH " + + " toDateTime(?) as target_time, " + + " (SELECT 123) as magic_number" + + " SELECT *, target_time, magic_number FROM " + table)) { + stmt.setTimestamp(1, target_time); + stmt.execute(); + ResultSet rs = stmt.getResultSet(); + int count = 0; + assertEquals(rs.getMetaData().getColumnCount(), 3); + while (rs.next()) { + Assert.assertEquals( + rs.getTimestamp("target_time").toLocalDateTime().truncatedTo(ChronoUnit.SECONDS), + target_time.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS)); + Assert.assertEquals(rs.getString("magic_number"), "123"); + Assert.assertEquals( + rs.getTimestamp(2).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS), + target_time.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS)); + Assert.assertEquals(rs.getString(3), "123"); + + count++; + } + assertEquals(count, 2, "Expected 2 rows"); + } + } + } + + @Test(groups = { "integration" }) + void testMultipleWithClauses() throws Exception { + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement( + "WITH data1 AS (SELECT 1 AS a), " + + " data2 AS (SELECT a + 1 AS b FROM data1) " + + "SELECT * FROM data2")) { + ResultSet rs = stmt.executeQuery(); + assertTrue(rs.next()); + assertEquals(2, rs.getInt(1)); + assertFalse(rs.next()); + } + } + + @Test(groups = { "integration" }) + void testRecursiveWithClause() throws Exception { + if (ClickHouseVersion.of(getServerVersion()).check("(,24.3]")) { + return; // recursive CTEs were introduced in 24.4 + } + + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement( + "WITH RECURSIVE numbers AS (" + + " SELECT 1 AS n " + + " UNION ALL " + + " SELECT n + 1 FROM numbers WHERE n < 5" + + ") " + + "SELECT * FROM numbers ORDER BY n")) { + ResultSet rs = stmt.executeQuery(); + for (int i = 1; i <= 5; i++) { + assertTrue(rs.next()); + assertEquals(i, rs.getInt(1)); + } + assertFalse(rs.next()); + } + } + + @Test(groups = { "integration" }) + void testWithClauseWithMultipleParameters() throws Exception { + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement( + "WITH data AS (" + + " (SELECT number AS n " + + " FROM numbers(?) " + + " WHERE n > ?)" + + ") " + + "SELECT * FROM data WHERE n < ?")) { + stmt.setInt(1, 10); // numbers(10) = 0-9 + stmt.setInt(2, 3); // n > 3 + stmt.setInt(3, 7); // n < 7 + + ResultSet rs = stmt.executeQuery(); + int count = 0; + while (rs.next()) { + count++; + int n = rs.getInt(1); + assertTrue(n > 3 && n < 7); + } + assertEquals(3, count); + } + } + + @Test(groups = { "integration" }) + void testSelectFromArray() throws Exception { + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement( + "SELECT * FROM numbers(?)")) { + stmt.setInt(1, 10); // numbers(10) = 0-9 + ResultSet rs = stmt.executeQuery(); + int count = 0; + while (rs.next()) { + count++; + } + assertEquals(10, count); + } + } + + @Test(groups = { "integration" }) + void testInsert() throws Exception { + int ROWS = 1000; + String payload = RandomStringUtils.random(1024, true, true); + String table = tablePrefix() + "insert_batch"; + try (Connection conn = getJdbcConnection()) { + for (int j = 0; j < 10; j++) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " ( `off16` Int16, `str` String, `p_int8` Int8, `p_int16` Int16, `p_int32` Int32, `p_int64` Int64, `p_float32` Float32, `p_float64` Float64, `p_bool` Bool) ORDER BY ()"); + } + String insertQuery = "INSERT INTO " + table + " (off16, str, p_int8, p_int16, p_int32, p_int64, p_float32, p_float64, p_bool) VALUES (?,?,?,?,?,?,?,?,?)"; + try (PreparedStatement stmt = conn.prepareStatement(insertQuery)) { + for (int i = 0; i < ROWS; i++) { + stmt.setShort(1, (short) i); + stmt.setString(2, payload); + stmt.setByte(3, (byte) i); + stmt.setShort(4, (short) i); + stmt.setInt(5, i); + stmt.setLong(6, (long) i); + stmt.setFloat(7, (float) (i * 0.1)); + stmt.setDouble(8, (double) (i * 0.1)); + stmt.setBoolean(9, true); + stmt.addBatch(); + } + stmt.executeBatch(); + } + try (Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT count(*) FROM " + table)) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), ROWS); + } + } + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE " + table); + } + } + } + } + + @Test(dataProvider = "testGetMetadataDataProvider") + void testGetMetadata(String sql, int colCountBeforeExecution, Object[] values, + int colCountAfterExecution) throws Exception { + String tableName = tablePrefix() + "get_metadata"; + runQuery("CREATE TABLE IF NOT EXISTS " + tableName + " ( a1 String, b2 Float, b3 Float ) ORDER BY ()"); + + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement(String.format(sql, tableName))) { + ResultSetMetaData metadataRs = stmt.getMetaData(); + assertNotNull(metadataRs); + Assert.assertEquals(metadataRs.getColumnCount(), colCountBeforeExecution); + + for (int i = 1; i <= metadataRs.getColumnCount(); i++) { + assertEquals(metadataRs.getSchemaName(i), stmt.getConnection().getSchema()); + } + + if (values != null) { + for (int i = 0; i < values.length; i++) { + stmt.setObject(i + 1, values[i]); + } + } + + stmt.execute(); + metadataRs = stmt.getMetaData(); + + assertNotNull(metadataRs); + assertEquals(metadataRs.getColumnCount(), colCountAfterExecution); + for (int i = 1; i <= metadataRs.getColumnCount(); i++) { + assertEquals(metadataRs.getSchemaName(i), stmt.getConnection().getSchema()); + } + } + } + + @DataProvider(name = "testGetMetadataDataProvider") + static Object[][] testGetMetadataDataProvider() { + return new Object[][] { + {"INSERT INTO `%s` VALUES (?, ?, ?)", 3, new Object[]{"test", 0.3f, 0.4f}, 3}, + {"SELECT * FROM `%s`", 3, null, 3}, + {"SHOW TABLES", 0, null, 1} + }; + } + + @Test(groups = { "integration" }) + void testGetMetadataAppliesCustomTypeMapping() throws Exception { + Properties properties = new Properties(); + properties.setProperty(DriverProperties.JDBC_TYPE_MAPPINGS.getKey(), "Int32=Long,UInt64=String"); + + Consumer verify = (metaData) -> { + try { + assertEquals(metaData.getColumnCount(), 3); + + assertEquals(metaData.getColumnName(1), "i32"); + assertEquals(metaData.getColumnClassName(1), Long.class.getName()); + assertEquals(metaData.getColumnType(1), Types.BIGINT); + + assertEquals(metaData.getColumnName(2), "u64"); + assertEquals(metaData.getColumnClassName(2), String.class.getName()); + assertEquals(metaData.getColumnType(2), Types.VARCHAR); + + assertEquals(metaData.getColumnName(3), "u16"); + assertEquals(metaData.getColumnClassName(3), Integer.class.getName()); + assertEquals(metaData.getColumnType(3), Types.INTEGER); + + } catch (SQLException e) { + fail("no exception expected", e); + } + }; + + try (Connection conn = getJdbcConnection(properties); + PreparedStatement stmt = conn.prepareStatement("SELECT toInt32(?) AS i32, toUInt64(?) AS u64, toUInt16(?) as u16")) { + ResultSetMetaData beforeExec = stmt.getMetaData(); + assertNotNull(beforeExec); + + stmt.setInt(1, 42); + stmt.setLong(2, 7L); + stmt.setInt(3, 20); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertTrue(rs.getObject("i32") instanceof Long, "i32 should be mapped to Long"); + assertTrue(rs.getObject("u64") instanceof String, "u64 should be mapped to String"); + assertTrue(rs.getObject("u16") instanceof Integer, "u16 should be mapped to Integer"); + + ResultSetMetaData afterExec = stmt.getMetaData(); + assertNotNull(afterExec); + verify.accept(afterExec); + } + } + } + + @Test(groups = { "integration" }) + void testMetabaseBug01() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `users`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp01`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp02`"); + stmt.execute("CREATE TABLE `users` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); + stmt.execute("CREATE TABLE `users_tmp` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); + stmt.execute("CREATE TABLE `users_tmp01` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); + stmt.execute("CREATE TABLE `users_tmp02` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); + } + try { + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users` (`name`, `last_login`, `password`, `id`) VALUES (?, `parseDateTimeBestEffort`(?, ?), ?, 1), (?, `parseDateTimeBestEffort`(?, ?), ?, 2), (?, `parseDateTimeBestEffort`(?, ?), ?, 3), (?, `parseDateTimeBestEffort`(?, ?), ?, 4), (?, `parseDateTimeBestEffort`(?, ?), ?, 5), (?, `parseDateTimeBestEffort`(?, ?), ?, 6), (?, `parseDateTimeBestEffort`(?, ?), ?, 7), (?, `parseDateTimeBestEffort`(?, ?), ?, 8), (?, `parseDateTimeBestEffort`(?, ?), ?, 9), (?, `parseDateTimeBestEffort`(?, ?), ?, 10), (?, `parseDateTimeBestEffort`(?, ?), ?, 11), (?, `parseDateTimeBestEffort`(?, ?), ?, 12), (?, `parseDateTimeBestEffort`(?, ?), ?, 13), (?, `parseDateTimeBestEffort`(?, ?), ?, 14), (?, `parseDateTimeBestEffort`(?, ?), ?, 15)")) { + stmt.setObject(1, "Plato Yeshua"); + stmt.setObject(2, "2014-04-01 08:30:00.000"); + stmt.setObject(3, "UTC"); + stmt.setObject(4, "4be68cda-6fd5-4ba7-944e-2b475600bda5"); + stmt.setObject(5, "Felipinho Asklepios"); + stmt.setObject(6, "2014-12-05 15:15:00.000"); + stmt.setObject(7, "UTC"); + stmt.setObject(8, "5bb19ad9-f3f8-421f-9750-7d398e38428d"); + stmt.setObject(9, "Kaneonuskatew Eiran"); + stmt.setObject(10, "2014-11-06 16:15:00.000"); + stmt.setObject(11, "UTC"); + stmt.setObject(12, "a329ccfe-b99c-42eb-9c93-cb9adc3eb1ab"); + stmt.setObject(13, "Simcha Yan"); + stmt.setObject(14, "2014-01-01 08:30:00.000"); + stmt.setObject(15, "UTC"); + stmt.setObject(16, "a61f97c6-4484-4a63-b37e-b5e58bfa2ecb"); + stmt.setObject(17, "Quentin Sören"); + stmt.setObject(18, "2014-10-03 17:30:00.000"); + stmt.setObject(19, "UTC"); + stmt.setObject(20, "10a0fea8-9bb4-48fe-a336-4d9cbbd78aa0"); + stmt.setObject(21, "Shad Ferdynand"); + stmt.setObject(22, "2014-08-02 12:30:00.000"); + stmt.setObject(23, "UTC"); + stmt.setObject(24, "d35c9d78-f9cf-4f52-b1cc-cb9078eebdcb"); + stmt.setObject(25, "Conchúr Tihomir"); + stmt.setObject(26, "2014-08-02 09:30:00.000"); + stmt.setObject(27, "UTC"); + stmt.setObject(28, "900335ad-e03b-4259-abc7-76aac21cedca"); + stmt.setObject(29, "Szymon Theutrich"); + stmt.setObject(30, "2014-02-01 10:15:00.000"); + stmt.setObject(31, "UTC"); + stmt.setObject(32, "d6c47a54-9d88-4c4a-8054-ace76764ed0d"); + stmt.setObject(33, "Nils Gotam"); + stmt.setObject(34, "2014-04-03 09:30:00.000"); + stmt.setObject(35, "UTC"); + stmt.setObject(36, "b085040c-7aa4-4e96-8c8f-420b2c99c920"); + stmt.setObject(37, "Frans Hevel"); + stmt.setObject(38, "2014-07-03 19:30:00.000"); + stmt.setObject(39, "UTC"); + stmt.setObject(40, "b7a43e91-9fb9-4fe9-ab6f-ea51ab0f94e4"); + stmt.setObject(41, "Spiros Teofil"); + stmt.setObject(42, "2014-11-01 07:00:00.000"); + stmt.setObject(43, "UTC"); + stmt.setObject(44, "62b9602c-27b8-44ea-adbd-2748f26537af"); + stmt.setObject(45, "Kfir Caj"); + stmt.setObject(46, "2014-07-03 01:30:00.000"); + stmt.setObject(47, "UTC"); + stmt.setObject(48, "dfe21df3-f364-479d-a5e7-04bc5d85ad2b"); + stmt.setObject(49, "Dwight Gresham"); + stmt.setObject(50, "2014-08-01 10:30:00.000"); + stmt.setObject(51, "UTC"); + stmt.setObject(52, "75a1ebf1-cae7-4a50-8743-32d97500f2cf"); + stmt.setObject(53, "Broen Olujimi"); + stmt.setObject(54, "2014-10-03 13:45:00.000"); + stmt.setObject(55, "UTC"); + stmt.setObject(56, "f9b65c74-9f91-4cfd-9248-94a53af82866"); + stmt.setObject(57, "Rüstem Hebel"); + stmt.setObject(58, "2014-08-01 12:45:00.000"); + stmt.setObject(59, "UTC"); + stmt.setObject(60, "02ad6b15-54b0-4491-bf0f-d781b0a2c4f5"); + stmt.addBatch(); + stmt.executeBatch(); + } + try (Statement stmt01 = conn.createStatement()) { + try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users`")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 15); + } + } + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp` SELECT * FROM `users` WHERE id = ?")) { + stmt.setInt(1, 1); + stmt.addBatch(); + stmt.setInt(1, 2); + stmt.addBatch(); + stmt.setInt(1, 3); + stmt.addBatch(); + stmt.executeBatch(); + } + + StringBuilder sb = new StringBuilder(); + try (Statement stmt01 = conn.createStatement()) { + try (ResultSet rs = stmt01.executeQuery("SELECT id, name FROM `users_tmp`")) { + while (rs.next()) { + sb.append(rs.getInt(1)).append(",").append(rs.getString(2)).append(";"); + } + } + } + + try (Statement stmt01 = conn.createStatement()) { + try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp`")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 3, "Users in users_tmp: " + sb); + } + } + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp01` SELECT * FROM `users` WHERE id = ?")) { + stmt.setInt(1, 1); + stmt.addBatch(); + stmt.executeBatch(); + } + + try (Statement stmt01 = conn.createStatement()) { + try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp01`")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + } + } + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp02` (`name`, `last_login`, `password`, `id`) VALUES (?, `parseDateTimeBestEffort`(?, ?), ?, ?)")) { + for (int i = 0; i < 10; i++) { + stmt.setObject(1, "Plato Yeshua"); + stmt.setObject(2, "2014-04-01 08:30:00.000"); + stmt.setObject(3, "UTC"); + stmt.setObject(4, "4be68cda-6fd5-4ba7-944e-2b475600bda5"); + stmt.setObject(5, i); + stmt.addBatch(); + } + stmt.executeBatch(); + } + + try (Statement stmt01 = conn.createStatement()) { + try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp02`")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 10); + } + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `users`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp01`"); + stmt.execute("DROP TABLE IF EXISTS `users_tmp02`"); + } + } + } + } + + @Test(groups = { "integration" }, dataProvider = "insertWithRewrittenValuesListDP") + void testInsertWithRewrittenValuesList(String valuesList) throws Exception { + final String table = tablePrefix() + "insert_rewritten_values_list"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (s String, n Int32) ORDER BY ()"); + } + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (s, n) VALUES " + valuesList)) { + assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); + stmt.setInt(1, 42); + stmt.addBatch(); + } + } + } + + @DataProvider(name = "insertWithRewrittenValuesListDP") + public static Object[][] insertWithRewrittenValuesListDP() { + return new Object[][] { + { "(toDateTime({ts '2024-01-01 00:00:00'}), ?)" }, + { "(toTime({t '10:20:30'}), ?)" }, + { "(toInt32({d:Int32}), ?)" }, + }; + } + + @Test(groups = { "integration" }) + void testBatchInsertWithRewrittenValuesList() throws Exception { + final String table = tablePrefix() + "batch_insert_rewritten_values_list"; + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (s DateTime, n Int32) ORDER BY ()"); + } + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + + " (s, n) VALUES (toDateTime({ts '2024-01-01 00:00:00'}), ?)")) { + stmt.setInt(1, 42); + stmt.addBatch(); + stmt.setInt(1, 43); + stmt.addBatch(); + assertEquals(stmt.executeBatch().length, 2); + stmt.clearBatch(); + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT n FROM " + table + " ORDER BY n")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 42); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 43); + assertFalse(rs.next()); + } + } + } + + @Test(groups = { "integration" }) + void testInsertWithHeredocValue() throws Exception { + final String table = tablePrefix() + "insert_heredoc"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (s String, n Int32) ORDER BY ()"); + } + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (s, n) VALUES ($$a@b$$, ?)")) { + stmt.setInt(1, 42); + assertEquals(stmt.executeUpdate(), 1); + } + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT s, n FROM " + table)) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "a@b"); + assertEquals(rs.getInt(2), 42); + assertFalse(rs.next()); + } + } + } + + @Test(groups = { "integration" }) + void testStatementSplit() throws Exception { + final String complexTable = tablePrefix() + "with_complex_id"; + final String splitTable = tablePrefix() + "stmt_split2"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `" + complexTable + "`"); + stmt.execute("DROP TABLE IF EXISTS `" + splitTable + "`"); + stmt.execute("CREATE TABLE `" + complexTable + "` (`v?``1` Int32, " + + "\"v?\"\"2\" Int32,`v?\\`3` Int32, \"v?\\\"4\" Int32) ORDER BY ();"); + stmt.execute("CREATE TABLE `" + splitTable + "` (v1 Int32, v2 String) ORDER BY (); "); + stmt.execute("INSERT INTO `" + splitTable + "` VALUES (1, 'abc'), (2, '?'), (3, '?')"); + } + String insertQuery = "-- line comment1 ?\n" + + "# line comment2 ?\n" + + "#! line comment3 ?\n" + + "/* block comment ? \n */" + + "INSERT INTO `" + complexTable + "`(`v?``1`, \"v?\"\"2\",`v?\\`3`, \"v?\\\"4\") VALUES (?, ?, ?, ?);"; + try (PreparedStatement stmt = conn.prepareStatement(insertQuery)) { + stmt.setInt(1, 1); + stmt.setInt(2, 2); + stmt.setInt(3, 3); + stmt.setInt(4, 4); + stmt.execute(); + } + String selectQuery = "-- line comment ?\n" + + "/* block comment ? \n */" + + "SELECT `v?``1`, \"v?\"\"2\",`v?\\`3`, \"v?\\\"4\", 'test '' string1 ?', 'test \\' string2 ?', 'test string3 ?\\\\' FROM `" + complexTable + "` WHERE `v?``1` = ? AND \"v?\"\"2\" = ? AND `v?\\`3` = ? AND \"v?\\\"4\" = ?"; + try (PreparedStatement stmt = conn.prepareStatement(selectQuery)) { + stmt.setInt(1, 1); + stmt.setInt(2, 2); + stmt.setInt(3, 3); + stmt.setInt(4, 4); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + assertEquals(rs.getInt(2), 2); + assertEquals(rs.getInt(3), 3); + assertEquals(rs.getInt(4), 4); + assertEquals(rs.getString(5), "test ' string1 ?"); + assertEquals(rs.getString(6), "test ' string2 ?"); + assertEquals(rs.getString(7), "test string3 ?\\"); + } + } + + try (PreparedStatement stmt = conn.prepareStatement("SELECT v1 FROM `" + splitTable + "` WHERE v1 > ? AND v2 = '?'")) { + stmt.setInt(1, 2); + try (ResultSet rs = stmt.executeQuery()) { + int count = 0; + while (rs.next()) { + count++; + assertEquals(rs.getInt(1), 3); + } + + Assert.assertEquals(count, 1); + } + } + } + } + + @Test(groups = { "integration" }, dataProvider = "commentsAndHeredocsDP") + void testPlaceholdersWithCommentsAndHeredocs(String sql, String expected) throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, "42"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), expected); + assertFalse(rs.next()); + } + } + } + } + + @DataProvider(name = "commentsAndHeredocsDP") + public static Object[][] commentsAndHeredocsDP() { + return new Object[][] { + {"SELECT ? AS v // ?", "42"}, + {"SELECT ? AS v // ?\nUNION ALL SELECT NULL WHERE 0", "42"}, + {"SELECT //\n? AS v", "42"}, + {"SELECT --\n? AS v", "42"}, + {"SELECT concat($$?$$, ?) AS v", "?42"}, + {"SELECT concat($tag$ ? $tag$, ?) AS v", " ? 42"}, + {"SELECT ? AS a$x$, 1 AS b$x$", "42"}, + {"SELECT ? AS a$$b$, 1 AS x$$b$", "42"}, + }; + } + + @Test(groups = {"integration"}) + void testClearParameters() throws Exception { + final String table = tablePrefix() + "clear_params"; + final String sql = "insert into `" + table + "` (`id`, `name`, `age`) values (?, ?, ?)"; + + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE TABLE IF NOT EXISTS `" + table + "` (`id` Nullable(String), `name` Nullable(String), `age` Int32) ENGINE Memory;"); + } + + try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { + Assert.assertEquals(ps.getParametersCount(), 3); + + ps.setString(1, "testId"); + ps.setString(2, "testName"); + ps.setInt(3, 18); + ps.execute(); + + ps.clearParameters(); + Assert.assertEquals(ps.getParametersCount(), 3); + + ps.setString(1, "testId2"); + ps.setString(2, "testName2"); + ps.setInt(3, 19); + ps.execute(); + } + } + } + + @DataProvider + Object[][] testBatchInsertWithRowBinary_dp() { + return new Object[][]{ + {"INSERT INTO \n `%s` \nVALUES (?, ?, abs(?), ?)", expectedPreparedStatementClass()}, + {"INSERT INTO\n `%s` \nVALUES (?, ?, ?, ?)", WriterStatementImpl.class}, + {" INSERT INTO %s (ts, v1, v2, v3) VALUES (?, ?, ?, ?)", WriterStatementImpl.class}, + {"INSERT INTO %s SELECT ?, ?, ?, ?", expectedPreparedStatementClass()}, + }; + } + + @Test(dataProvider = "testBatchInsertWithRowBinary_dp") + void testBatchInsertWithRowBinary(String sql, Class implClass) throws Exception { + String table = tablePrefix() + "batch_rowbinary"; + long seed = System.currentTimeMillis(); + Random rnd = new Random(seed); + Properties properties = new Properties(); + properties.put(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + try (Connection conn = getJdbcConnection(properties)) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE TABLE IF NOT EXISTS " + table + + " ( ts DateTime, v1 Int32, v2 Float32, v3 Int32) ORDER BY ()"); + } + + final int nBatches = 10; + try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { + Assert.assertEquals(stmt.getClass(), implClass); + for (int bI = 0; bI < nBatches; bI++) { + stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS))); + stmt.setInt(2, rnd.nextInt()); + stmt.setFloat(3, rnd.nextFloat()); + stmt.setInt(4, rnd.nextInt()); + stmt.addBatch(); + } + + int[] result = stmt.executeBatch(); + for (int r : result) { + Assert.assertTrue(r == 1 || r == PreparedStatement.SUCCESS_NO_INFO); + } + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) { + int count = 0; + while (rs.next()) { + Timestamp ts = rs.getTimestamp(1); + assertNotNull(ts); + assertTrue(rs.getInt(2) != 0); + assertTrue(rs.getFloat(3) != 0.0f); + assertTrue(rs.getInt(4) != 0); + count++; + } + assertEquals(count, nBatches); + + stmt.execute("TRUNCATE " + table); + } + } + } + + @Test(groups = {"integration"}, dataProvider = "sqlParserDP") + void testBatchInsertWithValueOfUnsupportedSyntax(String parserName) throws Exception { + String table = tablePrefix() + "batch_unsupported_syntax"; + Properties properties = new Properties(); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parserName); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection conn = getJdbcConnection(properties)) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (v1 Int32, v2 String) ORDER BY ()"); + } + + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (v1, v2) VALUES (?, hex(x'AB'))")) { + for (int i = 1; i <= 2; i++) { + stmt.setInt(1, i); + stmt.addBatch(); + } + assertEquals(stmt.executeBatch().length, 2); + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT v1, v2 FROM " + table + " ORDER BY v1")) { + for (int i = 1; i <= 2; i++) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), i); + assertEquals(rs.getString(2), "AB"); + } + assertFalse(rs.next()); + } + } + } + + @DataProvider(name = "sqlParserDP") + public static Object[][] sqlParserDP() { + return new Object[][] { + { SqlParserFacade.SQLParser.JAVACC.name() }, + { SqlParserFacade.SQLParser.ANTLR4.name() }, + { SqlParserFacade.SQLParser.ANTLR4_PARAMS_PARSER.name() }, + }; + } + + @Test(groups = {"integration"}) + void testWriteUUID() throws Exception { + String table = tablePrefix() + "write_uuid"; + String sql = "insert into `" + table + "` (`id`, `uuid`) values (?, ?)"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `" + table + "`"); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + table + "` (`id` Nullable(String), `uuid` UUID) ORDER BY ();"); + } + try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { + UUID uuid = UUID.randomUUID(); + ps.setString(1, "testId01"); + ps.setObject(2, uuid); + ps.execute(); + + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM `" + table + "`"); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt(1), 1); + } + + final String selectSQL = "SELECT * FROM `" + table + "` WHERE " + + "`" + getDatabase() + "`.`" + table + "`.`uuid` IN (CAST(? AS UUID))"; + try (PreparedStatement stmt = conn.prepareStatement(selectSQL)) { + stmt.setString(1, uuid.toString()); + try (ResultSet rs = stmt.executeQuery()) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString(1), "testId01"); + Assert.assertEquals(rs.getString(2), uuid.toString()); + } + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `" + table + "`"); + } + } + } + } + + @Test(groups = {"integration"}) + void testWriteCollection() throws Exception { + String table = tablePrefix() + "write_collection"; + String sql = "insert into `" + table + "` (`id`, `name`, `age`, `arr`) values (?, ?, ?, ?)"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `" + table + "`"); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + table + "` (`id` Nullable(String), `name` Nullable(String), `age` Int32, `arr` Array(String)) ORDER BY ();"); + } + try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { + Assert.assertEquals(ps.getParametersCount(), 4); + Collection arr = new ArrayList<>(); + ps.setString(1, "testId01"); + ps.setString(2, "testName"); + ps.setInt(3, 18); + ps.setObject(4, arr); + ps.execute(); + + try (Statement stmt = conn.createStatement()) { + ResultSet rs = stmt.executeQuery("SELECT count(*) FROM `" + table + "`"); + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getInt(1), 1); + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS `" + table + "`"); + } + } + } + } + + @Test + void testMethodsNotAllowedToBeCalled() throws Exception { + String sql = "SELECT number FROM system.numbers WHERE number = ?"; + try (Connection conn = getJdbcConnection(); + PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { + + Assert.assertThrows(SQLException.class, () -> ps.addBatch(sql)); + Assert.assertThrows(SQLException.class, () -> ps.executeQuery(sql)); + Assert.assertThrows(SQLException.class, () -> ps.execute(sql)); + Assert.assertThrows(SQLException.class, () -> ps.execute(sql, new int[]{0})); + Assert.assertThrows(SQLException.class, () -> ps.execute(sql, new String[]{""})); + Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql)); + Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql, new int[]{0})); + Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql, new String[]{""})); + Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql)); + Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql, new int[]{0})); + Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql, new String[]{""})); + } + } + + @Test(groups = { "integration" }) + public void testJdbcEscapeSyntax() throws Exception { + if (ClickHouseVersion.of(getServerVersion()).check("(,23.8]")) { + return; + } + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT {d '2021-11-01'} AS D, {ts '2021-08-01 12:34:56'} AS TS, " + + "toInt32({fn ABS(-1)}) AS FNABS, {fn CONCAT('Hello', 'World')} AS FNCONCAT, {fn UCASE('hello')} AS FNUPPER, " + + "{fn LCASE('HELLO')} AS FNLOWER, {fn LTRIM(' Hello ')} AS FNLTRIM, {fn RTRIM(' Hello ')} AS FNRTRIM, " + + "toInt32({fn LENGTH('Hello')}) AS FNLENGTH, toInt32({fn POSITION('Hello', 'l')}) AS FNPOSITION, toInt32({fn MOD(10, 3)}) AS FNMOD, " + + "{fn SQRT(9)} AS FNSQRT, {fn SUBSTRING('Hello', 3, 2)} AS FNSUBSTRING")) { + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getDate(1), Date.valueOf(LocalDate.of(2021, 11, 1))); + assertEquals(rs.getInt(3), 1); + assertEquals(rs.getInt("FNABS"), 1); + assertEquals(rs.getString(4), "HelloWorld"); + assertEquals(rs.getString("FNCONCAT"), "HelloWorld"); + assertEquals(rs.getString(5), "HELLO"); + assertEquals(rs.getString("FNUPPER"), "HELLO"); + assertEquals(rs.getString(6), "hello"); + assertEquals(rs.getString("FNLOWER"), "hello"); + assertEquals(rs.getString(7), "Hello "); + assertEquals(rs.getString("FNLTRIM"), "Hello "); + assertEquals(rs.getString(8), " Hello"); + assertEquals(rs.getString("FNRTRIM"), " Hello"); + assertEquals(rs.getInt(9), 5); + assertEquals(rs.getInt("FNLENGTH"), 5); + assertEquals(rs.getInt(10), 3); + assertEquals(rs.getInt("FNPOSITION"), 3); + assertEquals(rs.getInt(11), 1); + assertEquals(rs.getInt("FNMOD"), 1); + assertEquals(rs.getDouble(12), 3); + assertEquals(rs.getDouble("FNSQRT"), 3); + assertEquals(rs.getString(13), "ll"); + assertEquals(rs.getString("FNSUBSTRING"), "ll"); + assertThrows(SQLException.class, () -> rs.getString(14)); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testBoundValuesContainingJdbcEscapeSyntax() throws Exception { + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + final String table = tablePrefix() + "bound_values_with_escape_syntax"; + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + + "(v1 Int32, v2 Map(String, String), v3 String, v4 Int32) ORDER BY (v1)"); + } + + Map map1 = new LinkedHashMap<>(); + map1.put("user", "Z!F3{fn "); + map1.put("region", "{d '2024-01-02'}"); + Map map2 = Collections.singletonMap("user", "}"); + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)")) { + stmt.setInt(1, 1); + stmt.setObject(2, map1); + stmt.setString(3, "{fn UCASE('a')}"); + stmt.setInt(4, 40); + stmt.addBatch(); + stmt.setInt(1, 2); + stmt.setObject(2, map2); + stmt.setString(3, "{ts '2024-01-02 02:01:01'}"); + stmt.setInt(4, 41); + stmt.addBatch(); + assertEquals(stmt.executeBatch(), new int[]{1, 1}); + } + + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? AS v1, ? AS v2")) { + stmt.setString(1, "Z!F3{fn "); + stmt.setString(2, "}"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "Z!F3{fn "); + assertEquals(rs.getString(2), "}"); + assertFalse(rs.next()); + } + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " ORDER BY v1")) { + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + assertEquals(rs.getObject(2), map1); + assertEquals(rs.getString(3), "{fn UCASE('a')}"); + assertEquals(rs.getInt(4), 40); + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 2); + assertEquals(rs.getObject(2), map2); + assertEquals(rs.getString(3), "{ts '2024-01-02 02:01:01'}"); + assertEquals(rs.getInt(4), 41); + assertFalse(rs.next()); + } + } + } + + @Test(groups = {"integration"}) + public void testStatementsWithDatabaseInTableIdentifier() throws Exception { + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + final String db1Name = conn.getSchema() + "_" + tablePrefix() + "db1"; + final String table1Name = "table1"; + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE DATABASE IF NOT EXISTS " + db1Name + onCluster()); + stmt.execute("DROP TABLE IF EXISTS " + db1Name + "." + table1Name + onCluster()); + stmt.execute("CREATE TABLE " + db1Name + "." + table1Name + onCluster() + " " + + "(v1 Int32, v2 Int32) ORDER BY ()"); + } + try { + String[] tableIdentifier = new String[]{ + db1Name + "." + table1Name, + "`" + db1Name + "`.`" + table1Name + "`", + "\"" + db1Name + "\".\"" + table1Name + "\"" + }; + + for (int i = 0; i < tableIdentifier.length; i++) { + String tableId = tableIdentifier[i]; + final String insertStmt = "INSERT INTO " + tableId + " VALUES (?, ?)"; + try (PreparedStatement stmt = conn.prepareStatement(insertStmt)) { + stmt.setInt(1, i + 10); + stmt.setInt(2, i + 20); + assertEquals(stmt.executeUpdate(), 1); + } + } + } finally { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP DATABASE IF EXISTS " + db1Name + onCluster()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testNullValues() throws Exception { + try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { + final String table = tablePrefix() + "null_values"; + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + + "(v1 Int32, v2 Nullable(Int32)) ORDER BY ()"); + } + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?)")) { + stmt.setInt(1, 10); + expectThrows(SQLException.class, stmt::executeUpdate); + stmt.setInt(1, 20); + stmt.setObject(2, null); + assertEquals(stmt.executeUpdate(), 1); + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) { + int count = 0; + while (rs.next()) { + count++; + assertNull(rs.getObject(2)); + } + assertEquals(count, 1); + } + } + } + + @Test + public void testParamWithCast() throws Exception { + final String sql = " SELECT ?::integer, '?::integer', 123, ?:: UUID, ?"; + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement(sql)) { + UUID uuid = UUID.randomUUID(); + stmt.setString(1, "1000"); + stmt.setString(2, uuid.toString()); + stmt.setInt(3, 3003001); + + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + Assert.assertEquals(rs.getInt(1), 1000); + Assert.assertEquals(rs.getString(2), "?::integer"); + Assert.assertEquals(rs.getInt(3), 123); + Assert.assertEquals(rs.getString(4), uuid.toString()); + Assert.assertEquals(rs.getInt(5), 3003001); + } + } + } + } + + @Test(groups = {"integration"}) + public void testSelectWithTableAliasAsKeyword() throws Exception { + try (Connection conn = getJdbcConnection()) { + String[] keywords = { + "ALL", "AND", "ANY", "AS", "ASC", "BY", "CREATE", "DATABASE", "DELETE", "DESC", "DISTINCT", "DROP", "EXISTS", "FROM", "GRANT", "GROUP", "HAVING", "INSERT", "INTO", "LIMIT", "NOT", "NULL", "ON", "ORDER", "REVOKE", "SELECT", "SET", "TABLE", "TO", "UPDATE", "VALUES", "VIEW", "WHILE", "WITH", "WHERE" + }; + + for (String keyword : keywords) { + final String table = keyword; + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (v1 Int32, v2 String) ORDER BY ()"); + stmt.execute("INSERT INTO `" + table + "` VALUES (1000, 'test')"); + } + + try (PreparedStatement stmt = conn.prepareStatement("SELECT v1, v2 FROM " + table + " AS " + keyword + " WHERE v1 = ? AND v2 = ?")) { + stmt.setInt(1, 1000); + stmt.setString(2, "test"); + stmt.execute(); + try (ResultSet rs = stmt.getResultSet()) { + assertTrue(rs.next()); + Assert.assertEquals(rs.getInt(1), 1000); + Assert.assertEquals(rs.getString(2), "test"); + } + } catch (Exception e) { + fail("failed at keyword " + keyword, e); + } + } + } + } + + @Test(groups = {"integration"}) + public void testCTEWithUnboundCol() throws Exception { + try (Connection conn = getJdbcConnection()) { + String cte = "with ? as text, numz as (select text, number from system.numbers limit 10) select * from numz"; + try (PreparedStatement stmt = conn.prepareStatement(cte)) { + stmt.setString(1, "1000"); + + ResultSet rs = stmt.executeQuery(); + assertTrue(rs.next()); + assertEquals(rs.getString(1), "1000"); + assertEquals(rs.getString(2), "0"); + } + } + } + + @Test(groups = {"integration"}) + public void testWithInClause() throws Exception { + try (Connection conn = getJdbcConnection()) { + final String q1 = "select number from system.numbers where number in (?) limit 10"; + try (PreparedStatement stmt = conn.prepareStatement(q1)) { + Long[] filter = new Long[]{2L, 4L, 6L}; + stmt.setArray(1, conn.createArrayOf("Int64", filter)); + ResultSet rs = stmt.executeQuery(); + + for (Long filterValue : filter) { + assertTrue(rs.next()); + assertEquals(rs.getLong(1), filterValue); + } + Assert.assertFalse(rs.next()); + } + + final String q2 = "with t as (select arrayJoin([1, 2, 3]) as a ) select * from t where a in(?, ?)"; + try (PreparedStatement stmt = conn.prepareStatement(q2)) { + Long[] filter = new Long[]{2L, 3L}; + + stmt.setInt(1, 2); + stmt.setInt(2, 3); + ResultSet rs = stmt.executeQuery(); + + for (Long filterValue : filter) { + assertTrue(rs.next()); + assertEquals(rs.getLong(1), filterValue); + } + Assert.assertFalse(rs.next()); + } + } + } + + @Test(groups = {"integration"}, dataProvider = "testTypeCastsDP", enabled = false) + public void testTypeCastsWithoutArgument(Object value, SQLType targetType, ClickHouseDataType expectedType) throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { + stmt.setObject(1, value, targetType); + stmt.setObject(2, value, targetType); + + try (ResultSet rs = stmt.executeQuery()) { + rs.next(); + assertEquals(rs.getString(2), expectedType.getName()); + switch (expectedType) { + case IPv6: + break; + default: + assertEquals(rs.getString(1), String.valueOf(value)); + } + } + } + } + } + + @DataProvider(name = "testTypeCastsDP") + public static Object[][] testTypeCastsDP() { + return new Object[][] { + {100, ClickHouseDataType.Int8, ClickHouseDataType.Int8}, + {100L, ClickHouseDataType.Int16, ClickHouseDataType.Int16}, + {100L, ClickHouseDataType.Int32, ClickHouseDataType.Int32}, + {100L, ClickHouseDataType.Int64, ClickHouseDataType.Int64}, + {100L, ClickHouseDataType.UInt8, ClickHouseDataType.UInt8}, + {100L, ClickHouseDataType.UInt16, ClickHouseDataType.UInt16}, + {100L, ClickHouseDataType.UInt32, ClickHouseDataType.UInt32}, + {100L, ClickHouseDataType.UInt64, ClickHouseDataType.UInt64}, + {"ed0c77a3-2e4b-4954-98ee-22a4fdad9565", ClickHouseDataType.UUID, ClickHouseDataType.UUID}, + {"0:0:0:0:0:ffff:5ab0:4b61", ClickHouseDataType.IPv6, ClickHouseDataType.IPv6}, + {"116.253.40.133", ClickHouseDataType.IPv4, ClickHouseDataType.IPv4}, + {100, JDBCType.TINYINT, ClickHouseDataType.Int8} + }; + } + + @Test(groups = {"integration"}, dataProvider = "testJDBCTypeCastDP", enabled = false) + public void testJDBCTypeCast(Object value, int targetType, ClickHouseDataType expectedType) throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { + stmt.setObject(1, value, targetType); + stmt.setObject(2, value, targetType); + + try (ResultSet rs = stmt.executeQuery()) { + rs.next(); + assertEquals(rs.getString(2), expectedType.getName()); + switch (expectedType) { + case IPv4: + assertEquals(rs.getString(1), "/" + value); + break; + case IPv6: + break; + default: + assertEquals(rs.getString(1), String.valueOf(value)); + } + } + } + } + } + + @DataProvider(name = "testJDBCTypeCastDP") + public static Object[][] testJDBCTypeCastDP() { + return new Object[][] { + {100, JDBCType.TINYINT.getVendorTypeNumber().intValue(), ClickHouseDataType.Int8} + }; + } + + @Test(groups = {"integration"}, enabled = false) + public void testTypesInvalidForCast() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { + for (ClickHouseDataType type : JdbcUtils.INVALID_TARGET_TYPES) { + expectThrows(SQLException.class, () -> stmt.setObject(1, "", type)); + } + + expectThrows(SQLException.class, () -> stmt.setObject(1, "", JDBCType.OTHER.getVendorTypeNumber())); + expectThrows(SQLException.class, () -> stmt.setObject(1, "", ClickHouseDataType.DateTime64)); + } + } + } + + @Test(groups = {"integration"}, dataProvider = "testTypeCastWithScaleOrLengthDP", enabled = false) + public void testTypeCastWithScaleOrLength(Object value, SQLType targetType, Integer scaleOrLength, String expectedValue, + String expectedType) throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { + stmt.setObject(1, value, targetType, scaleOrLength); + stmt.setObject(2, value, targetType, scaleOrLength); + try (ResultSet rs = stmt.executeQuery()) { + rs.next(); + assertEquals(rs.getString(1), expectedValue); + assertEquals(rs.getString(2), expectedType); + } + } + } + } + + @DataProvider(name = "testTypeCastWithScaleOrLengthDP") + public static Object[][] testTypeCastWithScaleOrLengthDP() { + return new Object[][] { + {0.123456789, ClickHouseDataType.Decimal64, 3, "0.123", "Decimal(18, 3)"}, + {"hello", ClickHouseDataType.FixedString, 5, "hello", "FixedString(5)"}, + {"2017-10-02 10:20:30.333333", ClickHouseDataType.DateTime64, 3, "2017-10-02 10:20:30.333", "DateTime64(3)"} + }; + } + + @Test(groups = {"integration"}) + public void testCheckOfParametersAreSet() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ? as v1, ? as v2, ? as v3")) { + stmt.setString(1, "Test"); + stmt.setObject(2, null); + stmt.setString(3, null); + + try (ResultSet rs = stmt.executeQuery()) { + rs.next(); + Assert.assertEquals(rs.getString(1), "Test"); + Assert.assertEquals(rs.getInt(2), 0); + Assert.assertTrue(rs.wasNull()); + Assert.assertNull(rs.getString(2)); + Assert.assertTrue(rs.wasNull()); + } + + stmt.clearParameters(); + stmt.setString(1, "Test"); + stmt.setObject(2, null); + Assert.expectThrows(SQLException.class, stmt::executeQuery); + } + + try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO t VALUES (?, ?, ?)")) { + stmt.setString(1, "Test"); + + Assert.expectThrows(SQLException.class, stmt::executeUpdate); + } + } + } + + @Test + public void testParameterCount() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("select ?, ? as v1, ? as v2")) { + Assert.assertEquals(stmt.getMetaData().getColumnCount(), 3); + } + try (PreparedStatement stmt = conn.prepareStatement("WITH toDateTime(?) AS target_time SELECT * FROM table")) { + Assert.assertEquals(stmt.getMetaData().getColumnCount(), 1); + } + } + } + + @Test(dataProvider = "testGetMetadataIgnoresCommentsDataProvider") + public void testGetMetadataIgnoresComments(String sql) throws Exception { + try (Connection conn = getJdbcConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { + ResultSetMetaData metaData = stmt.getMetaData(); + assertEquals(metaData.getColumnCount(), 3); + assertEquals(metaData.getColumnName(1), "x"); + assertEquals(metaData.getColumnName(2), "y"); + assertEquals(metaData.getColumnName(3), "z"); + assertEquals(metaData.getColumnType(1), Types.VARCHAR); + assertEquals(metaData.getColumnType(3), Types.VARCHAR); + } + } + + @DataProvider(name = "testGetMetadataIgnoresCommentsDataProvider") + static Object[][] testGetMetadataIgnoresCommentsDataProvider() { + return new Object[][] { + {"SELECT 'a' AS x -- it's ?\n, ? AS y, 'z' AS z"}, + {"SELECT 'a' AS x # it's ?\n, ? AS y, 'z' AS z"}, + {"SELECT 'a' AS x /* it's ? */, ? AS y, 'z' AS z"}, + {"SELECT 'a?b' AS x, ? AS y, 'z' AS z"} + }; + } + + @Test(groups = {"integration"}) + void testDateDayShiftWithDifferentTimezones() throws Exception { + String table = tablePrefix() + "date_day_shift"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (id Int32, d Date) ORDER BY id"); + } + + String[] testDates = { + "2024-01-01", + "2024-12-31", + "2024-06-15", + "2024-03-10", + "2024-11-03" + }; + + TimeZone[] timezones = { + TimeZone.getTimeZone("UTC"), + TimeZone.getTimeZone("America/New_York"), + TimeZone.getTimeZone("America/Los_Angeles"), + TimeZone.getTimeZone("Europe/Moscow"), + TimeZone.getTimeZone("Asia/Tokyo"), + TimeZone.getTimeZone("Pacific/Auckland") + }; + + int id = 0; + for (String dateStr : testDates) { + LocalDate localDate = LocalDate.parse(dateStr); + java.sql.Date inputDate = java.sql.Date.valueOf(localDate); + for (TimeZone tz : timezones) { + id++; + Calendar calendar = new GregorianCalendar(tz); + LocalDate expectedLocalDate = DataTypeUtils.toLocalDate(inputDate, calendar.getTimeZone()); + java.sql.Date expectedDate = DataTypeUtils.toSqlDate(expectedLocalDate, calendar.getTimeZone()); + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { + stmt.setInt(1, id); + stmt.setDate(2, inputDate, calendar); + stmt.executeUpdate(); + } + + try (PreparedStatement stmt = conn.prepareStatement( + "SELECT d FROM " + table + " WHERE id = ?")) { + stmt.setInt(1, id); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next(), "Expected row for id=" + id); + java.sql.Date actualDate = rs.getDate(1, calendar); + LocalDate actualLocalDate = rs.getObject(1, LocalDate.class); + assertEquals(actualDate.getTime(), expectedDate.getTime()); + assertEquals(DataTypeUtils.toLocalDate(actualDate, calendar.getTimeZone()), expectedLocalDate, + String.format("Date mismatch for %s with timezone %s: expected %s, got %s", + dateStr, tz.getID(), expectedLocalDate, DataTypeUtils.toLocalDate(actualDate, calendar.getTimeZone()))); + assertEquals(actualLocalDate, expectedLocalDate, + String.format("LocalDate mismatch for %s with timezone %s: expected %s, got %s", + dateStr, tz.getID(), expectedLocalDate, actualLocalDate)); + } + } + } + } + + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE " + table); + } + } + } + + @Test(groups = {"integration"}) + void testDateWithAndWithoutCalendar() throws Exception { + String table = tablePrefix() + "date_calendar_comparison"; + try (Connection conn = getJdbcConnection()) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (id Int32, d Date) ORDER BY id"); + } + + java.sql.Date testDate = java.sql.Date.valueOf("2024-06-15"); + + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { + stmt.setInt(1, 1); + stmt.setDate(2, testDate); + stmt.executeUpdate(); + } + + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { + stmt.setInt(1, 2); + stmt.setDate(2, testDate, new GregorianCalendar(TimeZone.getTimeZone("UTC"))); + stmt.executeUpdate(); + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT id, d FROM " + table + " ORDER BY id")) { + + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 1); + java.sql.Date dateWithoutCalendar = rs.getDate(2); + + assertTrue(rs.next()); + assertEquals(rs.getInt(1), 2); + java.sql.Date dateWithCalendar = rs.getDate(2); + + assertEquals(dateWithoutCalendar.toString(), testDate.toString(), + "Date without Calendar should match original"); + assertEquals(dateWithCalendar.toString(), testDate.toString(), + "Date with Calendar should match original"); + } + + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE " + table); + } + } + } + + @Test(groups = {"integration"}) + public void testUnknownStatement() throws Exception { + try (Connection conn = getJdbcConnection()) { + try (PreparedStatement stmt = conn.prepareStatement("SELECT number, FROM system.numbers LIMIT 3")) { + Assert.assertTrue(stmt.execute()); + + try (ResultSet rs = stmt.getResultSet()) { + for (int i = 0; i < 3; i++) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getLong(1), i); + } + } + } + + try (Statement stmt = conn.createStatement()) { + Assert.assertTrue(stmt.execute("SELECT number, FROM system.numbers LIMIT 3")); + + try (ResultSet rs = stmt.getResultSet()) { + for (int i = 0; i < 3; i++) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getLong(1), i); + } + } + } + + String tmpTable = tablePrefix() + "tmp_no_result_" + RandomStringUtils.randomAlphanumeric(8); + try (PreparedStatement stmt = conn.prepareStatement( + "CREATE TABLE " + tmpTable + " (x Int32) ORDER BY()")) { + Assert.assertFalse(stmt.execute(), "DDL should not produce a ResultSet"); + Assert.assertNull(stmt.getResultSet(), "ResultSet should be null for DDL"); + assertThrows(SQLException.class, stmt::executeQuery); + } + String tmpTable2 = tablePrefix() + "tmp_no_result_" + RandomStringUtils.randomAlphanumeric(8); + try (Statement stmt = conn.createStatement()) { + Assert.assertFalse( + stmt.execute("CREATE TABLE " + tmpTable2 + " (x Int32) ORDER BY()"), + "DDL should not produce a ResultSet"); + Assert.assertNull(stmt.getResultSet(), "ResultSet should be null for DDL"); + assertThrows(SQLException.class, + () -> stmt.executeQuery("CREATE TABLE " + tmpTable2 + " (x Int32) ORDER BY()")); + } + } + } + + @DataProvider + public static Object[][] testInsertWithUnparsableValueExpression_dp() { + return new Object[][] { + {SqlParserFacade.SQLParser.ANTLR4.name()}, + {SqlParserFacade.SQLParser.ANTLR4_PARAMS_PARSER.name()}, + {SqlParserFacade.SQLParser.JAVACC.name()}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "testInsertWithUnparsableValueExpression_dp") + public void testInsertWithUnparsableValueExpression(String parserName) throws Exception { + String table = tablePrefix() + "unparsable_value_expr"; + Properties properties = new Properties(); + properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parserName); + properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); + try (Connection conn = getJdbcConnection(properties)) { + try (Statement stmt = conn.createStatement()) { + stmt.execute("DROP TABLE IF EXISTS " + table); + stmt.execute("CREATE TABLE " + table + " (v1 String, v2 String) ORDER BY ()"); + } + + try (PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO " + table + " (v1, v2) VALUES (hex(x'AB'), ?)")) { + assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); + stmt.setString(1, "abc"); + assertEquals(stmt.executeUpdate(), 1); + } + + try (Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT v1, v2 FROM " + table)) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "AB"); + assertEquals(rs.getString(2), "abc"); + assertFalse(rs.next()); + } + + try (PreparedStatement stmt = conn.prepareStatement("SELECT ? AS v1, hex(x'AB') AS v2")) { + assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); + stmt.setString(1, "abc"); + try (ResultSet rs = stmt.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getString(1), "abc"); + assertEquals(rs.getString(2), "AB"); + } + } + } + } +} diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/PreparedStatementTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/PreparedStatementTest.java index ab4c76191..b812128fb 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/PreparedStatementTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/PreparedStatementTest.java @@ -1,1464 +1,30 @@ package com.clickhouse.jdbc; -import com.clickhouse.client.api.DataTypeUtils; -import com.clickhouse.client.api.internal.ServerSettings; import com.clickhouse.data.ClickHouseColumn; -import com.clickhouse.data.ClickHouseDataType; -import com.clickhouse.data.ClickHouseVersion; -import com.clickhouse.data.Tuple; -import com.clickhouse.jdbc.internal.JdbcUtils; -import com.clickhouse.jdbc.internal.SqlParserFacade; -import org.apache.commons.lang3.RandomStringUtils; -import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.io.ByteArrayInputStream; -import java.io.InputStreamReader; -import java.sql.Array; import java.sql.Connection; -import java.sql.Date; -import java.sql.JDBCType; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.SQLType; -import java.sql.Statement; -import java.sql.Timestamp; -import java.sql.Types; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; +import java.util.Properties; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.expectThrows; -import static org.testng.Assert.fail; @Test(groups = { "integration" }) -public class PreparedStatementTest extends JdbcIntegrationTest { - - @Test(groups = { "integration" }) - public void testSetNull() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setNull(1, Types.INTEGER); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertNull(rs.getObject(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetBoolean() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setBoolean(1, true); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertTrue(rs.getBoolean(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetByte() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setByte(1, (byte) 1); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals((byte) 1, rs.getByte(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetShort() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setShort(1, (short) 1); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals((short) 1, rs.getShort(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetInt() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setInt(1, 1); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(1, rs.getInt(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetLong() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setLong(1, 1L); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(1L, rs.getLong(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetFloat() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setFloat(1, 1.0f); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(1.0f, rs.getFloat(1), 0.0f); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetDouble() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setDouble(1, 1.0); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(1.0, rs.getDouble(1), 0.0); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetString() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setString(1, "test"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals("test", rs.getString(1)); - assertFalse(rs.next()); - } - } - } - } - - @DataProvider(name = "specialCharacterStrings") - Object[][] specialCharacterStrings() { - return new Object[][] { - {"plain value"}, - {"tab\tinside"}, - {"newline\ninside"}, - {"C:\\temp"}, - {"quote'inside"}, - {"mixed\t'quote'\nand\\backslash"}, - {"unicode é中😀"}, - }; - } - - @Test(groups = { "integration" }, dataProvider = "specialCharacterStrings") - public void testSetStringWithSpecialCharacters(String value) throws Exception { - // A String bound with setString is inlined into the SQL as a single-quoted literal, so the - // backslash and single quote must be escaped (a tab or newline is a valid literal character). - // The value must round-trip byte-for-byte. - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setString(1, value); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), value); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetBytes() throws Exception { - // see com.clickhouse.jdbc.JdbcDataTypeTests.testStringsUsedAsBytes - // setBytes is dedicated for binary strings (see spec). - // arrays are set via Array object. - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setBytes(1, new byte[] { 1, 2, 3 }); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getBytes(1), new byte[] { 1, 2, 3 }); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetDate() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT toDate(?)")) { - stmt.setDate(1, java.sql.Date.valueOf("2021-01-01"), new GregorianCalendar(TimeZone.getTimeZone("UTC"))); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-01")); - assertFalse(rs.next()); - } - - stmt.setDate(1, java.sql.Date.valueOf("2021-01-02")); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-02")); - assertFalse(rs.next()); - } - - stmt.setObject(1, java.sql.Date.valueOf("2021-01-02")); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getDate(1), java.sql.Date.valueOf("2021-01-02")); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }, enabled = false) - public void testSetTime() throws Exception { - // https://github.com/ClickHouse/ClickHouse/issues/89896 - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT toTime(?)")) { - stmt.setTime(1, java.sql.Time.valueOf("12:34:56"), new GregorianCalendar(TimeZone.getTimeZone("UTC"))); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getTime(1).toString(), "12:34:56"); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testSetTimestamp() throws Exception { - final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT toDateTime64(?, 3)")) { - Timestamp tsToWrite = java.sql.Timestamp.valueOf("2021-01-01 01:34:56.456"); - ZonedDateTime tsSeenInCalendarTz = ZonedDateTime.ofInstant(tsToWrite.toInstant(), calendar.getTimeZone().toZoneId()); - stmt.setTimestamp(1, tsToWrite, calendar); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - - assertEquals(rs.getObject(1, ZonedDateTime.class), tsSeenInCalendarTz); - Timestamp dbTimestamp = rs.getTimestamp(1, calendar); - assertEquals(dbTimestamp.toInstant(), tsSeenInCalendarTz.toInstant()); - assertFalse(rs.next()); - } - } - - String localTimezone = TimeZone.getDefault().getID(); - try (PreparedStatement stmt = conn.prepareStatement("SELECT toDateTime64(?, 3, ?)")) { - LocalDateTime localTs = LocalDateTime.parse("2021-01-01T01:34:56").withNano((int) TimeUnit.MILLISECONDS.toNanos(456)); - stmt.setObject(1, localTs); - stmt.setString(2, localTimezone); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - - assertEquals(rs.getObject(1, LocalDateTime.class), localTs); - Timestamp dbTimestamp = rs.getTimestamp(1); - - assertEquals(dbTimestamp.getTime(), localTs.toInstant(ZoneId.systemDefault().getRules().getOffset(localTs)).toEpochMilli()); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testBigDecimal() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setBigDecimal(1, java.math.BigDecimal.valueOf(1.0)); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(java.math.BigDecimal.valueOf(1.0), rs.getBigDecimal(1)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testPrimitiveArrays() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setObject(1, new String[][] {new String[]{"a"}, new String[]{"b"}, new String[]{"c"}}); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - Array a1 = rs.getArray(1); - assertNotNull(a1); - assertEquals(Arrays.deepToString((Object[]) a1.getArray()), "[[a], [b], [c]]"); - Array a2 = rs.getObject(1, Array.class); - assertNotNull(a2); - assertEquals(Arrays.deepToString((Object[]) a2.getArray()), "[[a], [b], [c]]"); - Array a3 = rs.getObject(1) instanceof Array ? (Array) rs.getObject(1) : null; - assertNotNull(a3); - assertEquals(Arrays.deepToString((Object[]) a3.getArray()), "[[a], [b], [c]]"); - assertFalse(rs.next()); - } - } - - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setObject(1, new Object[] {1, 2, 3}); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - Array a1 = rs.getArray(1); - assertNotNull(a1); - assertEquals(Arrays.deepToString((Object[]) a1.getArray()), "[1, 2, 3]"); - } - } - } - } - - @Test - public void testTuple() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ?")) { - stmt.setObject(1, new Tuple("a", 1)); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(Arrays.asList(rs.getObject(1, Object[].class)).toString(), "[a, 1]"); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = {"integration"}) - public void testSetAsciiStream() throws Exception { - final String value = "Some long string with '' to check quote escaping"; - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { - stmt.setAsciiStream(1, new ByteArrayInputStream(value.getBytes())); - stmt.setAsciiStream(2, new ByteArrayInputStream(value.getBytes()), 10); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), value); - assertEquals(rs.getString(2), value.subSequence(0, 10)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = {"integration"}) - public void testSetUnicodeStream() throws Exception { - final String value = "Some long string with '' to check quote escaping"; - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { - stmt.setUnicodeStream(1, new ByteArrayInputStream(value.getBytes()), value.length()); - stmt.setUnicodeStream(2, new ByteArrayInputStream(value.getBytes()), 10); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), value); - assertEquals(rs.getString(2), value.subSequence(0, 10)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = {"integration"}) - public void testSetBinaryStream() throws Exception { - final String value = "Some long string with '' to check quote escaping"; - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { - stmt.setBinaryStream(1, new ByteArrayInputStream(value.getBytes())); - stmt.setBinaryStream(2, new ByteArrayInputStream(value.getBytes()), 10); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), value); - assertEquals(rs.getString(2), value.subSequence(0, 10)); - assertFalse(rs.next()); - } - } - } - } - - @Test - public void testSetNCharacterStream() throws Exception { - final String value = "Some long string with '' to check quote escaping"; - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? as v1, ? as v2")) { - stmt.setNCharacterStream(1, new InputStreamReader(new ByteArrayInputStream(value.getBytes()))); - stmt.setNCharacterStream(2, new InputStreamReader(new ByteArrayInputStream(value.getBytes())), 10); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), value); - assertEquals(rs.getString(2), value.subSequence(0, 10)); - assertFalse(rs.next()); - } - } - } - } - - - @Test(groups = { "integration" }) - public void testEscapeStrings() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT FALSE OR ? = 'test', ?")) { - stmt.setString(1, "test\\' OR 1 = 1 --"); - stmt.setString(2, "test\\\\' OR 1 = 1 --"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), "false"); - assertEquals(rs.getString(2), "test\\\\' OR 1 = 1 --"); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = { "integration" }) - public void testTernaryOperator() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT ( TRUE ? 1 : 0) as val1, ? as val2")) { - stmt.setString(1, "test\\' OR 1 = 1 --"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString("val1"), "1"); - assertEquals(rs.getString(2), "test\\' OR 1 = 1 --"); - assertFalse(rs.next()); - } - } - } - } - - - @Test(groups = "integration") - void testWithClause() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("with data as (SELECT number FROM numbers(100)) select * from data ")) { - stmt.execute(); - ResultSet rs = stmt.getResultSet(); - int count = 0; - while (rs.next()) { - count++; - } - assertEquals(count, 100); - } - } - } - - @Test(groups = "integration") - void testWithClauseWithParams() throws Exception { - final String table = "test_with_stmt"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (v1 String) ORDER BY ()"); - stmt.execute("INSERT INTO " + table + " VALUES ('A'), ('B')"); - } - final Timestamp target_time = Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS)); - try (PreparedStatement stmt = conn.prepareStatement("WITH " + - " toDateTime(?) as target_time, " + - " (SELECT 123) as magic_number" + - " SELECT *, target_time, magic_number FROM " + table)) { - stmt.setTimestamp(1, target_time); - stmt.execute(); - ResultSet rs = stmt.getResultSet(); - int count = 0; - assertEquals(rs.getMetaData().getColumnCount(), 3); - while (rs.next()) { - Assert.assertEquals( - rs.getTimestamp("target_time").toLocalDateTime().truncatedTo(ChronoUnit.SECONDS), - target_time.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS)); - Assert.assertEquals(rs.getString("magic_number"), "123"); - Assert.assertEquals( - rs.getTimestamp(2).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS), - target_time.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime().truncatedTo(ChronoUnit.SECONDS)); - Assert.assertEquals(rs.getString(3), "123"); - - count++; - } - assertEquals(count, 2, "Expected 2 rows"); - - } - } - } - - @Test(groups = { "integration" }) - void testMultipleWithClauses() throws Exception { - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement( - "WITH data1 AS (SELECT 1 AS a), " + - " data2 AS (SELECT a + 1 AS b FROM data1) " + - "SELECT * FROM data2")) { - ResultSet rs = stmt.executeQuery(); - assertTrue(rs.next()); - assertEquals(2, rs.getInt(1)); - assertFalse(rs.next()); - } - } - - @Test(groups = { "integration" }) - void testRecursiveWithClause() throws Exception { - if (ClickHouseVersion.of(getServerVersion()).check("(,24.3]")) { - return; // recursive CTEs were introduced in 24.4 - } - - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement( - "WITH RECURSIVE numbers AS (" + - " SELECT 1 AS n " + - " UNION ALL " + - " SELECT n + 1 FROM numbers WHERE n < 5" + - ") " + - "SELECT * FROM numbers ORDER BY n")) { - ResultSet rs = stmt.executeQuery(); - for (int i = 1; i <= 5; i++) { - assertTrue(rs.next()); - assertEquals(i, rs.getInt(1)); - } - assertFalse(rs.next()); - } - } - - @Test(groups = { "integration" }) - void testWithClauseWithMultipleParameters() throws Exception { - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement( - "WITH data AS (" + - " (SELECT number AS n " + - " FROM numbers(?) " + - " WHERE n > ?)" + - ") " + - "SELECT * FROM data WHERE n < ?")) { -//"WITH data AS ( (SELECT number AS n FROM numbers(?) WHERE n > ?)) SELECT * FROM data WHERE n < ?" - stmt.setInt(1, 10); // numbers(10) = 0-9 - stmt.setInt(2, 3); // n > 3 - stmt.setInt(3, 7); // n < 7 - - ResultSet rs = stmt.executeQuery(); - int count = 0; - int expected = 4; // 4,5,6 - while (rs.next()) { - count++; - int n = rs.getInt(1); - assertTrue(n > 3 && n < 7); - } - assertEquals(3, count); - } - } - - @Test(groups = { "integration" }) - void testSelectFromArray() throws Exception { - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement( - "SELECT * FROM numbers(?)")) { - stmt.setInt(1, 10); // numbers(10) = 0-9 - ResultSet rs = stmt.executeQuery(); - int count = 0; - while (rs.next()) { - count++; - } - assertEquals(10, count); - } - } - - @Test(groups = { "integration" }) - void testInsert() throws Exception { - int ROWS = 1000; - String payload = RandomStringUtils.random(1024, true, true); - try (Connection conn = getJdbcConnection()) { - for (int j = 0; j < 10; j++) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS insert_batch"); - stmt.execute("CREATE TABLE insert_batch ( `off16` Int16, `str` String, `p_int8` Int8, `p_int16` Int16, `p_int32` Int32, `p_int64` Int64, `p_float32` Float32, `p_float64` Float64, `p_bool` Bool) ORDER BY ()"); - } - String insertQuery = "INSERT INTO insert_batch (off16, str, p_int8, p_int16, p_int32, p_int64, p_float32, p_float64, p_bool) VALUES (?,?,?,?,?,?,?,?,?)"; - try (PreparedStatement stmt = conn.prepareStatement(insertQuery)) { - for (int i = 0; i < ROWS; i++) { - stmt.setShort(1, (short) i); - stmt.setString(2, payload); - stmt.setByte(3, (byte)i); - stmt.setShort(4, (short)i); - stmt.setInt(5, i); - stmt.setLong(6, (long)i); - stmt.setFloat(7, (float)(i*0.1)); - stmt.setDouble(8, (double)(i*0.1)); - stmt.setBoolean(9, true); - stmt.addBatch(); - } - long startBatchTime = System.currentTimeMillis(); - stmt.executeBatch(); - long endBatchTime = System.currentTimeMillis(); - System.out.println("Insertion Time for Final Batch: " + (endBatchTime - startBatchTime) + " ms"); - } - // count rows - try (Statement stmt = conn.createStatement()) { - try (ResultSet rs = stmt.executeQuery("SELECT count(*) FROM insert_batch")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), ROWS); - } - } - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE insert_batch"); - } - - } - - } - } - - @Test(dataProvider = "testGetMetadataDataProvider") - void testGetMetadata(String sql, int colCountBeforeExecution, Object[] values, - int colCountAfterExecution) throws Exception { - String tableName = "test_get_metadata"; - runQuery("CREATE TABLE IF NOT EXISTS " + tableName + " ( a1 String, b2 Float, b3 Float ) ORDER BY ()"); - - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement(String.format(sql, tableName))) { - ResultSetMetaData metadataRs = stmt.getMetaData(); - assertNotNull(metadataRs); - Assert.assertEquals(metadataRs.getColumnCount(), colCountBeforeExecution); - - for (int i = 1; i <= metadataRs.getColumnCount(); i++) { - assertEquals(metadataRs.getSchemaName(i), stmt.getConnection().getSchema()); - } - - if (values != null) { - for (int i = 0; i < values.length; i++) { - stmt.setObject(i + 1, values[i]); - } - } - - stmt.execute(); - metadataRs = stmt.getMetaData(); - - assertNotNull(metadataRs); - assertEquals(metadataRs.getColumnCount(), colCountAfterExecution); - for (int i = 1; i <= metadataRs.getColumnCount(); i++) { - assertEquals(metadataRs.getSchemaName(i), stmt.getConnection().getSchema()); - } - } - } - - @DataProvider(name = "testGetMetadataDataProvider") - static Object[][] testGetMetadataDataProvider() { - return new Object[][] { - {"INSERT INTO `%s` VALUES (?, ?, ?)", 3, new Object[]{"test", 0.3f, 0.4f}, 3}, - {"SELECT * FROM `%s`", 3, null, 3}, - {"SHOW TABLES", 0, null, 1} - }; - } - - @Test(groups = { "integration" }) - void testGetMetadataAppliesCustomTypeMapping() throws Exception { - // Custom mapping overrides the Java class / JDBC type reported for integer columns. The metadata - // returned by PreparedStatementImpl#getMetaData must honor this mapping both before the statement is - // executed (resolved from the parsed query schema) and after it is executed (resolved from the result set). - Properties properties = new Properties(); - properties.setProperty(DriverProperties.JDBC_TYPE_MAPPINGS.getKey(), "Int32=Long,UInt64=String"); - - Consumer verify = (metaData) -> { - try { - assertEquals(metaData.getColumnCount(), 3); - - assertEquals(metaData.getColumnName(1), "i32"); - assertEquals(metaData.getColumnClassName(1), Long.class.getName()); - assertEquals(metaData.getColumnType(1), Types.BIGINT); - - assertEquals(metaData.getColumnName(2), "u64"); - assertEquals(metaData.getColumnClassName(2), String.class.getName()); - assertEquals(metaData.getColumnType(2), Types.VARCHAR); - - assertEquals(metaData.getColumnName(3), "u16"); - assertEquals(metaData.getColumnClassName(3), Integer.class.getName()); - assertEquals(metaData.getColumnType(3), Types.INTEGER); - - } catch (SQLException e) { - fail("no exception expected", e); - } - }; - - try (Connection conn = getJdbcConnection(properties); - PreparedStatement stmt = conn.prepareStatement("SELECT toInt32(?) AS i32, toUInt64(?) AS u64, toUInt16(?) as u16")) { - // Before execution: metadata is derived from the query schema and must already reflect the mapping. - ResultSetMetaData beforeExec = stmt.getMetaData(); - assertNotNull(beforeExec); - - stmt.setInt(1, 42); - stmt.setLong(2, 7L); - stmt.setInt(3, 20); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - // Values are materialized using the same mapping. - assertTrue(rs.getObject("i32") instanceof Long, "i32 should be mapped to Long"); - assertTrue(rs.getObject("u64") instanceof String, "u64 should be mapped to String"); - assertTrue(rs.getObject("u16") instanceof Integer, "u16 should be mapped to Integer"); - - // After execution: metadata is taken from the result set but must stay in sync with the mapping. - ResultSetMetaData afterExec = stmt.getMetaData(); - assertNotNull(afterExec); - verify.accept(afterExec); - } - } - } - - @Test(groups = { "integration" }) - void testMetabaseBug01() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `users`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp01`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp02`"); - stmt.execute("CREATE TABLE `users` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); - stmt.execute("CREATE TABLE `users_tmp` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); - stmt.execute("CREATE TABLE `users_tmp01` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); - stmt.execute("CREATE TABLE `users_tmp02` (`id` Int32, `name` Nullable(String), `last_login` Nullable(DateTime64(3, 'GMT0')), `password` Nullable(String)) ORDER BY ();"); - } - try { - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users` (`name`, `last_login`, `password`, `id`) VALUES (?, `parseDateTimeBestEffort`(?, ?), ?, 1), (?, `parseDateTimeBestEffort`(?, ?), ?, 2), (?, `parseDateTimeBestEffort`(?, ?), ?, 3), (?, `parseDateTimeBestEffort`(?, ?), ?, 4), (?, `parseDateTimeBestEffort`(?, ?), ?, 5), (?, `parseDateTimeBestEffort`(?, ?), ?, 6), (?, `parseDateTimeBestEffort`(?, ?), ?, 7), (?, `parseDateTimeBestEffort`(?, ?), ?, 8), (?, `parseDateTimeBestEffort`(?, ?), ?, 9), (?, `parseDateTimeBestEffort`(?, ?), ?, 10), (?, `parseDateTimeBestEffort`(?, ?), ?, 11), (?, `parseDateTimeBestEffort`(?, ?), ?, 12), (?, `parseDateTimeBestEffort`(?, ?), ?, 13), (?, `parseDateTimeBestEffort`(?, ?), ?, 14), (?, `parseDateTimeBestEffort`(?, ?), ?, 15)")) { - stmt.setObject(1, "Plato Yeshua"); - stmt.setObject(2, "2014-04-01 08:30:00.000"); - stmt.setObject(3, "UTC"); - stmt.setObject(4, "4be68cda-6fd5-4ba7-944e-2b475600bda5"); - stmt.setObject(5, "Felipinho Asklepios"); - stmt.setObject(6, "2014-12-05 15:15:00.000"); - stmt.setObject(7, "UTC"); - stmt.setObject(8, "5bb19ad9-f3f8-421f-9750-7d398e38428d"); - stmt.setObject(9, "Kaneonuskatew Eiran"); - stmt.setObject(10, "2014-11-06 16:15:00.000"); - stmt.setObject(11, "UTC"); - stmt.setObject(12, "a329ccfe-b99c-42eb-9c93-cb9adc3eb1ab"); - stmt.setObject(13, "Simcha Yan"); - stmt.setObject(14, "2014-01-01 08:30:00.000"); - stmt.setObject(15, "UTC"); - stmt.setObject(16, "a61f97c6-4484-4a63-b37e-b5e58bfa2ecb"); - stmt.setObject(17, "Quentin Sören"); - stmt.setObject(18, "2014-10-03 17:30:00.000"); - stmt.setObject(19, "UTC"); - stmt.setObject(20, "10a0fea8-9bb4-48fe-a336-4d9cbbd78aa0"); - stmt.setObject(21, "Shad Ferdynand"); - stmt.setObject(22, "2014-08-02 12:30:00.000"); - stmt.setObject(23, "UTC"); - stmt.setObject(24, "d35c9d78-f9cf-4f52-b1cc-cb9078eebdcb"); - stmt.setObject(25, "Conchúr Tihomir"); - stmt.setObject(26, "2014-08-02 09:30:00.000"); - stmt.setObject(27, "UTC"); - stmt.setObject(28, "900335ad-e03b-4259-abc7-76aac21cedca"); - stmt.setObject(29, "Szymon Theutrich"); - stmt.setObject(30, "2014-02-01 10:15:00.000"); - stmt.setObject(31, "UTC"); - stmt.setObject(32, "d6c47a54-9d88-4c4a-8054-ace76764ed0d"); - stmt.setObject(33, "Nils Gotam"); - stmt.setObject(34, "2014-04-03 09:30:00.000"); - stmt.setObject(35, "UTC"); - stmt.setObject(36, "b085040c-7aa4-4e96-8c8f-420b2c99c920"); - stmt.setObject(37, "Frans Hevel"); - stmt.setObject(38, "2014-07-03 19:30:00.000"); - stmt.setObject(39, "UTC"); - stmt.setObject(40, "b7a43e91-9fb9-4fe9-ab6f-ea51ab0f94e4"); - stmt.setObject(41, "Spiros Teofil"); - stmt.setObject(42, "2014-11-01 07:00:00.000"); - stmt.setObject(43, "UTC"); - stmt.setObject(44, "62b9602c-27b8-44ea-adbd-2748f26537af"); - stmt.setObject(45, "Kfir Caj"); - stmt.setObject(46, "2014-07-03 01:30:00.000"); - stmt.setObject(47, "UTC"); - stmt.setObject(48, "dfe21df3-f364-479d-a5e7-04bc5d85ad2b"); - stmt.setObject(49, "Dwight Gresham"); - stmt.setObject(50, "2014-08-01 10:30:00.000"); - stmt.setObject(51, "UTC"); - stmt.setObject(52, "75a1ebf1-cae7-4a50-8743-32d97500f2cf"); - stmt.setObject(53, "Broen Olujimi"); - stmt.setObject(54, "2014-10-03 13:45:00.000"); - stmt.setObject(55, "UTC"); - stmt.setObject(56, "f9b65c74-9f91-4cfd-9248-94a53af82866"); - stmt.setObject(57, "Rüstem Hebel"); - stmt.setObject(58, "2014-08-01 12:45:00.000"); - stmt.setObject(59, "UTC"); - stmt.setObject(60, "02ad6b15-54b0-4491-bf0f-d781b0a2c4f5"); - stmt.addBatch(); - stmt.executeBatch(); - } - try (Statement stmt01 = conn.createStatement()) { - try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users`")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 15); - } - } - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp` SELECT * FROM `users` WHERE id = ?")) { - stmt.setInt(1, 1); - stmt.addBatch(); - stmt.setInt(1, 2); - stmt.addBatch(); - stmt.setInt(1, 3); - stmt.addBatch(); - stmt.executeBatch(); - } - - StringBuilder sb = new StringBuilder(); - try (Statement stmt01 = conn.createStatement()) { - try (ResultSet rs = stmt01.executeQuery("SELECT id, name FROM `users_tmp`")) { - while (rs.next()) { - sb.append(rs.getInt(1)).append(",").append(rs.getString(2)).append(";"); - } - } - } - - - try (Statement stmt01 = conn.createStatement()) { - try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp`")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 3,"Users in users_tmp: " + sb); - } - } - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp01` SELECT * FROM `users` WHERE id = ?")) { - stmt.setInt(1, 1); - stmt.addBatch(); - stmt.executeBatch(); - } - - try (Statement stmt01 = conn.createStatement()) { - try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp01`")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1); - } - } - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO `users_tmp02` (`name`, `last_login`, `password`, `id`) VALUES (?, `parseDateTimeBestEffort`(?, ?), ?, ?)")) { - for (int i=0; i < 10; i++) { - stmt.setObject(1, "Plato Yeshua"); - stmt.setObject(2, "2014-04-01 08:30:00.000"); - stmt.setObject(3, "UTC"); - stmt.setObject(4, "4be68cda-6fd5-4ba7-944e-2b475600bda5"); - stmt.setObject(5, i); - stmt.addBatch(); - } - stmt.executeBatch(); - } - - try (Statement stmt01 = conn.createStatement()) { - try (ResultSet rs = stmt01.executeQuery("SELECT count(*) FROM `users_tmp02`")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 10); - } - } - } finally { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `users`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp01`"); - stmt.execute("DROP TABLE IF EXISTS `users_tmp02`"); - } - } - } - } - - @Test(groups = { "integration" }, dataProvider = "insertWithRewrittenValuesListDP") - void testInsertWithRewrittenValuesList(String valuesList) throws Exception { - final String table = "test_insert_rewritten_values_list"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (s String, n Int32) ORDER BY ()"); - } - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (s, n) VALUES " + valuesList)) { - assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); - stmt.setInt(1, 42); - stmt.addBatch(); - } - } - } - - @DataProvider(name = "insertWithRewrittenValuesListDP") - public static Object[][] insertWithRewrittenValuesListDP() { - return new Object[][] { - { "(toDateTime({ts '2024-01-01 00:00:00'}), ?)" }, - { "(toTime({t '10:20:30'}), ?)" }, - { "(toInt32({d:Int32}), ?)" }, - }; - } - - @Test(groups = { "integration" }) - void testBatchInsertWithRewrittenValuesList() throws Exception { - final String table = "test_batch_insert_rewritten_values_list"; - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (s DateTime, n Int32) ORDER BY ()"); - } - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table - + " (s, n) VALUES (toDateTime({ts '2024-01-01 00:00:00'}), ?)")) { - stmt.setInt(1, 42); - stmt.addBatch(); - stmt.setInt(1, 43); - stmt.addBatch(); - assertEquals(stmt.executeBatch().length, 2); - stmt.clearBatch(); - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT n FROM " + table + " ORDER BY n")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 42); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 43); - assertFalse(rs.next()); - } - } - } - - @Test(groups = { "integration" }) - void testInsertWithHeredocValue() throws Exception { - final String table = "test_insert_heredoc"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (s String, n Int32) ORDER BY ()"); - } - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (s, n) VALUES ($$a@b$$, ?)")) { - stmt.setInt(1, 42); - assertEquals(stmt.executeUpdate(), 1); - } - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT s, n FROM " + table)) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), "a@b"); - assertEquals(rs.getInt(2), 42); - assertFalse(rs.next()); - } - } - } - - @Test(groups = { "integration" }) - void testStatementSplit() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS `with_complex_id` (`v?``1` Int32, " + - "\"v?\"\"2\" Int32,`v?\\`3` Int32, \"v?\\\"4\" Int32) ORDER BY ();"); - stmt.execute("CREATE TABLE IF NOT EXISTS `test_stmt_split2` (v1 Int32, v2 String) ORDER BY (); "); - stmt.execute("INSERT INTO `test_stmt_split2` VALUES (1, 'abc'), (2, '?'), (3, '?')"); - } - String insertQuery = "-- line comment1 ?\n" - + "# line comment2 ?\n" - + "#! line comment3 ?\n" - + "/* block comment ? \n */" - + "INSERT INTO `with_complex_id`(`v?``1`, \"v?\"\"2\",`v?\\`3`, \"v?\\\"4\") VALUES (?, ?, ?, ?);"; - try (PreparedStatement stmt = conn.prepareStatement(insertQuery)) { - stmt.setInt(1, 1); - stmt.setInt(2, 2); - stmt.setInt(3, 3); - stmt.setInt(4, 4); - stmt.execute(); - } - String selectQuery = "-- line comment ?\n" - + "/* block comment ? \n */" - + "SELECT `v?``1`, \"v?\"\"2\",`v?\\`3`, \"v?\\\"4\", 'test '' string1 ?', 'test \\' string2 ?', 'test string3 ?\\\\' FROM `with_complex_id` WHERE `v?``1` = ? AND \"v?\"\"2\" = ? AND `v?\\`3` = ? AND \"v?\\\"4\" = ?"; - try (PreparedStatement stmt = conn.prepareStatement(selectQuery)) { - stmt.setInt(1, 1); - stmt.setInt(2, 2); - stmt.setInt(3, 3); - stmt.setInt(4, 4); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1); - assertEquals(rs.getInt(2), 2); - assertEquals(rs.getInt(3), 3); - assertEquals(rs.getInt(4), 4); - assertEquals(rs.getString(5), "test ' string1 ?"); - assertEquals(rs.getString(6), "test ' string2 ?"); - assertEquals(rs.getString(7), "test string3 ?\\"); - } - } - - try (PreparedStatement stmt = conn.prepareStatement("SELECT v1 FROM `test_stmt_split2` WHERE v1 > ? AND v2 = '?'")) { - stmt.setInt(1, 2); - try (ResultSet rs = stmt.executeQuery()) { - int count = 0; - while (rs.next()) { - count++; - assertEquals(rs.getInt(1), 3); - } - - Assert.assertEquals(count, 1); - } - } - - } - } - - @Test(groups = { "integration" }, dataProvider = "commentsAndHeredocsDP") - void testPlaceholdersWithCommentsAndHeredocs(String sql, String expected) throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, "42"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), expected); - assertFalse(rs.next()); - } - } - } - } - - @DataProvider(name = "commentsAndHeredocsDP") - public static Object[][] commentsAndHeredocsDP() { - return new Object[][] { - {"SELECT ? AS v // ?", "42"}, - {"SELECT ? AS v // ?\nUNION ALL SELECT NULL WHERE 0", "42"}, - {"SELECT //\n? AS v", "42"}, - {"SELECT --\n? AS v", "42"}, - {"SELECT concat($$?$$, ?) AS v", "?42"}, - {"SELECT concat($tag$ ? $tag$, ?) AS v", " ? 42"}, - {"SELECT ? AS a$x$, 1 AS b$x$", "42"}, - {"SELECT ? AS a$$b$, 1 AS x$$b$", "42"}, - }; - } - - @Test(groups = {"integration"}) - void testClearParameters() throws Exception { - final String sql = "insert into `test_issue_2299` (`id`, `name`, `age`) values (?, ?, ?)"; - - - try (Connection conn = getJdbcConnection();) { - - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS `test_issue_2299` (`id` Nullable(String), `name` Nullable(String), `age` Int32) ENGINE Memory;"); - } - - try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { - - Assert.assertEquals(ps.getParametersCount(), 3); - - ps.setString(1, "testId"); - ps.setString(2, "testName"); - ps.setInt(3, 18); - ps.execute(); - - ps.clearParameters(); - Assert.assertEquals(ps.getParametersCount(), 3); - - ps.setString(1, "testId2"); - ps.setString(2, "testName2"); - ps.setInt(3, 19); - ps.execute(); - } - } - } - - @DataProvider - Object[][] testBatchInsertWithRowBinary_dp() { - return new Object[][]{ - {"INSERT INTO \n `%s` \nVALUES (?, ?, abs(?), ?)", PreparedStatementImpl.class}, // only string possible (because of abs(?)) - {"INSERT INTO\n `%s` \nVALUES (?, ?, ?, ?)", WriterStatementImpl.class}, // row binary writer - {" INSERT INTO %s (ts, v1, v2, v3) VALUES (?, ?, ?, ?)", WriterStatementImpl.class}, // only string supported now - {"INSERT INTO %s SELECT ?, ?, ?, ?", PreparedStatementImpl.class}, // only string possible (because of SELECT) - }; - } - - @Test(dataProvider = "testBatchInsertWithRowBinary_dp") - void testBatchInsertWithRowBinary(String sql, Class implClass) throws Exception { - String table = "test_batch"; - long seed = System.currentTimeMillis(); - Random rnd = new Random(seed); - System.out.println("testBatchInsert seed" + seed); - Properties properties = new Properties(); - properties.put(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); - try (Connection conn = getJdbcConnection(properties)) { - - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS " + table + - " ( ts DateTime, v1 Int32, v2 Float32, v3 Int32) ORDER BY ()"); - } - - final int nBatches = 10; - try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { - Assert.assertEquals(stmt.getClass(), implClass); - for (int bI = 0; bI < nBatches; bI++) { - // truncate to seconds to make fit into DateTime - stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS))); - stmt.setInt(2, rnd.nextInt()); - stmt.setFloat(3, rnd.nextFloat()); - stmt.setInt(4, rnd.nextInt()); - stmt.addBatch(); - } - - int[] result = stmt.executeBatch(); - for (int r : result) { - Assert.assertTrue(r == 1 || r == PreparedStatement.SUCCESS_NO_INFO); - } - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);) { - - int count = 0; - while (rs.next()) { - Timestamp ts = rs.getTimestamp(1); - assertNotNull(ts); - assertTrue(rs.getInt(2) != 0); - assertTrue(rs.getFloat(3) != 0.0f); - assertTrue(rs.getInt(4) != 0); - count++; - } - assertEquals(count, nBatches); - - stmt.execute("TRUNCATE " + table); - } - } - } - - @DataProvider - Object[][] testBatchInsertTextStatement_dp() { - return new Object[][]{ - {"INSERT INTO \n `%s` \nVALUES (?, ?, ?, ?)"}, // simple - {" INSERT INTO %s (ts, v1, v2, v3) VALUES (?, ?, ?, ?)"}, - }; - } - - @Test(dataProvider = "testBatchInsertTextStatement_dp") - void testBatchInsertTextStatement(String sql) throws Exception { - String table = "test_batch_text"; - long seed = System.currentTimeMillis(); - Random rnd = new Random(seed); - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS " + table + - " ( ts DateTime DEFAULT now(), v1 Int32, v2 Float32, v3 Int32) ORDER BY ()"); - } - - final int nBatches = 10; - - try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { - Assert.assertEquals(stmt.getClass(), PreparedStatementImpl.class); - for (int bI = 0; bI < nBatches; bI++) { - stmt.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS))); - stmt.setInt(2, rnd.nextInt()); - stmt.setFloat(3, rnd.nextFloat()); - stmt.setInt(4, rnd.nextInt()); - stmt.addBatch(); - } - - int[] result = stmt.executeBatch(); - for (int r : result) { - Assert.assertEquals(r, 1); - } - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);) { - - int count = 0; - while (rs.next()) { - Timestamp ts = rs.getTimestamp(1); - assertNotNull(ts); - assertTrue(rs.getInt(2) != 0); - assertTrue(rs.getFloat(3) != 0.0f); - assertTrue(rs.getInt(4) != 0); - count++; - } - assertEquals(count, nBatches); - - stmt.execute("TRUNCATE " + table); - } - - } - } - - @Test(groups = {"integration"}) - void testBatchInsertNoValuesReuse() throws Exception { - String table = "test_pstmt_batch_novalues_reuse"; - String sql = "INSERT INTO %s (v1, v2) VALUES (?, ?)"; - long seed = System.currentTimeMillis(); - Random rnd = new Random(seed); - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS " + table + - " (v1 Int32, v2 Int32) ORDER BY tuple()"); - } - - final int nBatches = 10; - try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { - Assert.assertEquals(stmt.getClass(), PreparedStatementImpl.class); - // add a batch with invalid values - stmt.setString(1, "invalid"); - stmt.setInt(2, rnd.nextInt()); - stmt.addBatch(); - assertThrows(SQLException.class, stmt::executeBatch); - // should fail due to the previous batch data. - assertThrows(SQLException.class, stmt::executeBatch); - // clear previous batch data - stmt.clearBatch(); - - for (int step = 0; step < 2; step++) { - for (int bI = 0; bI < (nBatches >> 1); bI++) { - stmt.setInt(1, rnd.nextInt()); - stmt.setInt(2, rnd.nextInt()); - stmt.addBatch(); - } - - // reuse the same statement - int[] result = stmt.executeBatch(); - for (int r : result) { - Assert.assertEquals(r, 1); - } - } - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);) { - - int count = 0; - while (rs.next()) { - assertTrue(rs.getInt(1) != 0); - assertTrue(rs.getInt(2) != 0); - count++; - } - assertEquals(count, nBatches); - } - } - } - - @Test() - void testBatchInsertValuesReuse() throws Exception { - String table = "test_pstmt_batch_values_reuse"; - String sql = "INSERT INTO %s (v1, v2) VALUES (1, ?)"; - long seed = System.currentTimeMillis(); - Random rnd = new Random(seed); - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS " + table + - " (v1 Int32, v2 Int32) ORDER BY tuple()"); - } - - final int nBatches = 10; - try (PreparedStatement stmt = conn.prepareStatement(String.format(sql, table))) { - Assert.assertEquals(stmt.getClass(), PreparedStatementImpl.class); - // add a batch with invalid values - stmt.setString(1, "invalid"); - stmt.addBatch(); - assertThrows(SQLException.class, stmt::executeBatch); - // should fail due to the previous batch data. - assertThrows(SQLException.class, stmt::executeBatch); - // clear previous batch data - stmt.clearBatch(); - - for (int step = 0; step < 2; step++) { - for (int bI = 0; bI < (nBatches >> 1); bI++) { - stmt.setInt(1, rnd.nextInt()); - stmt.addBatch(); - } - - // reuse the same statement - int[] result = stmt.executeBatch(); - for (int r : result) { - Assert.assertEquals(r, 1); - } - } - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table);) { - - int count = 0; - while (rs.next()) { - assertTrue(rs.getInt(1) != 0); - assertTrue(rs.getInt(2) != 0); - count++; - } - assertEquals(count, nBatches); - } - } - } - - @Test(groups = {"integration"}, dataProvider = "sqlParserDP") - void testBatchInsertWithValueOfUnsupportedSyntax(String parserName) throws Exception { - String table = "test_pstmt_batch_unsupported_syntax"; - Properties properties = new Properties(); - properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parserName); - properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); - try (Connection conn = getJdbcConnection(properties)) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (v1 Int32, v2 String) ORDER BY ()"); - } - - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (v1, v2) VALUES (?, hex(x'AB'))")) { - for (int i = 1; i <= 2; i++) { - stmt.setInt(1, i); - stmt.addBatch(); - } - assertEquals(stmt.executeBatch().length, 2); - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT v1, v2 FROM " + table + " ORDER BY v1")) { - for (int i = 1; i <= 2; i++) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), i); - assertEquals(rs.getString(2), "AB"); - } - assertFalse(rs.next()); - } - } - } - - @DataProvider(name = "sqlParserDP") - public static Object[][] sqlParserDP() { - return new Object[][] { - { SqlParserFacade.SQLParser.JAVACC.name() }, - { SqlParserFacade.SQLParser.ANTLR4.name() }, - { SqlParserFacade.SQLParser.ANTLR4_PARAMS_PARSER.name() }, - }; - } - - @Test(groups = {"integration"}) - void testWriteUUID() throws Exception { - String sql = "insert into `test_issue_2327` (`id`, `uuid`) values (?, ?)"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `test_issue_2327`"); - stmt.execute("CREATE TABLE IF NOT EXISTS `test_issue_2327` (`id` Nullable(String), `uuid` UUID) ORDER BY ();"); - } - try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { - UUID uuid = UUID.randomUUID(); - ps.setString(1, "testId01"); - ps.setObject(2, uuid); - ps.execute(); - - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("SELECT count(*) FROM `test_issue_2327`"); - Assert.assertTrue(rs.next()); - Assert.assertEquals(rs.getInt(1), 1); - } - - final String selectSQL = "SELECT * FROM `test_issue_2327` WHERE " + - "`" + getDatabase() + "`.`test_issue_2327`.`uuid` IN (CAST(? AS UUID))"; - try (PreparedStatement stmt = conn.prepareStatement(selectSQL)) { - stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { - Assert.assertTrue(rs.next()); - Assert.assertEquals(rs.getString(1), "testId01"); - Assert.assertEquals(rs.getString(2), uuid.toString()); - } - } - } finally { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `test_issue_2327`"); - } - } - } +public class PreparedStatementTest extends AbstractPreparedStatementTest { + @Override + protected void configureConnectionProperties(Properties properties) { + properties.setProperty(DriverProperties.STREAMING_PREPARED_STATEMENT.getKey(), "false"); } - @Test(groups = {"integration"}) - void testWriteCollection() throws Exception { - String sql = "insert into `test_issue_2329` (`id`, `name`, `age`, `arr`) values (?, ?, ?, ?)"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `test_issue_2329`"); - stmt.execute("CREATE TABLE IF NOT EXISTS `test_issue_2329` (`id` Nullable(String), `name` Nullable(String), `age` Int32, `arr` Array(String)) ORDER BY ();"); - } - try (PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { - Assert.assertEquals(ps.getParametersCount(), 4); - Collection arr = new ArrayList(); - ps.setString(1, "testId01"); - ps.setString(2, "testName"); - ps.setInt(3, 18); - ps.setObject(4, arr); - ps.execute(); - - try (Statement stmt = conn.createStatement()) { - ResultSet rs = stmt.executeQuery("SELECT count(*) FROM `test_issue_2329`"); - Assert.assertTrue(rs.next()); - Assert.assertEquals(rs.getInt(1), 1); - } - } finally { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS `test_issue_2329`"); - } - } - } - + @Override + protected Class expectedPreparedStatementClass() { + return PreparedStatementImpl.class; } - @Test - void testMethodsNotAllowedToBeCalled() throws Exception { - /* Story About Broken API - * There is a Statement interface. It is designed to operate with single statements. - * So there are method like execute(String) and addBatch(String). - * Some statements may be repeated over and over again. And they should be constructed - * over and over again. PreparedStatement was created to solve the issue by accepting - * an SQL statement as constructor parameter and making its method work in context of - * one, prepared SQL statement. - * But someone missed their OOP classes and done this: - * "interface PreparedStatement extends Statement" - * and - * declared some method from Statement interface not to be called on PreparedStatement - * instances. - * That is how today we have a great confusion and have to check it in all implementations. - */ - String sql = "SELECT number FROM system.numbers WHERE number = ?"; - try (Connection conn = getJdbcConnection(); - PreparedStatementImpl ps = (PreparedStatementImpl) conn.prepareStatement(sql)) { - - Assert.assertThrows(SQLException.class, () -> ps.addBatch(sql)); - Assert.assertThrows(SQLException.class, () -> ps.executeQuery(sql)); - Assert.assertThrows(SQLException.class, () -> ps.execute(sql)); - Assert.assertThrows(SQLException.class, () -> ps.execute(sql, new int[]{0})); - Assert.assertThrows(SQLException.class, () -> ps.execute(sql, new String[]{""})); - Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql)); - Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql, new int[]{0})); - Assert.assertThrows(SQLException.class, () -> ps.executeUpdate(sql, new String[]{""})); - Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql)); - Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql, new int[]{0})); - Assert.assertThrows(SQLException.class, () -> ps.executeLargeUpdate(sql, new String[]{""})); - } + @Override + protected String tablePrefix() { + return "ps_legacy_"; } @Test(dataProvider = "testReplaceQuestionMark_dataProvider") @@ -1477,473 +43,17 @@ public static Object[][] testReplaceQuestionMark_dataProvider() { }; } - @Test(groups = { "integration" }) - public void testJdbcEscapeSyntax() throws Exception { - if (ClickHouseVersion.of(getServerVersion()).check("(,23.8]")) { - return; // there is no `timestamp` function TODO: fix in JDBC - } - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT {d '2021-11-01'} AS D, {ts '2021-08-01 12:34:56'} AS TS, " + - "toInt32({fn ABS(-1)}) AS FNABS, {fn CONCAT('Hello', 'World')} AS FNCONCAT, {fn UCASE('hello')} AS FNUPPER, " + - "{fn LCASE('HELLO')} AS FNLOWER, {fn LTRIM(' Hello ')} AS FNLTRIM, {fn RTRIM(' Hello ')} AS FNRTRIM, " + - "toInt32({fn LENGTH('Hello')}) AS FNLENGTH, toInt32({fn POSITION('Hello', 'l')}) AS FNPOSITION, toInt32({fn MOD(10, 3)}) AS FNMOD, " + - "{fn SQRT(9)} AS FNSQRT, {fn SUBSTRING('Hello', 3, 2)} AS FNSUBSTRING")) { - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getDate(1), Date.valueOf(LocalDate.of(2021, 11, 1))); - //assertEquals(rs.getTimestamp(2), java.sql.Timestamp.valueOf(LocalDateTime.of(2021, 11, 1, 12, 34, 56))); - assertEquals(rs.getInt(3), 1); - assertEquals(rs.getInt("FNABS"), 1); - assertEquals(rs.getString(4), "HelloWorld"); - assertEquals(rs.getString("FNCONCAT"), "HelloWorld"); - assertEquals(rs.getString(5), "HELLO"); - assertEquals(rs.getString("FNUPPER"), "HELLO"); - assertEquals(rs.getString(6), "hello"); - assertEquals(rs.getString("FNLOWER"), "hello"); - assertEquals(rs.getString(7), "Hello "); - assertEquals(rs.getString("FNLTRIM"), "Hello "); - assertEquals(rs.getString(8), " Hello"); - assertEquals(rs.getString("FNRTRIM"), " Hello"); - assertEquals(rs.getInt(9), 5); - assertEquals(rs.getInt("FNLENGTH"), 5); - assertEquals(rs.getInt(10), 3); - assertEquals(rs.getInt("FNPOSITION"), 3); - assertEquals(rs.getInt(11), 1); - assertEquals(rs.getInt("FNMOD"), 1); - assertEquals(rs.getDouble(12), 3); - assertEquals(rs.getDouble("FNSQRT"), 3); - assertEquals(rs.getString(13), "ll"); - assertEquals(rs.getString("FNSUBSTRING"), "ll"); - assertThrows(SQLException.class, () -> rs.getString(14)); - assertFalse(rs.next()); - } - } - } - } - - @Test(groups = {"integration"}) - public void testBoundValuesContainingJdbcEscapeSyntax() throws Exception { - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - final String table = "test_bound_values_with_escape_syntax"; - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + - "(v1 Int32, v2 Map(String, String), v3 String, v4 Int32) ORDER BY (v1)"); - } - - Map map1 = new LinkedHashMap<>(); - map1.put("user", "Z!F3{fn "); - map1.put("region", "{d '2024-01-02'}"); - Map map2 = Collections.singletonMap("user", "}"); - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)")) { - stmt.setInt(1, 1); - stmt.setObject(2, map1); - stmt.setString(3, "{fn UCASE('a')}"); - stmt.setInt(4, 40); - stmt.addBatch(); - stmt.setInt(1, 2); - stmt.setObject(2, map2); - stmt.setString(3, "{ts '2024-01-02 02:01:01'}"); - stmt.setInt(4, 41); - stmt.addBatch(); - assertEquals(stmt.executeBatch(), new int[]{1, 1}); - } - - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? AS v1, ? AS v2")) { - stmt.setString(1, "Z!F3{fn "); - stmt.setString(2, "}"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), "Z!F3{fn "); - assertEquals(rs.getString(2), "}"); - assertFalse(rs.next()); - } - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table + " ORDER BY v1")) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1); - assertEquals(rs.getObject(2), map1); - assertEquals(rs.getString(3), "{fn UCASE('a')}"); - assertEquals(rs.getInt(4), 40); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 2); - assertEquals(rs.getObject(2), map2); - assertEquals(rs.getString(3), "{ts '2024-01-02 02:01:01'}"); - assertEquals(rs.getInt(4), 41); - assertFalse(rs.next()); - } - } - } - - @Test(groups = {"integration "}) - public void testStatementsWithDatabaseInTableIdentifier() throws Exception { - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - final String db1Name = conn.getSchema() + "_db1"; - final String table1Name = "table1"; - try (Statement stmt = conn.createStatement()) { - stmt.execute("CREATE DATABASE IF NOT EXISTS " + db1Name + onCluster()); - stmt.execute("DROP TABLE IF EXISTS " + db1Name + "." + table1Name + onCluster()); - stmt.execute("CREATE TABLE " + db1Name + "." + table1Name + onCluster() + " " + - "(v1 Int32, v2 Int32) ORDER BY ()"); - } - try { - String[] tableIdentifier = new String[]{ - db1Name + "." + table1Name, - "`" + db1Name + "`.`" + table1Name + "`", - "\"" + db1Name + "\".\"" + table1Name + "\"" - }; - - for (int i = 0; i < tableIdentifier.length; i++) { - String tableId = tableIdentifier[i]; - final String insertStmt = "INSERT INTO " + tableId + " VALUES (?, ?)"; - try (PreparedStatement stmt = conn.prepareStatement(insertStmt)) { - stmt.setInt(1, i + 10); - stmt.setInt(2, i + 20); - assertEquals(stmt.executeUpdate(), 1); - } - } - } finally { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP DATABASE IF EXISTS " + db1Name + onCluster()); - } - } - } - } - - @Test(groups = {"integration "}) - public void testNullValues() throws Exception { - try (Connection conn = getJdbcConnection(Map.of(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF))) { - final String table = "test_null_values"; - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + - "(v1 Int32, v2 Nullable(Int32)) ORDER BY ()"); - } - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?)")) { - stmt.setInt(1, 10); - // do not set second value - expectThrows(SQLException.class, stmt::executeUpdate); - stmt.setInt(1, 20); - stmt.setObject(2, null); - assertEquals(stmt.executeUpdate(), 1); - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT * FROM " + table)) { - - int count = 0; - while(rs.next()) { - count++; - assertNull(rs.getObject(2)); - } - - assertEquals(count, 1); - } - } - } - - @Test - public void testParamWithCast() throws Exception { - final String sql = " SELECT ?::integer, '?::integer', 123, ?:: UUID, ?"; - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, "1000"); - UUID uuid = UUID.randomUUID(); - stmt.setString(1, "1000"); - stmt.setString(2, uuid.toString()); - stmt.setInt(3, 3003001); - - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - Assert.assertEquals(rs.getInt(1), 1000); - Assert.assertEquals(rs.getString(2), "?::integer"); - Assert.assertEquals(rs.getInt(3), 123); - Assert.assertEquals(rs.getString(4), uuid.toString()); - Assert.assertEquals(rs.getInt(5), 3003001); - } - } - } - } - - @Test(groups = {"integration"}) - public void testSelectWithTableAliasAsKeyword() throws Exception { - try (Connection conn = getJdbcConnection()) { - String[] keywords = { - "ALL", "AND", "ANY", "AS", "ASC", "BY", "CREATE", "DATABASE", "DELETE", "DESC", "DISTINCT", "DROP", "EXISTS", "FROM", "GRANT", "GROUP", "HAVING", "INSERT", "INTO", "LIMIT", "NOT", "NULL", "ON", "ORDER", "REVOKE", "SELECT", "SET", "TABLE", "TO", "UPDATE", "VALUES", "VIEW", "WHILE", "WITH", "WHERE" - }; - - for (String keyword : keywords) { - final String table = keyword; - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute( -"CREATE TABLE " + table + " (v1 Int32, v2 String) ORDER BY ()"); - stmt.execute("INSERT INTO `" + table + "` VALUES (1000, 'test')"); - } - - try (PreparedStatement stmt = conn.prepareStatement("SELECT v1, v2 FROM " + table + " AS " + keyword + " WHERE v1 = ? AND v2 = ?")) { - stmt.setInt(1, 1000); - stmt.setString(2, "test"); - stmt.execute(); - try (ResultSet rs = stmt.getResultSet()) { - assertTrue(rs.next()); - Assert.assertEquals(rs.getInt(1), 1000); - Assert.assertEquals(rs.getString(2), "test"); - } - } catch (Exception e) { - fail("failed at keyword " + keyword, e); - } - } - } - } - - @Test(groups = {"integration"}) - public void testCTEWithUnboundCol() throws Exception { - - try (Connection conn = getJdbcConnection()) { - String cte = "with ? as text, numz as (select text, number from system.numbers limit 10) select * from numz"; - try (PreparedStatement stmt = conn.prepareStatement(cte)) { - stmt.setString(1, "1000"); - - ResultSet rs = stmt.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), "1000"); - assertEquals(rs.getString(2), "0"); - } - } - } - - @Test(groups = {"integration"}) - public void testWithInClause() throws Exception { - - try (Connection conn = getJdbcConnection()) { - final String q1 = "select number from system.numbers where number in (?) limit 10"; - try (PreparedStatement stmt = conn.prepareStatement(q1)) { - Long[] filter = new Long[]{2L, 4L, 6L}; - stmt.setArray(1, conn.createArrayOf("Int64", filter)); - ResultSet rs = stmt.executeQuery(); - - for (Long filterValue : filter) { - assertTrue(rs.next()); - assertEquals(rs.getLong(1), filterValue); - } - Assert.assertFalse(rs.next()); - } - - final String q2 = "with t as (select arrayJoin([1, 2, 3]) as a ) select * from t where a in(?, ?)"; - try (PreparedStatement stmt = conn.prepareStatement(q2)) { - Long[] filter = new Long[]{2L, 3L}; - - stmt.setInt(1, 2); - stmt.setInt(2, 3); - ResultSet rs = stmt.executeQuery(); - - for (Long filterValue : filter) { - assertTrue(rs.next()); - assertEquals(rs.getLong(1), filterValue); - } - Assert.assertFalse(rs.next()); - } - } - } - - // Disabled because implicit type casting is not a right way - @Test(groups = {"integration"}, dataProvider = "testTypeCastsDP", enabled = false) - public void testTypeCastsWithoutArgument(Object value, SQLType targetType, ClickHouseDataType expectedType) throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { - stmt.setObject(1, value, targetType); - stmt.setObject(2, value, targetType); - - try (ResultSet rs = stmt.executeQuery()) { - rs.next(); - assertEquals(rs.getString(2), expectedType.getName()); - switch (expectedType) { - case IPv6: - // do not check because auto-converted to IPv4 - break; - default: - assertEquals(rs.getString(1), String.valueOf(value)); - } - } - } - } - } - - @DataProvider(name = "testTypeCastsDP") - public static Object[][] testTypeCastsDP() { - return new Object[][] { - {100, ClickHouseDataType.Int8, ClickHouseDataType.Int8}, - {100L, ClickHouseDataType.Int16, ClickHouseDataType.Int16}, - {100L, ClickHouseDataType.Int32, ClickHouseDataType.Int32}, - {100L, ClickHouseDataType.Int64, ClickHouseDataType.Int64}, - {100L, ClickHouseDataType.UInt8, ClickHouseDataType.UInt8}, - {100L, ClickHouseDataType.UInt16, ClickHouseDataType.UInt16}, - {100L, ClickHouseDataType.UInt32, ClickHouseDataType.UInt32}, - {100L, ClickHouseDataType.UInt64, ClickHouseDataType.UInt64}, - {"ed0c77a3-2e4b-4954-98ee-22a4fdad9565", ClickHouseDataType.UUID, ClickHouseDataType.UUID}, - {"0:0:0:0:0:ffff:5ab0:4b61", ClickHouseDataType.IPv6, ClickHouseDataType.IPv6}, - {"116.253.40.133", ClickHouseDataType.IPv4, ClickHouseDataType.IPv4}, - {100, JDBCType.TINYINT, ClickHouseDataType.Int8} - }; - } - - // Disabled because implicit type casting is not a right way - @Test(groups = {"integration"}, dataProvider = "testJDBCTypeCastDP", enabled = false) - public void testJDBCTypeCast(Object value, int targetType, ClickHouseDataType expectedType) throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { - stmt.setObject(1, value, targetType); - stmt.setObject(2, value, targetType); - - try (ResultSet rs = stmt.executeQuery()) { - rs.next(); - assertEquals(rs.getString(2), expectedType.getName()); - switch (expectedType) { - case IPv4: - assertEquals(rs.getString(1), "/" + value); - break; - case IPv6: - // do not check - break; - default: - assertEquals(rs.getString(1), String.valueOf(value)); - } - } - } - } - } - - @DataProvider(name = "testJDBCTypeCastDP") - public static Object[][] testJDBCTypeCastDP() { - return new Object[][] { - {100, JDBCType.TINYINT.getVendorTypeNumber().intValue(), ClickHouseDataType.Int8} - }; - } - - // Disabled because implicit type casting is not a right way - @Test(groups = {"integration"}, enabled = false) - public void testTypesInvalidForCast() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { - for (ClickHouseDataType type : JdbcUtils.INVALID_TARGET_TYPES) { - expectThrows(SQLException.class, ()->stmt.setObject(1, "", type)); - } - - expectThrows(SQLException.class, ()->stmt.setObject(1, "", JDBCType.OTHER.getVendorTypeNumber())); - expectThrows(SQLException.class, ()->stmt.setObject(1, "", ClickHouseDataType.DateTime64)); - } - } - } - - // Disabled because implicit type casting is not a right way - @Test(groups = {"integration"}, dataProvider = "testTypeCastWithScaleOrLengthDP", enabled = false) - public void testTypeCastWithScaleOrLength(Object value, SQLType targetType, Integer scaleOrLength, String expectedValue, - String expectedType) throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("select ?, toTypeName(?)")) { - stmt.setObject(1, value, targetType, scaleOrLength); - stmt.setObject(2, value, targetType, scaleOrLength); - try (ResultSet rs = stmt.executeQuery()) { - rs.next(); - assertEquals(rs.getString(1), expectedValue); - assertEquals(rs.getString(2), expectedType); - } - } - } - } - - @DataProvider(name = "testTypeCastWithScaleOrLengthDP") - public static Object[][] testTypeCastWithScaleOrLengthDP() { - return new Object[][] { - {0.123456789, ClickHouseDataType.Decimal64, 3, "0.123", "Decimal(18, 3)"}, - {"hello", ClickHouseDataType.FixedString, 5, "hello", "FixedString(5)"}, - {"2017-10-02 10:20:30.333333", ClickHouseDataType.DateTime64, 3, "2017-10-02 10:20:30.333", "DateTime64(3)"} - }; - } - - @Test(groups = {"integration"}) - public void testCheckOfParametersAreSet() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("select ? as v1, ? as v2, ? as v3")) { - stmt.setString(1, "Test"); - stmt.setObject(2, null); - stmt.setString(3, null); - - try (ResultSet rs = stmt.executeQuery()) { - rs.next(); - Assert.assertEquals(rs.getString(1), "Test"); - Assert.assertEquals(rs.getInt(2), 0); - Assert.assertTrue(rs.wasNull()); - Assert.assertNull(rs.getString(2)); - Assert.assertTrue(rs.wasNull()); - } - - stmt.clearParameters(); - stmt.setString(1, "Test"); - stmt.setObject(2, null); - Assert.expectThrows(SQLException.class, stmt::executeQuery); - } - - try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO t VALUES (?, ?, ?)")) { - stmt.setString(1, "Test"); - - Assert.expectThrows(SQLException.class, stmt::executeUpdate); - } - } - } - - @Test - public void testParameterCount() throws Exception { - try (Connection conn = getJdbcConnection();) { - try (PreparedStatement stmt = conn.prepareStatement("select ?, ? as v1, ? as v2")) { - Assert.assertEquals(stmt.getMetaData().getColumnCount(), 3); - } - try (PreparedStatement stmt = conn.prepareStatement("WITH toDateTime(?) AS target_time SELECT * FROM table")) { - Assert.assertEquals(stmt.getMetaData().getColumnCount(), 1); - } - } - } - - @Test(dataProvider = "testGetMetadataIgnoresCommentsDataProvider") - public void testGetMetadataIgnoresComments(String sql) throws Exception { - try (Connection conn = getJdbcConnection(); - PreparedStatement stmt = conn.prepareStatement(sql)) { - ResultSetMetaData metaData = stmt.getMetaData(); - assertEquals(metaData.getColumnCount(), 3); - assertEquals(metaData.getColumnName(1), "x"); - assertEquals(metaData.getColumnName(2), "y"); - assertEquals(metaData.getColumnName(3), "z"); - assertEquals(metaData.getColumnType(1), Types.VARCHAR); - assertEquals(metaData.getColumnType(3), Types.VARCHAR); - } - } - - @DataProvider(name = "testGetMetadataIgnoresCommentsDataProvider") - static Object[][] testGetMetadataIgnoresCommentsDataProvider() { - return new Object[][] { - {"SELECT 'a' AS x -- it's ?\n, ? AS y, 'z' AS z"}, - {"SELECT 'a' AS x # it's ?\n, ? AS y, 'z' AS z"}, - {"SELECT 'a' AS x /* it's ? */, ? AS y, 'z' AS z"}, - {"SELECT 'a?b' AS x, ? AS y, 'z' AS z"} - }; - } - @Test public void testEncodingArray() throws Exception { - try (Connection conn = getJdbcConnection();) { + try (Connection conn = getJdbcConnection()) { try (PreparedStatementImpl stmt = (PreparedStatementImpl) conn.prepareStatement("SELECT ?")) { - { Object[] array1 = new Object[]{1, 2, 3}; ClickHouseColumn col1 = ClickHouseColumn.of("v", "Array(Int8)"); assertEquals(stmt.encodeArray(array1, col1.getArrayNestedLevel(), col1.getArrayBaseColumn().getDataType()), "[1,2,3]"); - } { + } + { Object[] array1 = new Object[]{1, 2, 3}; Object[] array2 = new Object[]{4, 5, 6}; Object[] array3 = new Object[]{array1, array2}; @@ -1972,8 +82,6 @@ public void testEncodingArray() throws Exception { assertEquals(stmt.encodeArray(array7, col1.getArrayNestedLevel(), col1.getArrayBaseColumn().getDataType()), "[[],[[],[1,2,3],[4,NULL,6]],[[],[7,NULL,9],[10,NULL,12]]]"); } - - { Object[] array1 = new Object[]{1, 2, 3}; Object[] array2 = new Object[]{4, 5, 6}; @@ -1982,7 +90,6 @@ public void testEncodingArray() throws Exception { assertEquals(stmt.encodeArray(array3, col1.getArrayNestedLevel(), col1.getArrayBaseColumn().getDataType()), "[(1,2,3),(4,5,6)]"); } - { Object[] array1 = new Object[]{1, 2, 3}; Object[] array2 = new Object[]{4, 5, 6}; @@ -1999,228 +106,4 @@ public void testEncodingArray() throws Exception { } } } - - @Test(groups = {"integration"}) - void testDateDayShiftWithDifferentTimezones() throws Exception { - String table = "test_date_day_shift"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (id Int32, d Date) ORDER BY id"); - } - - // Test dates that are prone to day shift issues (near year boundaries, month boundaries) - String[] testDates = { - "2024-01-01", // New Year - common edge case - "2024-12-31", // Year end - "2024-06-15", // Mid-year - "2024-03-10", // Near DST transition in US - "2024-11-03" // Near DST transition in US - }; - - // Timezones with significant offsets from UTC - TimeZone[] timezones = { - TimeZone.getTimeZone("UTC"), - TimeZone.getTimeZone("America/New_York"), // UTC-5 / UTC-4 (DST) - TimeZone.getTimeZone("America/Los_Angeles"), // UTC-8 / UTC-7 (DST) - TimeZone.getTimeZone("Europe/Moscow"), // UTC+3 - TimeZone.getTimeZone("Asia/Tokyo"), // UTC+9 - TimeZone.getTimeZone("Pacific/Auckland") // UTC+12 / UTC+13 (DST) - }; - - int id = 0; - for (String dateStr : testDates) { - LocalDate localDate = LocalDate.parse(dateStr); - java.sql.Date inputDate = java.sql.Date.valueOf(localDate); - for (TimeZone tz : timezones) { - id++; - Calendar calendar = new GregorianCalendar(tz); - LocalDate expectedLocalDate = DataTypeUtils.toLocalDate(inputDate, calendar.getTimeZone()); - java.sql.Date expectedDate = DataTypeUtils.toSqlDate(expectedLocalDate, calendar.getTimeZone()); - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { - stmt.setInt(1, id); - // Use Calendar to specify the timezone context for the date - stmt.setDate(2, inputDate, calendar); - stmt.executeUpdate(); - } - - // Verify the date was stored correctly - try (PreparedStatement stmt = conn.prepareStatement( - "SELECT d FROM " + table + " WHERE id = ?")) { - stmt.setInt(1, id); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next(), "Expected row for id=" + id); - java.sql.Date actualDate = rs.getDate(1, calendar); - LocalDate actualLocalDate = rs.getObject(1, LocalDate.class); - assertEquals(actualDate.getTime(), expectedDate.getTime()); - assertEquals(DataTypeUtils.toLocalDate(actualDate, calendar.getTimeZone()), expectedLocalDate, - String.format("Date mismatch for %s with timezone %s: expected %s, got %s", - dateStr, tz.getID(), expectedLocalDate, DataTypeUtils.toLocalDate(actualDate, calendar.getTimeZone()))); - assertEquals(actualLocalDate, expectedLocalDate, - String.format("LocalDate mismatch for %s with timezone %s: expected %s, got %s", - dateStr, tz.getID(), expectedLocalDate, actualLocalDate)); - } - } - } - } - - // Cleanup - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE " + table); - } - } - } - - /** - * Tests that setDate without Calendar uses the default timezone consistently. - * Compares behavior with and without explicit Calendar parameter. - */ - @Test(groups = {"integration"}) - void testDateWithAndWithoutCalendar() throws Exception { - String table = "test_date_calendar_comparison"; - try (Connection conn = getJdbcConnection()) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (id Int32, d Date) ORDER BY id"); - } - - java.sql.Date testDate = java.sql.Date.valueOf("2024-06-15"); - - // Insert without Calendar (uses default timezone) - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { - stmt.setInt(1, 1); - stmt.setDate(2, testDate); // No Calendar - uses default - stmt.executeUpdate(); - } - - // Insert with explicit UTC Calendar - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (id, d) VALUES (?, ?)")) { - stmt.setInt(1, 2); - stmt.setDate(2, testDate, new GregorianCalendar(TimeZone.getTimeZone("UTC"))); - stmt.executeUpdate(); - } - - // Both should retrieve the same date string - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT id, d FROM " + table + " ORDER BY id")) { - - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1); - java.sql.Date dateWithoutCalendar = rs.getDate(2); - - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 2); - java.sql.Date dateWithCalendar = rs.getDate(2); - - // The string representation should be the same - assertEquals(dateWithoutCalendar.toString(), testDate.toString(), - "Date without Calendar should match original"); - assertEquals(dateWithCalendar.toString(), testDate.toString(), - "Date with Calendar should match original"); - } - - // Cleanup - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE " + table); - } - } - } - - @Test(groups = {"integration"}) - public void testUnknownStatement() throws Exception { - try (Connection conn = getJdbcConnection()) { - try (PreparedStatement stmt = conn.prepareStatement("SELECT number, FROM system.numbers LIMIT 3")) { - Assert.assertTrue(stmt.execute()); - - try (ResultSet rs = stmt.getResultSet()) { - for (int i = 0; i < 3; i++) { - Assert.assertTrue(rs.next()); - Assert.assertEquals(rs.getLong(1), i); - } - } - } - - try (Statement stmt = conn.createStatement()) { - Assert.assertTrue(stmt.execute("SELECT number, FROM system.numbers LIMIT 3")); - - try (ResultSet rs = stmt.getResultSet()) { - for (int i = 0; i < 3; i++) { - Assert.assertTrue(rs.next()); - Assert.assertEquals(rs.getLong(1), i); - } - } - } - - // No-ResultSet path: DDL should not produce a ResultSet - String tmpTable = "tmp_no_result_" + RandomStringUtils.randomAlphanumeric(8); - // PreparedStatement: execute() should return false, executeQuery() should throw - try (PreparedStatement stmt = conn.prepareStatement( - "CREATE TABLE " + tmpTable + " (x Int32) ORDER BY()")) { - Assert.assertFalse(stmt.execute(), "DDL should not produce a ResultSet"); - Assert.assertNull(stmt.getResultSet(), "ResultSet should be null for DDL"); - assertThrows(SQLException.class, stmt::executeQuery); - } - // Statement: execute() should return false, executeQuery() should throw - String tmpTable2 = "tmp_no_result_" + RandomStringUtils.randomAlphanumeric(8); - try (Statement stmt = conn.createStatement()) { - Assert.assertFalse( - stmt.execute("CREATE TABLE " + tmpTable2 + " (x Int32) ORDER BY()"), - "DDL should not produce a ResultSet"); - Assert.assertNull(stmt.getResultSet(), "ResultSet should be null for DDL"); - assertThrows(SQLException.class, - () -> stmt.executeQuery("CREATE TABLE " + tmpTable2 + " (x Int32) ORDER BY()")); - } - } - } - - @DataProvider - public static Object[][] testInsertWithUnparsableValueExpression_dp() { - return new Object[][] { - {SqlParserFacade.SQLParser.ANTLR4.name()}, - {SqlParserFacade.SQLParser.ANTLR4_PARAMS_PARSER.name()}, - {SqlParserFacade.SQLParser.JAVACC.name()}, - }; - } - - @Test(groups = {"integration"}, dataProvider = "testInsertWithUnparsableValueExpression_dp") - public void testInsertWithUnparsableValueExpression(String parserName) throws Exception { - String table = "test_pstmt_unparsable_value_expr"; - Properties properties = new Properties(); - properties.setProperty(DriverProperties.SQL_PARSER.getKey(), parserName); - properties.setProperty(ASYNC_INSERT_SETTING_KEY, ServerSettings.OFF); - try (Connection conn = getJdbcConnection(properties)) { - try (Statement stmt = conn.createStatement()) { - stmt.execute("DROP TABLE IF EXISTS " + table); - stmt.execute("CREATE TABLE " + table + " (v1 String, v2 String) ORDER BY ()"); - } - - try (PreparedStatement stmt = conn.prepareStatement( - "INSERT INTO " + table + " (v1, v2) VALUES (hex(x'AB'), ?)")) { - assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); - stmt.setString(1, "abc"); - assertEquals(stmt.executeUpdate(), 1); - } - - try (Statement stmt = conn.createStatement(); - ResultSet rs = stmt.executeQuery("SELECT v1, v2 FROM " + table)) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), "AB"); - assertEquals(rs.getString(2), "abc"); - assertFalse(rs.next()); - } - - try (PreparedStatement stmt = conn.prepareStatement("SELECT ? AS v1, hex(x'AB') AS v2")) { - assertEquals(stmt.getParameterMetaData().getParameterCount(), 1); - stmt.setString(1, "abc"); - try (ResultSet rs = stmt.executeQuery()) { - assertTrue(rs.next()); - assertEquals(rs.getString(1), "abc"); - assertEquals(rs.getString(2), "AB"); - } - } - } - } } diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/StreamingPreparedStatementImplTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/StreamingPreparedStatementImplTest.java new file mode 100644 index 000000000..b26cb008c --- /dev/null +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/StreamingPreparedStatementImplTest.java @@ -0,0 +1,61 @@ +package com.clickhouse.jdbc; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.Properties; + +import static org.testng.Assert.assertEquals; + +@Test(groups = {"integration"}) +public class StreamingPreparedStatementImplTest extends AbstractPreparedStatementTest { + + @Override + protected void configureConnectionProperties(Properties properties) { + properties.setProperty(DriverProperties.STREAMING_PREPARED_STATEMENT.getKey(), "true"); + } + + @Override + protected Class expectedPreparedStatementClass() { + return StreamingPreparedStatementImpl.class; + } + + @Override + protected String tablePrefix() { + return "ps_stream_"; + } + + @DataProvider + public Object[][] statementSelectionProvider() { + return new Object[][]{ + {null, false, "INSERT INTO %s (id, val, label) VALUES (?, abs(?), upper(?))", StreamingPreparedStatementImpl.class}, + {null, false, "INSERT INTO %s (id, val, label) VALUES (?, ?, ?)", StreamingPreparedStatementImpl.class}, + {null, false, "INSERT INTO %s (id, val, label) SELECT ?, ?, ?", StreamingPreparedStatementImpl.class}, + {null, false, "SELECT * FROM %s WHERE id = ?", StreamingPreparedStatementImpl.class}, + {Boolean.FALSE, false, "INSERT INTO %s (id, val, label) VALUES (?, abs(?), upper(?))", PreparedStatementImpl.class}, + {Boolean.FALSE, false, "SELECT * FROM %s WHERE id = ?", PreparedStatementImpl.class}, + {Boolean.TRUE, true, "INSERT INTO %s (id, val, label) VALUES (?, ?, ?)", WriterStatementImpl.class}, + {Boolean.TRUE, true, "INSERT INTO %s (id, val, label) VALUES (?, abs(?), upper(?))", StreamingPreparedStatementImpl.class}, + {Boolean.TRUE, true, "SELECT * FROM %s WHERE id = ?", StreamingPreparedStatementImpl.class}, + }; + } + + @Test(dataProvider = "statementSelectionProvider") + public void testStatementSelection(Boolean streamingEnabled, boolean rowBinaryEnabled, String sqlTemplate, + Class expectedClass) throws Exception { + String table = "ps_stream_sel_" + System.nanoTime(); + Properties props = new Properties(); + props.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), String.valueOf(rowBinaryEnabled)); + if (streamingEnabled != null) { + props.setProperty(DriverProperties.STREAMING_PREPARED_STATEMENT.getKey(), streamingEnabled.toString()); + } + try (Connection conn = getDefaultJdbcConnection(props)) { + runQuery("CREATE TABLE " + table + " (id Int32, val Int32, label String) ENGINE = Memory"); + try (PreparedStatement ps = conn.prepareStatement(String.format(sqlTemplate, table))) { + assertEquals(ps.getClass(), expectedClass); + } + } + } +} diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriterTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriterTest.java new file mode 100644 index 000000000..ca81fbb62 --- /dev/null +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/fastwriter/FastSqlBatchWriterTest.java @@ -0,0 +1,281 @@ +package com.clickhouse.jdbc.internal.fastwriter; + +import com.clickhouse.jdbc.internal.ParsedPreparedStatement; +import com.clickhouse.jdbc.internal.SqlParserFacade; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.ByteArrayOutputStream; +import java.math.BigDecimal; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertThrows; + +@Test(groups = {"unit"}) +public class FastSqlBatchWriterTest { + + private static final String TEMPLATE_ONE = "VALUES (?)"; + private static final String TEMPLATE_THREE = "INSERT INTO events (id, name, active) VALUES (?, ?, ?);\n"; + + @DataProvider + public Object[][] singleParameterValuesProvider() { + UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-426614174000"); + BigDecimal decimal = new BigDecimal("12345.6789"); + Instant instant = Instant.parse("2026-12-04T12:34:56.789Z"); + return new Object[][]{ + {0, "VALUES (0)"}, + {-1, "VALUES (-1)"}, + {1, "VALUES (1)"}, + {Integer.MAX_VALUE, "VALUES (2147483647)"}, + {Integer.MIN_VALUE, "VALUES (-2147483648)"}, + {0L, "VALUES (0)"}, + {-1L, "VALUES (-1)"}, + {Long.MAX_VALUE, "VALUES (9223372036854775807)"}, + {Long.MIN_VALUE, "VALUES (-9223372036854775808)"}, + {(byte) -5, "VALUES (-5)"}, + {(short) 32000, "VALUES (32000)"}, + {1.5f, "VALUES (1.5)"}, + {3.14159d, "VALUES (3.14159)"}, + {"", "VALUES ('')"}, + {"plain ASCII", "VALUES ('plain ASCII')"}, + {"O'Reilly", "VALUES ('O\\'Reilly')"}, + {"'''", "VALUES ('\\'\\'\\'')"}, + {"'; DROP TABLE users; --", "VALUES ('\\'; DROP TABLE users; --')"}, + {"C:\\temp", "VALUES ('C:\\\\temp')"}, + {"test\\'", "VALUES ('test\\\\\\'')"}, + {"mixed\t'quote'\nand\\backslash", "VALUES ('mixed\t\\'quote\\'\nand\\\\backslash')"}, + {"café", "VALUES ('café')"}, + {"price: €99", "VALUES ('price: €99')"}, + {"launch 🚀 now", "VALUES ('launch 🚀 now')"}, + {"mix 'é' € '🚀'", "VALUES ('mix \\'é\\' € \\'🚀\\'')"}, + {new StringBuilder("sb'value 🚀"), "VALUES ('sb\\'value 🚀')"}, + {"a\uD83Db\uDE80c\uD83D", "VALUES ('a?b?c?')"}, + {null, "VALUES (NULL)"}, + {Boolean.TRUE, "VALUES (TRUE)"}, + {Boolean.FALSE, "VALUES (FALSE)"}, + {uuid, "VALUES ('123e4567-e89b-12d3-a456-426614174000')"}, + {decimal, "VALUES ('12345.6789')"}, + {instant, "VALUES ('2026-12-04T12:34:56.789Z')"}, + {LocalDate.of(2026, 4, 9), "VALUES ('2026-04-09')"}, + {LocalDateTime.of(2026, 6, 7, 8, 32, 0), "VALUES ('2026-06-07 08:32:00')"}, + {LocalDateTime.of(2026, 10, 3, 11, 33, 49, 30_000_000), "VALUES ('2026-10-03 11:33:49.03')"}, + {LocalDateTime.of(2026, 10, 3, 11, 33, 49, 1), "VALUES ('2026-10-03 11:33:49.000000001')"}, + }; + } + + @Test(dataProvider = "singleParameterValuesProvider") + public void testSingleParameterValues(Object value, String expected) throws Exception { + FastSqlBatchWriter writer = new FastSqlBatchWriter(TEMPLATE_ONE); + ByteArrayOutputStream out = new ByteArrayOutputStream(128); + writer.writeRow(out, value); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), expected); + + out.reset(); + SqlParameterBinder binder = writer.newBinder().setObject(0, value); + writer.writeRow(out, binder); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), expected); + } + + @Test + public void testTypedOverloadAndBinderParity() throws Exception { + FastSqlBatchWriter writer = new FastSqlBatchWriter(TEMPLATE_THREE); + assertEquals(writer.getParameterCount(), 3); + + ByteArrayOutputStream typedOut = new ByteArrayOutputStream(256); + writer.writeRow(typedOut, Long.MIN_VALUE, "O'Reilly 🚀", true); + writer.writeRow(typedOut, 42L, null, false); + + ByteArrayOutputStream binderOut = new ByteArrayOutputStream(256); + SqlParameterBinder binder = writer.newBinder(); + binder.setLong(0, Long.MIN_VALUE).setString(1, "O'Reilly 🚀").setBoolean(2, true); + writer.writeRow(binderOut, binder); + binder.reset().setLong(0, 42L).setBoolean(2, false); + writer.writeRow(binderOut, binder); + + String expected = "INSERT INTO events (id, name, active) VALUES (-9223372036854775808, 'O\\'Reilly 🚀', TRUE);\n" + + "INSERT INTO events (id, name, active) VALUES (42, NULL, FALSE);\n"; + assertEquals(typedOut.toString(StandardCharsets.UTF_8.name()), expected); + assertEquals(binderOut.toString(StandardCharsets.UTF_8.name()), expected); + } + + @Test + public void testZeroParameterTemplate() throws Exception { + FastSqlBatchWriter writer = new FastSqlBatchWriter("SELECT 1;\n"); + assertEquals(writer.getParameterCount(), 0); + ByteArrayOutputStream out = new ByteArrayOutputStream(32); + writer.writeRow(out); + writer.writeRow(out, writer.newBinder()); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), "SELECT 1;\nSELECT 1;\n"); + } + + @Test + public void testValidationAndNegativePaths() { + assertThrows(NullPointerException.class, () -> new FastSqlBatchWriter(null)); + + FastSqlBatchWriter writer = new FastSqlBatchWriter(TEMPLATE_THREE); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + assertThrows(NullPointerException.class, () -> writer.writeRow(null, 1, "a", true)); + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, (Object[]) null)); + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, 1, "a")); + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, 1, "a", true, "extra")); + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, (SqlParameterBinder) null)); + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, new SqlParameterBinder(2))); + + FastSqlBatchWriter oneParam = new FastSqlBatchWriter(TEMPLATE_ONE); + assertThrows(IllegalArgumentException.class, () -> oneParam.writeRow(out, 1L, "a", true)); + assertThrows(IllegalArgumentException.class, () -> new SqlParameterBinder(-1)); + assertThrows(IndexOutOfBoundsException.class, () -> new SqlParameterBinder(1).setLong(1, 10L)); + assertThrows(NullPointerException.class, () -> new FastSqlBatchWriter(TEMPLATE_ONE, null)); + } + + @DataProvider + public Object[][] sqlAwareParameterPositionsProvider() { + return new Object[][]{ + {"SELECT * FROM t WHERE a = '?' AND b = ?", new Object[]{1}, "SELECT * FROM t WHERE a = '?' AND b = 1"}, + {"SELECT `col?` FROM \"tbl?\" WHERE x = ?", new Object[]{"ok"}, "SELECT `col?` FROM \"tbl?\" WHERE x = 'ok'"}, + {"SELECT /* ? */ ? -- ?\n, ? // ?\n, ? # ?\n", new Object[]{1, 2, 3}, "SELECT /* ? */ 1 -- ?\n, 2 // ?\n, 3 # ?\n"}, + {"SELECT $$?$$, $tag$?$tag$, ?", new Object[]{7}, "SELECT $$?$$, $tag$?$tag$, 7"}, + {"SELECT a ? 1 : 2, ?", new Object[]{9}, "SELECT a ? 1 : 2, 9"}, + }; + } + + @Test(dataProvider = "sqlAwareParameterPositionsProvider") + public void testParameterPositionsMatchSqlParserFacade(String sql, Object[] params, String expected) throws Exception { + FastSqlBatchWriter writer = new FastSqlBatchWriter(sql); + assertEquals(writer.getParameterCount(), params.length); + ByteArrayOutputStream out = new ByteArrayOutputStream(128); + writer.writeRow(out, params); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), expected); + + ParsedPreparedStatement parsed = new ParsedPreparedStatement(); + SqlParserFacade.parseParameters(sql, parsed); + FastSqlBatchWriter fromParsed = new FastSqlBatchWriter(sql, parsed); + assertEquals(fromParsed.getParameterCount(), parsed.getArgCount()); + out.reset(); + fromParsed.writeRow(out, params); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), expected); + } + + @Test + public void testMultiRowSqlBatchWriter() throws Exception { + MultiRowSqlBatchWriter writer = new MultiRowSqlBatchWriter( + "INSERT INTO events (id, name, active) VALUES ", + "(?, ?, ?)", + ", ", + ";\n"); + assertEquals(writer.getParameterCount(), 3); + + ByteArrayOutputStream out = new ByteArrayOutputStream(256); + SqlParameterBinder binder = writer.newBinder(); + + writer.beginBatch(out); + assertEquals(writer.getRowCount(), 0); + writer.writeRow(out, 1L, "first's", true); + binder.setLong(0, 2L).setString(1, "second €").setBoolean(2, false); + writer.writeRow(out, binder); + writer.writeRow(out, (Object) 3, null, Boolean.TRUE); + assertEquals(writer.getRowCount(), 3); + writer.endBatch(out); + assertEquals(writer.getRowCount(), 0); + + // Reuse for a second batch + writer.beginBatch(out); + writer.writeRow(out, 4L, "fourth 🚀", true); + writer.endBatch(out); + + String expected = "INSERT INTO events (id, name, active) VALUES " + + "(1, 'first\\'s', TRUE), (2, 'second €', FALSE), (3, NULL, TRUE);\n" + + "INSERT INTO events (id, name, active) VALUES " + + "(4, 'fourth 🚀', TRUE);\n"; + assertEquals(out.toString(StandardCharsets.UTF_8.name()), expected); + } + + @Test + public void testMultiRowSqlBatchWriterStateAndValidationErrors() throws Exception { + assertThrows(NullPointerException.class, () -> new MultiRowSqlBatchWriter(null, "(?)", ",", ";")); + assertThrows(NullPointerException.class, () -> new MultiRowSqlBatchWriter("H", null, ",", ";")); + assertThrows(NullPointerException.class, () -> new MultiRowSqlBatchWriter("H", "(?)", null, ";")); + + MultiRowSqlBatchWriter writer = new MultiRowSqlBatchWriter("VALUES ", "(?, ?)", ", ", ";"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + + assertThrows(IllegalStateException.class, () -> writer.writeRow(out, 1, "a")); + assertThrows(IllegalStateException.class, () -> writer.endBatch(out)); + + writer.beginBatch(out); + assertThrows(IllegalStateException.class, () -> writer.beginBatch(out)); + writer.writeRow(out, 1, "ok"); + // Mismatched param count after row 0 must not write a stray delimiter + assertThrows(IllegalArgumentException.class, () -> writer.writeRow(out, 1)); + assertEquals(writer.getRowCount(), 1); + writer.endBatch(out); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), "VALUES (1, 'ok');"); + } + + @Test + public void testSharedCompiledTemplateAcrossThreads() throws Exception { + FastSqlBatchWriter sharedTemplate = new FastSqlBatchWriter(TEMPLATE_THREE); + int threads = 4; + int rowsPerThread = 500; + ExecutorService pool = Executors.newFixedThreadPool(threads); + try { + List> futures = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + final int threadId = t; + Callable task = () -> { + FastSqlBatchWriter localWriter = sharedTemplate.newWriter(); + SqlParameterBinder binder = localWriter.newBinder(); + ByteArrayOutputStream out = new ByteArrayOutputStream(rowsPerThread * 64); + for (int r = 0; r < rowsPerThread; r++) { + long id = threadId * 10000L + r; + binder.setLong(0, id).setString(1, "t" + threadId + "'r" + r).setBoolean(2, (r & 1) == 0); + localWriter.writeRow(out, binder); + } + return out.toString(StandardCharsets.UTF_8.name()); + }; + futures.add(pool.submit(task)); + } + + for (int t = 0; t < threads; t++) { + String actual = futures.get(t).get(); + StringBuilder expected = new StringBuilder(rowsPerThread * 64); + for (int r = 0; r < rowsPerThread; r++) { + long id = t * 10000L + r; + expected.append("INSERT INTO events (id, name, active) VALUES (") + .append(id).append(", 't").append(t).append("\\'r").append(r).append("', ") + .append((r & 1) == 0 ? "TRUE" : "FALSE").append(");\n"); + } + assertEquals(actual, expected.toString()); + } + } finally { + pool.shutdownNow(); + } + } + + @Test + public void testRawSqlUnixTimestampAndPrecomputedPositions() throws Exception { + FastSqlBatchWriter writer = new FastSqlBatchWriter("(?, ?, ?)", new int[]{1, 4, 7}, 3); + SqlParameterBinder binder = writer.newBinder() + .setRawSql(0, "[1, 'a\\'b']") + .setUnixTimestamp64Nano(1, 1700000000123456789L) + .setRawSql(2, null); + ByteArrayOutputStream out = new ByteArrayOutputStream(128); + writer.writeRow(out, binder); + assertEquals(out.toString(StandardCharsets.UTF_8.name()), + "([1, 'a\\'b'], fromUnixTimestamp64Nano(1700000000123456789), NULL)"); + + assertThrows(IllegalArgumentException.class, () -> new FastSqlBatchWriter("(?)", new int[]{5}, 1)); + } +} diff --git a/performance/README.md b/performance/README.md index 2d1d0567d..9ef3a58ce 100644 --- a/performance/README.md +++ b/performance/README.md @@ -191,7 +191,9 @@ Other options: - "reader" - Deserializer - deserialization-only logic benchmarks - "mixed" - MixedWorkload - "jq" - JDBCQuery - query operations using JDBC + - "jqp" - JDBCPreparedStatementQuery - parameterized PreparedStatement query operations using JDBC - "ji" - JDBCInsert - insert operation using JDBC + - "jis" - JDBCPreparedStatementInsert - SQL String vs Stream PreparedStatement insert operations using JDBC - "ws" - WriteStream - isolated V1/V2 HTTP request-body handoff `ws` uses throughput mode with a second time unit and must be selected by diff --git a/performance/src/main/java/com/clickhouse/benchmark/BenchmarkRunner.java b/performance/src/main/java/com/clickhouse/benchmark/BenchmarkRunner.java index d1b61fe12..8e3090fbf 100644 --- a/performance/src/main/java/com/clickhouse/benchmark/BenchmarkRunner.java +++ b/performance/src/main/java/com/clickhouse/benchmark/BenchmarkRunner.java @@ -6,6 +6,8 @@ import com.clickhouse.benchmark.clients.Deserializers; import com.clickhouse.benchmark.clients.InsertClient; import com.clickhouse.benchmark.clients.JDBCInsert; +import com.clickhouse.benchmark.clients.JDBCPreparedStatementInsert; +import com.clickhouse.benchmark.clients.JDBCPreparedStatementQuery; import com.clickhouse.benchmark.clients.JDBCQuery; import com.clickhouse.benchmark.clients.MixedWorkload; import com.clickhouse.benchmark.clients.QueryClient; @@ -145,7 +147,9 @@ private static Map buildBenchmarkFlags() { map.put("writer", Serializers.class.getName()); map.put("mixed", MixedWorkload.class.getName()); map.put("jq", JDBCQuery.class.getName()); + map.put("jqp", JDBCPreparedStatementQuery.class.getName()); map.put("ji", JDBCInsert.class.getName()); + map.put("jis", JDBCPreparedStatementInsert.class.getName()); map.put("ws", WriteStream.class.getName()); return map; } diff --git a/performance/src/main/java/com/clickhouse/benchmark/clients/FastSqlBatchWriterBenchmark.java b/performance/src/main/java/com/clickhouse/benchmark/clients/FastSqlBatchWriterBenchmark.java new file mode 100644 index 000000000..d9e58212c --- /dev/null +++ b/performance/src/main/java/com/clickhouse/benchmark/clients/FastSqlBatchWriterBenchmark.java @@ -0,0 +1,114 @@ +package com.clickhouse.benchmark.clients; + +import com.clickhouse.jdbc.internal.fastwriter.FastSqlBatchWriter; +import com.clickhouse.jdbc.internal.fastwriter.MultiRowSqlBatchWriter; +import com.clickhouse.jdbc.internal.fastwriter.SqlParameterBinder; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.profile.GCProfiler; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.concurrent.TimeUnit; + +@State(Scope.Thread) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 2, time = 2) +@Measurement(iterations = 3, time = 2) +@Fork(1) +public class FastSqlBatchWriterBenchmark { + + private static final String SINGLE_ROW_TEMPLATE = + "INSERT INTO events (id, name, active) VALUES (?, ?, ?);\n"; + + private FastSqlBatchWriter writer; + private MultiRowSqlBatchWriter multiRowWriter; + private SqlParameterBinder binder; + private ByteArrayOutputStream reusableBaos; + private BufferedOutputStream reusableBos; + private String sampleName; + private long counter; + + @Setup + public void setup() { + writer = new FastSqlBatchWriter(SINGLE_ROW_TEMPLATE); + multiRowWriter = new MultiRowSqlBatchWriter( + "INSERT INTO events (id, name, active) VALUES ", + "(?, ?, ?)", + ", ", + ";\n"); + binder = writer.newBinder(); + reusableBaos = new ByteArrayOutputStream(64 * 1024); + reusableBos = new BufferedOutputStream(new OutputStream() { + @Override + public void write(int b) { + } + + @Override + public void write(byte[] b, int off, int len) { + } + }, 64 * 1024); + sampleName = "O'Reilly event payload with café € and 🚀"; + counter = 1_000_000L; + } + + @Benchmark + public void writeRowTypedToBaos(Blackhole bh) throws IOException { + reusableBaos.reset(); + writer.writeRow(reusableBaos, ++counter, sampleName, (counter & 1L) == 0L); + bh.consume(reusableBaos.size()); + } + + @Benchmark + public void writeRowBinderToBaos(Blackhole bh) throws IOException { + reusableBaos.reset(); + long id = ++counter; + binder.setLong(0, id).setString(1, sampleName).setBoolean(2, (id & 1L) == 0L); + writer.writeRow(reusableBaos, binder); + bh.consume(reusableBaos.size()); + } + + @Benchmark + public void writeRowBinderToBufferedStream(Blackhole bh) throws IOException { + long id = ++counter; + binder.setLong(0, id).setString(1, sampleName).setBoolean(2, (id & 1L) == 0L); + writer.writeRow(reusableBos, binder); + bh.consume(id); + } + + @Benchmark + public void writeMultiRowBatchBinderToBaos(Blackhole bh) throws IOException { + reusableBaos.reset(); + multiRowWriter.beginBatch(reusableBaos); + for (int i = 0; i < 100; i++) { + long id = ++counter; + binder.setLong(0, id).setString(1, sampleName).setBoolean(2, (id & 1L) == 0L); + multiRowWriter.writeRow(reusableBaos, binder); + } + multiRowWriter.endBatch(reusableBaos); + bh.consume(reusableBaos.size()); + } + + public static void main(String[] args) throws Exception { + Options opt = new OptionsBuilder() + .include(FastSqlBatchWriterBenchmark.class.getSimpleName()) + .addProfiler(GCProfiler.class) + .build(); + new Runner(opt).run(); + } +} diff --git a/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementInsert.java b/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementInsert.java new file mode 100644 index 000000000..709e28f39 --- /dev/null +++ b/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementInsert.java @@ -0,0 +1,217 @@ +package com.clickhouse.benchmark.clients; + +import com.clickhouse.client.ClickHouseNode; +import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.client.api.CompressionMethod; +import com.clickhouse.jdbc.ClickHouseDriver; +import com.clickhouse.jdbc.DriverProperties; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.TearDown; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; + +import static com.clickhouse.benchmark.TestEnvironment.DB_NAME; +import static com.clickhouse.benchmark.TestEnvironment.getPassword; +import static com.clickhouse.benchmark.TestEnvironment.getServer; +import static com.clickhouse.benchmark.TestEnvironment.getUsername; +import static com.clickhouse.benchmark.TestEnvironment.isSsl; + +/** + * Benchmarks SQL-based {@link PreparedStatement} batch inserts comparing legacy SQL String assembly + * ({@code jdbc_streaming_prepared_statement=false}) against streaming {@link PreparedStatement} + * ({@code jdbc_streaming_prepared_statement=true}) and JDBC V1 across compression modes. + */ +public class JDBCPreparedStatementInsert extends BenchmarkBase { + + private Connection jdbcV2StreamUncompressed; + private Connection jdbcV2StreamNativeLz4; + private Connection jdbcV2StreamNativeZstd; + private Connection jdbcV2StreamHttpLz4; + private Connection jdbcV2StreamHttpZstd; + + private Connection jdbcV2StringUncompressed; + private Connection jdbcV2StringNativeLz4; + private Connection jdbcV2StringNativeZstd; + private Connection jdbcV2StringHttpLz4; + private Connection jdbcV2StringHttpZstd; + + private List preparedConnections; + + @Setup(Level.Iteration) + public void setUpPreparedStatementConnections() throws SQLException { + jdbcV2StreamUncompressed = getJdbcV2PreparedStatement(false, false, null, null, true); + jdbcV2StreamNativeLz4 = getJdbcV2PreparedStatement(true, false, CompressionMethod.LZ4, null, true); + jdbcV2StreamNativeZstd = getJdbcV2PreparedStatement(true, false, CompressionMethod.ZSTD, null, true); + jdbcV2StreamHttpLz4 = getJdbcV2PreparedStatement(true, true, null, "lz4", true); + jdbcV2StreamHttpZstd = getJdbcV2PreparedStatement(true, true, null, "zstd", true); + + jdbcV2StringUncompressed = getJdbcV2PreparedStatement(false, false, null, null, false); + jdbcV2StringNativeLz4 = getJdbcV2PreparedStatement(true, false, CompressionMethod.LZ4, null, false); + jdbcV2StringNativeZstd = getJdbcV2PreparedStatement(true, false, CompressionMethod.ZSTD, null, false); + jdbcV2StringHttpLz4 = getJdbcV2PreparedStatement(true, true, null, "lz4", false); + jdbcV2StringHttpZstd = getJdbcV2PreparedStatement(true, true, null, "zstd", false); + + preparedConnections = Arrays.asList( + jdbcV2StreamUncompressed, jdbcV2StreamNativeLz4, jdbcV2StreamNativeZstd, + jdbcV2StreamHttpLz4, jdbcV2StreamHttpZstd, + jdbcV2StringUncompressed, jdbcV2StringNativeLz4, jdbcV2StringNativeZstd, + jdbcV2StringHttpLz4, jdbcV2StringHttpZstd + ); + } + + @TearDown(Level.Iteration) + public void tearDownPreparedStatementConnections() { + if (preparedConnections == null) { + return; + } + for (Connection connection : preparedConnections) { + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignored) { + } + } + } + } + + @TearDown(Level.Invocation) + public void verifyRowsInsertedAndCleanup(DataState dataState) { + boolean success; + int count = 0; + do { + success = verifyCount(dataState.tableNameEmpty, dataState.dataSet.getSize()); + if (!success) { + try { + Thread.sleep(2500); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException("Interrupted while verifying inserted rows", e); + } + } + } while (!success && count++ < 10); + if (!success) { + throw new RuntimeException("Failed to verify rows inserted"); + } + truncateTable(dataState.tableNameEmpty); + } + + static Connection getJdbcV2PreparedStatement(boolean isCompressed, boolean useHttpCompression, + CompressionMethod compressionMethod, String httpEncoding, + boolean streamingPreparedStatement) throws SQLException { + Properties properties = new Properties(); + properties.put(ClientConfigProperties.USER.getKey(), getUsername()); + properties.put(ClientConfigProperties.PASSWORD.getKey(), getPassword()); + properties.put(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "false"); + properties.put(DriverProperties.STREAMING_PREPARED_STATEMENT.getKey(), String.valueOf(streamingPreparedStatement)); + if (isCompressed) { + properties.put(ClientConfigProperties.COMPRESS_CLIENT_REQUEST.getKey(), "true"); + properties.put(ClientConfigProperties.COMPRESS_SERVER_RESPONSE.getKey(), "true"); + properties.put(ClientConfigProperties.USE_HTTP_COMPRESSION.getKey(), String.valueOf(useHttpCompression)); + if (compressionMethod != null) { + properties.put(ClientConfigProperties.COMPRESSION_METHOD.getKey(), compressionMethod.name()); + } + if (useHttpCompression && httpEncoding != null) { + properties.put(ClientConfigProperties.httpHeader("Content-Encoding"), httpEncoding); + properties.put(ClientConfigProperties.httpHeader("Accept-Encoding"), httpEncoding); + } + } + properties.put(ClientConfigProperties.CLIENT_NETWORK_BUFFER_SIZE.getKey(), String.valueOf(10 * 1024 * 1024)); + properties.put(ClientConfigProperties.DATABASE.getKey(), DB_NAME); + + ClickHouseNode node = getServer(); + String jdbcURL = isSsl() + ? String.format("jdbc:clickhouse:https://%s:%s?ssl=true", node.getHost(), node.getPort()) + : String.format("jdbc:clickhouse://%s:%s", node.getHost(), node.getPort()); + return new ClickHouseDriver().connect(jdbcURL, properties); + } + + private void insertDataAsSqlValues(Connection connection, DataState dataState) throws SQLException { + int size = dataState.dataSet.getSchema().getColumns().size(); + // Wrap the first placeholder with identity(?) so jdbc-v1 uses SqlBasedPreparedStatement + // instead of its automatic RowBinary InputBasedPreparedStatement path. + StringBuilder values = new StringBuilder(size * 2 + 12); + for (int i = 0; i < size; i++) { + if (i > 0) { + values.append(','); + } + values.append(i == 0 ? "identity(?)" : "?"); + } + String sql = String.format("INSERT INTO `%s` VALUES (%s)", dataState.tableNameEmpty, values); + try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { + for (List data : dataState.dataSet.getRowsOrdered()) { + for (int j = 0; j < size; j++) { + preparedStatement.setObject(j + 1, data.get(j)); + } + preparedStatement.addBatch(); + } + preparedStatement.executeBatch(); + } + } + + @Benchmark + public void insertJDBCStringV1(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV1RowBinary, dataState); + } + + @Benchmark + public void insertJDBCStringCompressedV1(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV1Compressed, dataState); + } + + @Benchmark + public void insertJDBCStringV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StringUncompressed, dataState); + } + + @Benchmark + public void insertJDBCStringCompressedLz4V2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StringNativeLz4, dataState); + } + + @Benchmark + public void insertJDBCStringCompressedZstdV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StringNativeZstd, dataState); + } + + @Benchmark + public void insertJDBCStringHttpLz4V2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StringHttpLz4, dataState); + } + + @Benchmark + public void insertJDBCStringHttpZstdV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StringHttpZstd, dataState); + } + + @Benchmark + public void insertJDBCStreamV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StreamUncompressed, dataState); + } + + @Benchmark + public void insertJDBCStreamCompressedLz4V2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StreamNativeLz4, dataState); + } + + @Benchmark + public void insertJDBCStreamCompressedZstdV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StreamNativeZstd, dataState); + } + + @Benchmark + public void insertJDBCStreamHttpLz4V2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StreamHttpLz4, dataState); + } + + @Benchmark + public void insertJDBCStreamHttpZstdV2(DataState dataState) throws SQLException { + insertDataAsSqlValues(jdbcV2StreamHttpZstd, dataState); + } +} diff --git a/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementQuery.java b/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementQuery.java new file mode 100644 index 000000000..1e2e3cab8 --- /dev/null +++ b/performance/src/main/java/com/clickhouse/benchmark/clients/JDBCPreparedStatementQuery.java @@ -0,0 +1,135 @@ +package com.clickhouse.benchmark.clients; + +import com.clickhouse.client.api.CompressionMethod; +import com.clickhouse.data.ClickHouseColumn; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.infra.Blackhole; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.StringJoiner; + +/** + * Benchmarks parameterized {@link PreparedStatement} queries comparing JDBC V1, V2 legacy String + * ({@code jdbc_streaming_prepared_statement=false}), and V2 streaming ({@code jdbc_streaming_prepared_statement=true}). + */ +public class JDBCPreparedStatementQuery extends BenchmarkBase { + + private static final int PREPARED_FILTER_PARAMS = 1000; + + private Connection jdbcV2StreamUncompressed; + private Connection jdbcV2StreamCompressed; + private Connection jdbcV2StringUncompressed; + private Connection jdbcV2StringCompressed; + private List preparedConnections; + + @Setup(Level.Iteration) + public void setUpPreparedStatementConnections() throws SQLException { + jdbcV2StreamUncompressed = JDBCPreparedStatementInsert.getJdbcV2PreparedStatement( + false, false, null, null, true); + jdbcV2StreamCompressed = JDBCPreparedStatementInsert.getJdbcV2PreparedStatement( + true, false, CompressionMethod.LZ4, null, true); + jdbcV2StringUncompressed = JDBCPreparedStatementInsert.getJdbcV2PreparedStatement( + false, false, null, null, false); + jdbcV2StringCompressed = JDBCPreparedStatementInsert.getJdbcV2PreparedStatement( + true, false, CompressionMethod.LZ4, null, false); + preparedConnections = Arrays.asList( + jdbcV2StreamUncompressed, jdbcV2StreamCompressed, + jdbcV2StringUncompressed, jdbcV2StringCompressed + ); + } + + @TearDown(Level.Iteration) + public void tearDownPreparedStatementConnections() { + if (preparedConnections == null) { + return; + } + for (Connection connection : preparedConnections) { + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignored) { + } + } + } + } + + private void selectPreparedData(Connection connection, DataState dataState, Blackhole blackhole) throws SQLException { + List columns = dataState.dataSet.getSchema().getColumns(); + int nCol = columns.size(); + List> rows = dataState.dataSet.getRowsOrdered(); + List filterValues = new ArrayList<>(PREPARED_FILTER_PARAMS); + int step = Math.max(1, rows.size() / PREPARED_FILTER_PARAMS); + for (int idx = 0; idx < rows.size() && filterValues.size() < PREPARED_FILTER_PARAMS; idx += step) { + Object val = rows.get(idx).get(0); + if (val != null) { + filterValues.add(val); + } + } + + String sql; + if (filterValues.isEmpty()) { + sql = getSelectQuery(dataState.tableNameFilled) + " LIMIT ?"; + } else { + StringJoiner placeholders = new StringJoiner(","); + for (int i = 0; i < filterValues.size(); i++) { + placeholders.add("?"); + } + sql = getSelectQuery(dataState.tableNameFilled) + " WHERE `" + columns.get(0).getColumnName() + + "` IN (" + placeholders + ") LIMIT ?"; + } + + try (PreparedStatement stmt = connection.prepareStatement(sql)) { + int p = 1; + for (Object val : filterValues) { + stmt.setObject(p++, val); + } + stmt.setInt(p, dataState.limit); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + for (int i = 1; i <= nCol; i++) { + blackhole.consume(rs.getObject(i)); + } + } + } + } + } + + @Benchmark + public void selectJDBCPreparedStatementV1(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV1RowBinary, dataState, blackhole); + } + + @Benchmark + public void selectJDBCPreparedStatementCompressedV1(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV1Compressed, dataState, blackhole); + } + + @Benchmark + public void selectJDBCPreparedStatementStringV2(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV2StringUncompressed, dataState, blackhole); + } + + @Benchmark + public void selectJDBCPreparedStatementStringCompressedV2(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV2StringCompressed, dataState, blackhole); + } + + @Benchmark + public void selectJDBCPreparedStatementStreamV2(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV2StreamUncompressed, dataState, blackhole); + } + + @Benchmark + public void selectJDBCPreparedStatementStreamCompressedV2(DataState dataState, Blackhole blackhole) throws SQLException { + selectPreparedData(jdbcV2StreamCompressed, dataState, blackhole); + } +} diff --git a/performance/src/main/java/com/clickhouse/benchmark/data/DataSetGenerator.java b/performance/src/main/java/com/clickhouse/benchmark/data/DataSetGenerator.java index 3b316f6dc..e417829a5 100644 --- a/performance/src/main/java/com/clickhouse/benchmark/data/DataSetGenerator.java +++ b/performance/src/main/java/com/clickhouse/benchmark/data/DataSetGenerator.java @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -32,6 +33,11 @@ public class DataSetGenerator { */ public static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + /** + * Formatter for the DateTime type with milliseconds. + */ + public static DateTimeFormatter DATETIME_WITH_MILLIS_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); + /** * Formatter for the DateTime type with nanoseconds. */ @@ -115,9 +121,10 @@ public static void main(String[] args) throws IOException { writer.write("DATA>>\n"); Random rand = new Random(); + LocalDateTime baseNow = LocalDateTime.now(); for (int i = 0; i < rows; i++) { - List row = generateRow(originalColumns, i, seriesStart, seriesInterval, useSeries, rand); + List row = generateRow(originalColumns, i, baseNow, seriesStart, seriesInterval, useSeries, rand); writer.write(String.join(",", row) + "\n"); } } catch (IOException e) { @@ -176,11 +183,21 @@ private static String generateAbstractCreateTable(List columns) { } - private static List generateRow(List columns, int rowIndex, LocalDateTime seriesStart, - Duration seriesInterval, boolean useSeries, Random rand) { - List row = new ArrayList<>(); + private static List generateRow(List columns, int rowIndex, LocalDateTime baseNow, + LocalDateTime seriesStart, Duration seriesInterval, + boolean useSeries, Random rand) { + List row = new ArrayList<>(columns.size()); for (Column col : columns) { - String[] colDef = col.type.split("[\\s\\(\\)]+"); + String effectiveType = col.type.trim(); + if (effectiveType.startsWith("Nullable(") && effectiveType.endsWith(")")) { + if (rand.nextInt(10) == 0) { + row.add("\\N"); + continue; + } + effectiveType = effectiveType.substring("Nullable(".length(), effectiveType.length() - 1).trim(); + } + + String[] colDef = effectiveType.split("[\\s\\(\\)]+"); ClickHouseDataTypesShort chType; try { @@ -190,20 +207,10 @@ private static List generateRow(List columns, int rowIndex, Loca chType = ClickHouseDataTypesShort.String; // Default to String if unknown } - if (chType.hasParameters()) { - // Handle types with parameters (e.g., Decimal, Array, etc.) - String param = colDef[1]; - if (param.startsWith("(") && param.endsWith(")")) { - param = param.substring(1, param.length() - 1); - } - String[] params = param.split(","); - if (params.length > 0) { - // Use the first parameter for generating values - col.type = chType.name() + "(" + params[0] + ")"; - } - } - switch (chType) { + case Bool: + row.add(rand.nextBoolean() ? "true" : "false"); + break; case Int8: row.add(String.valueOf(rand.nextInt(256) - 128)); break; @@ -220,7 +227,7 @@ private static List generateRow(List columns, int rowIndex, Loca row.add(String.valueOf(rand.nextInt())); break; case UInt32: - row.add(String.valueOf(Math.abs(rand.nextLong()))); + row.add(String.valueOf(Integer.toUnsignedLong(rand.nextInt()))); break; case Int64: row.add(String.valueOf(rand.nextLong())); @@ -237,16 +244,35 @@ private static List generateRow(List columns, int rowIndex, Loca case String: row.add(randomString(10, rand)); break; + case UUID: + row.add(new UUID(rand.nextLong(), rand.nextLong()).toString()); + break; case DateTime: case DateTime32: case DateTime64: case Date: + LocalDateTime dateTime; if (useSeries && seriesStart != null) { - LocalDateTime dateTime = seriesStart.plus(seriesInterval.multipliedBy(rowIndex)); - row.add(dateTime.format(chType == ClickHouseDataTypesShort.Date ? DATE_FORMATTER : DATETIME_FORMATTER)); + dateTime = seriesStart.plus(seriesInterval.multipliedBy(rowIndex)); + } else { + dateTime = baseNow.minusDays(rand.nextInt(365)) + .minusSeconds(rand.nextInt(86400)) + .withNano(rand.nextInt(1_000_000_000)); + } + if (chType == ClickHouseDataTypesShort.Date) { + row.add(dateTime.format(DATE_FORMATTER)); + } else if (chType == ClickHouseDataTypesShort.DateTime64) { + int scale = 3; + if (colDef.length > 1) { + try { + scale = Integer.parseInt(colDef[1].split(",")[0].trim()); + } catch (NumberFormatException ignored) { + scale = 3; + } + } + row.add(dateTime.format(scale <= 3 ? DATETIME_WITH_MILLIS_FORMATTER : DATETIME_WITH_NANOS_FORMATTER)); } else { - LocalDateTime dateTime = LocalDateTime.now().minusDays(rand.nextInt(365)); - row.add(dateTime.format(chType == ClickHouseDataTypesShort.Date ? DATE_FORMATTER : DATETIME_FORMATTER)); + row.add(dateTime.format(DATETIME_FORMATTER)); } break; case Decimal: