From a2a8061b9fe810f84ebc992ca68afaf945f53fd5 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 27 Oct 2021 17:02:36 +0000 Subject: [PATCH 01/11] chore: release 2.5.2-SNAPSHOT (#654) :robot: I have created a release \*beep\* \*boop\* --- ### Updating meta-information for bleeding-edge SNAPSHOT release. --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- pom.xml | 2 +- samples/snapshot/pom.xml | 2 +- versions.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index d9b697624..899673f1f 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 google-cloud-spanner-jdbc - 2.5.1 + 2.5.2-SNAPSHOT jar Google Cloud Spanner JDBC https://github.com/googleapis/java-spanner-jdbc diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index 3771fd68a..6dd2b3033 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -28,7 +28,7 @@ com.google.cloud google-cloud-spanner-jdbc - 2.5.1 + 2.5.2-SNAPSHOT diff --git a/versions.txt b/versions.txt index 27d308fe0..00a220568 100644 --- a/versions.txt +++ b/versions.txt @@ -1,4 +1,4 @@ # Format: # module:released-version:current-version -google-cloud-spanner-jdbc:2.5.1:2.5.1 +google-cloud-spanner-jdbc:2.5.1:2.5.2-SNAPSHOT From bb13da583acd2d35d0495171fcc8fd50df2664e1 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Mon, 1 Nov 2021 03:30:23 +0100 Subject: [PATCH 02/11] chore(deps): update dependency com.google.cloud:google-cloud-spanner-jdbc to v2.5.1 (#655) --- samples/install-without-bom/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index 9093208b1..46322c634 100644 --- a/samples/install-without-bom/pom.xml +++ b/samples/install-without-bom/pom.xml @@ -29,7 +29,7 @@ com.google.cloud google-cloud-spanner-jdbc - 2.5.0 + 2.5.1 From e98ef8d573f5516f089a6ce9a67f7e929d00dce8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Mon, 1 Nov 2021 08:36:12 +0100 Subject: [PATCH 03/11] cleanup: remove warnings (#574) Remove as many warnings as possible. --- .../spanner/jdbc/AbstractJdbcConnection.java | 5 +- .../spanner/jdbc/AbstractJdbcResultSet.java | 20 +- .../spanner/jdbc/AbstractJdbcStatement.java | 19 +- .../spanner/jdbc/AbstractJdbcWrapper.java | 8 +- .../jdbc/CloudSpannerJdbcConnection.java | 34 +- .../google/cloud/spanner/jdbc/JdbcArray.java | 14 +- .../google/cloud/spanner/jdbc/JdbcBlob.java | 10 +- .../google/cloud/spanner/jdbc/JdbcClob.java | 28 +- .../cloud/spanner/jdbc/JdbcConnection.java | 17 +- .../cloud/spanner/jdbc/JdbcConstants.java | 5 +- .../cloud/spanner/jdbc/JdbcDataSource.java | 12 +- .../cloud/spanner/jdbc/JdbcDataType.java | 6 +- .../spanner/jdbc/JdbcDatabaseMetaData.java | 396 +++++++++--------- .../google/cloud/spanner/jdbc/JdbcDriver.java | 4 +- .../spanner/jdbc/JdbcParameterMetaData.java | 59 ++- .../spanner/jdbc/JdbcParameterStore.java | 37 +- .../cloud/spanner/jdbc/JdbcPreconditions.java | 4 +- .../spanner/jdbc/JdbcPreparedStatement.java | 5 +- .../cloud/spanner/jdbc/JdbcResultSet.java | 19 +- .../spanner/jdbc/JdbcResultSetMetaData.java | 50 +-- .../spanner/jdbc/JdbcSqlExceptionFactory.java | 3 +- .../cloud/spanner/jdbc/JdbcStatement.java | 7 +- .../cloud/spanner/jdbc/JdbcTypeConverter.java | 70 ++-- .../jdbc/TransactionRetryListener.java | 8 +- .../jdbc/AbstractJdbcResultSetTest.java | 10 +- .../spanner/jdbc/AbstractJdbcWrapperTest.java | 62 ++- .../jdbc/JdbcAbortedTransactionTest.java | 13 +- .../cloud/spanner/jdbc/JdbcArrayTest.java | 6 +- .../cloud/spanner/jdbc/JdbcClobTest.java | 11 +- .../JdbcConnectionGeneratedSqlScriptTest.java | 3 +- .../spanner/jdbc/JdbcConnectionTest.java | 16 +- .../spanner/jdbc/JdbcConnectionUrlTest.java | 40 +- .../jdbc/JdbcDatabaseMetaDataTest.java | 7 +- ...cDatabaseMetaDataWithMockedServerTest.java | 12 +- .../cloud/spanner/jdbc/JdbcDriverTest.java | 34 +- .../cloud/spanner/jdbc/JdbcGrpcErrorTest.java | 9 +- .../spanner/jdbc/JdbcParameterStoreTest.java | 37 +- .../jdbc/JdbcPreparedStatementTest.java | 40 +- ...PreparedStatementWithMockedServerTest.java | 3 +- .../jdbc/JdbcResultSetMetaDataTest.java | 93 ++-- .../cloud/spanner/jdbc/JdbcResultSetTest.java | 93 ++-- .../spanner/jdbc/JdbcSqlScriptVerifier.java | 18 +- .../cloud/spanner/jdbc/JdbcStatementTest.java | 65 ++- .../spanner/jdbc/JdbcTimeoutSqlTest.java | 4 +- .../spanner/jdbc/JdbcTypeConverterTest.java | 88 ++-- .../jdbc/SpannerJdbcExceptionMatcher.java | 4 +- .../spanner/jdbc/it/ITJdbcConnectTest.java | 7 +- .../cloud/spanner/jdbc/it/ITJdbcDdlTest.java | 2 +- .../jdbc/it/ITJdbcPreparedStatementTest.java | 49 +-- .../jdbc/it/ITJdbcQueryOptionsTest.java | 5 + .../spanner/jdbc/it/ITJdbcReadOnlyTest.java | 34 +- .../it/ITJdbcReadWriteAutocommitTest.java | 2 +- .../jdbc/it/ITJdbcSimpleStatementsTest.java | 2 +- .../jdbc/it/ITJdbcSqlMusicScriptTest.java | 2 +- .../spanner/jdbc/it/ITJdbcSqlScriptTest.java | 92 ++-- 55 files changed, 792 insertions(+), 911 deletions(-) diff --git a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java index 385a46fae..a666a7490 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java @@ -170,7 +170,7 @@ public SQLXML createSQLXML() throws SQLException { @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { - Properties supported = null; + Properties supported; try { checkClosed(); supported = JdbcDatabaseMetaData.getDefaultClientInfoProperties(); @@ -255,10 +255,9 @@ public int getNetworkTimeout() throws SQLException { void pushWarning(SQLWarning warning) { if (lastWarning == null) { firstWarning = warning; - lastWarning = warning; } else { lastWarning.setNextWarning(warning); - lastWarning = warning; } + lastWarning = warning; } } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSet.java b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSet.java index 74d5ccde3..652ed0b25 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSet.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSet.java @@ -47,12 +47,12 @@ abstract class AbstractJdbcResultSet extends AbstractJdbcWrapper implements Resu } @Override - public SQLWarning getWarnings() throws SQLException { + public SQLWarning getWarnings() { return null; } @Override - public void clearWarnings() throws SQLException {} + public void clearWarnings() {} @Override public String getCursorName() throws SQLException { @@ -105,42 +105,42 @@ public void setFetchDirection(int direction) throws SQLException { } @Override - public int getFetchDirection() throws SQLException { + public int getFetchDirection() { return FETCH_FORWARD; } @Override - public void setFetchSize(int rows) throws SQLException { + public void setFetchSize(int rows) { this.fetchSize = rows; } @Override - public int getFetchSize() throws SQLException { + public int getFetchSize() { return fetchSize; } @Override - public int getType() throws SQLException { + public int getType() { return TYPE_FORWARD_ONLY; } @Override - public int getConcurrency() throws SQLException { + public int getConcurrency() { return CONCUR_READ_ONLY; } @Override - public boolean rowUpdated() throws SQLException { + public boolean rowUpdated() { return false; } @Override - public boolean rowInserted() throws SQLException { + public boolean rowInserted() { return false; } @Override - public boolean rowDeleted() throws SQLException { + public boolean rowDeleted() { return false; } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcStatement.java b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcStatement.java index 9863f47c0..9c516609a 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcStatement.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcStatement.java @@ -20,6 +20,7 @@ import com.google.cloud.spanner.Options.QueryOption; import com.google.cloud.spanner.ReadContext.QueryAnalyzeMode; import com.google.cloud.spanner.SpannerException; +import com.google.cloud.spanner.connection.Connection; import com.google.cloud.spanner.connection.StatementResult; import com.google.cloud.spanner.connection.StatementResult.ClientSideStatementType; import com.google.rpc.Code; @@ -252,7 +253,7 @@ StatementResult execute(com.google.cloud.spanner.Statement statement) throws SQL if (mustResetTimeout && resultIsShowStatementTimeout(result)) { // it was a 'SHOW STATEMENT_TIMEOUT statement, we need to re-run to get the correct value mustResetTimeout = false; - result = rerunShowStatementTimeout(statement, result, originalTimeout); + result = rerunShowStatementTimeout(statement, originalTimeout); } return result; } catch (SpannerException e) { @@ -292,9 +293,7 @@ private boolean resultIsShowStatementTimeout(StatementResult result) { } private StatementResult rerunShowStatementTimeout( - com.google.cloud.spanner.Statement statement, - StatementResult result, - StatementTimeout originalTimeout) + com.google.cloud.spanner.Statement statement, StatementTimeout originalTimeout) throws SQLException { resetStatementTimeout(originalTimeout); return connection.getSpannerConnection().execute(statement); @@ -319,12 +318,12 @@ public void cancel() throws SQLException { } @Override - public void close() throws SQLException { + public void close() { this.closed = true; } @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return closed; } @@ -414,22 +413,22 @@ public void setFetchDirection(int direction) throws SQLException { } @Override - public int getFetchDirection() throws SQLException { + public int getFetchDirection() { return ResultSet.FETCH_FORWARD; } @Override - public int getResultSetConcurrency() throws SQLException { + public int getResultSetConcurrency() { return ResultSet.CONCUR_READ_ONLY; } @Override - public int getResultSetType() throws SQLException { + public int getResultSetType() { return ResultSet.TYPE_FORWARD_ONLY; } @Override - public int getResultSetHoldability() throws SQLException { + public int getResultSetHoldability() { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapper.java b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapper.java index 5f2967310..25ff70a6f 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapper.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapper.java @@ -199,7 +199,7 @@ static float checkedCastToFloat(double val) throws SQLException { static long parseLong(String val) throws SQLException { Preconditions.checkNotNull(val); try { - return Long.valueOf(val); + return Long.parseLong(val); } catch (NumberFormatException e) { throw JdbcSqlExceptionFactory.of( String.format("%s is not a valid number", val), com.google.rpc.Code.INVALID_ARGUMENT, e); @@ -233,7 +233,7 @@ static long checkedCastToLong(BigDecimal val) throws SQLException { static double parseDouble(String val) throws SQLException { Preconditions.checkNotNull(val); try { - return Double.valueOf(val); + return Double.parseDouble(val); } catch (NumberFormatException e) { throw JdbcSqlExceptionFactory.of( String.format("%s is not a valid number", val), com.google.rpc.Code.INVALID_ARGUMENT, e); @@ -333,7 +333,7 @@ static Timestamp parseTimestamp(String val, Calendar cal) throws SQLException { } /** Should return true if this object has been closed */ - public abstract boolean isClosed() throws SQLException; + public abstract boolean isClosed(); /** Throws a {@link SQLException} if this object is closed */ void checkClosed() throws SQLException { @@ -354,7 +354,7 @@ T checkClosedAndThrowUnsupported(String message) throws SQLException { } @Override - public boolean isWrapperFor(Class iface) throws SQLException { + public boolean isWrapperFor(Class iface) { return iface != null && iface.isAssignableFrom(getClass()); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/CloudSpannerJdbcConnection.java b/src/main/java/com/google/cloud/spanner/jdbc/CloudSpannerJdbcConnection.java index 50ae71c56..7801dcfdc 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/CloudSpannerJdbcConnection.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/CloudSpannerJdbcConnection.java @@ -16,6 +16,7 @@ package com.google.cloud.spanner.jdbc; +import com.google.cloud.spanner.AbortedDueToConcurrentModificationException; import com.google.cloud.spanner.AbortedException; import com.google.cloud.spanner.CommitResponse; import com.google.cloud.spanner.CommitStats; @@ -53,12 +54,12 @@ public interface CloudSpannerJdbcConnection extends Connection { */ default void setTransactionTag(String tag) throws SQLException { throw new UnsupportedOperationException(); - }; + } /** @return The transaction tag of the current transaction. */ default String getTransactionTag() throws SQLException { throw new UnsupportedOperationException(); - }; + } /** * Sets the statement tag to use for the next statement that will be executed. The tag is @@ -70,7 +71,7 @@ default String getTransactionTag() throws SQLException { */ default void setStatementTag(String tag) throws SQLException { throw new UnsupportedOperationException(); - }; + } /** * @return The statement tag that will be used with the next statement that is executed on this @@ -78,7 +79,7 @@ default void setStatementTag(String tag) throws SQLException { */ default String getStatementTag() throws SQLException { throw new UnsupportedOperationException(); - }; + } /** * Sets the transaction mode to use for current transaction. This method may only be called when @@ -96,10 +97,10 @@ default String getStatementTag() throws SQLException { * not acquire locks on Cloud Spanner, and read-only transactions never abort. *
  • {@link TransactionMode#READ_WRITE_TRANSACTION} this value is only allowed when the * connection is not in read-only mode and will create a read-write transaction. If - * {@link Connection#isRetryAbortsInternally()} is true, each read/write - * transaction will keep track of a running SHA256 checksum for each {@link ResultSet} - * that is returned in order to be able to retry the transaction in case the transaction - * is aborted by Spanner. + * {@link CloudSpannerJdbcConnection#isRetryAbortsInternally()} is true, + * each read/write transaction will keep track of a running SHA256 checksum for each + * {@link ResultSet} that is returned in order to be able to retry the transaction in + * case the transaction is aborted by Spanner. * */ void setTransactionMode(TransactionMode transactionMode) throws SQLException; @@ -175,9 +176,8 @@ default String getStatementTag() throws SQLException { /** * @return true if this connection has a transaction (that has not necessarily * started). This method will only return false when the {@link Connection} is in autocommit - * mode and no explicit transaction has been started by calling {@link - * Connection#beginTransaction()}. If the {@link Connection} is not in autocommit mode, there - * will always be a transaction. + * mode and no explicit transaction has been started by executing `BEGIN TRANSACTION`. If the + * {@link Connection} is not in autocommit mode, there will always be a transaction. */ boolean isInTransaction() throws SQLException; @@ -323,7 +323,7 @@ default String getStatementTag() throws SQLException { /** * @see - * com.google.cloud.spanner.connection.Connection#addTransactionRetryListener(TransactionRetryListener) + * com.google.cloud.spanner.connection.Connection#addTransactionRetryListener(com.google.cloud.spanner.connection.TransactionRetryListener) * @throws SQLException if the {@link Connection} is closed. */ void addTransactionRetryListener( @@ -331,7 +331,8 @@ void addTransactionRetryListener( /** * Use {@link - * #addTransactionRetryListener(com.google.cloud.spanner.jdbc.TransactionRetryListener)} + * #addTransactionRetryListener(com.google.cloud.spanner.connection.TransactionRetryListener)} + * instead. */ @Deprecated void addTransactionRetryListener(com.google.cloud.spanner.jdbc.TransactionRetryListener listener) @@ -339,7 +340,7 @@ void addTransactionRetryListener(com.google.cloud.spanner.jdbc.TransactionRetryL /** * @see - * com.google.cloud.spanner.connection.Connection#removeTransactionRetryListener(TransactionRetryListener) + * com.google.cloud.spanner.connection.Connection#removeTransactionRetryListener(com.google.cloud.spanner.connection.TransactionRetryListener) * @throws SQLException if the {@link Connection} is closed. */ boolean removeTransactionRetryListener( @@ -347,13 +348,14 @@ boolean removeTransactionRetryListener( /** * Use {@link - * #removeTransactionRetryListener(com.google.cloud.spanner.jdbc.TransactionRetryListener)} + * #removeTransactionRetryListener(com.google.cloud.spanner.connection.TransactionRetryListener)} + * instead. */ @Deprecated boolean removeTransactionRetryListener( com.google.cloud.spanner.jdbc.TransactionRetryListener listener) throws SQLException; - /** Use {@link #getTransactionRetryListenersFromConnection()} */ + /** Use {@link #getTransactionRetryListenersFromConnection()} instead. */ @Deprecated Iterator getTransactionRetryListeners() throws SQLException; diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcArray.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcArray.java index 436774050..f712b56ca 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcArray.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcArray.java @@ -67,13 +67,11 @@ static JdbcArray createArray(String typeName, Object[] elements) throws SQLExcep /** * Create a JDBC {@link Array} from the given type name and list. * - * @param typeName The Google Cloud Spanner type name to be used as the base type of the array. + * @param type The Google Cloud Spanner type to be used as the base type of the array. * @param elements The elements to store in the array. * @return the initialized {@link Array}. - * @throws SQLException if the type name is not a valid Cloud Spanner type or if the contents of - * the elements array is not compatible with the base type of the array. */ - static JdbcArray createArray(JdbcDataType type, List elements) { + static JdbcArray createArray(JdbcDataType type, List elements) { return new JdbcArray(type, elements); } @@ -93,7 +91,7 @@ private JdbcArray(JdbcDataType type, Object[] elements) throws SQLException { } } - private JdbcArray(JdbcDataType type, List elements) { + private JdbcArray(JdbcDataType type, List elements) { this.type = type; if (elements != null) { this.data = java.lang.reflect.Array.newInstance(type.getJavaClass(), elements.size()); @@ -179,7 +177,7 @@ public ResultSet getResultSet(long startIndex, int count) throws SQLException { Object value = ((Object[]) data)[index - 1]; ValueBinder binder = Struct.newBuilder().set("INDEX").to(index).set("VALUE"); - Struct.Builder builder = null; + Struct.Builder builder; switch (type.getCode()) { case BOOL: builder = binder.to((Boolean) value); @@ -237,7 +235,7 @@ public ResultSet getResultSet(long index, int count, Map> map) } @Override - public void free() throws SQLException { + public void free() { this.freed = true; this.data = null; } @@ -257,7 +255,7 @@ public String toString() { if (o == null) { builder.append("null"); } else { - builder.append(o.toString()); + builder.append(o); } } builder.append("}"); diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcBlob.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcBlob.java index 071e3258c..5a1566f7e 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcBlob.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcBlob.java @@ -63,7 +63,7 @@ private void checkPositionPlusLength(long pos, long length) { } @Override - public long length() throws SQLException { + public long length() { return value.length; } @@ -84,7 +84,7 @@ public byte[] getBytes(long pos, int length) throws SQLException { } @Override - public InputStream getBinaryStream() throws SQLException { + public InputStream getBinaryStream() { return new ByteArrayInputStream(value); } @@ -119,7 +119,7 @@ public long position(Blob pattern, long start) throws SQLException { int totalSize = 0; List totalBytes = new ArrayList<>(); try (InputStream is = pattern.getBinaryStream()) { - int bytesRead = 0; + int bytesRead; while ((bytesRead = is.read(buffer)) > -1) { if (bytesRead == buffer.length) { totalBytes.add(buffer); @@ -196,7 +196,7 @@ private BlobOutputStream(int pos) { } @Override - public void write(int b) throws IOException { + public void write(int b) { if (currentPos >= buffer.length) { byte[] newBuffer = new byte[buffer.length * 2]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); @@ -239,7 +239,7 @@ public void truncate(long len) throws SQLException { } @Override - public void free() throws SQLException { + public void free() { setLength(0); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcClob.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcClob.java index 40e26733a..2939dee1a 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcClob.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcClob.java @@ -17,6 +17,7 @@ package com.google.cloud.spanner.jdbc; import com.google.common.base.Preconditions; +import com.google.common.base.Strings; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; @@ -61,17 +62,8 @@ private void checkPositionPlusLength(long pos, long length) { "position+length larger than " + Integer.MAX_VALUE + " is not supported"); } - private StringBuilder repeat(char c, long length) { - checkLength(length); - StringBuilder res = new StringBuilder((int) length); - for (int i = 0; i < length; i++) { - res.append(c); - } - return res; - } - @Override - public long length() throws SQLException { + public long length() { return value.length(); } @@ -92,12 +84,12 @@ public String getSubString(long pos, int length) throws SQLException { } @Override - public Reader getCharacterStream() throws SQLException { + public Reader getCharacterStream() { return new StringReader(value.toString()); } @Override - public InputStream getAsciiStream() throws SQLException { + public InputStream getAsciiStream() { return new ByteArrayInputStream(StandardCharsets.US_ASCII.encode(value.toString()).array()); } @@ -131,10 +123,11 @@ public int setString(long pos, String str) throws SQLException { JdbcPreconditions.checkArgument(str != null, "str is null"); JdbcPreconditions.checkArgument(pos >= 1, "Position must be >= 1"); checkPosition(pos); - if ((pos - 1) > length()) { - value.append(repeat(' ', pos - length() - 1)); + int ipos = (int) pos; + if ((ipos - 1) > value.length()) { + value.append(Strings.repeat(" ", ipos - value.length() - 1)); } - value.replace((int) pos - 1, (int) pos + str.length() - 1, str); + value.replace(ipos - 1, ipos + str.length() - 1, str); return str.length(); } @@ -191,7 +184,7 @@ public void truncate(long len) throws SQLException { } @Override - public void free() throws SQLException { + public void free() { value = new StringBuilder(); } @@ -201,8 +194,7 @@ public Reader getCharacterStream(long pos, long length) throws SQLException { JdbcPreconditions.checkArgument(length >= 0, "length must be >= 0"); checkPosition(pos); checkPositionPlusLength(pos, length); - return new StringReader( - value.substring((int) pos - 1, (int) pos + (int) length - 1).toString()); + return new StringReader(value.substring((int) pos - 1, (int) pos + (int) length - 1)); } @Override diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcConnection.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcConnection.java index 53c1dc096..9e4623cab 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcConnection.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcConnection.java @@ -25,7 +25,6 @@ import com.google.cloud.spanner.connection.ConnectionOptions; import com.google.cloud.spanner.connection.StatementParser; import com.google.cloud.spanner.connection.TransactionMode; -import com.google.common.base.Function; import com.google.common.collect.Iterators; import java.sql.Array; import java.sql.Blob; @@ -222,7 +221,7 @@ public void close() throws SQLException { } @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return getSpannerConnection().isClosed(); } @@ -594,17 +593,11 @@ public Iterator getTransactionRetryListeners() throws checkClosed(); return Iterators.transform( getSpannerConnection().getTransactionRetryListeners(), - new Function< - com.google.cloud.spanner.connection.TransactionRetryListener, - TransactionRetryListener>() { - @Override - public TransactionRetryListener apply( - com.google.cloud.spanner.connection.TransactionRetryListener input) { - if (input instanceof JdbcToSpannerTransactionRetryListener) { - return ((JdbcToSpannerTransactionRetryListener) input).delegate; - } - return null; + input -> { + if (input instanceof JdbcToSpannerTransactionRetryListener) { + return ((JdbcToSpannerTransactionRetryListener) input).delegate; } + return null; }); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcConstants.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcConstants.java index 58c9e5bb3..164aec0ee 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcConstants.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcConstants.java @@ -30,8 +30,9 @@ public final class JdbcConstants { /** * Special value that is used to indicate that a statement had no result. The method {@link * Statement#getUpdateCount()} will return this value if the previous statement that was executed - * with {@link Statement#execute(String)} returned {@link ResultType#NO_RESULT}, such as DDL - * statements {@link ResultType}. + * with {@link Statement#execute(String)} returned {@link + * com.google.cloud.spanner.connection.StatementResult.ResultType#NO_RESULT}, such as DDL + * statements. */ public static final int STATEMENT_NO_RESULT = -2; diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataSource.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataSource.java index 72a641cc9..026406e2b 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataSource.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataSource.java @@ -35,7 +35,7 @@ public class JdbcDataSource extends AbstractJdbcWrapper implements DataSource { private Boolean readonly; private Boolean retryAbortsInternally; - /** Make sure the JDBC driver class is loaded. */ + // Make sure the JDBC driver class is loaded. static { try { Class.forName("com.google.cloud.spanner.jdbc.JdbcDriver"); @@ -46,22 +46,22 @@ public class JdbcDataSource extends AbstractJdbcWrapper implements DataSource { } @Override - public PrintWriter getLogWriter() throws SQLException { + public PrintWriter getLogWriter() { return null; } @Override - public void setLogWriter(PrintWriter out) throws SQLException { + public void setLogWriter(PrintWriter out) { // no-op } @Override - public void setLoginTimeout(int seconds) throws SQLException { + public void setLoginTimeout(int seconds) { // no-op } @Override - public int getLoginTimeout() throws SQLException { + public int getLoginTimeout() { return 0; } @@ -110,7 +110,7 @@ private Properties createProperties() { } @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return false; } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataType.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataType.java index 8da36e4c4..1a62775b7 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataType.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDataType.java @@ -111,7 +111,7 @@ public Type getSpannerType() { } }, FLOAT64 { - private Set> classes = new HashSet>(Arrays.asList(Float.class, Double.class)); + private final Set> classes = new HashSet<>(Arrays.asList(Float.class, Double.class)); @Override public int getSqlType() { @@ -144,8 +144,8 @@ public Type getSpannerType() { } }, INT64 { - private Set> classes = - new HashSet>(Arrays.asList(Byte.class, Integer.class, Long.class)); + private final Set> classes = + new HashSet<>(Arrays.asList(Byte.class, Integer.class, Long.class)); @Override public int getSqlType() { diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java index 191d991ea..42828fb5c 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java @@ -57,12 +57,11 @@ static String readSqlFromFile(String filename) { String line = scanner.nextLine(); builder.append(line).append("\n"); } - scanner.close(); } return builder.toString(); } - private JdbcConnection connection; + private final JdbcConnection connection; JdbcDatabaseMetaData(JdbcConnection connection) { this.connection = connection; @@ -74,22 +73,22 @@ public boolean isClosed() { } @Override - public boolean allProceduresAreCallable() throws SQLException { + public boolean allProceduresAreCallable() { return true; } @Override - public boolean allTablesAreSelectable() throws SQLException { + public boolean allTablesAreSelectable() { return true; } @Override - public String getURL() throws SQLException { + public String getURL() { return connection.getConnectionUrl(); } @Override - public String getUserName() throws SQLException { + public String getUserName() { Credentials credentials = connection.getConnectionOptions().getCredentials(); if (credentials != null) { if (credentials instanceof ServiceAccountSigner) { @@ -102,47 +101,47 @@ public String getUserName() throws SQLException { } @Override - public boolean isReadOnly() throws SQLException { + public boolean isReadOnly() { return false; } @Override - public boolean nullsAreSortedHigh() throws SQLException { + public boolean nullsAreSortedHigh() { return false; } @Override - public boolean nullsAreSortedLow() throws SQLException { + public boolean nullsAreSortedLow() { return true; } @Override - public boolean nullsAreSortedAtStart() throws SQLException { + public boolean nullsAreSortedAtStart() { return false; } @Override - public boolean nullsAreSortedAtEnd() throws SQLException { + public boolean nullsAreSortedAtEnd() { return false; } @Override - public String getDatabaseProductName() throws SQLException { + public String getDatabaseProductName() { return PRODUCT_NAME; } @Override - public String getDatabaseProductVersion() throws SQLException { + public String getDatabaseProductVersion() { return getDatabaseMajorVersion() + "." + getDatabaseMinorVersion(); } @Override - public String getDriverName() throws SQLException { + public String getDriverName() { return JdbcDriver.class.getName(); } @Override - public String getDriverVersion() throws SQLException { + public String getDriverVersion() { return getDriverMajorVersion() + "." + getDriverMinorVersion(); } @@ -157,528 +156,530 @@ public int getDriverMinorVersion() { } @Override - public boolean usesLocalFiles() throws SQLException { + public boolean usesLocalFiles() { return false; } @Override - public boolean usesLocalFilePerTable() throws SQLException { + public boolean usesLocalFilePerTable() { return false; } @Override - public boolean supportsMixedCaseIdentifiers() throws SQLException { + public boolean supportsMixedCaseIdentifiers() { return false; } @Override - public boolean storesUpperCaseIdentifiers() throws SQLException { + public boolean storesUpperCaseIdentifiers() { return false; } @Override - public boolean storesLowerCaseIdentifiers() throws SQLException { + public boolean storesLowerCaseIdentifiers() { return false; } @Override - public boolean storesMixedCaseIdentifiers() throws SQLException { + public boolean storesMixedCaseIdentifiers() { return true; } @Override - public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + public boolean supportsMixedCaseQuotedIdentifiers() { return false; } @Override - public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + public boolean storesUpperCaseQuotedIdentifiers() { return false; } @Override - public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + public boolean storesLowerCaseQuotedIdentifiers() { return false; } @Override - public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + public boolean storesMixedCaseQuotedIdentifiers() { return true; } @Override - public String getIdentifierQuoteString() throws SQLException { + public String getIdentifierQuoteString() { return "`"; } @Override - public String getSQLKeywords() throws SQLException { + public String getSQLKeywords() { return "ASSERT_ROWS_MODIFIED,ENUM,GROUPS,HASH,IGNORE,LOOKUP,PROTO,RESPECT,STRUCT,WINDOW"; } @Override - public String getNumericFunctions() throws SQLException { + public String getNumericFunctions() { return "ABS,SIGN,IS_INF,IS_NAN,IEEE_DIVIDE,SQRT,POW,POWER,EXP,LN,LOG,LOG10,GREATEST,LEAST,DIV,MOD,ROUND,TRUNC,CEIL,CEILING,FLOOR,COS,COSH,ACOS,ACOSH,SIN,SINH,ASIN,ASINH,TAN,TANH,ATAN,ATANH,ATAN2,FARM_FINGERPRINT,SHA1,SHA256,SHA512"; } @Override - public String getStringFunctions() throws SQLException { + public String getStringFunctions() { return "BYTE_LENGTH,CHAR_LENGTH,CHARACTER_LENGTH,CODE_POINTS_TO_BYTES,CODE_POINTS_TO_STRING,CONCAT,ENDS_WITH,FORMAT,FROM_BASE64,FROM_HEX,LENGTH,LPAD,LOWER,LTRIM,REGEXP_CONTAINS,REGEXP_EXTRACT,REGEXP_EXTRACT_ALL,REGEXP_REPLACE,REPLACE,REPEAT,REVERSE,RPAD,RTRIM,SAFE_CONVERT_BYTES_TO_STRING,SPLIT,STARTS_WITH,STRPOS,SUBSTR,TO_BASE64,TO_CODE_POINTS,TO_HEX,TRIM,UPPER,JSON_QUERY,JSON_VALUE"; } @Override - public String getSystemFunctions() throws SQLException { + public String getSystemFunctions() { return ""; } @Override - public String getTimeDateFunctions() throws SQLException { + public String getTimeDateFunctions() { return "CURRENT_DATE,EXTRACT,DATE,DATE_ADD,DATE_SUB,DATE_DIFF,DATE_TRUNC,DATE_FROM_UNIX_DATE,FORMAT_DATE,PARSE_DATE,UNIX_DATE,CURRENT_TIMESTAMP,STRING,TIMESTAMP,TIMESTAMP_ADD,TIMESTAMP_SUB,TIMESTAMP_DIFF,TIMESTAMP_TRUNC,FORMAT_TIMESTAMP,PARSE_TIMESTAMP,TIMESTAMP_SECONDS,TIMESTAMP_MILLIS,TIMESTAMP_MICROS,UNIX_SECONDS,UNIX_MILLIS,UNIX_MICROS"; } @Override - public String getSearchStringEscape() throws SQLException { + public String getSearchStringEscape() { return "\\"; } @Override - public String getExtraNameCharacters() throws SQLException { + public String getExtraNameCharacters() { return ""; } @Override - public boolean supportsAlterTableWithAddColumn() throws SQLException { + public boolean supportsAlterTableWithAddColumn() { return true; } @Override - public boolean supportsAlterTableWithDropColumn() throws SQLException { + public boolean supportsAlterTableWithDropColumn() { return true; } @Override - public boolean supportsColumnAliasing() throws SQLException { + public boolean supportsColumnAliasing() { return true; } @Override - public boolean nullPlusNonNullIsNull() throws SQLException { + public boolean nullPlusNonNullIsNull() { return true; } @Override - public boolean supportsConvert() throws SQLException { + public boolean supportsConvert() { return false; } @Override - public boolean supportsConvert(int fromType, int toType) throws SQLException { + public boolean supportsConvert(int fromType, int toType) { return false; } @Override - public boolean supportsTableCorrelationNames() throws SQLException { + public boolean supportsTableCorrelationNames() { return true; } @Override - public boolean supportsDifferentTableCorrelationNames() throws SQLException { + public boolean supportsDifferentTableCorrelationNames() { return false; } @Override - public boolean supportsExpressionsInOrderBy() throws SQLException { + public boolean supportsExpressionsInOrderBy() { return true; } @Override - public boolean supportsOrderByUnrelated() throws SQLException { + public boolean supportsOrderByUnrelated() { return true; } @Override - public boolean supportsGroupBy() throws SQLException { + public boolean supportsGroupBy() { return true; } @Override - public boolean supportsGroupByUnrelated() throws SQLException { + public boolean supportsGroupByUnrelated() { return true; } @Override - public boolean supportsGroupByBeyondSelect() throws SQLException { + public boolean supportsGroupByBeyondSelect() { return true; } @Override - public boolean supportsLikeEscapeClause() throws SQLException { + public boolean supportsLikeEscapeClause() { return true; } @Override - public boolean supportsMultipleResultSets() throws SQLException { + public boolean supportsMultipleResultSets() { return true; } @Override - public boolean supportsMultipleTransactions() throws SQLException { + public boolean supportsMultipleTransactions() { return true; } @Override - public boolean supportsNonNullableColumns() throws SQLException { + public boolean supportsNonNullableColumns() { return true; } @Override - public boolean supportsMinimumSQLGrammar() throws SQLException { + public boolean supportsMinimumSQLGrammar() { return false; } @Override - public boolean supportsCoreSQLGrammar() throws SQLException { + public boolean supportsCoreSQLGrammar() { return false; } @Override - public boolean supportsExtendedSQLGrammar() throws SQLException { + public boolean supportsExtendedSQLGrammar() { return false; } @Override - public boolean supportsANSI92EntryLevelSQL() throws SQLException { + public boolean supportsANSI92EntryLevelSQL() { return false; } @Override - public boolean supportsANSI92IntermediateSQL() throws SQLException { + public boolean supportsANSI92IntermediateSQL() { return false; } @Override - public boolean supportsANSI92FullSQL() throws SQLException { + public boolean supportsANSI92FullSQL() { return false; } @Override - public boolean supportsIntegrityEnhancementFacility() throws SQLException { + public boolean supportsIntegrityEnhancementFacility() { return false; } @Override - public boolean supportsOuterJoins() throws SQLException { + public boolean supportsOuterJoins() { return true; } @Override - public boolean supportsFullOuterJoins() throws SQLException { + public boolean supportsFullOuterJoins() { return true; } @Override - public boolean supportsLimitedOuterJoins() throws SQLException { + public boolean supportsLimitedOuterJoins() { return true; } @Override - public String getSchemaTerm() throws SQLException { + public String getSchemaTerm() { return "SCHEMA"; } @Override - public String getProcedureTerm() throws SQLException { + public String getProcedureTerm() { return "PROCEDURE"; } @Override - public String getCatalogTerm() throws SQLException { + public String getCatalogTerm() { // Spanner does not support catalogs, but the term is included for compatibility with the SQL // standard return "CATALOG"; } @Override - public boolean isCatalogAtStart() throws SQLException { + public boolean isCatalogAtStart() { return false; } @Override - public String getCatalogSeparator() throws SQLException { + public String getCatalogSeparator() { return "."; } @Override - public boolean supportsSchemasInDataManipulation() throws SQLException { + public boolean supportsSchemasInDataManipulation() { return false; } @Override - public boolean supportsSchemasInProcedureCalls() throws SQLException { + public boolean supportsSchemasInProcedureCalls() { return false; } @Override - public boolean supportsSchemasInTableDefinitions() throws SQLException { + public boolean supportsSchemasInTableDefinitions() { return false; } @Override - public boolean supportsSchemasInIndexDefinitions() throws SQLException { + public boolean supportsSchemasInIndexDefinitions() { return false; } @Override - public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { + public boolean supportsSchemasInPrivilegeDefinitions() { return false; } @Override - public boolean supportsCatalogsInDataManipulation() throws SQLException { + public boolean supportsCatalogsInDataManipulation() { return false; } @Override - public boolean supportsCatalogsInProcedureCalls() throws SQLException { + public boolean supportsCatalogsInProcedureCalls() { return false; } @Override - public boolean supportsCatalogsInTableDefinitions() throws SQLException { + public boolean supportsCatalogsInTableDefinitions() { return false; } @Override - public boolean supportsCatalogsInIndexDefinitions() throws SQLException { + public boolean supportsCatalogsInIndexDefinitions() { return false; } @Override - public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { + public boolean supportsCatalogsInPrivilegeDefinitions() { return false; } @Override - public boolean supportsPositionedDelete() throws SQLException { + public boolean supportsPositionedDelete() { return false; } @Override - public boolean supportsPositionedUpdate() throws SQLException { + public boolean supportsPositionedUpdate() { return false; } @Override - public boolean supportsSelectForUpdate() throws SQLException { + public boolean supportsSelectForUpdate() { return false; } @Override - public boolean supportsStoredProcedures() throws SQLException { + public boolean supportsStoredProcedures() { return false; } @Override - public boolean supportsSubqueriesInComparisons() throws SQLException { + public boolean supportsSubqueriesInComparisons() { return true; } @Override - public boolean supportsSubqueriesInExists() throws SQLException { + public boolean supportsSubqueriesInExists() { return true; } @Override - public boolean supportsSubqueriesInIns() throws SQLException { + public boolean supportsSubqueriesInIns() { return true; } @Override - public boolean supportsSubqueriesInQuantifieds() throws SQLException { + public boolean supportsSubqueriesInQuantifieds() { return true; } @Override - public boolean supportsCorrelatedSubqueries() throws SQLException { + public boolean supportsCorrelatedSubqueries() { return true; } @Override - public boolean supportsUnion() throws SQLException { + public boolean supportsUnion() { // Note that Cloud Spanner requires the user to specify 'UNION DISTINCT' or 'UNION ALL' in a // query. 'UNION DISTINCT' is equal to the SQL operation 'UNION'. return true; } @Override - public boolean supportsUnionAll() throws SQLException { + public boolean supportsUnionAll() { return true; } @Override - public boolean supportsOpenCursorsAcrossCommit() throws SQLException { + public boolean supportsOpenCursorsAcrossCommit() { return false; } @Override - public boolean supportsOpenCursorsAcrossRollback() throws SQLException { + public boolean supportsOpenCursorsAcrossRollback() { return false; } @Override - public boolean supportsOpenStatementsAcrossCommit() throws SQLException { + public boolean supportsOpenStatementsAcrossCommit() { return true; } @Override - public boolean supportsOpenStatementsAcrossRollback() throws SQLException { + public boolean supportsOpenStatementsAcrossRollback() { return true; } @Override - public int getMaxBinaryLiteralLength() throws SQLException { + public int getMaxBinaryLiteralLength() { return 0; } @Override - public int getMaxCharLiteralLength() throws SQLException { + public int getMaxCharLiteralLength() { return 0; } @Override - public int getMaxColumnNameLength() throws SQLException { + public int getMaxColumnNameLength() { return 128; } @Override - public int getMaxColumnsInGroupBy() throws SQLException { + public int getMaxColumnsInGroupBy() { return 1000; } @Override - public int getMaxColumnsInIndex() throws SQLException { + public int getMaxColumnsInIndex() { return 16; } @Override - public int getMaxColumnsInOrderBy() throws SQLException { + public int getMaxColumnsInOrderBy() { return 0; } @Override - public int getMaxColumnsInSelect() throws SQLException { + public int getMaxColumnsInSelect() { return 0; } @Override - public int getMaxColumnsInTable() throws SQLException { + public int getMaxColumnsInTable() { return 1024; } @Override - public int getMaxConnections() throws SQLException { + public int getMaxConnections() { // there is a max number of sessions, but that is not the same as the max number of connections return 0; } @Override - public int getMaxCursorNameLength() throws SQLException { + public int getMaxCursorNameLength() { return 0; } @Override - public int getMaxIndexLength() throws SQLException { + public int getMaxIndexLength() { return 8000; } @Override - public int getMaxSchemaNameLength() throws SQLException { + public int getMaxSchemaNameLength() { return 0; } @Override - public int getMaxProcedureNameLength() throws SQLException { + public int getMaxProcedureNameLength() { return 0; } @Override - public int getMaxCatalogNameLength() throws SQLException { + public int getMaxCatalogNameLength() { return 0; } @Override - public int getMaxRowSize() throws SQLException { - return 1024 * 10000000; + public int getMaxRowSize() { + // The limit is 1024 columns per table * 10MB per column, which is more than fits in an int. + // We therefore return 0 to indicate no limit (or an unknown limit). + return 0; } @Override - public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + public boolean doesMaxRowSizeIncludeBlobs() { return true; } @Override - public int getMaxStatementLength() throws SQLException { + public int getMaxStatementLength() { return 1000000; } @Override - public int getMaxStatements() throws SQLException { + public int getMaxStatements() { return 0; } @Override - public int getMaxTableNameLength() throws SQLException { + public int getMaxTableNameLength() { return 128; } @Override - public int getMaxTablesInSelect() throws SQLException { + public int getMaxTablesInSelect() { return 0; } @Override - public int getMaxUserNameLength() throws SQLException { + public int getMaxUserNameLength() { return 0; } @Override - public int getDefaultTransactionIsolation() throws SQLException { + public int getDefaultTransactionIsolation() { return Connection.TRANSACTION_SERIALIZABLE; } @Override - public boolean supportsTransactions() throws SQLException { + public boolean supportsTransactions() { return true; } @Override - public boolean supportsTransactionIsolationLevel(int level) throws SQLException { + public boolean supportsTransactionIsolationLevel(int level) { return Connection.TRANSACTION_SERIALIZABLE == level; } @Override - public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { + public boolean supportsDataDefinitionAndDataManipulationTransactions() { return false; } @Override - public boolean supportsDataManipulationTransactionsOnly() throws SQLException { + public boolean supportsDataManipulationTransactionsOnly() { return true; } @Override - public boolean dataDefinitionCausesTransactionCommit() throws SQLException { + public boolean dataDefinitionCausesTransactionCommit() { return false; } @Override - public boolean dataDefinitionIgnoredInTransactions() throws SQLException { + public boolean dataDefinitionIgnoredInTransactions() { return false; } @Override - public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) - throws SQLException { + public ResultSet getProcedures( + String catalog, String schemaPattern, String procedureNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -691,13 +692,12 @@ public ResultSet getProcedures(String catalog, String schemaPattern, String proc StructField.of("REMARKS", Type.string()), StructField.of("PROCEDURE_TYPE", Type.int64()), StructField.of("SPECIFIC_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override public ResultSet getProcedureColumns( - String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) - throws SQLException { + String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -721,7 +721,7 @@ public ResultSet getProcedureColumns( StructField.of("ORDINAL_POSITION", Type.int64()), StructField.of("IS_NULLABLE", Type.string()), StructField.of("SPECIFIC_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } private JdbcPreparedStatement prepareStatementReplaceNullWithAnyString( @@ -768,15 +768,15 @@ public ResultSet getSchemas() throws SQLException { } @Override - public ResultSet getCatalogs() throws SQLException { + public ResultSet getCatalogs() { return JdbcResultSet.of( ResultSets.forRows( Type.struct(StructField.of("TABLE_CAT", Type.string())), - Arrays.asList(Struct.newBuilder().set("TABLE_CAT").to("").build()))); + Collections.singletonList(Struct.newBuilder().set("TABLE_CAT").to("").build()))); } @Override - public ResultSet getTableTypes() throws SQLException { + public ResultSet getTableTypes() { return JdbcResultSet.of( ResultSets.forRows( Type.struct(StructField.of("TABLE_TYPE", Type.string())), @@ -798,7 +798,7 @@ public ResultSet getColumns( @Override public ResultSet getColumnPrivileges( - String catalog, String schema, String table, String columnNamePattern) throws SQLException { + String catalog, String schema, String table, String columnNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -810,12 +810,12 @@ public ResultSet getColumnPrivileges( StructField.of("GRANTEE", Type.string()), StructField.of("PRIVILEGE", Type.string()), StructField.of("IS_GRANTABLE", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override - public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) - throws SQLException { + public ResultSet getTablePrivileges( + String catalog, String schemaPattern, String tableNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -826,30 +826,21 @@ public ResultSet getTablePrivileges(String catalog, String schemaPattern, String StructField.of("GRANTEE", Type.string()), StructField.of("PRIVILEGE", Type.string()), StructField.of("IS_GRANTABLE", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override public ResultSet getBestRowIdentifier( - String catalog, String schema, String table, int scope, boolean nullable) - throws SQLException { - return JdbcResultSet.of( - ResultSets.forRows( - Type.struct( - StructField.of("SCOPE", Type.int64()), - StructField.of("COLUMN_NAME", Type.string()), - StructField.of("DATA_TYPE", Type.int64()), - StructField.of("TYPE_NAME", Type.string()), - StructField.of("COLUMN_SIZE", Type.int64()), - StructField.of("BUFFER_LENGTH", Type.int64()), - StructField.of("DECIMAL_DIGITS", Type.int64()), - StructField.of("PSEUDO_COLUMN", Type.int64())), - Collections.emptyList())); + String catalog, String schema, String table, int scope, boolean nullable) { + return getEmptyColumnsResultSet(); } @Override - public ResultSet getVersionColumns(String catalog, String schema, String table) - throws SQLException { + public ResultSet getVersionColumns(String catalog, String schema, String table) { + return getEmptyColumnsResultSet(); + } + + private ResultSet getEmptyColumnsResultSet() { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -861,7 +852,7 @@ public ResultSet getVersionColumns(String catalog, String schema, String table) StructField.of("BUFFER_LENGTH", Type.int64()), StructField.of("DECIMAL_DIGITS", Type.int64()), StructField.of("PSEUDO_COLUMN", Type.int64())), - Collections.emptyList())); + Collections.emptyList())); } @Override @@ -916,7 +907,7 @@ public ResultSet getCrossReference( } @Override - public ResultSet getTypeInfo() throws SQLException { + public ResultSet getTypeInfo() { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1268,69 +1259,68 @@ private ResultSet getIndexInfo( } @Override - public boolean supportsResultSetType(int type) throws SQLException { + public boolean supportsResultSetType(int type) { return type == ResultSet.TYPE_FORWARD_ONLY; } @Override - public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { + public boolean supportsResultSetConcurrency(int type, int concurrency) { return type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY; } @Override - public boolean ownUpdatesAreVisible(int type) throws SQLException { + public boolean ownUpdatesAreVisible(int type) { return false; } @Override - public boolean ownDeletesAreVisible(int type) throws SQLException { + public boolean ownDeletesAreVisible(int type) { return false; } @Override - public boolean ownInsertsAreVisible(int type) throws SQLException { + public boolean ownInsertsAreVisible(int type) { return false; } @Override - public boolean othersUpdatesAreVisible(int type) throws SQLException { + public boolean othersUpdatesAreVisible(int type) { return false; } @Override - public boolean othersDeletesAreVisible(int type) throws SQLException { + public boolean othersDeletesAreVisible(int type) { return false; } @Override - public boolean othersInsertsAreVisible(int type) throws SQLException { + public boolean othersInsertsAreVisible(int type) { return false; } @Override - public boolean updatesAreDetected(int type) throws SQLException { + public boolean updatesAreDetected(int type) { return false; } @Override - public boolean deletesAreDetected(int type) throws SQLException { + public boolean deletesAreDetected(int type) { return false; } @Override - public boolean insertsAreDetected(int type) throws SQLException { + public boolean insertsAreDetected(int type) { return false; } @Override - public boolean supportsBatchUpdates() throws SQLException { + public boolean supportsBatchUpdates() { return true; } @Override public ResultSet getUDTs( - String catalog, String schemaPattern, String typeNamePattern, int[] types) - throws SQLException { + String catalog, String schemaPattern, String typeNamePattern, int[] types) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1341,37 +1331,36 @@ public ResultSet getUDTs( StructField.of("DATA_TYPE", Type.int64()), StructField.of("REMARKS", Type.string()), StructField.of("BASE_TYPE", Type.int64())), - Collections.emptyList())); + Collections.emptyList())); } @Override - public Connection getConnection() throws SQLException { + public Connection getConnection() { return connection; } @Override - public boolean supportsSavepoints() throws SQLException { + public boolean supportsSavepoints() { return false; } @Override - public boolean supportsNamedParameters() throws SQLException { + public boolean supportsNamedParameters() { return false; } @Override - public boolean supportsMultipleOpenResults() throws SQLException { + public boolean supportsMultipleOpenResults() { return true; } @Override - public boolean supportsGetGeneratedKeys() throws SQLException { + public boolean supportsGetGeneratedKeys() { return false; } @Override - public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) - throws SQLException { + public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1381,12 +1370,11 @@ public ResultSet getSuperTypes(String catalog, String schemaPattern, String type StructField.of("SUPERTYPE_CAT", Type.string()), StructField.of("SUPERTYPE_SCHEM", Type.string()), StructField.of("SUPERTYPE_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override - public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) - throws SQLException { + public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1394,13 +1382,12 @@ public ResultSet getSuperTables(String catalog, String schemaPattern, String tab StructField.of("TABLE_SCHEM", Type.string()), StructField.of("TABLE_NAME", Type.string()), StructField.of("SUPERTABLE_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override public ResultSet getAttributes( - String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) - throws SQLException { + String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1425,56 +1412,56 @@ public ResultSet getAttributes( StructField.of("SCOPE_SCHEMA", Type.string()), StructField.of("SCOPE_TABLE", Type.string()), StructField.of("SOURCE_DATA_TYPE", Type.int64())), - Collections.emptyList())); + Collections.emptyList())); } @Override - public boolean supportsResultSetHoldability(int holdability) throws SQLException { + public boolean supportsResultSetHoldability(int holdability) { return holdability == ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override - public int getResultSetHoldability() throws SQLException { + public int getResultSetHoldability() { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } @Override - public int getDatabaseMajorVersion() throws SQLException { + public int getDatabaseMajorVersion() { return DATABASE_MAJOR_VERSION; } @Override - public int getDatabaseMinorVersion() throws SQLException { + public int getDatabaseMinorVersion() { return DATABASE_MINOR_VERSION; } @Override - public int getJDBCMajorVersion() throws SQLException { + public int getJDBCMajorVersion() { return JDBC_MAJOR_VERSION; } @Override - public int getJDBCMinorVersion() throws SQLException { + public int getJDBCMinorVersion() { return JDBC_MINOR_VERSION; } @Override - public int getSQLStateType() throws SQLException { + public int getSQLStateType() { return sqlStateSQL; } @Override - public boolean locatorsUpdateCopy() throws SQLException { + public boolean locatorsUpdateCopy() { return true; } @Override - public boolean supportsStatementPooling() throws SQLException { + public boolean supportsStatementPooling() { return false; } @Override - public RowIdLifetime getRowIdLifetime() throws SQLException { + public RowIdLifetime getRowIdLifetime() { return RowIdLifetime.ROWID_UNSUPPORTED; } @@ -1487,12 +1474,12 @@ public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLExce } @Override - public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { + public boolean supportsStoredFunctionsUsingCallSyntax() { return false; } @Override - public boolean autoCommitFailureClosesAllResultSets() throws SQLException { + public boolean autoCommitFailureClosesAllResultSets() { return false; } @@ -1511,7 +1498,7 @@ static Properties getDefaultClientInfoProperties() throws SQLException { return info; } - private static ResultSet getDefaultClientInfo() throws SQLException { + private static ResultSet getDefaultClientInfo() { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1556,13 +1543,12 @@ private static ResultSet getDefaultClientInfo() throws SQLException { } @Override - public ResultSet getClientInfoProperties() throws SQLException { + public ResultSet getClientInfoProperties() { return getDefaultClientInfo(); } @Override - public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) - throws SQLException { + public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) { // TODO: return system functions return JdbcResultSet.of( ResultSets.forRows( @@ -1573,13 +1559,12 @@ public ResultSet getFunctions(String catalog, String schemaPattern, String funct StructField.of("REMARKS", Type.string()), StructField.of("FUNCTION_TYPE", Type.int64()), StructField.of("SPECIFIC_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override public ResultSet getFunctionColumns( - String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) - throws SQLException { + String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) { // TODO: return system functions return JdbcResultSet.of( ResultSets.forRows( @@ -1601,13 +1586,12 @@ public ResultSet getFunctionColumns( StructField.of("ORDINAL_POSITION", Type.int64()), StructField.of("IS_NULLABLE", Type.string()), StructField.of("SPECIFIC_NAME", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override public ResultSet getPseudoColumns( - String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) - throws SQLException { + String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) { return JdbcResultSet.of( ResultSets.forRows( Type.struct( @@ -1623,22 +1607,22 @@ public ResultSet getPseudoColumns( StructField.of("REMARKS", Type.string()), StructField.of("CHAR_OCTET_LENGTH", Type.int64()), StructField.of("IS_NULLABLE", Type.string())), - Collections.emptyList())); + Collections.emptyList())); } @Override - public boolean generatedKeyAlwaysReturned() throws SQLException { + public boolean generatedKeyAlwaysReturned() { return false; } @Override - public long getMaxLogicalLobSize() throws SQLException { + public long getMaxLogicalLobSize() { // BYTES(MAX) return 10485760L; } @Override - public boolean supportsRefCursors() throws SQLException { + public boolean supportsRefCursors() { return false; } } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java index 08dd5fafe..b127e6825 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java @@ -220,12 +220,12 @@ private String appendPropertiesToUrl(String url, Properties info) { } @Override - public boolean acceptsURL(String url) throws SQLException { + public boolean acceptsURL(String url) { return URL_PATTERN.matcher(url).matches(); } @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { + public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) { String connectionUri = appendPropertiesToUrl(url.substring(5), info); DriverPropertyInfo[] res = new DriverPropertyInfo[ConnectionOptions.VALID_PROPERTIES.size()]; int i = 0; diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterMetaData.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterMetaData.java index 59b10b68f..f5188653b 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterMetaData.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterMetaData.java @@ -40,19 +40,20 @@ public boolean isClosed() { } @Override - public int getParameterCount() throws SQLException { + public int getParameterCount() { ParametersInfo info = statement.getParametersInfo(); return info.numberOfParameters; } @Override - public int isNullable(int param) throws SQLException { + public int isNullable(int param) { Integer nullable = statement.getParameters().getNullable(param); - return nullable == null ? parameterNullableUnknown : nullable.intValue(); + //noinspection MagicConstant + return nullable == null ? parameterNullableUnknown : nullable; } @Override - public boolean isSigned(int param) throws SQLException { + public boolean isSigned(int param) { int type = getParameterType(param); return type == Types.DOUBLE || type == Types.FLOAT @@ -65,20 +66,20 @@ public boolean isSigned(int param) throws SQLException { } @Override - public int getPrecision(int param) throws SQLException { + public int getPrecision(int param) { Integer length = statement.getParameters().getScaleOrLength(param); - return length == null ? 0 : length.intValue(); + return length == null ? 0 : length; } @Override - public int getScale(int param) throws SQLException { + public int getScale(int param) { return 0; } @Override - public int getParameterType(int param) throws SQLException { + public int getParameterType(int param) { Integer type = statement.getParameters().getType(param); - if (type != null) return type.intValue(); + if (type != null) return type; Object value = statement.getParameters().getParameter(param); if (value == null) { @@ -115,45 +116,41 @@ public int getParameterType(int param) throws SQLException { } @Override - public String getParameterTypeName(int param) throws SQLException { + public String getParameterTypeName(int param) { return getSpannerTypeName(getParameterType(param)); } @Override - public String getParameterClassName(int param) throws SQLException { + public String getParameterClassName(int param) { Object value = statement.getParameters().getParameter(param); if (value != null) return value.getClass().getName(); Integer type = statement.getParameters().getType(param); - if (type != null) return getClassName(type.intValue()); + if (type != null) return getClassName(type); return null; } @Override - public int getParameterMode(int param) throws SQLException { + public int getParameterMode(int param) { return parameterModeIn; } @Override public String toString() { StringBuilder res = new StringBuilder(); - try { - res.append("CloudSpannerPreparedStatementParameterMetaData, parameter count: ") - .append(getParameterCount()); - for (int param = 1; param <= getParameterCount(); param++) { - res.append("\nParameter ") - .append(param) - .append(":\n\t Class name: ") - .append(getParameterClassName(param)); - res.append(",\n\t Parameter type name: ").append(getParameterTypeName(param)); - res.append(",\n\t Parameter type: ").append(getParameterType(param)); - res.append(",\n\t Parameter precision: ").append(getPrecision(param)); - res.append(",\n\t Parameter scale: ").append(getScale(param)); - res.append(",\n\t Parameter signed: ").append(isSigned(param)); - res.append(",\n\t Parameter nullable: ").append(isNullable(param)); - res.append(",\n\t Parameter mode: ").append(getParameterMode(param)); - } - } catch (SQLException e) { - res.append("Error while fetching parameter metadata: ").append(e.getMessage()); + res.append("CloudSpannerPreparedStatementParameterMetaData, parameter count: ") + .append(getParameterCount()); + for (int param = 1; param <= getParameterCount(); param++) { + res.append("\nParameter ") + .append(param) + .append(":\n\t Class name: ") + .append(getParameterClassName(param)); + res.append(",\n\t Parameter type name: ").append(getParameterTypeName(param)); + res.append(",\n\t Parameter type: ").append(getParameterType(param)); + res.append(",\n\t Parameter precision: ").append(getPrecision(param)); + res.append(",\n\t Parameter scale: ").append(getScale(param)); + res.append(",\n\t Parameter signed: ").append(isSigned(param)); + res.append(",\n\t Parameter nullable: ").append(isNullable(param)); + res.append(",\n\t Parameter mode: ").append(getParameterMode(param)); } return res.toString(); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterStore.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterStore.java index 24773cdce..a475646a6 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterStore.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcParameterStore.java @@ -420,15 +420,13 @@ static ParametersInfo convertPositionalParametersToNamedParameters(String sql) isInQuoted = false; startQuote = 0; } - } else if (c == '\\') { - lastCharWasEscapeChar = true; } else { - lastCharWasEscapeChar = false; + lastCharWasEscapeChar = (c == '\\'); } named.append(c); } else { if (c == POS_PARAM) { - named.append("@p" + paramIndex); + named.append("@p").append(paramIndex); paramIndex++; } else { if (c == SINGLE_QUOTE || c == DOUBLE_QUOTE || c == BACKTICK_QUOTE) { @@ -487,7 +485,7 @@ Builder setValue(ValueBinder binder, Object value, Integer sqlType) thr } if (res == null && value != null) { throw JdbcSqlExceptionFactory.of( - "Unsupported parameter type: " + value.getClass().getName() + " - " + value.toString(), + "Unsupported parameter type: " + value.getClass().getName() + " - " + value, Code.INVALID_ARGUMENT); } return res; @@ -497,7 +495,7 @@ private Builder setSingleValue(ValueBinder binder, Object value, Intege throws SQLException { if (value == null) { return setNullValue(binder, sqlType); - } else if (sqlType == null || sqlType == Integer.valueOf(Types.OTHER)) { + } else if (sqlType == null || sqlType.equals(Types.OTHER)) { return setParamWithUnknownType(binder, value); } else { return setParamWithKnownType(binder, value, sqlType); @@ -559,7 +557,7 @@ private Builder setParamWithKnownType(ValueBinder binder, Object value, } else if (value instanceof Reader) { stringValue = getStringFromReader((Reader) value); } else if (value instanceof URL) { - stringValue = ((URL) value).toString(); + stringValue = value.toString(); } else if (value instanceof UUID) { stringValue = ((UUID) value).toString(); } else { @@ -621,7 +619,7 @@ private Builder setParamWithKnownType(ValueBinder binder, Object value, case Types.ARRAY: if (value instanceof Array) { Array jdbcArray = (Array) value; - return setArrayValue(binder, sqlType, jdbcArray == null ? null : jdbcArray.getArray()); + return setArrayValue(binder, sqlType, jdbcArray.getArray()); } throw JdbcSqlExceptionFactory.of(value + " is not a valid array", Code.INVALID_ARGUMENT); case Types.BLOB: @@ -719,8 +717,7 @@ private Builder setParamWithUnknownType(ValueBinder binder, Object valu } catch (IOException e) { throw new IllegalArgumentException("Could not read from readable", e); } - } else if (Clob.class.isAssignableFrom(value.getClass()) - || NClob.class.isAssignableFrom(value.getClass())) { + } else if (Clob.class.isAssignableFrom(value.getClass())) { try { Clob clob = (Clob) value; return binder.to(CharStreams.toString(clob.getCharacterStream())); @@ -739,7 +736,7 @@ private Builder setParamWithUnknownType(ValueBinder binder, Object valu } else if (char[].class.isAssignableFrom(value.getClass())) { return binder.to(String.valueOf((char[]) value)); } else if (URL.class.isAssignableFrom(value.getClass())) { - return binder.to(((URL) value).toString()); + return binder.to(value.toString()); } else if (UUID.class.isAssignableFrom(value.getClass())) { return binder.to(((UUID) value).toString()); } else if (byte[].class.isAssignableFrom(value.getClass())) { @@ -761,12 +758,10 @@ private Builder setParamWithUnknownType(ValueBinder binder, Object valu } else if (Array.class.isAssignableFrom(value.getClass())) { try { Array jdbcArray = (Array) value; - if (value != null) { - return setArrayValue(binder, jdbcArray.getBaseType(), jdbcArray.getArray()); - } + return setArrayValue(binder, jdbcArray.getBaseType(), jdbcArray.getArray()); } catch (SQLException e) { throw new IllegalArgumentException( - "Unsupported parameter type: " + value.getClass().getName() + " - " + value.toString()); + "Unsupported parameter type: " + value.getClass().getName() + " - " + value); } } return null; @@ -813,7 +808,7 @@ private Builder setArrayValue(ValueBinder binder, int type, Object valu case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: - return binder.toBytesArray((Iterable) null); + return binder.toBytesArray(null); } throw JdbcSqlExceptionFactory.unsupported("Unknown/unsupported array base type: " + type); } @@ -874,16 +869,16 @@ private Builder setArrayValue(ValueBinder binder, int type, Object valu private List toLongList(Number[] input) { List res = new ArrayList<>(input.length); - for (int i = 0; i < input.length; i++) { - res.add(input[i] == null ? null : input[i].longValue()); + for (Number number : input) { + res.add(number == null ? null : number.longValue()); } return res; } private List toDoubleList(Number[] input) { List res = new ArrayList<>(input.length); - for (int i = 0; i < input.length; i++) { - res.add(input[i] == null ? null : input[i].doubleValue()); + for (Number number : input) { + res.add(number == null ? null : number.doubleValue()); } return res; } @@ -892,7 +887,7 @@ private List toDoubleList(Number[] input) { * Sets a null value with a specific SQL type. If the sqlType is null, the value will be set as a * String. */ - private Builder setNullValue(ValueBinder binder, Integer sqlType) throws SQLException { + private Builder setNullValue(ValueBinder binder, Integer sqlType) { if (sqlType == null) { return binder.to((String) null); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreconditions.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreconditions.java index a516e68b7..19586efe1 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreconditions.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreconditions.java @@ -31,7 +31,7 @@ class JdbcPreconditions { * * @param expression the boolean expression that should be true. * @param value the parameter value that is being checked. - * @throws JdbcSqlException with {@link Code#INVALID_ARGUMENT} if {@code expression} is false + * @throws SQLException with {@link Code#INVALID_ARGUMENT} if {@code expression} is false */ static void checkArgument(boolean expression, Object value) throws SQLException { if (!expression) { @@ -46,7 +46,7 @@ static void checkArgument(boolean expression, Object value) throws SQLException * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} - * @throws JdbcSqlException with {@link Code#FAILED_PRECONDITION} if {@code expression} is false + * @throws SQLException with {@link Code#FAILED_PRECONDITION} if {@code expression} is false */ static void checkState(boolean expression, @Nullable Object errorMessage) throws SQLException { if (!expression) { diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatement.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatement.java index 919aad302..a25b39c04 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatement.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatement.java @@ -20,7 +20,6 @@ import com.google.cloud.spanner.ReadContext.QueryAnalyzeMode; import com.google.cloud.spanner.ResultSets; import com.google.cloud.spanner.Statement; -import com.google.cloud.spanner.Struct; import com.google.cloud.spanner.Type; import com.google.cloud.spanner.connection.StatementParser; import com.google.cloud.spanner.jdbc.JdbcParameterStore.ParametersInfo; @@ -45,7 +44,7 @@ class JdbcPreparedStatement extends AbstractJdbcPreparedStatement { JdbcParameterStore.convertPositionalParametersToNamedParameters(sqlWithoutComments); } - ParametersInfo getParametersInfo() throws SQLException { + ParametersInfo getParametersInfo() { return parameters; } @@ -107,7 +106,7 @@ public ResultSetMetaData getMetaData() throws SQLException { // Return metadata for an empty result set as DML statements do not return any results (as a // result set). com.google.cloud.spanner.ResultSet resultSet = - ResultSets.forRows(Type.struct(), ImmutableList.of()); + ResultSets.forRows(Type.struct(), ImmutableList.of()); resultSet.next(); return new JdbcResultSetMetaData(JdbcResultSet.of(resultSet), this); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSet.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSet.java index 489c2d27f..c06c147f8 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSet.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSet.java @@ -99,7 +99,7 @@ public boolean next() throws SQLException { } @Override - public void close() throws SQLException { + public void close() { spanner.close(); this.closed = true; } @@ -161,15 +161,15 @@ public boolean getBoolean(int columnIndex) throws SQLException { Code type = spanner.getColumnType(spannerIndex).getCode(); switch (type) { case BOOL: - return isNull ? false : spanner.getBoolean(spannerIndex); + return !isNull && spanner.getBoolean(spannerIndex); case FLOAT64: - return isNull ? false : spanner.getDouble(spannerIndex) != 0D; + return !isNull && spanner.getDouble(spannerIndex) != 0D; case INT64: - return isNull ? false : spanner.getLong(spannerIndex) != 0L; + return !isNull && spanner.getLong(spannerIndex) != 0L; case NUMERIC: - return isNull ? false : !spanner.getBigDecimal(spannerIndex).equals(BigDecimal.ZERO); + return !isNull && !spanner.getBigDecimal(spannerIndex).equals(BigDecimal.ZERO); case STRING: - return isNull ? false : Boolean.valueOf(spanner.getString(spannerIndex)); + return !isNull && Boolean.parseBoolean(spanner.getString(spannerIndex)); case BYTES: case JSON: case DATE: @@ -591,8 +591,7 @@ private Object getObject(Type type, int columnIndex) throws SQLException { if (type == Type.json()) return getString(columnIndex); if (type == Type.timestamp()) return getTimestamp(columnIndex); if (type.getCode() == Code.ARRAY) return getArray(columnIndex); - throw JdbcSqlExceptionFactory.of( - "Unknown type: " + type.toString(), com.google.rpc.Code.INVALID_ARGUMENT); + throw JdbcSqlExceptionFactory.of("Unknown type: " + type, com.google.rpc.Code.INVALID_ARGUMENT); } @Override @@ -737,7 +736,7 @@ public Array getArray(int columnIndex) throws SQLException { "Column with index " + columnIndex + " does not contain an array", com.google.rpc.Code.INVALID_ARGUMENT); JdbcDataType dataType = JdbcDataType.getType(type.getArrayElementType().getCode()); - List elements = dataType.getArrayElements(spanner, columnIndex - 1); + List elements = dataType.getArrayElements(spanner, columnIndex - 1); return JdbcArray.createArray(dataType, elements); } @@ -864,7 +863,7 @@ public int getHoldability() throws SQLException { } @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return closed; } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaData.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaData.java index a598b109e..69162e807 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaData.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaData.java @@ -46,44 +46,44 @@ public boolean isClosed() { } @Override - public int getColumnCount() throws SQLException { + public int getColumnCount() { return spannerResultSet.getColumnCount(); } @Override - public boolean isAutoIncrement(int column) throws SQLException { + public boolean isAutoIncrement(int column) { return false; } @Override - public boolean isCaseSensitive(int column) throws SQLException { + public boolean isCaseSensitive(int column) { int type = getColumnType(column); return type == Types.NVARCHAR || type == Types.BINARY; } @Override - public boolean isSearchable(int column) throws SQLException { + public boolean isSearchable(int column) { return true; } @Override - public boolean isCurrency(int column) throws SQLException { + public boolean isCurrency(int column) { return false; } @Override - public int isNullable(int column) throws SQLException { + public int isNullable(int column) { return columnNullableUnknown; } @Override - public boolean isSigned(int column) throws SQLException { + public boolean isSigned(int column) { int type = getColumnType(column); return type == Types.DOUBLE || type == Types.BIGINT || type == Types.NUMERIC; } @Override - public int getColumnDisplaySize(int column) throws SQLException { + public int getColumnDisplaySize(int column) { int colType = getColumnType(column); switch (colType) { case Types.ARRAY: @@ -112,12 +112,12 @@ public int getColumnDisplaySize(int column) throws SQLException { } @Override - public String getColumnLabel(int column) throws SQLException { + public String getColumnLabel(int column) { return spannerResultSet.getType().getStructFields().get(column - 1).getName(); } @Override - public String getColumnName(int column) throws SQLException { + public String getColumnName(int column) { return spannerResultSet.getType().getStructFields().get(column - 1).getName(); } @@ -127,7 +127,7 @@ public String getSchemaName(int column) throws SQLException { } @Override - public int getPrecision(int column) throws SQLException { + public int getPrecision(int column) { int colType = getColumnType(column); switch (colType) { case Types.BOOLEAN: @@ -152,14 +152,14 @@ public int getPrecision(int column) throws SQLException { } @Override - public int getScale(int column) throws SQLException { + public int getScale(int column) { int colType = getColumnType(column); if (colType == Types.DOUBLE || colType == Types.NUMERIC) return 15; return 0; } @Override - public String getTableName(int column) throws SQLException { + public String getTableName(int column) { return ""; } @@ -169,46 +169,42 @@ public String getCatalogName(int column) throws SQLException { } @Override - public int getColumnType(int column) throws SQLException { + public int getColumnType(int column) { return extractColumnType(spannerResultSet.getColumnType(column - 1)); } @Override - public String getColumnTypeName(int column) throws SQLException { + public String getColumnTypeName(int column) { return spannerResultSet.getColumnType(column - 1).getCode().name(); } @Override - public boolean isReadOnly(int column) throws SQLException { + public boolean isReadOnly(int column) { return false; } @Override - public boolean isWritable(int column) throws SQLException { + public boolean isWritable(int column) { return !isReadOnly(column); } @Override - public boolean isDefinitelyWritable(int column) throws SQLException { + public boolean isDefinitelyWritable(int column) { return false; } @Override - public String getColumnClassName(int column) throws SQLException { + public String getColumnClassName(int column) { return getClassName(spannerResultSet.getColumnType(column - 1)); } @Override public String toString() { StringBuilder res = new StringBuilder(); - try { - for (int col = 1; col <= getColumnCount(); col++) { - res.append("Col ").append(col).append(": "); - res.append(getColumnName(col)).append(" ").append(getColumnTypeName(col)); - res.append("\n"); - } - } catch (SQLException e) { - return "An error occurred while generating string: " + e.getMessage(); + for (int col = 1; col <= getColumnCount(); col++) { + res.append("Col ").append(col).append(": "); + res.append(getColumnName(col)).append(" ").append(getColumnTypeName(col)); + res.append("\n"); } return res.toString(); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcSqlExceptionFactory.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcSqlExceptionFactory.java index 33d3bb422..6ddc7d683 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcSqlExceptionFactory.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcSqlExceptionFactory.java @@ -22,7 +22,6 @@ import com.google.cloud.spanner.SpannerException; import com.google.rpc.Code; import java.sql.BatchUpdateException; -import java.sql.ClientInfoStatus; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; @@ -89,7 +88,7 @@ public static class JdbcSqlClientInfoException extends SQLClientInfoException private final Code code; private JdbcSqlClientInfoException(String message, Code code) { - super(message, Collections.emptyMap()); + super(message, Collections.emptyMap()); this.code = code; } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java index 5a8f69166..3674ae02b 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java @@ -21,7 +21,6 @@ import com.google.cloud.spanner.SpannerBatchUpdateException; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.Statement; -import com.google.cloud.spanner.Struct; import com.google.cloud.spanner.Type; import com.google.cloud.spanner.Type.StructField; import com.google.cloud.spanner.connection.StatementParser; @@ -41,7 +40,7 @@ class JdbcStatement extends AbstractJdbcStatement { enum BatchType { NONE, DML, - DDL; + DDL } private ResultSet currentResultSet; @@ -332,7 +331,7 @@ int[] convertUpdateCounts(long[] updateCounts) throws SQLException { } @VisibleForTesting - void convertUpdateCountsToSuccessNoInfo(long[] updateCounts, long[] res) throws SQLException { + void convertUpdateCountsToSuccessNoInfo(long[] updateCounts, long[] res) { Preconditions.checkNotNull(updateCounts); Preconditions.checkNotNull(res); Preconditions.checkArgument(res.length >= updateCounts.length); @@ -355,7 +354,7 @@ public ResultSet getGeneratedKeys() throws SQLException { Type.struct( StructField.of("COLUMN_NAME", Type.string()), StructField.of("VALUE", Type.int64())), - Collections.emptyList()); + Collections.emptyList()); return JdbcResultSet.of(rs); } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/JdbcTypeConverter.java b/src/main/java/com/google/cloud/spanner/jdbc/JdbcTypeConverter.java index 4b2e4f0f7..56043b041 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcTypeConverter.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcTypeConverter.java @@ -25,6 +25,7 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.SQLException; import java.sql.Time; @@ -41,7 +42,7 @@ /** Convenience class for converting values between Java, JDBC and Cloud Spanner. */ class JdbcTypeConverter { private static final DateTimeFormatter TIMESTAMP_FORMAT = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - private static final Charset UTF8 = Charset.forName("UTF8"); + private static final Charset UTF8 = StandardCharsets.UTF_8; /** * Converts the given value from the Google {@link Type} to the Java {@link Class} type. The input @@ -86,10 +87,9 @@ static Object convert(Object value, Type type, Class targetType) throws SQLEx } if (targetType.equals(Boolean.class)) { if (type.getCode() == Code.BOOL) return value; - if (type.getCode() == Code.INT64) return Boolean.valueOf((Long) value != 0); - if (type.getCode() == Code.FLOAT64) return Boolean.valueOf((Double) value != 0d); - if (type.getCode() == Code.NUMERIC) - return Boolean.valueOf(!((BigDecimal) value).equals(BigDecimal.ZERO)); + if (type.getCode() == Code.INT64) return (Long) value != 0; + if (type.getCode() == Code.FLOAT64) return (Double) value != 0d; + if (type.getCode() == Code.NUMERIC) return !value.equals(BigDecimal.ZERO); } if (targetType.equals(BigDecimal.class)) { if (type.getCode() == Code.BOOL) return (Boolean) value ? BigDecimal.ONE : BigDecimal.ZERO; @@ -223,40 +223,31 @@ private static void checkValidTypeAndValueForConvert(Type type, Object value) throws SQLException { if (value == null) return; JdbcPreconditions.checkArgument( - (type.getCode() == Code.ARRAY && Array.class.isAssignableFrom(value.getClass())) - || type.getCode() != Code.ARRAY, + type.getCode() != Code.ARRAY || Array.class.isAssignableFrom(value.getClass()), "input type is array, but input value is not an instance of java.sql.Array"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.BOOL && value.getClass().equals(Boolean.class)) - || type.getCode() != Code.BOOL, + type.getCode() != Code.BOOL || value.getClass().equals(Boolean.class), "input type is bool, but input value is not an instance of Boolean"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.BYTES && value.getClass().equals(byte[].class)) - || type.getCode() != Code.BYTES, + type.getCode() != Code.BYTES || value.getClass().equals(byte[].class), "input type is bytes, but input value is not an instance of byte[]"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.DATE && value.getClass().equals(java.sql.Date.class)) - || type.getCode() != Code.DATE, + type.getCode() != Code.DATE || value.getClass().equals(java.sql.Date.class), "input type is date, but input value is not an instance of java.sql.Date"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.FLOAT64 && value.getClass().equals(Double.class)) - || type.getCode() != Code.FLOAT64, + type.getCode() != Code.FLOAT64 || value.getClass().equals(Double.class), "input type is float64, but input value is not an instance of Double"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.INT64 && value.getClass().equals(Long.class)) - || type.getCode() != Code.INT64, + type.getCode() != Code.INT64 || value.getClass().equals(Long.class), "input type is int64, but input value is not an instance of Long"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.STRING && value.getClass().equals(String.class)) - || type.getCode() != Code.STRING, + type.getCode() != Code.STRING || value.getClass().equals(String.class), "input type is string, but input value is not an instance of String"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.TIMESTAMP && value.getClass().equals(java.sql.Timestamp.class)) - || type.getCode() != Code.TIMESTAMP, + type.getCode() != Code.TIMESTAMP || value.getClass().equals(java.sql.Timestamp.class), "input type is timestamp, but input value is not an instance of java.sql.Timestamp"); JdbcPreconditions.checkArgument( - (type.getCode() == Code.NUMERIC && value.getClass().equals(BigDecimal.class)) - || type.getCode() != Code.NUMERIC, + type.getCode() != Code.NUMERIC || value.getClass().equals(BigDecimal.class), "input type is numeric, but input value is not an instance of BigDecimal"); } @@ -280,7 +271,9 @@ static Date toGoogleDate(java.sql.Timestamp date) { static List toGoogleDates(java.sql.Date[] dates) { List res = new ArrayList<>(dates.length); - for (int index = 0; index < dates.length; index++) res.add(toGoogleDate(dates[index])); + for (java.sql.Date date : dates) { + res.add(toGoogleDate(date)); + } return res; } @@ -290,6 +283,7 @@ static java.sql.Date toSqlDate(Date date) { static java.sql.Date toSqlDate(Date date, Calendar cal) { if (date != null) { + //noinspection MagicConstant cal.set(date.getYear(), date.getMonth() - 1, date.getDayOfMonth(), 0, 0, 0); cal.clear(Calendar.MILLISECOND); return new java.sql.Date(cal.getTimeInMillis()); @@ -329,7 +323,7 @@ static java.sql.Timestamp setTimestampInCalendar(java.sql.Timestamp sqlTs, Calen private enum GetOrSetTimestampInCalendar { GET, - SET; + SET } private static java.sql.Timestamp getOrSetTimestampInCalendar( @@ -363,20 +357,10 @@ static List toSqlTimestamps(List timestamps) { return res; } - static Timestamp toGoogleTimestamp(java.sql.Date ts) { - if (ts != null) { - long milliseconds = ts.getTime(); - long seconds = milliseconds / 1000l; - long nanos = (milliseconds - (seconds * 1000)) * 1000000; - return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, (int) nanos); - } - return null; - } - - static Timestamp toGoogleTimestamp(java.sql.Time ts) { + static Timestamp toGoogleTimestamp(java.util.Date ts) { if (ts != null) { long milliseconds = ts.getTime(); - long seconds = milliseconds / 1000l; + long seconds = milliseconds / 1000L; long nanos = (milliseconds - (seconds * 1000)) * 1000000; return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, (int) nanos); } @@ -386,7 +370,7 @@ static Timestamp toGoogleTimestamp(java.sql.Time ts) { static Timestamp toGoogleTimestamp(java.sql.Timestamp ts) { if (ts != null) { long milliseconds = ts.getTime(); - long seconds = milliseconds / 1000l; + long seconds = milliseconds / 1000L; int nanos = ts.getNanos(); return com.google.cloud.Timestamp.ofTimeSecondsAndNanos(seconds, nanos); } @@ -395,8 +379,8 @@ static Timestamp toGoogleTimestamp(java.sql.Timestamp ts) { static List toGoogleTimestamps(java.sql.Timestamp[] timestamps) { List res = new ArrayList<>(timestamps.length); - for (int index = 0; index < timestamps.length; index++) { - res.add(toGoogleTimestamp(timestamps[index])); + for (java.sql.Timestamp timestamp : timestamps) { + res.add(toGoogleTimestamp(timestamp)); } return res; } @@ -429,7 +413,7 @@ static Time toSqlTime(Timestamp ts, Calendar cal) { static java.sql.Time parseSqlTime(String val, Calendar cal) { if (val != null) { Time time = Time.valueOf(val); - cal.set(1970, 0, 1, time.getHours(), time.getMinutes(), time.getSeconds()); + cal.set(1970, Calendar.JANUARY, 1, time.getHours(), time.getMinutes(), time.getSeconds()); cal.clear(Calendar.MILLISECOND); return new java.sql.Time(cal.getTimeInMillis()); } @@ -438,8 +422,8 @@ static java.sql.Time parseSqlTime(String val, Calendar cal) { static List toGoogleBytes(byte[][] bytes) { List res = new ArrayList<>(bytes.length); - for (int index = 0; index < bytes.length; index++) { - res.add(bytes[index] == null ? null : ByteArray.copyFrom(bytes[index])); + for (byte[] aByte : bytes) { + res.add(aByte == null ? null : ByteArray.copyFrom(aByte)); } return res; } diff --git a/src/main/java/com/google/cloud/spanner/jdbc/TransactionRetryListener.java b/src/main/java/com/google/cloud/spanner/jdbc/TransactionRetryListener.java index 6d85dc7c0..d837e7364 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/TransactionRetryListener.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/TransactionRetryListener.java @@ -28,14 +28,14 @@ public interface TransactionRetryListener { /** Use {@link com.google.cloud.spanner.connection.TransactionRetryListener.RetryResult} */ @InternalApi @Deprecated - public enum RetryResult { + enum RetryResult { /** The retry executed successfully and the transaction will continue. */ RETRY_SUCCESSFUL, /** The retry was aborted by Spanner and another retry attempt will be started. */ RETRY_ABORTED_AND_RESTARTING, /** - * The retry was aborted by the {@link Connection} because of a concurrent modification. The - * transaction cannot continue and will throw an {@link + * The retry was aborted by the {@link java.sql.Connection} because of a concurrent + * modification. The transaction cannot continue and will throw an {@link * AbortedDueToConcurrentModificationException}. */ RETRY_ABORTED_DUE_TO_CONCURRENT_MODIFICATION, @@ -48,7 +48,7 @@ public enum RetryResult { * An unexpected error occurred during transaction retry, the transaction cannot continue and * will throw an exception. */ - RETRY_ERROR; + RETRY_ERROR } /** diff --git a/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSetTest.java b/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSetTest.java index 53fd0e6d2..e17f2b49e 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSetTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcResultSetTest.java @@ -62,7 +62,7 @@ public void setup() { } @Test - public void testFetchSize() throws SQLException { + public void testFetchSize() { assertEquals(0, rs.getFetchSize()); for (int size : new int[] {0, 1, 10, 100}) { rs.setFetchSize(size); @@ -71,24 +71,24 @@ public void testFetchSize() throws SQLException { } @Test - public void testGetType() throws SQLException { + public void testGetType() { assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType()); } @Test - public void testGetConcurrency() throws SQLException { + public void testGetConcurrency() { assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency()); } @Test - public void testRowInsertedUpdatedDeleted() throws SQLException { + public void testRowInsertedUpdatedDeleted() { assertFalse(rs.rowInserted()); assertFalse(rs.rowUpdated()); assertFalse(rs.rowDeleted()); } @Test - public void testGetFetchDirection() throws SQLException { + public void testGetFetchDirection() { assertEquals(ResultSet.FETCH_FORWARD, rs.getFetchDirection()); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapperTest.java b/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapperTest.java index 593466f75..3569e67c5 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapperTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/AbstractJdbcWrapperTest.java @@ -35,7 +35,7 @@ public class AbstractJdbcWrapperTest { /** Create a concrete sub class to use for testing. */ private static class TestWrapper extends AbstractJdbcWrapper { @Override - public boolean isClosed() throws SQLException { + public boolean isClosed() { return false; } } @@ -44,7 +44,7 @@ public boolean isClosed() throws SQLException { private static class SubTestWrapper extends TestWrapper {} @Test - public void testIsWrapperFor() throws SQLException { + public void testIsWrapperFor() { TestWrapper subject = new TestWrapper(); assertThat(subject.isWrapperFor(TestWrapper.class)).isTrue(); assertThat(subject.isWrapperFor(SubTestWrapper.class)).isFalse(); @@ -59,7 +59,7 @@ public void testIsWrapperFor() throws SQLException { } @Test - public void testUnwrap() throws SQLException { + public void testUnwrap() { TestWrapper subject = new TestWrapper(); assertThat(unwrapSucceeds(subject, TestWrapper.class)).isTrue(); assertThat(unwrapSucceeds(subject, SubTestWrapper.class)).isFalse(); @@ -67,12 +67,7 @@ public void testUnwrap() throws SQLException { assertThat(unwrapSucceeds(subject, getClass())).isFalse(); } - private static interface CheckedCastChecker { - boolean cast(V val); - } - - private static final class CheckedCastToByteChecker implements CheckedCastChecker { - @Override + private static final class CheckedCastToByteChecker { public boolean cast(Long val) { try { AbstractJdbcWrapper.checkedCastToByte(val); @@ -84,21 +79,20 @@ public boolean cast(Long val) { } @Test - public void testCheckedCastToByte() throws SQLException { + public void testCheckedCastToByte() { CheckedCastToByteChecker checker = new CheckedCastToByteChecker(); assertThat(checker.cast(0L)).isTrue(); assertThat(checker.cast(1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Byte.MAX_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Byte.MAX_VALUE) + 1L)).isFalse(); + assertThat(checker.cast((long) Byte.MAX_VALUE)).isTrue(); + assertThat(checker.cast((long) Byte.MAX_VALUE + 1L)).isFalse(); assertThat(checker.cast(Long.MAX_VALUE)).isFalse(); assertThat(checker.cast(-1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Byte.MIN_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Byte.MIN_VALUE) - 1L)).isFalse(); + assertThat(checker.cast((long) Byte.MIN_VALUE)).isTrue(); + assertThat(checker.cast((long) Byte.MIN_VALUE - 1L)).isFalse(); assertThat(checker.cast(Long.MIN_VALUE)).isFalse(); } - private static final class CheckedCastToShortChecker implements CheckedCastChecker { - @Override + private static final class CheckedCastToShortChecker { public boolean cast(Long val) { try { AbstractJdbcWrapper.checkedCastToShort(val); @@ -110,21 +104,20 @@ public boolean cast(Long val) { } @Test - public void testCheckedCastToShort() throws SQLException { + public void testCheckedCastToShort() { CheckedCastToShortChecker checker = new CheckedCastToShortChecker(); assertThat(checker.cast(0L)).isTrue(); assertThat(checker.cast(1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Short.MAX_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Short.MAX_VALUE) + 1L)).isFalse(); + assertThat(checker.cast((long) Short.MAX_VALUE)).isTrue(); + assertThat(checker.cast((long) Short.MAX_VALUE + 1L)).isFalse(); assertThat(checker.cast(Long.MAX_VALUE)).isFalse(); assertThat(checker.cast(-1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Short.MIN_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Short.MIN_VALUE) - 1L)).isFalse(); + assertThat(checker.cast((long) Short.MIN_VALUE)).isTrue(); + assertThat(checker.cast((long) Short.MIN_VALUE - 1L)).isFalse(); assertThat(checker.cast(Long.MIN_VALUE)).isFalse(); } - private static final class CheckedCastToIntChecker implements CheckedCastChecker { - @Override + private static final class CheckedCastToIntChecker { public boolean cast(Long val) { try { AbstractJdbcWrapper.checkedCastToInt(val); @@ -136,21 +129,20 @@ public boolean cast(Long val) { } @Test - public void testCheckedCastToInt() throws SQLException { + public void testCheckedCastToInt() { CheckedCastToIntChecker checker = new CheckedCastToIntChecker(); assertThat(checker.cast(0L)).isTrue(); assertThat(checker.cast(1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Integer.MAX_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Integer.MAX_VALUE) + 1L)).isFalse(); + assertThat(checker.cast((long) Integer.MAX_VALUE)).isTrue(); + assertThat(checker.cast((long) Integer.MAX_VALUE + 1L)).isFalse(); assertThat(checker.cast(Long.MAX_VALUE)).isFalse(); assertThat(checker.cast(-1L)).isTrue(); - assertThat(checker.cast(Long.valueOf(Integer.MIN_VALUE))).isTrue(); - assertThat(checker.cast(Long.valueOf(Integer.MIN_VALUE) - 1L)).isFalse(); + assertThat(checker.cast((long) Integer.MIN_VALUE)).isTrue(); + assertThat(checker.cast((long) Integer.MIN_VALUE - 1L)).isFalse(); assertThat(checker.cast(Long.MIN_VALUE)).isFalse(); } - private static final class CheckedCastToFloatChecker implements CheckedCastChecker { - @Override + private static final class CheckedCastToFloatChecker { public boolean cast(Double val) { try { AbstractJdbcWrapper.checkedCastToFloat(val); @@ -162,16 +154,16 @@ public boolean cast(Double val) { } @Test - public void testCheckedCastToFloat() throws SQLException { + public void testCheckedCastToFloat() { CheckedCastToFloatChecker checker = new CheckedCastToFloatChecker(); assertThat(checker.cast(0D)).isTrue(); assertThat(checker.cast(1D)).isTrue(); - assertThat(checker.cast(Double.valueOf(Float.MAX_VALUE))).isTrue(); - assertThat(checker.cast(Double.valueOf(Float.MAX_VALUE) * 2.0D)).isFalse(); + assertThat(checker.cast((double) Float.MAX_VALUE)).isTrue(); + assertThat(checker.cast((double) Float.MAX_VALUE * 2.0D)).isFalse(); assertThat(checker.cast(Double.MAX_VALUE)).isFalse(); assertThat(checker.cast(-1D)).isTrue(); - assertThat(checker.cast(Double.valueOf(Float.MIN_VALUE))).isTrue(); - assertThat(checker.cast(Double.valueOf(-Float.MAX_VALUE * 2))).isFalse(); + assertThat(checker.cast((double) Float.MIN_VALUE)).isTrue(); + assertThat(checker.cast(-Float.MAX_VALUE * 2d)).isFalse(); assertThat(checker.cast(-Double.MAX_VALUE)).isFalse(); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcAbortedTransactionTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcAbortedTransactionTest.java index 9c5628399..b7253df82 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcAbortedTransactionTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcAbortedTransactionTest.java @@ -99,13 +99,9 @@ public void retryFinished( private static final int UPDATE_COUNT = 1; private static MockSpannerServiceImpl mockSpanner; - private static MockInstanceAdminImpl mockInstanceAdmin; - private static MockDatabaseAdminImpl mockDatabaseAdmin; private static Server server; - private static InetSocketAddress address; - @Parameter(0) - public boolean retryAbortsInternally; + @Parameter public boolean retryAbortsInternally; @Parameters(name = "retryAbortsInternally = {0}") public static Collection data() { @@ -121,9 +117,9 @@ public static void startStaticServer() throws IOException { mockSpanner.setAbortProbability(0.0D); // We don't want any unpredictable aborted transactions. mockSpanner.putStatementResult(StatementResult.query(SELECT1, SELECT1_RESULTSET)); mockSpanner.putStatementResult(StatementResult.update(UPDATE_STATEMENT, UPDATE_COUNT)); - mockInstanceAdmin = new MockInstanceAdminImpl(); - mockDatabaseAdmin = new MockDatabaseAdminImpl(); - address = new InetSocketAddress("localhost", 0); + MockInstanceAdminImpl mockInstanceAdmin = new MockInstanceAdminImpl(); + MockDatabaseAdminImpl mockDatabaseAdmin = new MockDatabaseAdminImpl(); + InetSocketAddress address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address) .addService(mockSpanner) @@ -267,6 +263,7 @@ public void testTransactionalUpdateWithConcurrentModificationsAborted() throws S mockSpanner.putStatementResult( StatementResult.query(SELECT_RANDOM, new RandomResultSetGenerator(25).generate())); try (ResultSet rs = connection.createStatement().executeQuery(SELECT_RANDOM.getSql())) { + //noinspection StatementWithEmptyBody while (rs.next()) {} } // Set a new random answer that will be returned during the retry. diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcArrayTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcArrayTest.java index 74b8354eb..5888b3b40 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcArrayTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcArrayTest.java @@ -97,7 +97,7 @@ public void testCreateArrayTypeName() throws SQLException { array = JdbcArray.createArray("FLOAT64", new Double[] {1.1D, 2.2D, Math.PI}); assertThat(array.getBaseType()).isEqualTo(Types.DOUBLE); - assertThat(((Double[]) array.getArray(1, 3))[2]).isEqualTo(Double.valueOf(Math.PI)); + assertThat(((Double[]) array.getArray(1, 3))[2]).isEqualTo(Math.PI); try (ResultSet rs = array.getResultSet()) { assertThat(rs.next()).isTrue(); assertThat(rs.getDouble(2)).isEqualTo(1.1D); @@ -110,7 +110,7 @@ public void testCreateArrayTypeName() throws SQLException { array = JdbcArray.createArray("INT64", new Long[] {1L, 2L, 3L}); assertThat(array.getBaseType()).isEqualTo(Types.BIGINT); - assertThat(((Long[]) array.getArray(1, 1))[0]).isEqualTo(Long.valueOf(1L)); + assertThat(((Long[]) array.getArray(1, 1))[0]).isEqualTo(1L); try (ResultSet rs = array.getResultSet()) { assertThat(rs.next()).isTrue(); assertThat(rs.getLong(2)).isEqualTo(1L); @@ -210,7 +210,7 @@ public void testCreateArrayOfStruct() throws SQLException { .asList() .containsExactly(Struct.newBuilder().set("f1").to("v1").set("f2").to(1L).build(), null) .inOrder(); - assertThrows(SQLFeatureNotSupportedException.class, () -> array.getResultSet()); + assertThrows(SQLFeatureNotSupportedException.class, array::getResultSet); } @Test diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcClobTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcClobTest.java index 87011ab41..b19522918 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcClobTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcClobTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; import com.google.rpc.Code; import java.io.IOException; @@ -113,20 +114,20 @@ public void testGetCharacterStream() throws SQLException, IOException { clob.setString(1L, "test"); char[] cbuf = new char[4]; try (Reader reader = clob.getCharacterStream()) { - reader.read(cbuf, 0, 4); + assertEquals(4, reader.read(cbuf, 0, 4)); } assertThat(cbuf, is(equalTo(new char[] {'t', 'e', 's', 't'}))); try (Reader reader = clob.getCharacterStream()) { - reader.read(cbuf, 0, 2); - reader.read(cbuf, 2, 2); + assertEquals(2, reader.read(cbuf, 0, 2)); + assertEquals(2, reader.read(cbuf, 2, 2)); } assertThat(cbuf, is(equalTo(new char[] {'t', 'e', 's', 't'}))); try (Reader reader = clob.getCharacterStream()) { - reader.read(cbuf, 0, 2); + assertEquals(2, reader.read(cbuf, 0, 2)); // changing the value of the clob will not change a character stream that has already been // opened clob.setString(1L, "foobar"); - reader.read(cbuf, 2, 2); + assertEquals(2, reader.read(cbuf, 2, 2)); } assertThat(cbuf, is(equalTo(new char[] {'t', 'e', 's', 't'}))); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionGeneratedSqlScriptTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionGeneratedSqlScriptTest.java index b818c63fe..2ec3f1b08 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionGeneratedSqlScriptTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionGeneratedSqlScriptTest.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.when; import com.google.cloud.spanner.SpannerExceptionFactory; +import com.google.cloud.spanner.connection.AbstractConnectionImplTest; import com.google.cloud.spanner.connection.AbstractSqlScriptVerifier.GenericConnection; import com.google.cloud.spanner.connection.AbstractSqlScriptVerifier.GenericConnectionProvider; import com.google.cloud.spanner.connection.ConnectionImplTest; @@ -66,6 +67,6 @@ public GenericConnection getConnection() { public void testGeneratedScript() throws Exception { JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new TestConnectionProvider()); verifier.verifyStatementsInFile( - "ConnectionImplGeneratedSqlScriptTest.sql", SqlScriptVerifier.class); + "ConnectionImplGeneratedSqlScriptTest.sql", SqlScriptVerifier.class, false); } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java index ab503d21f..3205cbb5e 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java @@ -47,7 +47,6 @@ import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.sql.Savepoint; -import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.Properties; @@ -62,7 +61,7 @@ public class JdbcConnectionTest { private static final com.google.cloud.spanner.ResultSet SELECT1_RESULTSET = ResultSets.forRows( Type.struct(StructField.of("", Type.int64())), - Arrays.asList(Struct.newBuilder().set("").to(1L).build())); + Collections.singletonList(Struct.newBuilder().set("").to(1L).build())); private JdbcConnection createConnection(ConnectionOptions options) throws SQLException { com.google.cloud.spanner.connection.Connection spannerConnection = @@ -90,7 +89,7 @@ public void testAutoCommit() throws SQLException { } @Test - public void testReadOnly() throws SQLException { + public void testReadOnly() { ConnectionOptions options = mock(ConnectionOptions.class); when(options.isAutocommit()).thenReturn(true); when(options.isReadOnly()).thenReturn(true); @@ -150,11 +149,6 @@ public void testRollback() throws SQLException { } } - @Test - public void testClosedAbstractJdbcConnection() - throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, - IllegalArgumentException {} - @Test public void testClosedJdbcConnection() throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, @@ -729,7 +723,7 @@ public void testIsReturnCommitStats() throws SQLException { } @Test - public void testIsReturnCommitStats_throwsSqlException() throws SQLException { + public void testIsReturnCommitStats_throwsSqlException() { ConnectionOptions options = mock(ConnectionOptions.class); com.google.cloud.spanner.connection.Connection spannerConnection = mock(com.google.cloud.spanner.connection.Connection.class); @@ -751,7 +745,7 @@ public void testIsReturnCommitStats_throwsSqlException() throws SQLException { } @Test - public void testSetReturnCommitStats_throwsSqlException() throws SQLException { + public void testSetReturnCommitStats_throwsSqlException() { ConnectionOptions options = mock(ConnectionOptions.class); com.google.cloud.spanner.connection.Connection spannerConnection = mock(com.google.cloud.spanner.connection.Connection.class); @@ -774,7 +768,7 @@ public void testSetReturnCommitStats_throwsSqlException() throws SQLException { } @Test - public void testGetCommitResponse_throwsSqlException() throws SQLException { + public void testGetCommitResponse_throwsSqlException() { ConnectionOptions options = mock(ConnectionOptions.class); com.google.cloud.spanner.connection.Connection spannerConnection = mock(com.google.cloud.spanner.connection.Connection.class); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionUrlTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionUrlTest.java index 64ebe9556..c0f9473bf 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionUrlTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionUrlTest.java @@ -17,14 +17,12 @@ package com.google.cloud.spanner.jdbc; import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertTrue; import com.google.cloud.spanner.connection.AbstractMockServerTest; -import com.google.common.base.Predicate; -import com.google.protobuf.AbstractMessage; import com.google.spanner.v1.BatchCreateSessionsRequest; import java.sql.Connection; import java.sql.SQLException; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -54,13 +52,9 @@ protected String getBaseUrl() { public void testMinSessions() throws InterruptedException, TimeoutException, SQLException { try (Connection connection = createJdbcConnection()) { mockSpanner.waitForRequestsToContain( - new Predicate() { - @Override - public boolean apply(AbstractMessage input) { - return input instanceof BatchCreateSessionsRequest - && ((BatchCreateSessionsRequest) input).getSessionCount() == 1; - } - }, + input -> + input instanceof BatchCreateSessionsRequest + && ((BatchCreateSessionsRequest) input).getSessionCount() == 1, 5000L); } } @@ -88,25 +82,19 @@ public void testMaxSessions() final CountDownLatch latch = new CountDownLatch(1); Future fut1 = executor1.submit( - new Callable() { - @Override - public Void call() throws SQLException, InterruptedException { - latch.await(5L, TimeUnit.SECONDS); - connection1.createStatement().executeUpdate(INSERT_STATEMENT.getSql()); - connection1.commit(); - return null; - } + () -> { + assertTrue(latch.await(5L, TimeUnit.SECONDS)); + connection1.createStatement().executeUpdate(INSERT_STATEMENT.getSql()); + connection1.commit(); + return null; }); Future fut2 = executor2.submit( - new Callable() { - @Override - public Void call() throws SQLException { - latch.countDown(); - connection2.createStatement().executeUpdate(INSERT_STATEMENT.getSql()); - connection2.commit(); - return null; - } + () -> { + latch.countDown(); + connection2.createStatement().executeUpdate(INSERT_STATEMENT.getSql()); + connection2.commit(); + return null; }); // Wait until both finishes. fut1.get(5L, TimeUnit.SECONDS); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java index e7e634a2e..0d977c995 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java @@ -36,6 +36,7 @@ import java.sql.RowIdLifetime; import java.sql.SQLException; import java.sql.Types; +import java.util.Objects; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -105,7 +106,7 @@ public void testTrivialMethods() throws SQLException { assertThat(meta.getMaxCursorNameLength(), is(equalTo(0))); assertThat(meta.getMaxIndexLength(), is(equalTo(8000))); assertThat(meta.getMaxProcedureNameLength(), is(equalTo(0))); - assertThat(meta.getMaxRowSize(), is(equalTo(1024 * 10000000))); + assertThat(meta.getMaxRowSize(), is(equalTo(0))); assertThat(meta.getMaxSchemaNameLength(), is(equalTo(0))); assertThat(meta.getMaxStatementLength(), is(equalTo(1000000))); assertThat(meta.getMaxStatements(), is(equalTo(0))); @@ -344,6 +345,7 @@ public void testGetClientInfoProperties() throws SQLException { } } + @Test public void testGetColumnPrivileges() throws SQLException { JdbcConnection connection = mock(JdbcConnection.class); DatabaseMetaData meta = new JdbcDatabaseMetaData(connection); @@ -511,7 +513,8 @@ public void testGetVersionColumns() throws SQLException { public void testGetUserName() throws SQLException, IOException { GoogleCredentials credentials = GoogleCredentials.fromStream( - ConnectionOptionsTest.class.getResource("test-key.json").openStream()); + Objects.requireNonNull(ConnectionOptionsTest.class.getResource("test-key.json")) + .openStream()); JdbcConnection connection = mock(JdbcConnection.class); ConnectionOptions options = mock(ConnectionOptions.class); when(options.getCredentials()).thenReturn(credentials); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataWithMockedServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataWithMockedServerTest.java index 0b8cd64c3..af7b8942b 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataWithMockedServerTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataWithMockedServerTest.java @@ -68,13 +68,12 @@ public class JdbcDatabaseMetaDataWithMockedServerTest { private static MockSpannerServiceImpl mockSpanner; private static Server server; - private static InetSocketAddress address; @BeforeClass public static void startStaticServer() throws IOException { mockSpanner = new MockSpannerServiceImpl(); mockSpanner.setAbortProbability(0.0D); // We don't want any unpredictable aborted transactions. - address = new InetSocketAddress("localhost", 0); + InetSocketAddress address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address).addService(mockSpanner).build().start(); } @@ -130,6 +129,7 @@ public void getTablesInDdlBatch() throws SQLException { // Executing an internal metadata query should be allowed during a DDL batch. // This query will be executed on a single use read-only transaction. try (ResultSet tables = connection.getMetaData().getTables("CAT", "SCH", "TAB", null)) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); @@ -159,6 +159,7 @@ public void getColumnsInDdlBatch() throws SQLException { try (java.sql.Connection connection = createConnection()) { connection.createStatement().execute("START BATCH DDL"); try (ResultSet tables = connection.getMetaData().getColumns("CAT", "SCH", "TAB", null)) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); @@ -192,12 +193,15 @@ public void getKeysInDdlBatch() throws SQLException { try (java.sql.Connection connection = createConnection()) { connection.createStatement().execute("START BATCH DDL"); try (ResultSet tables = connection.getMetaData().getPrimaryKeys("CAT", "SCH", "TAB")) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } try (ResultSet tables = connection.getMetaData().getImportedKeys("CAT", "SCH", "TAB")) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } try (ResultSet tables = connection.getMetaData().getExportedKeys("CAT", "SCH", "TAB")) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); @@ -232,6 +236,7 @@ public void getCrossReferencesInDdlBatch() throws SQLException { connection.createStatement().execute("START BATCH DDL"); try (ResultSet tables = connection.getMetaData().getCrossReference("CAT", "SCH", "TAB", "CAT2", "SCH2", "TAB2")) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); @@ -264,6 +269,7 @@ public void getIndexInfoInDdlBatch() throws SQLException { connection.createStatement().execute("START BATCH DDL"); try (ResultSet tables = connection.getMetaData().getIndexInfo("CAT", "SCH", "TAB", true, false)) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); @@ -289,9 +295,11 @@ public void getSchemasInDdlBatch() throws SQLException { try (java.sql.Connection connection = createConnection()) { connection.createStatement().execute("START BATCH DDL"); try (ResultSet tables = connection.getMetaData().getSchemas()) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } try (ResultSet tables = connection.getMetaData().getSchemas(null, null)) { + //noinspection StatementWithEmptyBody while (tables.next()) {} } connection.createStatement().execute("CREATE TABLE FOO"); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDriverTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDriverTest.java index c6709b348..dd988ca71 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDriverTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDriverTest.java @@ -24,7 +24,6 @@ import com.google.cloud.spanner.connection.ConnectionOptions; import com.google.cloud.spanner.connection.ConnectionOptions.ConnectionProperty; import com.google.cloud.spanner.connection.SpannerPool; -import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableList; import com.google.rpc.Code; @@ -37,6 +36,7 @@ import java.sql.DriverPropertyInfo; import java.sql.SQLException; import java.util.Collection; +import java.util.Objects; import java.util.Properties; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -46,9 +46,7 @@ @RunWith(JUnit4.class) public class JdbcDriverTest { - /** - * Make sure the JDBC driver class is loaded. This is needed when running the test using Maven. - */ + // Make sure the JDBC driver class is loaded. This is needed when running the test using Maven. static { try { Class.forName("com.google.cloud.spanner.jdbc.JdbcDriver"); @@ -58,16 +56,14 @@ public class JdbcDriverTest { } } - private static MockSpannerServiceImpl mockSpanner; private static Server server; - private static InetSocketAddress address; private static final String TEST_KEY_PATH = - JdbcDriverTest.class.getResource("test-key.json").getFile(); + Objects.requireNonNull(JdbcDriverTest.class.getResource("test-key.json")).getFile(); @BeforeClass public static void startStaticServer() throws IOException { - mockSpanner = new MockSpannerServiceImpl(); - address = new InetSocketAddress("localhost", 0); + MockSpannerServiceImpl mockSpanner = new MockSpannerServiceImpl(); + InetSocketAddress address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address).addService(mockSpanner).build().start(); } @@ -128,7 +124,7 @@ public void testInvalidConnect() throws SQLException { } @Test - public void testConnectWithCredentialsAndOAuthToken() throws SQLException { + public void testConnectWithCredentialsAndOAuthToken() { try (Connection connection = DriverManager.getConnection( String.format( @@ -149,23 +145,9 @@ public void testGetPropertyInfo() throws SQLException { assertThat(props).hasLength(ConnectionOptions.VALID_PROPERTIES.size()); Collection validConnectionPropertyNames = - Collections2.transform( - ConnectionOptions.VALID_PROPERTIES, - new Function() { - @Override - public String apply(ConnectionProperty input) { - return input.getName(); - } - }); + Collections2.transform(ConnectionOptions.VALID_PROPERTIES, ConnectionProperty::getName); Collection driverPropertyNames = - Collections2.transform( - ImmutableList.copyOf(props), - new Function() { - @Override - public String apply(DriverPropertyInfo input) { - return input.name; - } - }); + Collections2.transform(ImmutableList.copyOf(props), input -> input.name); assertThat(driverPropertyNames).containsExactlyElementsIn(validConnectionPropertyNames); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcGrpcErrorTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcGrpcErrorTest.java index 51e9ab07b..0668f88fa 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcGrpcErrorTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcGrpcErrorTest.java @@ -80,10 +80,7 @@ public class JdbcGrpcErrorTest { Statement.of("UPDATE NON_EXISING_TABLE SET FOO=1 WHERE BAR=2"); private static MockSpannerServiceImpl mockSpanner; - private static MockInstanceAdminImpl mockInstanceAdmin; - private static MockDatabaseAdminImpl mockDatabaseAdmin; private static Server server; - private static InetSocketAddress address; // FAILED_PRECONDITION is chosen as the test error code as it should never be retryable. private final Exception serverException = @@ -102,9 +99,9 @@ public static void startStaticServer() throws IOException { StatementResult.exception( INVALID_UPDATE_STATEMENT, Status.NOT_FOUND.withDescription("Unknown table name").asRuntimeException())); - mockInstanceAdmin = new MockInstanceAdminImpl(); - mockDatabaseAdmin = new MockDatabaseAdminImpl(); - address = new InetSocketAddress("localhost", 0); + MockInstanceAdminImpl mockInstanceAdmin = new MockInstanceAdminImpl(); + MockDatabaseAdminImpl mockDatabaseAdmin = new MockDatabaseAdminImpl(); + InetSocketAddress address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address) .addService(mockSpanner) diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcParameterStoreTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcParameterStoreTest.java index 9d12b1b05..89f4ae4cf 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcParameterStoreTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcParameterStoreTest.java @@ -53,11 +53,7 @@ @RunWith(JUnit4.class) public class JdbcParameterStoreTest { - /** - * Tests setting a {@link Value} as a parameter value. - * - * @throws SQLException - */ + /** Tests setting a {@link Value} as a parameter value. */ @Test public void testSetValueAsParameter() throws SQLException { JdbcParameterStore params = new JdbcParameterStore(); @@ -130,10 +126,10 @@ public void testSetParameterWithType() throws SQLException, IOException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.int64(1)); params.setParameter(1, (float) 1, Types.FLOAT); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.float64(1)); params.setParameter(1, (double) 1, Types.DOUBLE); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.float64(1)); params.setParameter(1, new Date(1970 - 1900, 0, 1), Types.DATE); assertEquals(new Date(1970 - 1900, 0, 1), params.getParameter(1)); @@ -208,10 +204,10 @@ public void testSetParameterWithType() throws SQLException, IOException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.int64(1)); params.setParameter(1, (float) 1, type); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.int64(1)); params.setParameter(1, (double) 1, type); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.int64(1)); params.setParameter(1, BigDecimal.ONE, type); assertEquals(BigDecimal.ONE, params.getParameter(1)); @@ -233,10 +229,10 @@ public void testSetParameterWithType() throws SQLException, IOException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.float64(1)); params.setParameter(1, (float) 1, type); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.float64(1)); params.setParameter(1, (double) 1, type); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.float64(1)); params.setParameter(1, BigDecimal.ONE, type); assertEquals(BigDecimal.ONE, params.getParameter(1)); @@ -332,10 +328,10 @@ public void testSetParameterWithType() throws SQLException, IOException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.bool(true)); params.setParameter(1, (float) 1, type); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.bool(true)); params.setParameter(1, (double) 1, type); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.bool(true)); params.setParameter(1, BigDecimal.ZERO, type); assertEquals(BigDecimal.ZERO, params.getParameter(1)); @@ -361,10 +357,10 @@ public void testSetParameterWithType() throws SQLException, IOException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.numeric(BigDecimal.ONE)); params.setParameter(1, (float) 1, type); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.numeric(BigDecimal.valueOf(1.0))); params.setParameter(1, (double) 1, type); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.numeric(BigDecimal.valueOf(1.0))); } } @@ -502,10 +498,10 @@ public void testSetParameterWithoutType() throws SQLException { assertEquals(1, ((Long) params.getParameter(1)).longValue()); verifyParameter(params, Value.int64(1)); params.setParameter(1, (float) 1, (Integer) null); - assertEquals(1.0f, ((Float) params.getParameter(1)).floatValue(), 0.0f); + assertEquals(1.0f, (Float) params.getParameter(1), 0.0f); verifyParameter(params, Value.float64(1)); params.setParameter(1, (double) 1, (Integer) null); - assertEquals(1.0d, ((Double) params.getParameter(1)).doubleValue(), 0.0d); + assertEquals(1.0d, (Double) params.getParameter(1), 0.0d); verifyParameter(params, Value.float64(1)); params.setParameter(1, new Date(1970 - 1900, 0, 1), (Integer) null); assertEquals(new Date(1970 - 1900, 0, 1), params.getParameter(1)); @@ -618,7 +614,8 @@ public void testSetArrayParameter() throws SQLException { assertEquals(JdbcArray.createArray("DATE", new Date[] {sqlDate}), params.getParameter(1)); verifyParameter( params, - Value.dateArray(Arrays.asList(com.google.cloud.Date.fromYearMonthDay(2018, 12, 14)))); + Value.dateArray( + Collections.singletonList(com.google.cloud.Date.fromYearMonthDay(2018, 12, 14)))); params.setParameter(1, JdbcArray.createArray("DATE", new Date[] {sqlDate, null}), Types.ARRAY); assertEquals(JdbcArray.createArray("DATE", new Date[] {sqlDate, null}), params.getParameter(1)); @@ -636,7 +633,9 @@ public void testSetArrayParameter() throws SQLException { assertEquals( JdbcArray.createArray("TIMESTAMP", new Timestamp[] {sqlTimestamp}), params.getParameter(1)); verifyParameter( - params, Value.timestampArray(Arrays.asList(com.google.cloud.Timestamp.of(sqlTimestamp)))); + params, + Value.timestampArray( + Collections.singletonList(com.google.cloud.Timestamp.of(sqlTimestamp)))); params.setParameter( 1, JdbcArray.createArray("TIMESTAMP", new Timestamp[] {sqlTimestamp, null}), Types.ARRAY); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementTest.java index 8bb6ef4cb..fdc9969cb 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementTest.java @@ -44,15 +44,11 @@ import java.sql.Date; import java.sql.JDBCType; import java.sql.PreparedStatement; -import java.sql.Ref; import java.sql.ResultSetMetaData; -import java.sql.RowId; import java.sql.SQLException; -import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; -import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.TimeZone; @@ -149,33 +145,33 @@ public void testParameters() throws SQLException, MalformedURLException { ps.setArray(1, connection.createArrayOf("INT64", new Long[] {1L, 2L, 3L})); ps.setAsciiStream(2, new ByteArrayInputStream("TEST".getBytes())); ps.setAsciiStream(3, new ByteArrayInputStream("TEST".getBytes()), 4); - ps.setAsciiStream(4, new ByteArrayInputStream("TEST".getBytes()), 4l); + ps.setAsciiStream(4, new ByteArrayInputStream("TEST".getBytes()), 4L); ps.setBinaryStream(6, new ByteArrayInputStream("TEST".getBytes())); ps.setBinaryStream(7, new ByteArrayInputStream("TEST".getBytes()), 4); - ps.setBinaryStream(8, new ByteArrayInputStream("TEST".getBytes()), 4l); + ps.setBinaryStream(8, new ByteArrayInputStream("TEST".getBytes()), 4L); ps.setBlob(9, connection.createBlob()); ps.setBlob(10, new ByteArrayInputStream("TEST".getBytes())); - ps.setBlob(11, new ByteArrayInputStream("TEST".getBytes()), 4l); + ps.setBlob(11, new ByteArrayInputStream("TEST".getBytes()), 4L); ps.setBoolean(12, Boolean.TRUE); ps.setByte(13, (byte) 1); ps.setBytes(14, "TEST".getBytes()); ps.setCharacterStream(15, new StringReader("TEST")); ps.setCharacterStream(16, new StringReader("TEST"), 4); - ps.setCharacterStream(17, new StringReader("TEST"), 4l); + ps.setCharacterStream(17, new StringReader("TEST"), 4L); ps.setClob(18, connection.createClob()); ps.setClob(19, new StringReader("TEST")); - ps.setClob(20, new StringReader("TEST"), 4l); - ps.setDate(21, new Date(1000l)); - ps.setDate(22, new Date(1000l), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); + ps.setClob(20, new StringReader("TEST"), 4L); + ps.setDate(21, new Date(1000L)); + ps.setDate(22, new Date(1000L), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); ps.setDouble(23, 1d); ps.setFloat(24, 1f); ps.setInt(25, 1); - ps.setLong(26, 1l); + ps.setLong(26, 1L); ps.setNCharacterStream(27, new StringReader("TEST")); - ps.setNCharacterStream(28, new StringReader("TEST"), 4l); + ps.setNCharacterStream(28, new StringReader("TEST"), 4L); ps.setNClob(29, connection.createNClob()); ps.setNClob(30, new StringReader("TEST")); - ps.setNClob(31, new StringReader("TEST"), 4l); + ps.setNClob(31, new StringReader("TEST"), 4L); ps.setNString(32, "TEST"); ps.setNull(33, Types.BIGINT); ps.setNull(34, Types.BIGINT, "INT64"); @@ -184,10 +180,10 @@ public void testParameters() throws SQLException, MalformedURLException { ps.setObject(37, "TEST", Types.NVARCHAR, 20); ps.setShort(40, (short) 1); ps.setString(42, "TEST"); - ps.setTime(43, new Time(1000l)); - ps.setTime(44, new Time(1000l), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); - ps.setTimestamp(45, new Timestamp(1000l)); - ps.setTimestamp(46, new Timestamp(1000l), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); + ps.setTime(43, new Time(1000L)); + ps.setTime(44, new Time(1000L), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); + ps.setTimestamp(45, new Timestamp(1000L)); + ps.setTimestamp(46, new Timestamp(1000L), Calendar.getInstance(TimeZone.getTimeZone("GMT"))); ps.setUnicodeStream(47, new ByteArrayInputStream("TEST".getBytes()), 4); ps.setURL(48, new URL("https://spanner.google.com")); ps.setObject(49, UUID.fromString("83b988cf-1f4e-428a-be3d-cc712621942e")); @@ -257,21 +253,21 @@ public void testParameters() throws SQLException, MalformedURLException { private void testSetUnsupportedTypes(PreparedStatement ps) { try { - ps.setRef(38, (Ref) null); + ps.setRef(38, null); fail("missing expected exception"); } catch (SQLException e) { assertTrue(e instanceof JdbcSqlException); assertEquals(Code.INVALID_ARGUMENT, ((JdbcSqlException) e).getCode()); } try { - ps.setRowId(39, (RowId) null); + ps.setRowId(39, null); fail("missing expected exception"); } catch (SQLException e) { assertTrue(e instanceof JdbcSqlException); assertEquals(Code.INVALID_ARGUMENT, ((JdbcSqlException) e).getCode()); } try { - ps.setSQLXML(41, (SQLXML) null); + ps.setSQLXML(41, null); fail("missing expected exception"); } catch (SQLException e) { assertTrue(e instanceof JdbcSqlException); @@ -334,7 +330,7 @@ public void testGetResultSetMetadata() throws SQLException { StructField.of("ID", Type.int64()), StructField.of("NAME", Type.string()), StructField.of("AMOUNT", Type.float64())), - Arrays.asList( + Collections.singletonList( Struct.newBuilder() .set("ID") .to(1L) diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementWithMockedServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementWithMockedServerTest.java index 3f36f0001..9da17d7db 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementWithMockedServerTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcPreparedStatementWithMockedServerTest.java @@ -51,7 +51,6 @@ public class JdbcPreparedStatementWithMockedServerTest { private static MockSpannerServiceImpl mockSpanner; private static Server server; - private static InetSocketAddress address; @Parameter public boolean executeLarge; @@ -64,7 +63,7 @@ public static Collection data() { public static void startStaticServer() throws IOException { mockSpanner = new MockSpannerServiceImpl(); mockSpanner.setAbortProbability(0.0D); - address = new InetSocketAddress("localhost", 0); + InetSocketAddress address = new InetSocketAddress("localhost", 0); server = NettyServerBuilder.forAddress(address).addService(mockSpanner).build().start(); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaDataTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaDataTest.java index b3fcffcf1..559ad2935 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaDataTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetMetaDataTest.java @@ -49,7 +49,6 @@ @RunWith(JUnit4.class) public class JdbcResultSetMetaDataTest { private JdbcResultSetMetaData subject; - private java.sql.Connection connection; private static class TestColumn { private final Type type; @@ -57,7 +56,7 @@ private static class TestColumn { private final int defaultSize; private final boolean calculated; - private TestColumn(Type type, String name, Integer nulls, int size, boolean calculated) { + private TestColumn(Type type, String name, Integer nulls, boolean calculated) { Preconditions.checkNotNull(type); Preconditions.checkNotNull(name); Preconditions.checkNotNull(nulls); @@ -87,7 +86,6 @@ private static class Builder { private Type type; private String name; private Integer nulls; - private int size = 0; private boolean calculated = false; public static Builder getBuilder() { @@ -95,7 +93,7 @@ public static Builder getBuilder() { } private TestColumn build() { - return new TestColumn(type, name, nulls, size, calculated); + return new TestColumn(type, name, nulls, calculated); } private Builder withType(Type type) { @@ -123,13 +121,8 @@ private Builder withNullableUnknown() { return this; } - private Builder withSize(int size) { - this.size = size; - return this; - } - - private Builder withCalculated(boolean calculated) { - this.calculated = calculated; + private Builder withCalculated() { + this.calculated = true; return this; } } @@ -139,7 +132,7 @@ private Builder withCalculated(boolean calculated) { @Before public void setup() throws SQLException { - connection = mock(java.sql.Connection.class); + java.sql.Connection connection = mock(java.sql.Connection.class); Statement statement = mock(Statement.class); JdbcResultSet resultSet = getFooTestResultSet(statement); when(connection.getSchema()).thenReturn(""); @@ -154,27 +147,27 @@ private static List createTestColumns() { int index = 1; for (Type type : getAllTypes()) { TestColumn.Builder builder = TestColumn.Builder.getBuilder(); - builder.withName("COL" + index).withType(type).withSize(getDefaultSize(type)); - if (index % 2 == 1) builder.withNotNull(); - else builder.withNullable(); + builder.withName("COL" + index).withType(type); + if (index % 2 == 1) { + builder.withNotNull(); + } else { + builder.withNullable(); + } res.add(builder.build()); index++; } TestColumn.Builder builder = TestColumn.Builder.getBuilder(); - builder - .withName("CALCULATED") - .withType(Type.int64()) - .withNullableUnknown() - .withCalculated(true); - res.add(builder.build()); + TestColumn column = + builder + .withName("CALCULATED") + .withType(Type.int64()) + .withNullableUnknown() + .withCalculated() + .build(); + res.add(column); return res; } - private static int getDefaultSize(Type type) { - if (type == Type.string()) return 100; - return 0; - } - private static List getAllTypes() { List types = new ArrayList<>(); types.add(Type.bool()); @@ -194,7 +187,7 @@ private static List getAllTypes() { return types; } - private JdbcResultSet getFooTestResultSet(Statement statement) throws SQLException { + private JdbcResultSet getFooTestResultSet(Statement statement) { List rows = new ArrayList<>(4); for (int row = 1; row <= 4; row++) { Struct.Builder builder = Struct.newBuilder(); @@ -254,19 +247,19 @@ private Value getDefaultValue(Type type, int row) { } @Test - public void testGetColumnCount() throws SQLException { + public void testGetColumnCount() { assertEquals(TEST_COLUMNS.size(), subject.getColumnCount()); } @Test - public void testIsAutoIncrement() throws SQLException { + public void testIsAutoIncrement() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { - assertEquals(false, subject.isAutoIncrement(i)); + assertFalse(subject.isAutoIncrement(i)); } } @Test - public void testIsCaseSensitive() throws SQLException { + public void testIsCaseSensitive() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { Type type = TEST_COLUMNS.get(i - 1).type; assertEquals( @@ -276,28 +269,28 @@ public void testIsCaseSensitive() throws SQLException { } @Test - public void testIsSearchable() throws SQLException { + public void testIsSearchable() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { - assertEquals(true, subject.isSearchable(i)); + assertTrue(subject.isSearchable(i)); } } @Test - public void testIsCurrency() throws SQLException { + public void testIsCurrency() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { - assertEquals(false, subject.isCurrency(i)); + assertFalse(subject.isCurrency(i)); } } @Test - public void testIsNullable() throws SQLException { + public void testIsNullable() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(ResultSetMetaData.columnNullableUnknown, subject.isNullable(i)); } } @Test - public void testIsSigned() throws SQLException { + public void testIsSigned() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { Type type = TEST_COLUMNS.get(i - 1).type; if (type == Type.int64() || type == Type.float64()) { @@ -309,14 +302,14 @@ public void testIsSigned() throws SQLException { } @Test - public void testGetColumnDisplaySize() throws SQLException { + public void testGetColumnDisplaySize() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals( getDefaultDisplaySize(TEST_COLUMNS.get(i - 1).type, i), subject.getColumnDisplaySize(i)); } } - private int getDefaultDisplaySize(Type type, int column) throws SQLException { + private int getDefaultDisplaySize(Type type, int column) { if (type.getCode() == Code.ARRAY) return 50; if (type == Type.bool()) return 5; if (type == Type.bytes()) return 50; @@ -333,14 +326,14 @@ private int getDefaultDisplaySize(Type type, int column) throws SQLException { } @Test - public void testGetColumnLabel() throws SQLException { + public void testGetColumnLabel() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(TEST_COLUMNS.get(i - 1).name, subject.getColumnLabel(i)); } } @Test - public void testGetColumnName() throws SQLException { + public void testGetColumnName() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(TEST_COLUMNS.get(i - 1).name, subject.getColumnName(i)); } @@ -352,7 +345,7 @@ public void testGetSchemaName() throws SQLException { } @Test - public void testGetPrecision() throws SQLException { + public void testGetPrecision() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(getPrecision(TEST_COLUMNS.get(i - 1)), subject.getPrecision(i)); } @@ -369,7 +362,7 @@ private int getPrecision(TestColumn col) { } @Test - public void testGetScale() throws SQLException { + public void testGetScale() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(getScale(TEST_COLUMNS.get(i - 1)), subject.getScale(i)); } @@ -381,7 +374,7 @@ private int getScale(TestColumn col) { } @Test - public void testGetTableName() throws SQLException { + public void testGetTableName() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals("", subject.getTableName(i)); } @@ -393,7 +386,7 @@ public void testGetCatalogName() throws SQLException { } @Test - public void testGetColumnType() throws SQLException { + public void testGetColumnType() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(getSqlType(TEST_COLUMNS.get(i - 1).type), subject.getColumnType(i)); } @@ -413,7 +406,7 @@ private int getSqlType(Type type) { } @Test - public void getColumnTypeName() throws SQLException { + public void getColumnTypeName() { int index = 1; for (TestColumn col : TEST_COLUMNS) { assertEquals(col.type.getCode().name(), subject.getColumnTypeName(index)); @@ -422,28 +415,28 @@ public void getColumnTypeName() throws SQLException { } @Test - public void testIsReadOnly() throws SQLException { + public void testIsReadOnly() { for (int i = 0; i < TEST_COLUMNS.size(); i++) { assertFalse(subject.isReadOnly(i)); } } @Test - public void testIsWritable() throws SQLException { + public void testIsWritable() { for (int i = 0; i < TEST_COLUMNS.size(); i++) { assertTrue(subject.isWritable(i)); } } @Test - public void testIsDefinitelyWritable() throws SQLException { + public void testIsDefinitelyWritable() { for (int i = 0; i < TEST_COLUMNS.size(); i++) { assertFalse(subject.isDefinitelyWritable(i)); } } @Test - public void testGetColumnClassName() throws SQLException { + public void testGetColumnClassName() { for (int i = 1; i <= TEST_COLUMNS.size(); i++) { assertEquals(getTypeClassName(TEST_COLUMNS.get(i - 1).type), subject.getColumnClassName(i)); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetTest.java index 506992c47..7ed85ef89 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcResultSetTest.java @@ -157,7 +157,7 @@ public class JdbcResultSetTest { private static final String JSON_ARRAY_COL = "JSON_ARRAY"; private static final List JSON_ARRAY_VALUE = Arrays.asList(JSON_VALUE, null); - private JdbcResultSet subject; + private final JdbcResultSet subject; static ResultSet getMockResultSet() { return ResultSets.forRows( @@ -199,7 +199,7 @@ static ResultSet getMockResultSet() { StructField.of(JSON_ARRAY_COL, Type.array(Type.json())), StructField.of(STRING_ARRAY_COL, Type.array(Type.string())), StructField.of(TIMESTAMP_ARRAY_COL, Type.array(Type.timestamp()))), - Arrays.asList( + Collections.singletonList( Struct.newBuilder() .set(STRING_COL_NULL) .to((String) null) @@ -402,7 +402,7 @@ public void testGetStringIndexForTimestamp() throws SQLException { } @Test - public void testGetStringIndexForArray() throws SQLException { + public void testGetStringIndexForArray() { try { subject.getString(ARRAY_COLINDEX_NOTNULL); fail("missing SQLException"); @@ -414,7 +414,7 @@ public void testGetStringIndexForArray() throws SQLException { } @Test - public void testGetStringIndexForNullArray() throws SQLException { + public void testGetStringIndexForNullArray() { try { subject.getString(ARRAY_COLINDEX_NULL); fail("missing SQLException"); @@ -461,7 +461,7 @@ public void testGetURLIndexInvalid() throws SQLException { @Test public void testGetBooleanIndex() throws SQLException { - assertNotNull(subject.getBoolean(BOOLEAN_COLINDEX_NOTNULL)); + assertTrue(subject.getBoolean(BOOLEAN_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertFalse(subject.getBoolean(BOOLEAN_COLINDEX_NULL)); assertTrue(subject.wasNull()); @@ -469,7 +469,7 @@ public void testGetBooleanIndex() throws SQLException { @Test public void testGetBooleanIndexForLong() throws SQLException { - assertNotNull(subject.getBoolean(LONG_COLINDEX_NOTNULL)); + assertTrue(subject.getBoolean(LONG_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertFalse(subject.getBoolean(LONG_COLINDEX_NULL)); assertTrue(subject.wasNull()); @@ -477,7 +477,7 @@ public void testGetBooleanIndexForLong() throws SQLException { @Test public void testGetBooleanIndexForDouble() throws SQLException { - assertNotNull(subject.getBoolean(DOUBLE_COLINDEX_NOTNULL)); + assertTrue(subject.getBoolean(DOUBLE_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertFalse(subject.getBoolean(DOUBLE_COLINDEX_NULL)); assertTrue(subject.wasNull()); @@ -485,14 +485,14 @@ public void testGetBooleanIndexForDouble() throws SQLException { @Test public void testGetBooleanIndexForString() throws SQLException { - assertNotNull(subject.getBoolean(STRING_COLINDEX_NOTNULL)); + assertFalse(subject.getBoolean(STRING_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertFalse(subject.getBoolean(STRING_COLINDEX_NULL)); assertTrue(subject.wasNull()); } @Test - public void testGetBooleanIndexForDate() throws SQLException { + public void testGetBooleanIndexForDate() { try { subject.getBoolean(DATE_COLINDEX_NOTNULL); fail("missing expected SQLException"); @@ -521,7 +521,7 @@ public void testGetNullBooleanIndex() throws SQLException { @Test public void testGetLongIndex() throws SQLException { - assertNotNull(subject.getLong(LONG_COLINDEX_NOTNULL)); + assertEquals(1L, subject.getLong(LONG_COLINDEX_NOTNULL)); assertEquals(LONG_VALUE, subject.getLong(LONG_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertEquals(0L, subject.getLong(LONG_COLINDEX_NULL)); @@ -530,7 +530,7 @@ public void testGetLongIndex() throws SQLException { @Test public void testGetLongIndexForBool() throws SQLException { - assertNotNull(subject.getLong(BOOLEAN_COLINDEX_NOTNULL)); + assertEquals(1L, subject.getLong(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1L : 0L, subject.getLong(BOOLEAN_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertEquals(0L, subject.getLong(BOOLEAN_COLINDEX_NULL)); @@ -539,7 +539,7 @@ public void testGetLongIndexForBool() throws SQLException { @Test public void testGetLongIndexForFloat64() throws SQLException { - assertNotNull(subject.getLong(DOUBLE_COLINDEX_NOTNULL)); + assertEquals(3L, subject.getLong(DOUBLE_COLINDEX_NOTNULL)); assertEquals((long) DOUBLE_VALUE, subject.getLong(DOUBLE_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertEquals(0L, subject.getLong(DOUBLE_COLINDEX_NULL)); @@ -547,7 +547,7 @@ public void testGetLongIndexForFloat64() throws SQLException { } @Test - public void testGetLongIndexForString() throws SQLException { + public void testGetLongIndexForString() { try { subject.getLong(STRING_COLINDEX_NOTNULL); fail("missing expected SQLException"); @@ -571,7 +571,7 @@ public void testGetLongIndexForNullString() throws SQLException { } @Test - public void testGetLongIndexForTimestamp() throws SQLException { + public void testGetLongIndexForTimestamp() { try { subject.getLong(TIMESTAMP_COLINDEX_NOTNULL); fail("missing expected SQLException"); @@ -583,7 +583,6 @@ public void testGetLongIndexForTimestamp() throws SQLException { @Test public void testGetDoubleIndex() throws SQLException { - assertNotNull(subject.getDouble(DOUBLE_COLINDEX_NOTNULL)); assertEquals(DOUBLE_VALUE, subject.getDouble(DOUBLE_COLINDEX_NOTNULL), 0d); assertFalse(subject.wasNull()); assertEquals(0d, subject.getDouble(DOUBLE_COLINDEX_NULL), 0d); @@ -592,11 +591,8 @@ public void testGetDoubleIndex() throws SQLException { @Test public void testGetDoubleIndexFromString() throws SQLException { - assertNotNull(subject.getDouble(STRING_COLINDEX_NUMBER)); assertEquals( - Double.valueOf(STRING_NUMBER_VALUE).doubleValue(), - subject.getDouble(STRING_COLINDEX_NUMBER), - 0d); + Double.parseDouble(STRING_NUMBER_VALUE), subject.getDouble(STRING_COLINDEX_NUMBER), 0d); assertFalse(subject.wasNull()); assertEquals(0d, subject.getDouble(STRING_COLINDEX_NULL), 0d); assertTrue(subject.wasNull()); @@ -604,7 +600,6 @@ public void testGetDoubleIndexFromString() throws SQLException { @Test public void testGetDoubleIndexFromBool() throws SQLException { - assertNotNull(subject.getDouble(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1d : 0d, subject.getDouble(BOOLEAN_COLINDEX_NOTNULL), 0d); assertFalse(subject.wasNull()); assertEquals(0d, subject.getDouble(BOOLEAN_COLINDEX_NULL), 0d); @@ -613,7 +608,6 @@ public void testGetDoubleIndexFromBool() throws SQLException { @Test public void testGetDoubleIndexFromInt64() throws SQLException { - assertNotNull(subject.getDouble(LONG_COLINDEX_NOTNULL)); assertEquals(LONG_VALUE, subject.getDouble(LONG_COLINDEX_NOTNULL), 0d); assertFalse(subject.wasNull()); assertEquals(0d, subject.getDouble(LONG_COLINDEX_NULL), 0d); @@ -621,7 +615,7 @@ public void testGetDoubleIndexFromInt64() throws SQLException { } @Test - public void testGetDoubleIndexFromTimestamp() throws SQLException { + public void testGetDoubleIndexFromTimestamp() { try { subject.getDouble(TIMESTAMP_COLINDEX_NULL); fail("missing expected SQLException"); @@ -800,7 +794,7 @@ public void testGetURLLabelInvalid() throws SQLException { @Test public void testGetBooleanLabel() throws SQLException { - assertNotNull(subject.getBoolean(BOOLEAN_COL_NOT_NULL)); + assertTrue(subject.getBoolean(BOOLEAN_COL_NOT_NULL)); assertFalse(subject.wasNull()); assertFalse(subject.getBoolean(BOOLEAN_COL_NULL)); assertTrue(subject.wasNull()); @@ -808,16 +802,14 @@ public void testGetBooleanLabel() throws SQLException { @Test public void testGetLongLabel() throws SQLException { - assertNotNull(subject.getLong(LONG_COL_NOT_NULL)); - assertEquals(1l, subject.getLong(LONG_COL_NOT_NULL)); + assertEquals(1L, subject.getLong(LONG_COL_NOT_NULL)); assertFalse(subject.wasNull()); - assertEquals(0l, subject.getLong(LONG_COL_NULL)); + assertEquals(0L, subject.getLong(LONG_COL_NULL)); assertTrue(subject.wasNull()); } @Test public void testGetDoubleLabel() throws SQLException { - assertNotNull(subject.getDouble(DOUBLE_COL_NOT_NULL)); assertEquals(DOUBLE_VALUE, subject.getDouble(DOUBLE_COL_NOT_NULL), 0d); assertFalse(subject.wasNull()); assertEquals(0d, subject.getDouble(DOUBLE_COL_NULL), 0d); @@ -970,6 +962,7 @@ public void testGetDateIndexCalendar() throws SQLException { Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Calendar expectedCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); expectedCal.clear(); + //noinspection MagicConstant expectedCal.set(DATE_VALUE.getYear(), DATE_VALUE.getMonth() - 1, DATE_VALUE.getDayOfMonth()); java.sql.Date expected = new java.sql.Date(expectedCal.getTimeInMillis()); assertEquals(expected, subject.getDate(DATE_COLINDEX_NOTNULL, calGMT)); @@ -990,6 +983,7 @@ public void testGetDateLabelCalendar() throws SQLException { Calendar calGMT = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Calendar expected = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + //noinspection MagicConstant expected.set( DATE_VALUE.getYear(), DATE_VALUE.getMonth() - 1, DATE_VALUE.getDayOfMonth(), 0, 0, 0); expected.clear(Calendar.MILLISECOND); @@ -1053,8 +1047,7 @@ public void testGetTimestampIndexCalendarFromDate() throws SQLException { assertNotNull(subject.getTimestamp(DATE_COLINDEX_NOTNULL, cal)); assertEquals( - Timestamp.parseTimestamp(String.format("%sT00:00:00-08:00", DATE_VALUE.toString())) - .toSqlTimestamp(), + Timestamp.parseTimestamp(String.format("%sT00:00:00-08:00", DATE_VALUE)).toSqlTimestamp(), subject.getTimestamp(DATE_COLINDEX_NOTNULL, cal)); assertFalse(subject.wasNull()); assertNull(subject.getTimestamp(DATE_COLINDEX_NULL, cal)); @@ -1074,7 +1067,7 @@ public void testGetTimestampLabelCalendar() throws SQLException { } @Test - public void testIsClosed() throws SQLException { + public void testIsClosed() { try (JdbcResultSet rs = JdbcResultSet.of(mock(Statement.class), getMockResultSet())) { assertFalse(rs.isClosed()); rs.close(); @@ -1084,7 +1077,6 @@ public void testIsClosed() throws SQLException { @Test public void testGetByteIndex() throws SQLException { - assertNotNull(subject.getByte(LONG_COLINDEX_NOTNULL)); assertEquals(LONG_VALUE, subject.getByte(LONG_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertEquals(0, subject.getByte(LONG_COLINDEX_NULL)); @@ -1093,7 +1085,6 @@ public void testGetByteIndex() throws SQLException { @Test public void testGetByteIndexFromString() throws SQLException { - assertNotNull(subject.getByte(STRING_COLINDEX_NUMBER)); assertEquals( Byte.valueOf(STRING_NUMBER_VALUE).byteValue(), subject.getByte(STRING_COLINDEX_NUMBER)); assertFalse(subject.wasNull()); @@ -1101,14 +1092,12 @@ public void testGetByteIndexFromString() throws SQLException { @Test public void testGetByteIndexFromDouble() throws SQLException { - assertNotNull(subject.getByte(DOUBLE_COLINDEX_NOTNULL)); assertEquals((byte) DOUBLE_VALUE, subject.getByte(DOUBLE_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @Test public void testGetByteIndexFromBoolean() throws SQLException { - assertNotNull(subject.getByte(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1 : 0, subject.getByte(BOOLEAN_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @@ -1134,7 +1123,6 @@ public void testGetNullByteIndex() throws SQLException { @Test public void testGetShortIndex() throws SQLException { - assertNotNull(subject.getShort(LONG_COLINDEX_NOTNULL)); assertEquals(LONG_VALUE, subject.getShort(LONG_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); assertEquals(0, subject.getShort(LONG_COLINDEX_NULL)); @@ -1143,7 +1131,6 @@ public void testGetShortIndex() throws SQLException { @Test public void testGetShortIndexFromString() throws SQLException { - assertNotNull(subject.getShort(STRING_COLINDEX_NUMBER)); assertEquals( Short.valueOf(STRING_NUMBER_VALUE).shortValue(), subject.getShort(STRING_COLINDEX_NUMBER)); assertFalse(subject.wasNull()); @@ -1151,20 +1138,18 @@ public void testGetShortIndexFromString() throws SQLException { @Test public void testGetShortIndexFromDouble() throws SQLException { - assertNotNull(subject.getShort(DOUBLE_COLINDEX_NOTNULL)); assertEquals((short) DOUBLE_VALUE, subject.getShort(DOUBLE_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @Test public void testGetShortIndexFromBoolean() throws SQLException { - assertNotNull(subject.getShort(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1 : 0, subject.getShort(BOOLEAN_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @Test - public void testGetShortIndexFromBytes() throws SQLException { + public void testGetShortIndexFromBytes() { try { subject.getShort(BYTES_COL_NULL); fail("missing expected SQLException"); @@ -1195,7 +1180,6 @@ public void testGetNullShortIndex() throws SQLException { @Test public void testGetIntIndex() throws SQLException { - assertNotNull(subject.getInt(LONG_COLINDEX_NOTNULL)); int expected = (int) LONG_VALUE; assertEquals(expected, subject.getInt(LONG_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); @@ -1205,7 +1189,6 @@ public void testGetIntIndex() throws SQLException { @Test public void testGetIntIndexFromString() throws SQLException { - assertNotNull(subject.getInt(STRING_COLINDEX_NUMBER)); assertEquals( Integer.valueOf(STRING_NUMBER_VALUE).intValue(), subject.getInt(STRING_COLINDEX_NUMBER)); assertFalse(subject.wasNull()); @@ -1213,20 +1196,18 @@ public void testGetIntIndexFromString() throws SQLException { @Test public void testGetIntIndexFromDouble() throws SQLException { - assertNotNull(subject.getInt(DOUBLE_COLINDEX_NOTNULL)); assertEquals((int) DOUBLE_VALUE, subject.getInt(DOUBLE_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @Test public void testGetIntIndexFromBoolean() throws SQLException { - assertNotNull(subject.getInt(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1 : 0, subject.getInt(BOOLEAN_COLINDEX_NOTNULL)); assertFalse(subject.wasNull()); } @Test - public void testGetIntIndexFromTimestamp() throws SQLException { + public void testGetIntIndexFromTimestamp() { try { subject.getInt(TIMESTAMP_COL_NULL); fail("missing expected SQLException"); @@ -1257,7 +1238,6 @@ public void testGetNullIntIndex() throws SQLException { @Test public void testGetFloatIndex() throws SQLException { - assertNotNull(subject.getFloat(DOUBLE_COLINDEX_NOTNULL)); float expected = (float) DOUBLE_VALUE; assertEquals(expected, subject.getFloat(DOUBLE_COLINDEX_NOTNULL), 0f); assertFalse(subject.wasNull()); @@ -1267,11 +1247,8 @@ public void testGetFloatIndex() throws SQLException { @Test public void testGetFloatIndexFromString() throws SQLException { - assertNotNull(subject.getFloat(STRING_COLINDEX_NUMBER)); assertEquals( - Float.valueOf(STRING_NUMBER_VALUE).floatValue(), - subject.getFloat(STRING_COLINDEX_NUMBER), - 0f); + Float.parseFloat(STRING_NUMBER_VALUE), subject.getFloat(STRING_COLINDEX_NUMBER), 0f); assertFalse(subject.wasNull()); assertEquals(0f, subject.getFloat(STRING_COLINDEX_NULL), 0f); assertTrue(subject.wasNull()); @@ -1279,7 +1256,6 @@ public void testGetFloatIndexFromString() throws SQLException { @Test public void testGetFloatIndexFromBool() throws SQLException { - assertNotNull(subject.getFloat(BOOLEAN_COLINDEX_NOTNULL)); assertEquals(BOOLEAN_VALUE ? 1f : 0f, subject.getFloat(BOOLEAN_COLINDEX_NOTNULL), 0f); assertFalse(subject.wasNull()); assertEquals(0f, subject.getFloat(BOOLEAN_COLINDEX_NULL), 0f); @@ -1288,7 +1264,6 @@ public void testGetFloatIndexFromBool() throws SQLException { @Test public void testGetFloatIndexFromInt64() throws SQLException { - assertNotNull(subject.getFloat(LONG_COLINDEX_NOTNULL)); assertEquals(LONG_VALUE, subject.getFloat(LONG_COLINDEX_NOTNULL), 0f); assertFalse(subject.wasNull()); assertEquals(0f, subject.getFloat(LONG_COLINDEX_NULL), 0f); @@ -1296,7 +1271,7 @@ public void testGetFloatIndexFromInt64() throws SQLException { } @Test - public void testGetFloatIndexFromTimestamp() throws SQLException { + public void testGetFloatIndexFromTimestamp() { try { subject.getFloat(TIMESTAMP_COLINDEX_NULL); fail("missing expected SQLException"); @@ -1308,7 +1283,6 @@ public void testGetFloatIndexFromTimestamp() throws SQLException { @Test public void testGetByteLabel() throws SQLException { - assertNotNull(subject.getByte(LONG_COL_NOT_NULL)); assertEquals(1, subject.getByte(LONG_COL_NOT_NULL)); assertFalse(subject.wasNull()); assertEquals(0, subject.getByte(LONG_COL_NULL)); @@ -1317,7 +1291,6 @@ public void testGetByteLabel() throws SQLException { @Test public void testGetShortLabel() throws SQLException { - assertNotNull(subject.getShort(LONG_COL_NOT_NULL)); assertEquals(1, subject.getShort(LONG_COL_NOT_NULL)); assertFalse(subject.wasNull()); assertEquals(0, subject.getShort(LONG_COL_NULL)); @@ -1326,7 +1299,6 @@ public void testGetShortLabel() throws SQLException { @Test public void testGetIntLabel() throws SQLException { - assertNotNull(subject.getInt(LONG_COL_NOT_NULL)); assertEquals(1, subject.getInt(LONG_COL_NOT_NULL)); assertFalse(subject.wasNull()); assertEquals(0, subject.getInt(LONG_COL_NULL)); @@ -1335,7 +1307,6 @@ public void testGetIntLabel() throws SQLException { @Test public void testGetFloatLabel() throws SQLException { - assertNotNull(subject.getFloat(DOUBLE_COL_NOT_NULL)); float expected = (float) DOUBLE_VALUE; assertEquals(expected, subject.getFloat(DOUBLE_COL_NOT_NULL), 0f); assertFalse(subject.wasNull()); @@ -1429,12 +1400,12 @@ public void testGetArrayIndex() throws SQLException { } @Test - public void testGetWarnings() throws SQLException { + public void testGetWarnings() { assertNull(subject.getWarnings()); } @Test - public void testClearWarnings() throws SQLException { + public void testClearWarnings() { subject.clearWarnings(); } @@ -1452,7 +1423,7 @@ public void testIsAfterLast() throws SQLException { try (JdbcResultSet rs = JdbcResultSet.of(mock(Statement.class), getMockResultSet())) { assertFalse(rs.isAfterLast()); while (rs.next()) { - // do nothing + assertFalse(rs.isAfterLast()); } assertTrue(rs.isAfterLast()); } @@ -1677,7 +1648,7 @@ public void testGetBeforeNext() { public void testGetAfterLast() { try (JdbcResultSet rs = JdbcResultSet.of(mock(Statement.class), getMockResultSet())) { while (rs.next()) { - // do nothing + assertNotNull(rs.getBigDecimal(LONG_COLINDEX_NOTNULL)); } rs.getBigDecimal(LONG_COLINDEX_NOTNULL); fail("missing expected exception"); @@ -1693,7 +1664,7 @@ public void testGetAfterLast() { } @Test - public void testFindIllegalColumnName() throws SQLException { + public void testFindIllegalColumnName() { try { subject.findColumn(UNKNOWN_COLUMN); fail("missing expected exception"); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcSqlScriptVerifier.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcSqlScriptVerifier.java index 4f41771eb..3143d5ac1 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcSqlScriptVerifier.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcSqlScriptVerifier.java @@ -31,6 +31,7 @@ import java.sql.Timestamp; import java.sql.Types; import java.util.ArrayList; +import java.util.Collections; import java.util.List; /** SQL Script verifier for JDBC connections */ @@ -93,18 +94,13 @@ protected Object getValue(String col) throws SQLException { return com.google.cloud.Timestamp.of((Timestamp) value); } else if (value instanceof Array) { Array array = (Array) value; - switch (array.getBaseType()) { - case Types.BIGINT: - Long[] longs = (Long[]) array.getArray(); - List res = new ArrayList<>(); - for (Long l : longs) { - res.add(l); - } - return res; - default: - throw new IllegalArgumentException( - "Unsupported array base type: " + array.getBaseType()); + if (array.getBaseType() == Types.BIGINT) { + Long[] longs = (Long[]) array.getArray(); + List res = new ArrayList<>(); + Collections.addAll(res, longs); + return res; } + throw new IllegalArgumentException("Unsupported array base type: " + array.getBaseType()); } return value; } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcStatementTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcStatementTest.java index e5efb773d..e73be4ef7 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcStatementTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcStatementTest.java @@ -43,7 +43,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @RunWith(JUnit4.class) @@ -53,6 +52,7 @@ public class JdbcStatementTest { private static final String LARGE_UPDATE = "UPDATE FOO SET BAR=1 WHERE 1=1"; private static final String DDL = "CREATE INDEX FOO ON BAR(ID)"; + @SuppressWarnings("unchecked") private JdbcStatement createStatement() { Connection spanner = mock(Connection.class); @@ -101,24 +101,21 @@ private JdbcStatement createStatement() { when(spanner.executeBatchUpdate(anyList())) .thenAnswer( - new Answer() { - @SuppressWarnings("unchecked") - @Override - public long[] answer(InvocationOnMock invocation) throws Throwable { - List statements = - (List) invocation.getArguments()[0]; - if (statements.isEmpty() - || StatementParser.INSTANCE.isDdlStatement(statements.get(0).getSql())) { - return new long[0]; - } - long[] res = - new long - [((List) invocation.getArguments()[0]) - .size()]; - Arrays.fill(res, 1L); - return res; - } - }); + (Answer) + invocation -> { + List statements = + (List) invocation.getArguments()[0]; + if (statements.isEmpty() + || StatementParser.INSTANCE.isDdlStatement(statements.get(0).getSql())) { + return new long[0]; + } + long[] res = + new long + [((List) invocation.getArguments()[0]) + .size()]; + Arrays.fill(res, 1L); + return res; + }); JdbcConnection connection = mock(JdbcConnection.class); when(connection.getSpannerConnection()).thenReturn(spanner); @@ -331,7 +328,7 @@ public void testExecuteLargeUpdate() throws SQLException { } @Test - public void testExecuteUpdateWithSelectStatement() throws SQLException { + public void testExecuteUpdateWithSelectStatement() { Statement statement = createStatement(); try { statement.executeUpdate(SELECT); @@ -438,7 +435,7 @@ public void testLargeDmlBatch() throws SQLException { } @Test - public void testConvertUpdateCounts() throws SQLException { + public void testConvertUpdateCounts() { try (JdbcStatement statement = new JdbcStatement(mock(JdbcConnection.class))) { int[] updateCounts = statement.convertUpdateCounts(new long[] {1L, 2L, 3L}); assertThat(updateCounts).asList().containsExactly(1, 2, 3); @@ -453,41 +450,41 @@ public void testConvertUpdateCounts() throws SQLException { } @Test - public void testConvertUpdateCountsToSuccessNoInfo() throws SQLException { + public void testConvertUpdateCountsToSuccessNoInfo() { try (JdbcStatement statement = new JdbcStatement(mock(JdbcConnection.class))) { long[] updateCounts = new long[3]; statement.convertUpdateCountsToSuccessNoInfo(new long[] {1L, 2L, 3L}, updateCounts); assertThat(updateCounts) .asList() .containsExactly( - Long.valueOf(Statement.SUCCESS_NO_INFO), - Long.valueOf(Statement.SUCCESS_NO_INFO), - Long.valueOf(Statement.SUCCESS_NO_INFO)); + (long) Statement.SUCCESS_NO_INFO, + (long) Statement.SUCCESS_NO_INFO, + (long) Statement.SUCCESS_NO_INFO); statement.convertUpdateCountsToSuccessNoInfo(new long[] {0L, 0L, 0L}, updateCounts); assertThat(updateCounts) .asList() .containsExactly( - Long.valueOf(Statement.EXECUTE_FAILED), - Long.valueOf(Statement.EXECUTE_FAILED), - Long.valueOf(Statement.EXECUTE_FAILED)); + (long) Statement.EXECUTE_FAILED, + (long) Statement.EXECUTE_FAILED, + (long) Statement.EXECUTE_FAILED); statement.convertUpdateCountsToSuccessNoInfo(new long[] {1L, 0L, 2L}, updateCounts); assertThat(updateCounts) .asList() .containsExactly( - Long.valueOf(Statement.SUCCESS_NO_INFO), - Long.valueOf(Statement.EXECUTE_FAILED), - Long.valueOf(Statement.SUCCESS_NO_INFO)); + (long) Statement.SUCCESS_NO_INFO, + (long) Statement.EXECUTE_FAILED, + (long) Statement.SUCCESS_NO_INFO); statement.convertUpdateCountsToSuccessNoInfo( new long[] {1L, Integer.MAX_VALUE + 1L, 2L}, updateCounts); assertThat(updateCounts) .asList() .containsExactly( - Long.valueOf(Statement.SUCCESS_NO_INFO), - Long.valueOf(Statement.SUCCESS_NO_INFO), - Long.valueOf(Statement.SUCCESS_NO_INFO)); + (long) Statement.SUCCESS_NO_INFO, + (long) Statement.SUCCESS_NO_INFO, + (long) Statement.SUCCESS_NO_INFO); } } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcTimeoutSqlTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcTimeoutSqlTest.java index 6d743d147..8e36a7db1 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcTimeoutSqlTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcTimeoutSqlTest.java @@ -27,7 +27,7 @@ * As JDBC connections store the statement timeout on {@link Statement} objects instead of on the * {@link Connection}, the JDBC driver needs to set and reset the connection timeout on the * underlying connection after each statement execution. JDBC also uses seconds as the time unit for - * timeouts, while the underlying {@link com.google.cloud.spanner.jdbc.Connection}s use + * timeouts, while the underlying {@link com.google.cloud.spanner.connection.Connection}s use * milliseconds. This test script tests a number of special cases regarding this. */ @RunWith(JUnit4.class) @@ -35,6 +35,6 @@ public class JdbcTimeoutSqlTest { @Test public void testTimeoutScript() throws Exception { JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new TestConnectionProvider()); - verifier.verifyStatementsInFile("TimeoutSqlScriptTest.sql", getClass()); + verifier.verifyStatementsInFile("TimeoutSqlScriptTest.sql", getClass(), false); } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/JdbcTypeConverterTest.java b/src/test/java/com/google/cloud/spanner/jdbc/JdbcTypeConverterTest.java index 1bb0e374e..f1ed83303 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcTypeConverterTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcTypeConverterTest.java @@ -40,6 +40,7 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.Date; import java.sql.SQLException; @@ -57,7 +58,7 @@ @RunWith(JUnit4.class) public class JdbcTypeConverterTest { - private static final Charset UTF8 = Charset.forName("UTF8"); + private static final Charset UTF8 = StandardCharsets.UTF_8; @Test public void testConvertArray() throws SQLException { @@ -94,14 +95,12 @@ public void testConvertBool() throws SQLException { Boolean[] testValues = new Boolean[] {Boolean.TRUE, Boolean.FALSE}; for (Boolean b : testValues) { assertThat(convert(b, Type.bool(), Boolean.class)).isEqualTo(b); - assertThat(convert(b, Type.bool(), Byte.class)) - .isEqualTo(Byte.valueOf(b ? (byte) 1 : (byte) 0)); - assertThat(convert(b, Type.bool(), Short.class)) - .isEqualTo(Short.valueOf(b ? (short) 1 : (short) 0)); - assertThat(convert(b, Type.bool(), Integer.class)).isEqualTo(Integer.valueOf(b ? 1 : 0)); - assertThat(convert(b, Type.bool(), Long.class)).isEqualTo(Long.valueOf(b ? 1L : 0L)); - assertThat(convert(b, Type.bool(), Float.class)).isEqualTo(Float.valueOf(b ? 1F : 0F)); - assertThat(convert(b, Type.bool(), Double.class)).isEqualTo(Double.valueOf(b ? 1D : 0D)); + assertThat(convert(b, Type.bool(), Byte.class)).isEqualTo(b ? (byte) 1 : (byte) 0); + assertThat(convert(b, Type.bool(), Short.class)).isEqualTo(b ? (short) 1 : (short) 0); + assertThat(convert(b, Type.bool(), Integer.class)).isEqualTo(b ? 1 : 0); + assertThat(convert(b, Type.bool(), Long.class)).isEqualTo(b ? 1L : 0L); + assertThat(convert(b, Type.bool(), Float.class)).isEqualTo(b ? 1F : 0F); + assertThat(convert(b, Type.bool(), Double.class)).isEqualTo(b ? 1D : 0D); assertThat(convert(b, Type.bool(), BigInteger.class)) .isEqualTo(b ? BigInteger.ONE : BigInteger.ZERO); assertThat(convert(b, Type.bool(), BigDecimal.class)) @@ -238,18 +237,18 @@ public void testConvertInt64() throws SQLException { 1L, Long.MIN_VALUE, Long.MAX_VALUE, - Long.valueOf(Integer.MIN_VALUE), - Long.valueOf(Integer.MAX_VALUE), - Long.valueOf(Integer.MIN_VALUE - 1), - Long.valueOf(Integer.MAX_VALUE + 1), - Long.valueOf(Short.MIN_VALUE), - Long.valueOf(Short.MAX_VALUE), - Long.valueOf(Short.MIN_VALUE - 1), - Long.valueOf(Short.MAX_VALUE + 1), - Long.valueOf(Byte.MIN_VALUE), - Long.valueOf(Byte.MAX_VALUE), - Long.valueOf(Byte.MIN_VALUE - 1), - Long.valueOf(Byte.MAX_VALUE + 1) + (long) Integer.MIN_VALUE, + (long) Integer.MAX_VALUE, + ((long) Integer.MIN_VALUE - 1), + ((long) Integer.MAX_VALUE + 1), + (long) Short.MIN_VALUE, + (long) Short.MAX_VALUE, + (long) (Short.MIN_VALUE - 1), + (long) (Short.MAX_VALUE + 1), + (long) Byte.MIN_VALUE, + (long) Byte.MAX_VALUE, + (long) (Byte.MIN_VALUE - 1), + (long) (Byte.MAX_VALUE + 1) }; testConvertInt64ToNumber(testValues, Long.class, Long.MIN_VALUE, Long.MAX_VALUE); testConvertInt64ToNumber(testValues, Integer.class, Integer.MIN_VALUE, Integer.MAX_VALUE); @@ -260,7 +259,7 @@ public void testConvertInt64() throws SQLException { for (Long l : testValues) { assertThat(convert(l, Type.int64(), String.class)).isEqualTo(String.valueOf(l)); - assertThat(convert(l, Type.int64(), Boolean.class)).isEqualTo(Boolean.valueOf(l != 0L)); + assertThat(convert(l, Type.int64(), Boolean.class)).isEqualTo(l != 0L); assertConvertThrows(l, Type.int64(), Double.class, Code.INVALID_ARGUMENT); assertConvertThrows(l, Type.int64(), Float.class, Code.INVALID_ARGUMENT); } @@ -288,19 +287,19 @@ public void testConvertFloat64() throws SQLException { 1D, Double.MIN_VALUE, Double.MAX_VALUE, - Double.valueOf(Float.MIN_VALUE), - Double.valueOf(Float.MAX_VALUE), - Double.valueOf(Float.MAX_VALUE + 1D) + (double) Float.MIN_VALUE, + (double) Float.MAX_VALUE, + Float.MAX_VALUE + 1D }; for (Double d : testValues) { assertThat(convert(d, Type.float64(), Double.class)).isEqualTo(d); - if (d > Float.MAX_VALUE || d < -Float.MAX_VALUE) { + if (Math.abs(d) > Math.abs(Float.MAX_VALUE)) { assertConvertThrows(d, Type.float64(), Float.class, Code.OUT_OF_RANGE); } else { assertThat(convert(d, Type.float64(), Float.class)).isEqualTo(d.floatValue()); } assertThat(convert(d, Type.float64(), String.class)).isEqualTo(String.valueOf(d)); - assertThat(convert(d, Type.float64(), Boolean.class)).isEqualTo(Boolean.valueOf(d != 0D)); + assertThat(convert(d, Type.float64(), Boolean.class)).isEqualTo(d != 0D); assertConvertThrows(d, Type.float64(), Long.class, Code.INVALID_ARGUMENT); assertConvertThrows(d, Type.float64(), Integer.class, Code.INVALID_ARGUMENT); assertConvertThrows(d, Type.float64(), Short.class, Code.INVALID_ARGUMENT); @@ -328,8 +327,7 @@ public void testConvertNumeric() throws SQLException { assertThat(convert(d, Type.numeric(), Double.class)).isEqualTo(d.doubleValue()); assertThat(convert(d, Type.numeric(), Float.class)).isEqualTo(d.floatValue()); assertThat(convert(d, Type.numeric(), String.class)).isEqualTo(String.valueOf(d)); - assertThat(convert(d, Type.numeric(), Boolean.class)) - .isEqualTo(Boolean.valueOf(!d.equals(BigDecimal.ZERO))); + assertThat(convert(d, Type.numeric(), Boolean.class)).isEqualTo(!d.equals(BigDecimal.ZERO)); if (d.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) > 0 || d.compareTo(BigDecimal.valueOf(Long.MIN_VALUE)) < 0 || d.scale() > 0) { @@ -446,35 +444,35 @@ public void testToSqlDate() { public void testToSqlDateWithCalendar() { for (TimeZone zone : getTestTimeZones()) { Calendar cal = Calendar.getInstance(zone); - cal.set(2019, 7, 24, 0, 0, 0); + cal.set(2019, Calendar.AUGUST, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); assertThat( toSqlDate( com.google.cloud.Date.fromYearMonthDay(2019, 8, 24), Calendar.getInstance(zone))) .isEqualTo(new Date(cal.getTimeInMillis())); - cal.set(2019, 0, 1, 0, 0, 0); + cal.set(2019, Calendar.JANUARY, 1, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); assertThat( toSqlDate( com.google.cloud.Date.fromYearMonthDay(2019, 1, 1), Calendar.getInstance(zone))) .isEqualTo(new Date(cal.getTimeInMillis())); - cal.set(2019, 11, 31, 0, 0, 0); + cal.set(2019, Calendar.DECEMBER, 31, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); assertThat( toSqlDate( com.google.cloud.Date.fromYearMonthDay(2019, 12, 31), Calendar.getInstance(zone))) .isEqualTo(new Date(cal.getTimeInMillis())); - cal.set(2016, 1, 29, 0, 0, 0); + cal.set(2016, Calendar.FEBRUARY, 29, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); assertThat( toSqlDate( com.google.cloud.Date.fromYearMonthDay(2016, 2, 29), Calendar.getInstance(zone))) .isEqualTo(new Date(cal.getTimeInMillis())); - cal.set(2000, 1, 29, 0, 0, 0); + cal.set(2000, Calendar.FEBRUARY, 29, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); assertThat( toSqlDate( @@ -513,7 +511,7 @@ public void testToSqlDates() { @SuppressWarnings("deprecation") @Test - public void testToSqlTimestamp() throws SQLException { + public void testToSqlTimestamp() { TimeZone initialDefault = TimeZone.getDefault(); try { for (TimeZone zone : getTestTimeZones()) { @@ -564,12 +562,12 @@ public void testToSqlTimestamp() throws SQLException { } @Test - public void testGetAsSqlTimestamp() throws SQLException { + public void testGetAsSqlTimestamp() { for (TimeZone zone : getTestTimeZones()) { com.google.cloud.Timestamp gts = ReadOnlyStalenessUtil.parseRfc3339("2019-08-24T11:23:01.1998+03:00"); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+03:00")); - cal.set(2019, 7, 24, 11, 23, 1); + cal.set(2019, Calendar.AUGUST, 24, 11, 23, 1); cal.set(Calendar.MILLISECOND, 0); Timestamp ts = new Timestamp(cal.getTimeInMillis() + zone.getRawOffset()); ts.setNanos(199800000); @@ -577,7 +575,7 @@ public void testGetAsSqlTimestamp() throws SQLException { gts = ReadOnlyStalenessUtil.parseRfc3339("2019-12-31T23:59:59.999999999-03:00"); cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-03:00")); - cal.set(2019, 11, 31, 23, 59, 59); + cal.set(2019, Calendar.DECEMBER, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 0); ts = new Timestamp(cal.getTimeInMillis() + zone.getRawOffset()); ts.setNanos(999999999); @@ -585,14 +583,14 @@ public void testGetAsSqlTimestamp() throws SQLException { gts = ReadOnlyStalenessUtil.parseRfc3339("2016-02-29T12:00:00Z"); cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); - cal.set(2016, 1, 29, 12, 0, 0); + cal.set(2016, Calendar.FEBRUARY, 29, 12, 0, 0); cal.set(Calendar.MILLISECOND, 0); ts = new Timestamp(cal.getTimeInMillis() + zone.getRawOffset()); assertThat(getAsSqlTimestamp(gts, Calendar.getInstance(zone))).isEqualTo(ts); gts = ReadOnlyStalenessUtil.parseRfc3339("2000-02-29T00:00:00.000000000-10:00"); cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-10:00")); - cal.set(2000, 1, 29, 0, 0, 0); + cal.set(2000, Calendar.FEBRUARY, 29, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); ts = new Timestamp(cal.getTimeInMillis() + zone.getRawOffset()); assertThat(getAsSqlTimestamp(gts, Calendar.getInstance(zone))).isEqualTo(ts); @@ -601,10 +599,10 @@ public void testGetAsSqlTimestamp() throws SQLException { @SuppressWarnings("deprecation") @Test - public void testSetTimestampInCalendar() throws SQLException { + public void testSetTimestampInCalendar() { for (TimeZone zone : getTestTimeZones()) { Calendar cal = Calendar.getInstance(zone); - cal.set(2019, 7, 24, 11, 23, 1); + cal.set(2019, Calendar.AUGUST, 24, 11, 23, 1); cal.set(Calendar.MILLISECOND, 0); Timestamp ts = new Timestamp(2019 - 1900, 7, 24, 11, 23, 1, 0); Timestamp tsInCal = setTimestampInCalendar(ts, Calendar.getInstance(zone)); @@ -612,7 +610,7 @@ public void testSetTimestampInCalendar() throws SQLException { .isEqualTo(cal.getTimeInMillis() - TimeZone.getDefault().getOffset(ts.getTime())); cal = Calendar.getInstance(zone); - cal.set(2019, 11, 31, 23, 59, 59); + cal.set(2019, Calendar.DECEMBER, 31, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); ts = new Timestamp(2019 - 1900, 11, 31, 23, 59, 59, 999000000); tsInCal = setTimestampInCalendar(ts, Calendar.getInstance(zone)); @@ -620,7 +618,7 @@ public void testSetTimestampInCalendar() throws SQLException { .isEqualTo(cal.getTimeInMillis() - TimeZone.getDefault().getOffset(ts.getTime())); cal = Calendar.getInstance(zone); - cal.set(2016, 1, 29, 12, 0, 0); + cal.set(2016, Calendar.FEBRUARY, 29, 12, 0, 0); cal.set(Calendar.MILLISECOND, 0); ts = new Timestamp(2016 - 1900, 1, 29, 12, 0, 0, 0); tsInCal = setTimestampInCalendar(ts, Calendar.getInstance(zone)); @@ -628,7 +626,7 @@ public void testSetTimestampInCalendar() throws SQLException { .isEqualTo(cal.getTimeInMillis() - TimeZone.getDefault().getOffset(ts.getTime())); cal = Calendar.getInstance(zone); - cal.set(2000, 1, 29, 0, 0, 0); + cal.set(2000, Calendar.FEBRUARY, 29, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); ts = new Timestamp(2000 - 1900, 1, 29, 0, 0, 0, 0); tsInCal = setTimestampInCalendar(ts, Calendar.getInstance(zone)); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/SpannerJdbcExceptionMatcher.java b/src/test/java/com/google/cloud/spanner/jdbc/SpannerJdbcExceptionMatcher.java index be5fed233..062a5ac42 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/SpannerJdbcExceptionMatcher.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/SpannerJdbcExceptionMatcher.java @@ -30,7 +30,7 @@ public static SpannerJdbcExceptionMatcher matchC Class exceptionClass, Code errorCode) { Preconditions.checkNotNull(exceptionClass); Preconditions.checkNotNull(errorCode); - return new SpannerJdbcExceptionMatcher(exceptionClass, errorCode, null); + return new SpannerJdbcExceptionMatcher<>(exceptionClass, errorCode, null); } public static SpannerJdbcExceptionMatcher matchCodeAndMessage( @@ -38,7 +38,7 @@ public static SpannerJdbcExceptionMatcher matchC Preconditions.checkNotNull(exceptionClass); Preconditions.checkNotNull(errorCode); Preconditions.checkNotNull(message); - return new SpannerJdbcExceptionMatcher(exceptionClass, errorCode, message); + return new SpannerJdbcExceptionMatcher<>(exceptionClass, errorCode, message); } private SpannerJdbcExceptionMatcher(Class exceptionClass, Code errorCode, String message) { diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcConnectTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcConnectTest.java index 6d7cd0622..3626e4594 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcConnectTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcConnectTest.java @@ -25,6 +25,7 @@ import com.google.cloud.spanner.jdbc.CloudSpannerJdbcConnection; import com.google.cloud.spanner.jdbc.ITAbstractJdbcTest; import com.google.cloud.spanner.jdbc.JdbcDataSource; +import com.google.cloud.spanner.testing.EmulatorSpannerHelper; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; @@ -55,11 +56,11 @@ public class ITJdbcConnectTest extends ITAbstractJdbcTest { private String createBaseUrl() { StringBuilder url = new StringBuilder("jdbc:cloudspanner:"); - if (env.getTestHelper().isEmulator()) { + if (EmulatorSpannerHelper.isUsingEmulator()) { url.append("//").append(System.getenv("SPANNER_EMULATOR_HOST")); } url.append("/").append(getDatabase().getId().getName()); - if (env.getTestHelper().isEmulator()) { + if (EmulatorSpannerHelper.isUsingEmulator()) { url.append(";usePlainText=true"); } return url.toString(); @@ -174,7 +175,7 @@ public void testConnectWithDataSourceWithDefaultValues() throws SQLException { public void testConnectWithDataSourceWithNonDefaultValues() throws SQLException { JdbcDataSource ds = new JdbcDataSource(); ds.setUrl(createBaseUrl()); - if (hasValidKeyFile() && !env.getTestHelper().isEmulator()) { + if (hasValidKeyFile() && !EmulatorSpannerHelper.isUsingEmulator()) { ds.setCredentials(getKeyFile()); } ds.setAutocommit(false); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcDdlTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcDdlTest.java index c559bb3fc..abc14e35d 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcDdlTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcDdlTest.java @@ -33,6 +33,6 @@ public class ITJdbcDdlTest extends ITAbstractJdbcTest { @Test public void testSqlScript() throws Exception { JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new ITJdbcConnectionProvider()); - verifier.verifyStatementsInFile("ITDdlTest.sql", SqlScriptVerifier.class); + verifier.verifyStatementsInFile("ITDdlTest.sql", SqlScriptVerifier.class, false); } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcPreparedStatementTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcPreparedStatementTest.java index 24a9e01f4..bdc35b079 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcPreparedStatementTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcPreparedStatementTest.java @@ -53,6 +53,7 @@ import java.util.Arrays; import java.util.Calendar; import java.util.List; +import java.util.Objects; import java.util.Scanner; import java.util.TimeZone; import java.util.UUID; @@ -81,7 +82,7 @@ private static Singer of(String values) { throw new IllegalArgumentException(values); } return new Singer( - Long.valueOf(array[0]), // singer id + Long.parseLong(array[0]), // singer id array[1].substring(1, array[1].length() - 1), // first name array[2].substring(1, array[2].length() - 1), // last name parseBytes(array[3].substring(13, array[3].length() - 2)), // singer info @@ -111,10 +112,10 @@ private static Album of(String values) { throw new IllegalArgumentException(values); } return new Album( - Long.valueOf(array[0]), // singer id - Long.valueOf(array[1]), // album id + Long.parseLong(array[0]), // singer id + Long.parseLong(array[1]), // album id array[2].substring(1, array[2].length() - 1), // album title - Long.valueOf(array[3]) // marketing budget + Long.parseLong(array[3]) // marketing budget ); } @@ -140,11 +141,11 @@ private static Song of(String values) { throw new IllegalArgumentException(values); } return new Song( - Long.valueOf(array[0]), // singer id - Long.valueOf(array[1]), // album id - Long.valueOf(array[2]), // song id + Long.parseLong(array[0]), // singer id + Long.parseLong(array[1]), // album id + Long.parseLong(array[2]), // song id array[3].substring(1, array[3].length() - 1), // song name - Long.valueOf(array[4]), // duration + Long.parseLong(array[4]), // duration array[5].substring(1, array[5].length() - 1)); } @@ -173,14 +174,14 @@ private static final class Concert { private final Long[] ticketPrices; private static Concert of(String values) { - values = values.replaceAll("\\[(\\d+),(\\d+),(\\d+),(\\d+)\\]", "[$1;$2;$3;$4]"); + values = values.replaceAll("\\[(\\d+),(\\d+),(\\d+),(\\d+)]", "[$1;$2;$3;$4]"); String[] array = values.split(","); if (array.length != 6) { throw new IllegalArgumentException(values); } return new Concert( - Long.valueOf(array[0]), // venue id - Long.valueOf(array[1]), // singer id + Long.parseLong(array[0]), // venue id + Long.parseLong(array[1]), // singer id parseDate(array[2].substring(6, array[2].length() - 1)), // concert date parseTimestamp(array[3].substring(11, array[3].length() - 1)), // begin time parseTimestamp(array[4].substring(11, array[4].length() - 1)), // end time @@ -421,17 +422,17 @@ public void test03_Dates() throws SQLException { // requested timezone) should be returned. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); - cal.set(2015, 10, 15, 10, 0, 0); + cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0); testDates.add(new Date(cal.getTimeInMillis())); cal = Calendar.getInstance(TimeZone.getTimeZone("CET")); cal.clear(); - cal.set(2015, 10, 15, 10, 0, 0); + cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0); testDates.add(new Date(cal.getTimeInMillis())); cal = Calendar.getInstance(TimeZone.getTimeZone("PST")); cal.clear(); - cal.set(2015, 10, 15, 10, 0, 0); + cal.set(2015, Calendar.NOVEMBER, 15, 10, 0, 0); testDates.add(new Date(cal.getTimeInMillis())); List calendars = new ArrayList<>(); @@ -503,17 +504,6 @@ public void test04_Timestamps() throws SQLException { expectedValues.add("2015-11-15 10:00:00"); expectedValues.add("2015-11-15 10:00:00"); - List timezones = new ArrayList<>(); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getDefault()); - timezones.add(TimeZone.getTimeZone("UTC")); - timezones.add(TimeZone.getTimeZone("CET")); - timezones.add(TimeZone.getTimeZone("PST")); - List testTimestamps = new ArrayList<>(); testTimestamps.add(Timestamp.valueOf(expectedValues.get(0))); testTimestamps.add(Timestamp.valueOf(expectedValues.get(1))); @@ -526,17 +516,17 @@ public void test04_Timestamps() throws SQLException { // format. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); - cal.set(2015, 10, 15); + cal.set(2015, Calendar.NOVEMBER, 15); testTimestamps.add(new Timestamp(cal.getTimeInMillis())); cal = Calendar.getInstance(TimeZone.getTimeZone("CET")); cal.clear(); - cal.set(2015, 10, 15); + cal.set(2015, Calendar.NOVEMBER, 15); testTimestamps.add(new Timestamp(cal.getTimeInMillis())); cal = Calendar.getInstance(TimeZone.getTimeZone("PST")); cal.clear(); - cal.set(2015, 10, 15); + cal.set(2015, Calendar.NOVEMBER, 15); testTimestamps.add(new Timestamp(cal.getTimeInMillis())); List calendars = new ArrayList<>(); @@ -1063,14 +1053,13 @@ private void assertDefaultParameterMetaData(ParameterMetaData pmd, int expectedP } private List readValuesFromFile(String filename) { - File file = new File(getClass().getResource(filename).getFile()); + File file = new File(Objects.requireNonNull(getClass().getResource(filename)).getFile()); StringBuilder builder = new StringBuilder(); try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); builder.append(line).append("\n"); } - scanner.close(); } catch (FileNotFoundException e) { throw new RuntimeException(e); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcQueryOptionsTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcQueryOptionsTest.java index 990331074..1c01ce2fa 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcQueryOptionsTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcQueryOptionsTest.java @@ -34,6 +34,7 @@ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import javax.annotation.Nonnull; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -187,11 +188,13 @@ public void testOptionsInEnvironment() throws SQLException { try { SpannerOptions.useEnvironment( new SpannerOptions.SpannerEnvironment() { + @Nonnull @Override public String getOptimizerVersion() { return "1"; } + @Nonnull @Override public String getOptimizerStatisticsPackage() { return "latest"; @@ -212,11 +215,13 @@ public String getOptimizerStatisticsPackage() { // Now set an invalid version on the environment. The query will now fail. SpannerOptions.useEnvironment( new SpannerOptions.SpannerEnvironment() { + @Nonnull @Override public String getOptimizerVersion() { return "9999999"; } + @Nonnull @Override public String getOptimizerStatisticsPackage() { return "latest"; diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadOnlyTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadOnlyTest.java index 0e5a2f91a..5fef9dbf1 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadOnlyTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadOnlyTest.java @@ -16,6 +16,8 @@ package com.google.cloud.spanner.jdbc.it; +import static org.junit.Assert.assertTrue; + import com.google.cloud.spanner.Mutation; import com.google.cloud.spanner.ParallelIntegrationTest; import com.google.cloud.spanner.connection.ConnectionOptions; @@ -54,7 +56,7 @@ public void createTestTables() throws Exception { // create tables JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new ITJdbcConnectionProvider()); verifier.verifyStatementsInFile( - "ITReadOnlySpannerTest_CreateTables.sql", SqlScriptVerifier.class); + "ITReadOnlySpannerTest_CreateTables.sql", SqlScriptVerifier.class, false); // fill tables with data connection.setAutoCommit(false); @@ -94,7 +96,7 @@ public void testSqlScript() throws Exception { // Wait 100ms to ensure that staleness tests in the script succeed. Thread.sleep(100L); JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new ITJdbcConnectionProvider()); - verifier.verifyStatementsInFile("ITReadOnlySpannerTest.sql", SqlScriptVerifier.class); + verifier.verifyStatementsInFile("ITReadOnlySpannerTest.sql", SqlScriptVerifier.class, false); } @Test @@ -106,29 +108,27 @@ public void testMultipleOpenResultSets() throws InterruptedException, SQLExcepti connection.createStatement().executeQuery("SELECT * FROM NUMBERS"); ExecutorService exec = Executors.newFixedThreadPool(2); exec.submit( - new Runnable() { - @Override - public void run() { - try { - while (rs1.next()) {} - } catch (SQLException e) { - throw new RuntimeException(e); + () -> { + try { + while (rs1.next()) { + assertTrue(rs1.getInt(1) > 0); } + } catch (SQLException e) { + throw new RuntimeException(e); } }); exec.submit( - new Runnable() { - @Override - public void run() { - try { - while (rs2.next()) {} - } catch (SQLException e) { - throw new RuntimeException(e); + () -> { + try { + while (rs2.next()) { + assertTrue(rs2.getInt(1) > 0); } + } catch (SQLException e) { + throw new RuntimeException(e); } }); exec.shutdown(); - exec.awaitTermination(1000L, TimeUnit.SECONDS); + assertTrue(exec.awaitTermination(1000L, TimeUnit.SECONDS)); rs1.close(); rs2.close(); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadWriteAutocommitTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadWriteAutocommitTest.java index d72992aec..b620f5a7f 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadWriteAutocommitTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcReadWriteAutocommitTest.java @@ -52,7 +52,7 @@ public boolean doCreateDefaultTestTable() { public void test01_SqlScript() throws Exception { JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(new ITJdbcConnectionProvider()); verifier.verifyStatementsInFile( - "ITReadWriteAutocommitSpannerTest.sql", SqlScriptVerifier.class); + "ITReadWriteAutocommitSpannerTest.sql", SqlScriptVerifier.class, false); } @Test diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSimpleStatementsTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSimpleStatementsTest.java index 079384934..4a8dab592 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSimpleStatementsTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSimpleStatementsTest.java @@ -186,7 +186,7 @@ public void testSelectArrayOfStructs() throws SQLException { Struct.newBuilder().set("point").to(Value.int64Array(new long[] {5L, 7L})).build()); // Getting a result set from an array of structs is not supported, as structs are not // supported as a valid column type in a result set. - assertThrows(SQLFeatureNotSupportedException.class, () -> array.getResultSet()); + assertThrows(SQLFeatureNotSupportedException.class, array::getResultSet); assertFalse(resultSet.next()); } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlMusicScriptTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlMusicScriptTest.java index 31b8394ad..f3dfb8489 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlMusicScriptTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlMusicScriptTest.java @@ -37,7 +37,7 @@ public void testRunScript() throws Exception { JdbcSqlScriptVerifier verifier = new JdbcSqlScriptVerifier(); try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), SCRIPT_FILE, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), SCRIPT_FILE, SqlScriptVerifier.class, false); } } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlScriptTest.java b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlScriptTest.java index fdb752965..344177c60 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlScriptTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/it/ITJdbcSqlScriptTest.java @@ -28,6 +28,7 @@ import com.google.cloud.spanner.jdbc.ITAbstractJdbcTest; import com.google.cloud.spanner.jdbc.JdbcSqlScriptVerifier; import com.google.cloud.spanner.jdbc.JdbcSqlScriptVerifier.JdbcGenericConnection; +import com.google.cloud.spanner.testing.EmulatorSpannerHelper; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -76,7 +77,7 @@ public class ITJdbcSqlScriptTest extends ITAbstractJdbcTest { public void test01_CreateTables() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), CREATE_TABLES_FILE, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), CREATE_TABLES_FILE, SqlScriptVerifier.class, false); } } @@ -87,17 +88,21 @@ public void test02_InsertTestData() throws Exception { verifier.verifyStatementsInFile( JdbcGenericConnection.of(connection), INSERT_AND_VERIFY_TEST_DATA, - SqlScriptVerifier.class); + SqlScriptVerifier.class, + false); } catch (SQLException e) { - if (env.getTestHelper().isEmulator() - && e.getErrorCode() == ErrorCode.ALREADY_EXISTS.getGrpcStatusCode().value()) { - // Ignore, this is expected as errors during a read/write transaction are sticky on the - // emulator. + // Ignore these errors on the emulator, as they are sticky during a read/write transaction on + // the emulator. + if (!(EmulatorSpannerHelper.isUsingEmulator() + && e.getErrorCode() == ErrorCode.ALREADY_EXISTS.getGrpcStatusCode().value())) { + throw e; } } catch (SpannerException e) { - if (env.getTestHelper().isEmulator() && e.getErrorCode() == ErrorCode.ALREADY_EXISTS) { - // Ignore, this is expected as errors during a read/write transaction are sticky on the - // emulator. + // Ignore these errors on the emulator, as they are sticky during a read/write transaction on + // the emulator. + if (!(EmulatorSpannerHelper.isUsingEmulator() + && e.getErrorCode() == ErrorCode.ALREADY_EXISTS)) { + throw e; } } } @@ -106,7 +111,10 @@ public void test02_InsertTestData() throws Exception { public void test03_TestGetReadTimestamp() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_GET_READ_TIMESTAMP, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_GET_READ_TIMESTAMP, + SqlScriptVerifier.class, + false); } } @@ -114,16 +122,23 @@ public void test03_TestGetReadTimestamp() throws Exception { public void test04_TestGetCommitTimestamp() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_GET_COMMIT_TIMESTAMP, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_GET_COMMIT_TIMESTAMP, + SqlScriptVerifier.class, + false); } catch (SQLException e) { - if (env.getTestHelper().isEmulator() - && e.getErrorCode() == ErrorCode.INVALID_ARGUMENT.getGrpcStatusCode().value()) { - // Ignore as errors during read/write transactions are sticky on the emulator. + // Ignore these errors on the emulator, as they are sticky during a read/write transaction on + // the emulator. + if (!(EmulatorSpannerHelper.isUsingEmulator() + && e.getErrorCode() == ErrorCode.INVALID_ARGUMENT.getGrpcStatusCode().value())) { + throw e; } } catch (SpannerException e) { - if (env.getTestHelper().isEmulator() && e.getErrorCode() == ErrorCode.ALREADY_EXISTS) { - // Ignore, this is expected as errors during a read/write transaction are sticky on the - // emulator. + // Ignore these errors on the emulator, as they are sticky during a read/write transaction on + // the emulator. + if (!(EmulatorSpannerHelper.isUsingEmulator() + && e.getErrorCode() == ErrorCode.ALREADY_EXISTS)) { + throw e; } } } @@ -134,7 +149,8 @@ public void test05_TestTemporaryTransactions() throws Exception { verifier.verifyStatementsInFile( JdbcGenericConnection.of(connection), TEST_TEMPORARY_TRANSACTIONS, - SqlScriptVerifier.class); + SqlScriptVerifier.class, + false); } } @@ -142,7 +158,10 @@ public void test05_TestTemporaryTransactions() throws Exception { public void test06_TestTransactionMode() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_TRANSACTION_MODE, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_TRANSACTION_MODE, + SqlScriptVerifier.class, + false); } } @@ -152,7 +171,8 @@ public void test07_TestTransactionModeReadOnly() throws Exception { verifier.verifyStatementsInFile( JdbcGenericConnection.of(connection), TEST_TRANSACTION_MODE_READ_ONLY, - SqlScriptVerifier.class); + SqlScriptVerifier.class, + false); } } @@ -160,7 +180,10 @@ public void test07_TestTransactionModeReadOnly() throws Exception { public void test08_TestReadOnlyStaleness() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_READ_ONLY_STALENESS, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_READ_ONLY_STALENESS, + SqlScriptVerifier.class, + false); } } @@ -168,7 +191,10 @@ public void test08_TestReadOnlyStaleness() throws Exception { public void test09_TestAutocommitDmlMode() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_AUTOCOMMIT_DML_MODE, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_AUTOCOMMIT_DML_MODE, + SqlScriptVerifier.class, + false); } } @@ -176,7 +202,10 @@ public void test09_TestAutocommitDmlMode() throws Exception { public void test10_TestAutocommitReadOnly() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_AUTOCOMMIT_READ_ONLY, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_AUTOCOMMIT_READ_ONLY, + SqlScriptVerifier.class, + false); } } @@ -184,7 +213,10 @@ public void test10_TestAutocommitReadOnly() throws Exception { public void test11_TestStatementTimeout() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_STATEMENT_TIMEOUT, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_STATEMENT_TIMEOUT, + SqlScriptVerifier.class, + false); } try (Connection connection = createConnection()) { // Create a statement with a query timeout, but do not set a statement timeout on the @@ -222,7 +254,10 @@ public void test11_TestStatementTimeout() throws Exception { public void test12_TestSetStatements() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_SET_STATEMENTS, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_SET_STATEMENTS, + SqlScriptVerifier.class, + false); } } @@ -230,7 +265,10 @@ public void test12_TestSetStatements() throws Exception { public void test13_TestInvalidStatements() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_INVALID_STATEMENTS, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), + TEST_INVALID_STATEMENTS, + SqlScriptVerifier.class, + false); } } @@ -238,7 +276,7 @@ public void test13_TestInvalidStatements() throws Exception { public void test14_TestQueryOptions() throws Exception { try (Connection connection = createConnection()) { verifier.verifyStatementsInFile( - JdbcGenericConnection.of(connection), TEST_QUERY_OPTIONS, SqlScriptVerifier.class); + JdbcGenericConnection.of(connection), TEST_QUERY_OPTIONS, SqlScriptVerifier.class, false); } } } From bb982de3a0946ab8d7ca0521032eb239b9206da4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Knut=20Olav=20L=C3=B8ite?= Date: Thu, 4 Nov 2021 12:07:30 +0100 Subject: [PATCH 04/11] test(deps): update dependency org.mockito:mockito-core to v4 (#658) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 899673f1f..ac3142a2c 100644 --- a/pom.xml +++ b/pom.xml @@ -53,7 +53,7 @@ 3.0.2 1.4.4 1.1.3 - 3.12.4 + 4.0.0 2.2 From 87975982cbbb95c6e5c3132761510b3ad42b3347 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 4 Nov 2021 21:16:17 +0000 Subject: [PATCH 05/11] chore(java): remove pin on Apache Maven 3.8.1 from github actions (#1268) (#659) --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/ci.yaml | 17 +---------------- 2 files changed, 2 insertions(+), 17 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 0df65ebe9..5a79fcd57 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-java:latest - digest: sha256:a3ac08d167454718ff057b97a1950d3cb5e16fc39fb3f355d90276285a6cac75 + digest: sha256:ed012741acaae5d03e011244585a1f0625a596d31568967d77772aa5a0a51d5e diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2425d7234..d95a11a26 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -12,9 +12,6 @@ jobs: java: [8, 11, 17] steps: - uses: actions/checkout@v2 - - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.8.1 - uses: actions/setup-java@v2 with: distribution: zulu @@ -27,9 +24,6 @@ jobs: runs-on: windows-latest steps: - uses: actions/checkout@v2 - - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.8.1 - uses: actions/setup-java@v2 with: distribution: zulu @@ -45,9 +39,6 @@ jobs: java: [8, 11, 17] steps: - uses: actions/checkout@v2 - - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.8.1 - uses: actions/setup-java@v2 with: distribution: zulu @@ -58,9 +49,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.8.1 - uses: actions/setup-java@v2 with: distribution: zulu @@ -73,9 +61,6 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - - uses: stCarolas/setup-maven@v4 - with: - maven-version: 3.8.1 - uses: actions/setup-java@v2 with: distribution: zulu @@ -83,4 +68,4 @@ jobs: - run: java -version - run: .kokoro/build.sh env: - JOB_TYPE: clirr + JOB_TYPE: clirr \ No newline at end of file From 3105704b4bc8ff87adc7ac14667609c1a154ba6a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 6 Nov 2021 00:34:16 +0000 Subject: [PATCH 06/11] Update ci.yaml (#1275) (#660) --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/ci.yaml | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 5a79fcd57..994dd04bf 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-java:latest - digest: sha256:ed012741acaae5d03e011244585a1f0625a596d31568967d77772aa5a0a51d5e + digest: sha256:fecf6bd85f19eb046d913982ea36f6d434f9a49ab0545d25e31186aa64367c0c diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index d95a11a26..93b337c62 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -8,6 +8,7 @@ jobs: units: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: java: [8, 11, 17] steps: @@ -68,4 +69,4 @@ jobs: - run: java -version - run: .kokoro/build.sh env: - JOB_TYPE: clirr \ No newline at end of file + JOB_TYPE: clirr From cd2c03ce3b52c788aa4d7b6067985176ed5a5489 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 8 Nov 2021 21:52:19 +0000 Subject: [PATCH 07/11] chore: cleanup cloud RAD generation (#1269) (#661) --- .github/.OwlBot.lock.yaml | 2 +- .kokoro/release/publish_javadoc11.sh | 10 +++------- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 994dd04bf..325daaa4b 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-java:latest - digest: sha256:fecf6bd85f19eb046d913982ea36f6d434f9a49ab0545d25e31186aa64367c0c + digest: sha256:204b7af96e6d481f19b0ff377aa379d46bc56dd06e1cc7c523f361dd9cbfeeaa diff --git a/.kokoro/release/publish_javadoc11.sh b/.kokoro/release/publish_javadoc11.sh index 3b65375ef..49678864c 100755 --- a/.kokoro/release/publish_javadoc11.sh +++ b/.kokoro/release/publish_javadoc11.sh @@ -36,13 +36,9 @@ mvn clean install -B -q -DskipTests=true export NAME=google-cloud-spanner-jdbc export VERSION=$(grep ${NAME}: versions.txt | cut -d: -f3) -# V3 generates docfx yml from javadoc -# generate yml -mvn clean site -B -q -P docFX - -# copy README to docfx-yml dir and rename index.md -cp README.md target/docfx-yml/index.md -# copy CHANGELOG to docfx-yml dir and rename history.md +# cloud RAD generation +mvn clean javadoc:aggregate -B -q -P docFX +# include CHANGELOG cp CHANGELOG.md target/docfx-yml/history.md pushd target/docfx-yml From 9e57dc41e737de1f2853dd2edd645efa6b50fdbc Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Tue, 9 Nov 2021 00:22:25 +0100 Subject: [PATCH 08/11] build(deps): update dependency com.google.cloud:google-cloud-shared-config to v1.2.1 (#662) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [![WhiteSource Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | [com.google.cloud:google-cloud-shared-config](https://togithub.com/googleapis/java-shared-config) | `1.2.0` -> `1.2.1` | [![age](https://badges.renovateapi.com/packages/maven/com.google.cloud:google-cloud-shared-config/1.2.1/age-slim)](https://docs.renovatebot.com/merge-confidence/) | [![adoption](https://badges.renovateapi.com/packages/maven/com.google.cloud:google-cloud-shared-config/1.2.1/adoption-slim)](https://docs.renovatebot.com/merge-confidence/) | [![passing](https://badges.renovateapi.com/packages/maven/com.google.cloud:google-cloud-shared-config/1.2.1/compatibility-slim/1.2.0)](https://docs.renovatebot.com/merge-confidence/) | [![confidence](https://badges.renovateapi.com/packages/maven/com.google.cloud:google-cloud-shared-config/1.2.1/confidence-slim/1.2.0)](https://docs.renovatebot.com/merge-confidence/) | --- ### Release Notes
    googleapis/java-shared-config ### [`v1.2.1`](https://togithub.com/googleapis/java-shared-config/blob/master/CHANGELOG.md#​121-httpswwwgithubcomgoogleapisjava-shared-configcomparev120v121-2021-11-08) [Compare Source](https://togithub.com/googleapis/java-shared-config/compare/v1.2.0...v1.2.1)
    --- ### Configuration 📅 **Schedule**: At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] If you want to rebase/retry this PR, click this checkbox. --- This PR has been generated by [WhiteSource Renovate](https://renovate.whitesourcesoftware.com). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/java-spanner-jdbc). --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index ac3142a2c..40bbbab63 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ com.google.cloud google-cloud-shared-config - 1.2.0 + 1.2.1 From c0e2237f2b1a5879b92dd290290f4f90251757cd Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 9 Nov 2021 14:46:21 +0000 Subject: [PATCH 09/11] chore: update jre to 11 for linter (#1278) (#663) --- .github/.OwlBot.lock.yaml | 2 +- .github/workflows/ci.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 325daaa4b..886d09496 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,3 @@ docker: image: gcr.io/cloud-devrel-public-resources/owlbot-java:latest - digest: sha256:204b7af96e6d481f19b0ff377aa379d46bc56dd06e1cc7c523f361dd9cbfeeaa + digest: sha256:14ecf64ec36f67c7bf04e3dc0f68eafcc01df3955121c38862b695e2ae7515d8 diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 93b337c62..05de1f60d 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -53,7 +53,7 @@ jobs: - uses: actions/setup-java@v2 with: distribution: zulu - java-version: 8 + java-version: 11 - run: java -version - run: .kokoro/build.sh env: From 9f22c331ee4c7340ed6f1b9f91a44ce1e4c5b792 Mon Sep 17 00:00:00 2001 From: WhiteSource Renovate Date: Thu, 11 Nov 2021 04:01:43 +0100 Subject: [PATCH 10/11] deps: update dependency com.google.cloud:google-cloud-spanner-bom to v6.15.2 (#664) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 40bbbab63..a1d0fc23e 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,7 @@ com.google.cloud google-cloud-spanner-bom - 6.15.1 + 6.15.2 pom import From 26edf64f77cb474fdf900d01820cbd30a337e775 Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Thu, 11 Nov 2021 03:08:18 +0000 Subject: [PATCH 11/11] chore: release 2.5.2 (#665) :robot: I have created a release \*beep\* \*boop\* --- ### [2.5.2](https://www.github.com/googleapis/java-spanner-jdbc/compare/v2.5.1...v2.5.2) (2021-11-11) ### Dependencies * update dependency com.google.cloud:google-cloud-spanner-bom to v6.15.2 ([#664](https://www.github.com/googleapis/java-spanner-jdbc/issues/664)) ([9f22c33](https://www.github.com/googleapis/java-spanner-jdbc/commit/9f22c331ee4c7340ed6f1b9f91a44ce1e4c5b792)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). --- CHANGELOG.md | 7 +++++++ pom.xml | 2 +- samples/snapshot/pom.xml | 2 +- versions.txt | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83b7e7d84..c884c7f4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +### [2.5.2](https://www.github.com/googleapis/java-spanner-jdbc/compare/v2.5.1...v2.5.2) (2021-11-11) + + +### Dependencies + +* update dependency com.google.cloud:google-cloud-spanner-bom to v6.15.2 ([#664](https://www.github.com/googleapis/java-spanner-jdbc/issues/664)) ([9f22c33](https://www.github.com/googleapis/java-spanner-jdbc/commit/9f22c331ee4c7340ed6f1b9f91a44ce1e4c5b792)) + ### [2.5.1](https://www.github.com/googleapis/java-spanner-jdbc/compare/v2.5.0...v2.5.1) (2021-10-27) diff --git a/pom.xml b/pom.xml index a1d0fc23e..8df06d811 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 google-cloud-spanner-jdbc - 2.5.2-SNAPSHOT + 2.5.2 jar Google Cloud Spanner JDBC https://github.com/googleapis/java-spanner-jdbc diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index 6dd2b3033..2a3757e2e 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -28,7 +28,7 @@ com.google.cloud google-cloud-spanner-jdbc - 2.5.2-SNAPSHOT + 2.5.2 diff --git a/versions.txt b/versions.txt index 00a220568..bf290eb99 100644 --- a/versions.txt +++ b/versions.txt @@ -1,4 +1,4 @@ # Format: # module:released-version:current-version -google-cloud-spanner-jdbc:2.5.1:2.5.2-SNAPSHOT +google-cloud-spanner-jdbc:2.5.2:2.5.2