diff --git a/.github/workflows/unmanaged_dependency_check.yaml b/.github/workflows/unmanaged_dependency_check.yaml index 6b4a8e5c5..fdc1fa6a6 100644 --- a/.github/workflows/unmanaged_dependency_check.yaml +++ b/.github/workflows/unmanaged_dependency_check.yaml @@ -14,6 +14,6 @@ jobs: shell: bash run: .kokoro/build.sh - name: Unmanaged dependency check - uses: googleapis/sdk-platform-java/java-shared-dependencies/unmanaged-dependency-check@google-cloud-shared-dependencies/v3.45.1 + uses: googleapis/sdk-platform-java/java-shared-dependencies/unmanaged-dependency-check@google-cloud-shared-dependencies/v3.46.0 with: bom-path: pom.xml diff --git a/.kokoro/build.sh b/.kokoro/build.sh index f4ea82a43..236faa2ad 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -76,6 +76,8 @@ integration) -DtrimStackTrace=false \ -Dclirr.skip=true \ -Denforcer.skip=true \ + -Dspanner.testenv.instance=projects/span-cloud-testing/instances/java-client-integration-test \ + -Dspanner.gce.config.project_id=span-cloud-testing \ -fae \ verify RETURN_CODE=$? diff --git a/.kokoro/presubmit/graalvm-native-17.cfg b/.kokoro/presubmit/graalvm-native-17.cfg index 07ae08a98..ed336a5a8 100644 --- a/.kokoro/presubmit/graalvm-native-17.cfg +++ b/.kokoro/presubmit/graalvm-native-17.cfg @@ -3,7 +3,7 @@ # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-public-resources/graalvm_sdk_platform_b:3.45.1" + value: "gcr.io/cloud-devrel-public-resources/graalvm_sdk_platform_b:3.46.0" } env_vars: { diff --git a/.kokoro/presubmit/graalvm-native.cfg b/.kokoro/presubmit/graalvm-native.cfg index fb1979a33..4477760a6 100644 --- a/.kokoro/presubmit/graalvm-native.cfg +++ b/.kokoro/presubmit/graalvm-native.cfg @@ -3,7 +3,7 @@ # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-public-resources/graalvm_sdk_platform_a:3.45.1" + value: "gcr.io/cloud-devrel-public-resources/graalvm_sdk_platform_a:3.46.0" } env_vars: { diff --git a/.kokoro/presubmit/integration.cfg b/.kokoro/presubmit/integration.cfg index 5864c603e..929a8b346 100644 --- a/.kokoro/presubmit/integration.cfg +++ b/.kokoro/presubmit/integration.cfg @@ -11,24 +11,13 @@ env_vars: { value: "integration" } -# TODO: remove this after we've migrated all tests and scripts -env_vars: { - key: "GCLOUD_PROJECT" - value: "gcloud-devel" -} - -env_vars: { - key: "GOOGLE_CLOUD_PROJECT" - value: "gcloud-devel" -} - env_vars: { key: "GOOGLE_APPLICATION_CREDENTIALS" - value: "secret_manager/java-it-service-account" + value: "secret_manager/java-client-testing" } env_vars: { key: "SECRET_MANAGER_KEYS" - value: "java-it-service-account" + value: "java-client-testing" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ef8ddf1f..711575150 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## [2.29.0](https://github.com/googleapis/java-spanner-jdbc/compare/v2.28.0...v2.29.0) (2025-04-22) + + +### Features + +* Support isolation level repeatable read ([#1973](https://github.com/googleapis/java-spanner-jdbc/issues/1973)) ([010a502](https://github.com/googleapis/java-spanner-jdbc/commit/010a502310db88f8c676960c641a7e9a6581bf11)) + + +### Dependencies + +* Update dependency com.google.cloud:google-cloud-spanner-bom to v6.90.0 ([#1970](https://github.com/googleapis/java-spanner-jdbc/issues/1970)) ([7153c39](https://github.com/googleapis/java-spanner-jdbc/commit/7153c39464fd9b83609bb7cc2ada5c0f9aab3af8)) +* Update dependency com.google.cloud:google-cloud-spanner-bom to v6.91.1 ([#1993](https://github.com/googleapis/java-spanner-jdbc/issues/1993)) ([97d4840](https://github.com/googleapis/java-spanner-jdbc/commit/97d4840bd3e7cee7f1ddb9b26f3946f1b10ed894)) +* Update dependency com.google.cloud:sdk-platform-java-config to v3.46.0 ([#1992](https://github.com/googleapis/java-spanner-jdbc/issues/1992)) ([ea0b557](https://github.com/googleapis/java-spanner-jdbc/commit/ea0b55729d1bf9e8b5994758314841591ea0c883)) +* Update dependency io.opentelemetry:opentelemetry-bom to v1.49.0 ([#1982](https://github.com/googleapis/java-spanner-jdbc/issues/1982)) ([6b7ddf4](https://github.com/googleapis/java-spanner-jdbc/commit/6b7ddf4352d4db87eab6d9f3fd4945e5650e7798)) +* Update dependency org.springframework.data:spring-data-bom to v2024.1.5 ([#1995](https://github.com/googleapis/java-spanner-jdbc/issues/1995)) ([6bedf12](https://github.com/googleapis/java-spanner-jdbc/commit/6bedf124b9da233e6f4001dff2c1b56f0249aaad)) + ## [2.28.0](https://github.com/googleapis/java-spanner-jdbc/compare/v2.27.1...v2.28.0) (2025-03-21) diff --git a/README.md b/README.md index 53eaa1408..0ed64c571 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ If you are using Maven, add this to your pom.xml file: com.google.cloud google-cloud-spanner-jdbc - 2.28.0 + 2.29.0 ``` @@ -30,7 +30,7 @@ If you are using Gradle without BOM, add this to your dependencies ```Groovy -implementation 'com.google.cloud:google-cloud-spanner-jdbc:2.28.0' +implementation 'com.google.cloud:google-cloud-spanner-jdbc:2.29.0' ``` @@ -38,7 +38,7 @@ If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-spanner-jdbc" % "2.28.0" +libraryDependencies += "com.google.cloud" % "google-cloud-spanner-jdbc" % "2.29.0" ``` diff --git a/documentation/connection_properties.md b/documentation/connection_properties.md index abc908842..cedb01d04 100644 --- a/documentation/connection_properties.md +++ b/documentation/connection_properties.md @@ -10,7 +10,7 @@ The 'Context' value indicates whether the property can only be set when a connec | auto_batch_dml_update_count | DML statements that are executed when auto_batch_dml is set to true, are not directly sent to Spanner, but are buffered in the client until the batch is flushed. This property determines the update count that is returned for these DML statements. The default is 1, as that is the update count that is expected by most ORMs (e.g. Hibernate). | 1 | | USER | | auto_batch_dml_update_count_verification | The update count that is returned for DML statements that are buffered during an automatic DML batch is by default 1. This value can be changed by setting the connection variable auto_batch_dml_update_count. The update counts that are returned by Spanner when the DML statements are actually executed are verified against the update counts that were returned when they were buffered. If these do not match, a com.google.cloud.spanner.DmlBatchUpdateCountVerificationFailedException will be thrown. You can disable this verification by setting auto_batch_dml_update_count_verification to false. | true | true, false | USER | | autocommit | Should the connection start in autocommit (true/false) | true | true, false | USER | -| autocommit_dml_mode | Determines the transaction type that is used to execute DML statements when the connection is in auto-commit mode. | TRANSACTIONAL | TRANSACTIONAL, PARTITIONED_NON_ATOMIC, TRANSACTIONAL_WITH_FALLBACK_TO_PARTITIONED_NON_ATOMIC | USER | +| autocommit_dml_mode | Determines the transaction type that is used to execute DML statements when the connection is in auto-commit mode. | TRANSACTIONAL | TRANSACTIONAL, PARTITIONED_NON_ATOMIC, TRANSACTIONAL_WITH_FALLBACK_TO_PARTITIONED_NON_ATOMIC, null | USER | | autoconfigemulator | Automatically configure the connection to try to connect to the Cloud Spanner emulator (true/false). The instance and database in the connection string will automatically be created if these do not yet exist on the emulator. Add dialect=postgresql to the connection string to make sure that the database that is created uses the PostgreSQL dialect. | false | true, false | STARTUP | | autopartitionmode | Execute all queries on this connection as partitioned queries. Executing a query that cannot be partitioned will fail. Executing a query in a read/write transaction will also fail. | false | true, false | USER | | channelprovider | The name of the channel provider class. The name must reference an implementation of ExternalChannelProvider. If this property is not set, the connection will use the default grpc channel provider. | | | STARTUP | @@ -22,6 +22,7 @@ The 'Context' value indicates whether the property can only be set when a connec | databaserole | Sets the database role to use for this connection. The default is privileges assigned to IAM role | | | STARTUP | | databoostenabled | Enable data boost for all partitioned queries that are executed by this connection. This setting is only used for partitioned queries and is ignored by all other statements. | false | true, false | USER | | ddlintransactionmode | Determines how the connection should handle DDL statements in a read/write transaction. | ALLOW_IN_EMPTY_TRANSACTION | FAIL, ALLOW_IN_EMPTY_TRANSACTION, AUTO_COMMIT_TRANSACTION | USER | +| default_isolation_level | The transaction isolation level that is used by default for read/write transactions. The default is isolation_level_unspecified, which means that the connection will use the default isolation level of the database that it is connected to. | ISOLATION_LEVEL_UNSPECIFIED | ISOLATION_LEVEL_UNSPECIFIED, SERIALIZABLE, REPEATABLE_READ | USER | | defaultsequencekind | The default sequence kind that should be used for the database. This property is only used when a DDL statement that requires a default sequence kind is executed on this connection. | | | USER | | delaytransactionstartuntilfirstwrite | Enabling this option will delay the actual start of a read/write transaction until the first write operation is seen in that transaction. All reads that happen before the first write in a transaction will instead be executed as if the connection was in auto-commit mode. Enabling this option will make read/write transactions lose their SERIALIZABLE isolation level. Read operations that are executed after the first write operation in a read/write transaction will be executed using the read/write transaction. Enabling this mode can reduce locking and improve performance for applications that can handle the lower transaction isolation semantics. | false | true, false | USER | | dialect | Sets the dialect to use for new databases that are created by this connection. | GOOGLE_STANDARD_SQL | GOOGLE_STANDARD_SQL, POSTGRESQL | STARTUP | @@ -48,7 +49,7 @@ The 'Context' value indicates whether the property can only be set when a connec | retryabortsinternally | Should the connection automatically retry Aborted errors (true/false) | true | true, false | USER | | returncommitstats | Request that Spanner returns commit statistics for read/write transactions (true/false) | false | true, false | USER | | routetoleader | Should read/write transactions and partitioned DML be routed to leader region (true/false) | true | true, false | STARTUP | -| rpcpriority | Sets the priority for all RPC invocations from this connection (HIGH/MEDIUM/LOW). The default is HIGH. | | LOW, MEDIUM, HIGH, UNSPECIFIED | USER | +| rpcpriority | Sets the priority for all RPC invocations from this connection (HIGH/MEDIUM/LOW). The default is HIGH. | | LOW, MEDIUM, HIGH, UNSPECIFIED, null | USER | | savepoint_support | Determines the behavior of the connection when savepoints are used. | FAIL_AFTER_ROLLBACK | ENABLED, FAIL_AFTER_ROLLBACK, DISABLED | USER | | tracing_prefix | The prefix that will be prepended to all OpenTelemetry traces that are generated by a Connection. | CloudSpanner | | STARTUP | | trackconnectionleaks | Capture the call stack of the thread that created a connection. This will pre-create a LeakedConnectionException already when a connection is created. This can be disabled, for example if a monitoring system logs the pre-created exception. If disabled, the LeakedConnectionException will only be created when an actual connection leak is detected. The stack trace of the exception will in that case not contain the call stack of when the connection was created. | true | true, false | STARTUP | diff --git a/pom.xml b/pom.xml index 16a221b07..2b5a38a57 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.28.0 + 2.29.0 jar Google Cloud Spanner JDBC https://github.com/googleapis/java-spanner-jdbc @@ -14,7 +14,7 @@ com.google.cloud sdk-platform-java-config - 3.45.1 + 3.46.0 @@ -61,7 +61,7 @@ com.google.cloud google-cloud-spanner-bom - 6.89.0 + 6.91.1 pom import diff --git a/samples/install-without-bom/pom.xml b/samples/install-without-bom/pom.xml index 8be01f537..86d3c5fb4 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.27.1 + 2.28.0 diff --git a/samples/quickperf/pom.xml b/samples/quickperf/pom.xml index f39aa299c..49ad5f842 100644 --- a/samples/quickperf/pom.xml +++ b/samples/quickperf/pom.xml @@ -12,7 +12,7 @@ com.google.cloud sdk-platform-java-config - 3.45.1 + 3.46.0 @@ -27,7 +27,7 @@ com.google.cloud libraries-bom - 26.56.0 + 26.59.0 pom import diff --git a/samples/snapshot/pom.xml b/samples/snapshot/pom.xml index f5f01ee07..a8ad559b3 100644 --- a/samples/snapshot/pom.xml +++ b/samples/snapshot/pom.xml @@ -29,7 +29,7 @@ com.google.cloud google-cloud-spanner-jdbc - 2.28.0 + 2.29.0 diff --git a/samples/snippets/pom.xml b/samples/snippets/pom.xml index 6224f029f..082c1993e 100644 --- a/samples/snippets/pom.xml +++ b/samples/snippets/pom.xml @@ -9,7 +9,7 @@ com.google.cloud sdk-platform-java-config - 3.45.1 + 3.46.0 @@ -26,7 +26,7 @@ com.google.cloud libraries-bom - 26.56.0 + 26.59.0 pom import diff --git a/samples/spring-data-jdbc/pom.xml b/samples/spring-data-jdbc/pom.xml index 6e2cbdf7e..9514cb50b 100644 --- a/samples/spring-data-jdbc/pom.xml +++ b/samples/spring-data-jdbc/pom.xml @@ -23,28 +23,28 @@ org.springframework.data spring-data-bom - 2024.1.4 + 2024.1.5 import pom com.google.cloud google-cloud-spanner-bom - 6.89.0 + 6.91.1 import pom com.google.cloud libraries-bom - 26.56.0 + 26.59.0 import pom io.opentelemetry opentelemetry-bom - 1.48.0 + 1.49.0 pom import diff --git a/samples/spring-data-mybatis/pom.xml b/samples/spring-data-mybatis/pom.xml index 03b732041..c55f5b954 100644 --- a/samples/spring-data-mybatis/pom.xml +++ b/samples/spring-data-mybatis/pom.xml @@ -28,14 +28,14 @@ org.springframework.data spring-data-bom - 2024.1.4 + 2024.1.5 import pom com.google.cloud libraries-bom - 26.56.0 + 26.59.0 import pom diff --git a/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertiesHelper.java b/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertiesHelper.java index 7e64b8f11..cde651e02 100644 --- a/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertiesHelper.java +++ b/src/main/java/com/google/cloud/spanner/connection/ConnectionPropertiesHelper.java @@ -21,6 +21,7 @@ import java.sql.DriverPropertyInfo; import java.util.Arrays; import java.util.Comparator; +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -50,7 +51,7 @@ public static DriverPropertyInfo toDriverPropertyInfo( connectionProperty.getValidValues() == null ? null : Arrays.stream(connectionProperty.getValidValues()) - .map(Object::toString) + .map(Objects::toString) .toArray(String[]::new); return result; } 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 38430cf12..00d0823f0 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/AbstractJdbcConnection.java @@ -41,8 +41,8 @@ abstract class AbstractJdbcConnection extends AbstractJdbcWrapper implements CloudSpannerJdbcConnection { private static final String CALLABLE_STATEMENTS_UNSUPPORTED = "Callable statements are not supported"; - private static final String ONLY_SERIALIZABLE = - "Only isolation level TRANSACTION_SERIALIZABLE is supported"; + private static final String ONLY_SERIALIZABLE_OR_REPEATABLE_READ = + "Only isolation levels TRANSACTION_SERIALIZABLE and TRANSACTION_REPEATABLE_READ are supported"; private static final String ONLY_CLOSE_ALLOWED = "Only holdability CLOSE_CURSORS_AT_COMMIT is supported"; private static final String SQLXML_UNSUPPORTED = "SQLXML is not supported"; @@ -147,13 +147,15 @@ public void setTransactionIsolation(int level) throws SQLException { || level == TRANSACTION_READ_COMMITTED, "Not a transaction isolation level"); JdbcPreconditions.checkSqlFeatureSupported( - level == TRANSACTION_SERIALIZABLE, ONLY_SERIALIZABLE); + JdbcDatabaseMetaData.supportsIsolationLevel(level), ONLY_SERIALIZABLE_OR_REPEATABLE_READ); + spanner.setDefaultIsolationLevel(IsolationLevelConverter.convertToSpanner(level)); } @Override public int getTransactionIsolation() throws SQLException { checkClosed(); - return TRANSACTION_SERIALIZABLE; + //noinspection MagicConstant + return IsolationLevelConverter.convertToJdbc(spanner.getDefaultIsolationLevel()); } @Override diff --git a/src/main/java/com/google/cloud/spanner/jdbc/IsolationLevelConverter.java b/src/main/java/com/google/cloud/spanner/jdbc/IsolationLevelConverter.java new file mode 100644 index 000000000..3e3e10c9f --- /dev/null +++ b/src/main/java/com/google/cloud/spanner/jdbc/IsolationLevelConverter.java @@ -0,0 +1,54 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner.jdbc; + +import com.google.spanner.v1.TransactionOptions.IsolationLevel; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; + +class IsolationLevelConverter { + static IsolationLevel convertToSpanner(int jdbcIsolationLevel) throws SQLException { + switch (jdbcIsolationLevel) { + case Connection.TRANSACTION_SERIALIZABLE: + return IsolationLevel.SERIALIZABLE; + case Connection.TRANSACTION_REPEATABLE_READ: + return IsolationLevel.REPEATABLE_READ; + case Connection.TRANSACTION_READ_COMMITTED: + case Connection.TRANSACTION_READ_UNCOMMITTED: + case Connection.TRANSACTION_NONE: + throw new SQLFeatureNotSupportedException( + "Unsupported JDBC isolation level: " + jdbcIsolationLevel); + default: + throw new IllegalArgumentException("Invalid JDBC isolation level: " + jdbcIsolationLevel); + } + } + + static int convertToJdbc(IsolationLevel isolationLevel) { + switch (isolationLevel) { + // Translate UNSPECIFIED to SERIALIZABLE as that is the default isolation level. + case ISOLATION_LEVEL_UNSPECIFIED: + case SERIALIZABLE: + return Connection.TRANSACTION_SERIALIZABLE; + case REPEATABLE_READ: + return Connection.TRANSACTION_REPEATABLE_READ; + default: + throw new IllegalArgumentException( + "Unknown or unsupported isolation level: " + isolationLevel); + } + } +} 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 bdebcad89..b7fe95145 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaData.java @@ -664,7 +664,12 @@ public boolean supportsTransactions() { @Override public boolean supportsTransactionIsolationLevel(int level) { - return Connection.TRANSACTION_SERIALIZABLE == level; + return supportsIsolationLevel(level); + } + + static boolean supportsIsolationLevel(int level) { + return Connection.TRANSACTION_SERIALIZABLE == level + || Connection.TRANSACTION_REPEATABLE_READ == level; } @Override 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 7c9b46052..f7bdb3b09 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcDriver.java @@ -26,6 +26,7 @@ import com.google.cloud.spanner.connection.ConnectionPropertiesHelper; import com.google.cloud.spanner.connection.ConnectionProperty; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Suppliers; import com.google.rpc.Code; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; @@ -222,7 +223,9 @@ public Connection connect(String url, Properties info) throws SQLException { Matcher matcherExternalHost = EXTERNAL_HOST_URL_PATTERN.matcher(url); if (matcher.matches() || matcherExternalHost.matches()) { // strip 'jdbc:' from the URL, add any extra properties and pass on to the generic - // Connection API + // Connection API. Also set the user-agent if we detect that the connection + // comes from known framework like Hibernate, and there is no other user-agent set. + maybeAddUserAgent(info); String connectionUri = appendPropertiesToUrl(url.substring(5), info); ConnectionOptions options = buildConnectionOptions(connectionUri, info); JdbcConnection connection = new JdbcConnection(url, options); @@ -259,6 +262,48 @@ private ConnectionOptions buildConnectionOptions(String connectionUrl, Propertie return builder.build(); } + static void maybeAddUserAgent(Properties properties) { + if (properties.containsKey("userAgent")) { + return; + } + if (isHibernate()) { + properties.setProperty("userAgent", "sp-hib"); + } + } + + static boolean isHibernate() { + // Cache the result as the check is relatively expensive, and we also don't want to create + // multiple different Spanner instances just to get the correct user-agent in every case. + return Suppliers.memoize( + () -> { + try { + // First check if the Spanner Hibernate dialect is on the classpath. If it is, then + // we assume that Hibernate will (eventually) be used. + Class.forName( + "com.google.cloud.spanner.hibernate.SpannerDialect", + /*initialize=*/ false, + JdbcDriver.class.getClassLoader()); + return true; + } catch (Throwable ignore) { + } + + // If we did not find the Spanner Hibernate dialect on the classpath, then do a + // check if the connection is still being created by Hibernate using the built-in + // Spanner dialect in Hibernate. + try { + StackTraceElement[] callStack = Thread.currentThread().getStackTrace(); + for (StackTraceElement element : callStack) { + if (element.getClassName().contains(".hibernate.")) { + return true; + } + } + } catch (Throwable ignore) { + } + return false; + }) + .get(); + } + private String appendPropertiesToUrl(String url, Properties info) { StringBuilder res = new StringBuilder(url); for (Entry entry : info.entrySet()) { 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 5d8dfd9ee..0a764b351 100644 --- a/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java +++ b/src/main/java/com/google/cloud/spanner/jdbc/JdbcStatement.java @@ -201,15 +201,13 @@ Statement addReturningToStatement(Statement statement, ImmutableList gen if (generatedKeysColumns.size() == 1 && ALL_COLUMNS.get(0).equals(generatedKeysColumns.get(0))) { // Add a 'THEN RETURN/RETURNING *' clause to the statement. - return statement - .toBuilder() + return statement.toBuilder() .replace(statement.getSql() + getReturningAllColumnsClause()) .build(); } // Add a 'THEN RETURN/RETURNING col1, col2, ...' to the statement. // The column names will be quoted using the dialect-specific identifier quoting character. - return statement - .toBuilder() + return statement.toBuilder() .replace( generatedKeysColumns.stream() .map(this::quoteColumn) diff --git a/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertiesFileGenerator.java b/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertiesFileGenerator.java index fe8dd9c96..4307fbcb0 100644 --- a/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertiesFileGenerator.java +++ b/src/test/java/com/google/cloud/spanner/connection/ConnectionPropertiesFileGenerator.java @@ -20,6 +20,7 @@ import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; +import java.util.Objects; import java.util.stream.Collectors; /** Generator for the documentation/connection_properties.md file. */ @@ -65,7 +66,7 @@ static String getValidValues(ConnectionProperty connectionProperty) { return connectionProperty.getValidValues() == null ? "" : Arrays.stream(connectionProperty.getValidValues()) - .map(Object::toString) + .map(Objects::toString) .collect(Collectors.joining(", ")); } } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/AllTypesMockServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/AllTypesMockServerTest.java index cf4b7dfb5..c38489339 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/AllTypesMockServerTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/AllTypesMockServerTest.java @@ -144,8 +144,7 @@ public void testInsertAllTypes() { if (dialect == Dialect.POSTGRESQL) { Statement insertStatement = createInsertStatement(dialect); insertStatement = - insertStatement - .toBuilder() + insertStatement.toBuilder() .replace(insertStatement.getSql().replaceAll("@p", "\\$")) .bind("p16") .to( diff --git a/src/test/java/com/google/cloud/spanner/jdbc/BatchMockServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/BatchMockServerTest.java new file mode 100644 index 000000000..a6fb7a72d --- /dev/null +++ b/src/test/java/com/google/cloud/spanner/jdbc/BatchMockServerTest.java @@ -0,0 +1,100 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner.jdbc; + +import static com.google.cloud.spanner.jdbc.FallbackToPartitionedDMLMockServerTest.createTransactionMutationLimitExceededException; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; + +import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; +import com.google.cloud.spanner.SpannerBatchUpdateException; +import com.google.cloud.spanner.TransactionMutationLimitExceededException; +import com.google.cloud.spanner.connection.AbstractMockServerTest; +import com.google.spanner.v1.ExecuteBatchDmlRequest; +import com.google.spanner.v1.ExecuteSqlRequest; +import java.sql.BatchUpdateException; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class BatchMockServerTest extends AbstractMockServerTest { + private static final String NON_PARAMETERIZED_INSERT = + "insert into foo (id, value) values (1, 'One')"; + private static final String NON_PARAMETERIZED_UPDATE = "update foo set value='Zero' where id=0"; + private static final String LARGE_UPDATE = "update foo set value='Zero' where true"; + + @BeforeClass + public static void setup() { + mockSpanner.putStatementResult( + StatementResult.update( + com.google.cloud.spanner.Statement.of(NON_PARAMETERIZED_INSERT), 1L)); + mockSpanner.putStatementResult( + StatementResult.update( + com.google.cloud.spanner.Statement.of(NON_PARAMETERIZED_UPDATE), 1L)); + mockSpanner.putStatementResult( + StatementResult.exception( + com.google.cloud.spanner.Statement.of(LARGE_UPDATE), + createTransactionMutationLimitExceededException())); + } + + @After + public void clearRequests() { + mockSpanner.clearRequests(); + } + + @Test + public void testStatementBatch() throws SQLException { + try (Connection connection = createJdbcConnection()) { + try (Statement statement = connection.createStatement()) { + statement.addBatch(NON_PARAMETERIZED_INSERT); + statement.addBatch(NON_PARAMETERIZED_UPDATE); + assertArrayEquals(new int[] {1, 1}, statement.executeBatch()); + } + } + assertEquals(1, mockSpanner.countRequestsOfType(ExecuteBatchDmlRequest.class)); + assertEquals(0, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + } + + @Test + public void testStatementBatchFailsDueToMutationLimit() throws SQLException { + try (Connection connection = createJdbcConnection()) { + try (Statement statement = connection.createStatement()) { + statement.addBatch(NON_PARAMETERIZED_INSERT); + statement.addBatch(LARGE_UPDATE); + + BatchUpdateException batchUpdateException = + assertThrows(BatchUpdateException.class, statement::executeBatch); + assertNotNull(batchUpdateException.getCause()); + assertEquals(SpannerBatchUpdateException.class, batchUpdateException.getCause().getClass()); + assertNotNull(batchUpdateException.getCause().getCause()); + assertEquals( + TransactionMutationLimitExceededException.class, + batchUpdateException.getCause().getCause().getClass()); + } + } + assertEquals(1, mockSpanner.countRequestsOfType(ExecuteBatchDmlRequest.class)); + assertEquals(0, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + } +} diff --git a/src/test/java/com/google/cloud/spanner/jdbc/ExecuteMockServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/ExecuteMockServerTest.java index 0da181444..c226bd673 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/ExecuteMockServerTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/ExecuteMockServerTest.java @@ -176,22 +176,19 @@ public void setupResults() { mockSpanner.putStatementResult( StatementResult.query( com.google.cloud.spanner.Statement.of(dmlReturning), - resultSet - .toBuilder() + resultSet.toBuilder() .setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build()) .build())); mockSpanner.putStatementResult( StatementResult.query( com.google.cloud.spanner.Statement.of(DML_THEN_RETURN_ID), - returnIdResultSet - .toBuilder() + returnIdResultSet.toBuilder() .setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build()) .build())); mockSpanner.putStatementResult( StatementResult.query( com.google.cloud.spanner.Statement.of(LARGE_DML_THEN_RETURN_ID), - returnIdResultSet - .toBuilder() + returnIdResultSet.toBuilder() .setStats( ResultSetStats.newBuilder().setRowCountExact(LARGE_UPDATE_COUNT).build()) .build())); diff --git a/src/test/java/com/google/cloud/spanner/jdbc/IsolationLevelConverterTest.java b/src/test/java/com/google/cloud/spanner/jdbc/IsolationLevelConverterTest.java new file mode 100644 index 000000000..2be9e5ea4 --- /dev/null +++ b/src/test/java/com/google/cloud/spanner/jdbc/IsolationLevelConverterTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.spanner.jdbc; + +import static com.google.cloud.spanner.jdbc.IsolationLevelConverter.convertToJdbc; +import static com.google.cloud.spanner.jdbc.IsolationLevelConverter.convertToSpanner; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; + +import com.google.spanner.v1.TransactionOptions.IsolationLevel; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class IsolationLevelConverterTest { + + @Test + public void testConvertToSpanner() throws SQLException { + assertEquals( + IsolationLevel.SERIALIZABLE, convertToSpanner(Connection.TRANSACTION_SERIALIZABLE)); + assertEquals( + IsolationLevel.REPEATABLE_READ, convertToSpanner(Connection.TRANSACTION_REPEATABLE_READ)); + + assertThrows( + SQLFeatureNotSupportedException.class, + () -> convertToSpanner(Connection.TRANSACTION_READ_COMMITTED)); + assertThrows( + SQLFeatureNotSupportedException.class, + () -> convertToSpanner(Connection.TRANSACTION_READ_UNCOMMITTED)); + assertThrows( + SQLFeatureNotSupportedException.class, () -> convertToSpanner(Connection.TRANSACTION_NONE)); + + assertThrows(IllegalArgumentException.class, () -> convertToSpanner(-1)); + } + + @Test + public void testConvertToJdbc() { + // There is no 'unspecified' isolation level in JDBC, so we convert this to the default + // SERIALIZABLE isolation level in Spanner. + assertEquals( + Connection.TRANSACTION_SERIALIZABLE, + convertToJdbc(IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED)); + assertEquals(Connection.TRANSACTION_SERIALIZABLE, convertToJdbc(IsolationLevel.SERIALIZABLE)); + assertEquals( + Connection.TRANSACTION_REPEATABLE_READ, convertToJdbc(IsolationLevel.REPEATABLE_READ)); + + assertThrows(IllegalArgumentException.class, () -> convertToJdbc(IsolationLevel.UNRECOGNIZED)); + } +} 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 e0ea49f6f..d4cfeb8d0 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcConnectionTest.java @@ -366,34 +366,28 @@ private void testInvokeMethodOnClosedConnection(Method method, Object... args) public void testTransactionIsolation() throws SQLException { ConnectionOptions options = mockOptions(); try (JdbcConnection connection = createConnection(options)) { - assertThat(connection.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - // assert that setting it to this value is ok. + assertEquals(Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation()); + // assert that setting it to these values is ok. connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + assertEquals(Connection.TRANSACTION_SERIALIZABLE, connection.getTransactionIsolation()); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + assertEquals(Connection.TRANSACTION_REPEATABLE_READ, connection.getTransactionIsolation()); // assert that setting it to something else is not ok. - int[] settings = + int[] invalidValues = new int[] { - Connection.TRANSACTION_READ_COMMITTED, - Connection.TRANSACTION_READ_UNCOMMITTED, - Connection.TRANSACTION_REPEATABLE_READ, - -100 + Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_READ_UNCOMMITTED, -100 }; - for (int setting : settings) { - boolean exception = false; - try { - connection.setTransactionIsolation(setting); - } catch (SQLException e) { - if (setting == -100) { - exception = - (e instanceof JdbcSqlException - && ((JdbcSqlException) e).getCode() == Code.INVALID_ARGUMENT); - } else { - exception = - (e instanceof JdbcSqlException - && ((JdbcSqlException) e).getCode() == Code.UNIMPLEMENTED); - } + for (int invalidValue : invalidValues) { + SQLException exception = + assertThrows( + SQLException.class, () -> connection.setTransactionIsolation(invalidValue)); + assertTrue(exception instanceof JdbcSqlException); + JdbcSqlException spannerException = (JdbcSqlException) exception; + if (invalidValue == -100) { + assertEquals(Code.INVALID_ARGUMENT, spannerException.getCode()); + } else { + assertEquals(Code.UNIMPLEMENTED, spannerException.getCode()); } - assertThat(exception).isTrue(); } } } 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 47ab2e549..c8970fd76 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/JdbcDatabaseMetaDataTest.java @@ -265,12 +265,12 @@ public void testTrivialMethods() throws SQLException { assertFalse(meta.usesLocalFiles()); assertFalse(meta.usesLocalFilePerTable()); assertTrue(meta.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE)); + assertTrue(meta.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ)); for (int level : new int[] { Connection.TRANSACTION_NONE, Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_READ_UNCOMMITTED, - Connection.TRANSACTION_REPEATABLE_READ }) { assertFalse(meta.supportsTransactionIsolationLevel(level)); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/MultiplexedSessionsTest.java b/src/test/java/com/google/cloud/spanner/jdbc/MultiplexedSessionsTest.java index b7b2d2869..171832414 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/MultiplexedSessionsTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/MultiplexedSessionsTest.java @@ -167,15 +167,13 @@ public void setupResults() { mockSpanner.putStatementResult( StatementResult.query( com.google.cloud.spanner.Statement.of(dmlReturning), - resultSet - .toBuilder() + resultSet.toBuilder() .setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build()) .build())); mockSpanner.putStatementResult( StatementResult.query( com.google.cloud.spanner.Statement.of(DML_THEN_RETURN_ID), - returnIdResultSet - .toBuilder() + returnIdResultSet.toBuilder() .setStats(ResultSetStats.newBuilder().setRowCountExact(1L).build()) .build())); } diff --git a/src/test/java/com/google/cloud/spanner/jdbc/TransactionMockServerTest.java b/src/test/java/com/google/cloud/spanner/jdbc/TransactionMockServerTest.java index 954d12e80..91086055d 100644 --- a/src/test/java/com/google/cloud/spanner/jdbc/TransactionMockServerTest.java +++ b/src/test/java/com/google/cloud/spanner/jdbc/TransactionMockServerTest.java @@ -17,10 +17,14 @@ package com.google.cloud.spanner.jdbc; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import com.google.cloud.spanner.MockSpannerServiceImpl.StatementResult; import com.google.cloud.spanner.connection.AbstractMockServerTest; import com.google.cloud.spanner.connection.SpannerPool; import com.google.spanner.v1.CommitRequest; +import com.google.spanner.v1.ExecuteSqlRequest; +import com.google.spanner.v1.TransactionOptions.IsolationLevel; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -45,9 +49,13 @@ public void clearRequests() { } private String createUrl() { + return createUrl(""); + } + + private String createUrl(String extraOptions) { return String.format( - "jdbc:cloudspanner://localhost:%d/projects/%s/instances/%s/databases/%s?usePlainText=true;autoCommit=false", - getPort(), "proj", "inst", "db"); + "jdbc:cloudspanner://localhost:%d/projects/%s/instances/%s/databases/%s?usePlainText=true;autoCommit=false%s", + getPort(), "proj", "inst", "db", extraOptions); } @Override @@ -98,4 +106,62 @@ public void testRollingBackEmptyExplicitTransactionIsNoOp() throws SQLException assertEquals(0, mockSpanner.countRequestsOfType(CommitRequest.class)); } + + @Test + public void testUsesDefaultIsolationLevel() throws SQLException { + try (Connection connection = createJdbcConnection()) { + for (IsolationLevel isolationLevel : + new IsolationLevel[] {IsolationLevel.SERIALIZABLE, IsolationLevel.REPEATABLE_READ}) { + //noinspection MagicConstant + connection.setTransactionIsolation(IsolationLevelConverter.convertToJdbc(isolationLevel)); + runTestTransaction(connection, isolationLevel); + } + } + } + + @Test + public void testUsesManualIsolationLevel() throws SQLException { + try (Connection connection = createJdbcConnection()) { + connection.setAutoCommit(true); + for (IsolationLevel isolationLevel : + new IsolationLevel[] {IsolationLevel.SERIALIZABLE, IsolationLevel.REPEATABLE_READ}) { + connection + .createStatement() + .execute( + "begin transaction isolation level " + isolationLevel.toString().replace("_", " ")); + runTestTransaction(connection, isolationLevel); + } + } + } + + @Test + public void testUsesDefaultIsolationLevelInConnectionString() throws SQLException { + for (IsolationLevel isolationLevel : + new IsolationLevel[] {IsolationLevel.SERIALIZABLE, IsolationLevel.REPEATABLE_READ}) { + try (Connection connection = + DriverManager.getConnection( + createUrl(";default_isolation_level=" + isolationLevel.name()))) { + runTestTransaction(connection, isolationLevel); + } + } + } + + void runTestTransaction(Connection connection, IsolationLevel expectedIsolationLevel) + throws SQLException { + String sql = "insert into foo (id) values (1)"; + mockSpanner.putStatementResult( + StatementResult.update(com.google.cloud.spanner.Statement.of(sql), 1L)); + + assertEquals(1, connection.createStatement().executeUpdate(sql)); + connection.commit(); + + assertEquals(1, mockSpanner.countRequestsOfType(ExecuteSqlRequest.class)); + ExecuteSqlRequest request = mockSpanner.getRequestsOfType(ExecuteSqlRequest.class).get(0); + assertTrue(request.hasTransaction()); + assertTrue(request.getTransaction().hasBegin()); + assertTrue(request.getTransaction().getBegin().hasReadWrite()); + assertEquals(expectedIsolationLevel, request.getTransaction().getBegin().getIsolationLevel()); + + mockSpanner.clearRequests(); + } } 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 60698799f..99ee00165 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 @@ -745,7 +745,8 @@ public void test04_Timestamps() throws SQLException { // Then get it in the test timezone. if (testCalendar != null && !System.getProperty("java.vm.name", "").toLowerCase().contains("graalvm") - && !System.getProperty("java.vendor", "").toLowerCase().contains("graalvm")) { + && !System.getProperty("java.vendor", "").toLowerCase().contains("graalvm") + && !System.getProperty("java.vendor", "").toLowerCase().contains("oracle")) { Timestamp inOtherTZ = rs.getTimestamp(4, testCalendar); assertEquals( "Timezone: " @@ -768,7 +769,8 @@ public void test04_Timestamps() throws SQLException { if (testCalendar == null) { assertEquals(testTimestamp.getTime(), inDefaultTZ.getTime()); } else if (!System.getProperty("java.vm.name", "").toLowerCase().contains("graalvm") - && !System.getProperty("java.vendor", "").toLowerCase().contains("graalvm")) { + && !System.getProperty("java.vendor", "").toLowerCase().contains("graalvm") + && !System.getProperty("java.vendor", "").toLowerCase().contains("oracle")) { assertEquals( "Timezone: " + testCalendar diff --git a/src/test/resources/META-INF/native-image/com.google.cloud/google-cloud-spanner-jdbc/native-image.properties b/src/test/resources/META-INF/native-image/com.google.cloud/google-cloud-spanner-jdbc/native-image.properties new file mode 100644 index 000000000..714d90fb1 --- /dev/null +++ b/src/test/resources/META-INF/native-image/com.google.cloud/google-cloud-spanner-jdbc/native-image.properties @@ -0,0 +1 @@ +Args=--strict-image-heap diff --git a/versions.txt b/versions.txt index 3fd7810ad..638e723bb 100644 --- a/versions.txt +++ b/versions.txt @@ -1,4 +1,4 @@ # Format: # module:released-version:current-version -google-cloud-spanner-jdbc:2.28.0:2.28.0 +google-cloud-spanner-jdbc:2.29.0:2.29.0