This is an automated email from the ASF dual-hosted git repository. rmaucher pushed a commit to branch 10.1.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 3c4fa0f3311a613a05698f00d69fcbbfe02d8b87 Author: opencode <[email protected]> AuthorDate: Tue Dec 1 16:49:00 2026 +0100 Add initSQLs for multiple connection initialization statements Bugzilla 56779. A connection can need more than one setup statement, but the single initSQL string cannot express that without a vendor-specific multi-statement block. Add an ordered initSQLs collection that runs every statement on each newly established session; initSQL remains the single-statement fallback and a non-empty initSQLs collection takes precedence. Execute the statements in order on one statement. When auto commit is off they share one transaction, committed after the last statement succeeds; a failure rolls the whole initialization back and takes the session out of service. Blank entries are ignored and the collection is copied, so callers cannot reconfigure the pool through a retained collection. The collection is programmatic-only: XML and JNDI text cannot carry a collection, so the single initSQL attribute remains the declarative route. Wire the property through the configuration, data source, JMX and documentation surfaces, and add tests for ordering, precedence, commit semantics, failure rollback and live configuration changes. --- modules/jdbc-pool/doc/jdbc-pool.xml | 16 +- .../apache/tomcat/jdbc/pool/ConnectionPool.java | 3 +- .../apache/tomcat/jdbc/pool/DataSourceProxy.java | 13 ++ .../apache/tomcat/jdbc/pool/PoolConfiguration.java | 56 ++++-- .../tomcat/jdbc/pool/PoolConfigurationView.java | 5 + .../apache/tomcat/jdbc/pool/PoolProperties.java | 97 +++++++++- .../apache/tomcat/jdbc/pool/PooledConnection.java | 41 +++-- .../tomcat/jdbc/pool/jmx/ConnectionPool.java | 12 ++ .../apache/tomcat/jdbc/pool/mbeans-descriptors.xml | 5 + .../tomcat/jdbc/pool/MultipleInitSqlBase.java | 205 +++++++++++++++++++++ .../tomcat/jdbc/pool/TestConnectionSetup.java | 4 + webapps/docs/changelog.xml | 8 + 12 files changed, 425 insertions(+), 40 deletions(-) diff --git a/modules/jdbc-pool/doc/jdbc-pool.xml b/modules/jdbc-pool/doc/jdbc-pool.xml index 5cdad469d3..42f28c1061 100644 --- a/modules/jdbc-pool/doc/jdbc-pool.xml +++ b/modules/jdbc-pool/doc/jdbc-pool.xml @@ -120,7 +120,8 @@ <subsection name="Additional features"> <p>The Tomcat connection pool offers a few additional features over what most other pools let you do:</p> <ul> - <li><code>initSQL</code> - the ability to run an SQL statement exactly once, when the connection is created</li> + <li><code>initSQL</code> / <code>initSQLs</code> - the ability to run one or more SQL statements exactly once, + when the connection is created</li> <li><code>validationInterval</code> - in addition to running validations on connections, avoid running them too frequently.</li> <li><code>jdbcInterceptors</code> - flexible and pluggable interceptors to create any customizations around the pool, the query execution and the result set handling. More on this in the advanced section.</li> @@ -376,9 +377,9 @@ <attribute name="validationQueryTimeout" required="false"> <p>(int) The timeout in seconds before a connection validation query fails. This works by calling <code>java.sql.Statement.setQueryTimeout(seconds)</code> on the statement that executes the - <code>validationQuery</code>, and also on the statement that executes a configured <code>initSQL</code> - when the connection is initialized. The pool itself doesn't timeout the query; it is still up to the JDBC - driver to enforce query timeouts. Some drivers do not enforce this timeout once the database or network + <code>validationQuery</code>, and also on the statement that executes a configured <code>initSQL</code> or + <code>initSQLs</code> when the connection is initialized. The pool itself doesn't timeout the query; it is + still up to the JDBC driver to enforce query timeouts. Some drivers do not enforce this timeout once the database or network stops responding, and a driver-level socket or connect timeout (for example <code>socketTimeout</code> or <code>connectTimeout</code>) may be required. A value less than or equal to zero will disable this feature. The default value is <code>-1</code>. @@ -468,6 +469,13 @@ <attribute name="initSQL" required="false"> <p>(String) A custom query to be run when a connection is first created. The default value is <code>null</code>.</p> + <p>The programmatic API also provides + <code>setInitSQLs(Collection<String>)</code> for more than one statement. The statements are executed in + order on every newly established connection. When the pool runs with auto commit off, they share one + transaction that is committed after the last statement succeeds; a failure rolls the whole initialization back + and takes the session out of service. A non-empty <code>initSQLs</code> collection takes precedence over + <code>initSQL</code>. The collection is not available as a JNDI/XML attribute because XML text cannot carry a + collection; the single <code>initSQL</code> attribute remains the declarative route.</p> </attribute> <attribute name="jdbcInterceptors" required="false"> diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java index 7881a08abd..b382c5030f 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java @@ -2307,8 +2307,7 @@ public class ConnectionPool { // would send a freshly re-established session down the init-check // path - which an unset statement makes a check that runs nothing - // instead of the borrow check the configuration did ask for. - return poolProperties.isTestOnConnect() || - PoolProperties.configuredStatement(poolProperties.getInitSQL()) != null; + return poolProperties.isTestOnConnect() || PoolProperties.hasInitSQL(poolProperties); } /** diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java index c20c534eac..bbc4621c2f 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java @@ -21,6 +21,7 @@ import java.lang.ref.WeakReference; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; +import java.util.Collection; import java.util.Properties; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; @@ -690,6 +691,12 @@ public class DataSourceProxy implements PoolConfiguration { } + @Override + public void setInitSQLs(Collection<String> initSQLs) { + this.poolProperties.setInitSQLs(initSQLs); + } + + @Override public void setLogAbandoned(boolean logAbandoned) { this.poolProperties.setLogAbandoned(logAbandoned); @@ -1374,6 +1381,12 @@ public class DataSourceProxy implements PoolConfiguration { } + @Override + public Collection<String> getInitSQLs() { + return getPoolProperties().getInitSQLs(); + } + + /** * Returns the interceptor configuration with any credential its definitions carry masked out, so the data source's * own bean/JMX surface does not expose a password in cleartext. Use {@link #getPoolProperties()} for the raw value. diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java index b31ee1c10b..ff2bd088b7 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java @@ -16,6 +16,7 @@ */ package org.apache.tomcat.jdbc.pool; +import java.util.Collection; import java.util.Properties; import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorDefinition; @@ -764,12 +765,13 @@ public interface PoolConfiguration { * per connection, and that is when a new connection is established to the database. If this value is non null, it * will replace the validation query during connection creation. * <p> - * The query runs while the pool is initializing the freshly established session, and the pool terminates the - * transaction it executes into by commit, so its effects - a data change or a session setting - persist for the - * lifetime of the connection even when the pool runs with auto commit off. A validation query follows the opposite - * rule and terminates an open transaction by rollback, so a health check never commits application work. A pool - * configured with a custom {@link Validator} does not run this query at all: the validator replaces the - * validation itself. + * This is the single-statement form. When {@link #getInitSQLs()} returns a non-empty collection, that collection is + * used instead and this value is ignored. The query runs while the pool is initializing the freshly established + * session, and the pool terminates the transaction it executes into by commit, so its effects - a data change or a + * session setting - persist for the lifetime of the connection even when the pool runs with auto commit off. A + * validation query follows the opposite rule and terminates an open transaction by rollback, so a health check never + * commits application work. A pool configured with a custom {@link Validator} does not run this query at all: the + * validator replaces the validation itself. * * @return the init SQL used to run against the DB or null if not set */ @@ -780,17 +782,47 @@ public interface PoolConfiguration { * per connection, and that is when a new connection is established to the database. If this value is non null, it * will replace the validation query during connection creation. * <p> - * The query runs while the pool is initializing the freshly established session, and the pool terminates the - * transaction it executes into by commit, so its effects - a data change or a session setting - persist for the - * lifetime of the connection even when the pool runs with auto commit off. A validation query follows the opposite - * rule and terminates an open transaction by rollback, so a health check never commits application work. A pool - * configured with a custom {@link Validator} does not run this query at all: the validator replaces the - * validation itself. + * This is the single-statement form. When {@link #getInitSQLs()} returns a non-empty collection, that collection is + * used instead and this value is ignored. The query runs while the pool is initializing the freshly established + * session, and the pool terminates the transaction it executes into by commit, so its effects - a data change or a + * session setting - persist for the lifetime of the connection even when the pool runs with auto commit off. A + * validation query follows the opposite rule and terminates an open transaction by rollback, so a health check never + * commits application work. A pool configured with a custom {@link Validator} does not run this query at all: the + * validator replaces the validation itself. * * @param initSQL the init SQL used to run against the DB or null if no query should be executed */ void setInitSQL(String initSQL); + /** + * Returns the custom statements to run when a connection is first created, in order. A non-empty collection takes + * precedence over {@link #getInitSQL()}; an empty collection means no multi-statement initialization is configured + * and the single {@link #getInitSQL()} value, if any, is used. + * <p> + * The statements are executed in the order returned, on one session, when the pool creates or re-establishes that + * session. When the pool runs with auto commit off, all of the statements run in one transaction that is committed + * after the last one succeeds; a failure rolls the whole initialization back and takes the session out of service. + * Blank entries are not statements and are ignored. + * <p> + * This is a programmatic configuration surface. A JNDI/XML attribute cannot carry a collection; the single + * {@link #setInitSQL(String)} attribute remains the declarative route. + * + * @return the initialization statements, possibly empty but never {@code null} + */ + Collection<String> getInitSQLs(); + + /** + * Sets the custom statements to run when a connection is first created, in order. A non-empty collection takes + * precedence over {@link #setInitSQL(String)}; an empty collection or {@code null} clears the multi-statement + * configuration and leaves the single init SQL, if set, in effect. + * <p> + * The collection is copied. Blank entries are ignored, and the remaining statements run in the order supplied, + * under the transaction rules described by {@link #getInitSQLs()}. + * + * @param initSQLs the initialization statements in execution order, or {@code null} to clear them + */ + void setInitSQLs(Collection<String> initSQLs); + /** * Returns true if we should run the validation query when connecting to the database for the first time on a * connection. Normally this is always set to false, unless one wants to use the validationQuery as an init query. diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfigurationView.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfigurationView.java index e0fa1e08a4..9a32ba21a3 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfigurationView.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfigurationView.java @@ -20,6 +20,8 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Collection; import java.util.Properties; /** @@ -113,6 +115,9 @@ final class PoolConfigurationView { if ("getDbProperties".equals(name) && result instanceof Properties) { return PoolUtilities.clone((Properties) result); } + if ("getInitSQLs".equals(name) && result instanceof Collection) { + return new ArrayList<>((Collection<?>) result); + } if ("getJdbcInterceptorsAsArray".equals(name) && result instanceof PoolProperties.InterceptorDefinition[]) { // A shallow array clone would share the live definitions with diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java index e6e2544f39..478a31bff5 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java @@ -23,6 +23,8 @@ import java.io.Serializable; import java.io.StringReader; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; @@ -44,8 +46,9 @@ import org.apache.tomcat.jdbc.pool.util.MessageFactory; /** * Implementation of {@link PoolConfiguration} that holds the configuration properties for a connection pool. * <p> - * The setters that maintain the database properties, the credentials, the validator and the interceptor list publish - * their changes under this instance's monitor, which is also the monitor {@link #clone()} and serialization take. + * The setters that maintain the database properties, the credentials, the validator, the interceptor list and the + * initialization statement list publish their changes under this instance's monitor, which is also the monitor + * {@link #clone()} and serialization take. * Those setters are the snapshot boundary for the state they own. Setters that assign a single plain field do not take * the monitor, so a copy taken under it is not a consistent snapshot of those fields against a concurrent write. * <p> @@ -184,6 +187,8 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl private volatile boolean jmxEnabled = true; /** The SQL to execute on connection creation. */ private volatile String initSQL; + /** The ordered SQL statements to execute on connection creation. */ + private volatile String[] initSQLs; /** Whether to validate connections on creation. */ private volatile boolean testOnConnect = false; /** The JDBC interceptors configuration. */ @@ -497,6 +502,16 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl } + @Override + public Collection<String> getInitSQLs() { + String[] statements = initSQLs; + if (statements == null) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(Arrays.asList(statements.clone())); + } + + @Override public boolean isTestOnConnect() { return testOnConnect; @@ -1235,6 +1250,70 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl } + /** + * {@inheritDoc} + * <p> + * The collection is copied and stored in execution order. Null entries and + * entries that are blank after {@link #configuredStatement(String)} treats + * them are discarded, so an empty result really means no multi-statement + * initialization was configured. + */ + @Override + public synchronized void setInitSQLs(Collection<String> initSQLs) { + if (initSQLs == null) { + this.initSQLs = null; + return; + } + ArrayList<String> statements = new ArrayList<>(); + for (String statement : initSQLs) { + String configured = configuredStatement(statement); + if (configured != null) { + statements.add(configured); + } + } + this.initSQLs = statements.isEmpty() ? null : statements.toArray(new String[0]); + } + + + /** + * Returns the statements the pool should execute for connection creation, + * preferring the multi-statement list when it carries one and otherwise + * falling back to the single {@link #getInitSQL() init SQL}. + * + * @param configuration the configuration to read + * + * @return the statements in execution order, never {@code null} + */ + static String[] initStatements(PoolConfiguration configuration) { + Collection<String> configured = configuration.getInitSQLs(); + if (configured != null && !configured.isEmpty()) { + ArrayList<String> statements = new ArrayList<>(); + for (String statement : configured) { + String value = configuredStatement(statement); + if (value != null) { + statements.add(value); + } + } + return statements.toArray(new String[0]); + } + String single = configuredStatement(configuration.getInitSQL()); + return single == null ? new String[0] : new String[] { single }; + } + + + /** + * Returns whether the configuration has any connection initialization + * statements, including the single {@link #getInitSQL() init SQL}. + * + * @param configuration the configuration to read + * + * @return {@code true} if at least one statement would be executed + */ + static boolean hasInitSQL(PoolConfiguration configuration) { + return initStatements(configuration).length > 0; + } + + @Override public void setTestOnConnect(boolean testOnConnect) { this.testOnConnect = testOnConnect; @@ -1275,8 +1354,8 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl * and {@code jdbcInterceptors} strings pass through credential masking, * and a configured live {@code dataSource} object is printed as its class * and identity rather than through its own {@code toString()}, and the - * {@code initSQL} and {@code validationQuery} statements print as - * {@code <sql>} rather than as text SQL syntax can shape around a + * {@code initSQL}, {@code initSQLs} and {@code validationQuery} statements + * print as {@code <sql>} rather than as text SQL syntax can shape around a * credential, so the dump * can be logged without carrying a cleartext credential. The * masking is best effort in the way {@link #maskCredentials(String)} and @@ -1376,6 +1455,12 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl break; } } + // initSQLs is programmatic-only and therefore absent from + // ALL_PROPERTIES. Report its presence without printing the SQL, as + // the single initSQL field above does. + if (initSQLs != null && initSQLs.length > 0) { + buf.append("initSQLs=<sql>; "); + } } catch (Exception x) { // Shouldn't happen if (log.isDebugEnabled()) { @@ -2703,6 +2788,7 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl copy.validationInterval = from.validationInterval; copy.jmxEnabled = from.jmxEnabled; copy.initSQL = from.initSQL; + copy.initSQLs = from.initSQLs == null ? null : from.initSQLs.clone(); copy.testOnConnect = from.testOnConnect; copy.jdbcInterceptors = from.jdbcInterceptors; copy.fairQueue = from.fairQueue; @@ -2761,6 +2847,9 @@ public class PoolProperties implements PoolConfiguration, Cloneable, Serializabl } clone.interceptors = copies; } + if (clone.initSQLs != null) { + clone.initSQLs = clone.initSQLs.clone(); + } Set<String> keys = clone.connectionPropertyKeys; if (keys != null && !keys.isEmpty()) { clone.connectionPropertyKeys = new HashSet<>(keys); diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PooledConnection.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PooledConnection.java index cec757c500..612eeb9851 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PooledConnection.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PooledConnection.java @@ -1289,8 +1289,7 @@ public class PooledConnection implements PooledConnectionMBean { return true; } else if (action == VALIDATE_INIT && configuration.isTestOnConnect()) { return true; - } else if (action == VALIDATE_INIT && - PoolProperties.configuredStatement(configuration.getInitSQL()) != null) { + } else if (action == VALIDATE_INIT && PoolProperties.hasInitSQL(configuration)) { return true; } else { return false; @@ -1317,11 +1316,12 @@ public class PooledConnection implements PooledConnectionMBean { * @param validateAction the action used. One of {@link #VALIDATE_BORROW}, {@link #VALIDATE_IDLE}, * {@link #VALIDATE_INIT} or {@link #VALIDATE_RETURN} * @param sql the SQL to be used during validation. If the {@link PoolConfiguration#setInitSQL(String)} - * has been called with a statement and the action is {@link #VALIDATE_INIT} the init SQL - * will be used for validation, and a blank argument, like a blank configured statement, - * reads as no statement. Whether anything runs at all is the action's own configuration - * that decides: for an action the pool has not enabled, this method returns true without - * executing the statement or touching the connection. + * or {@link PoolConfiguration#setInitSQLs(java.util.Collection)} has configured + * initialization work and the action is {@link #VALIDATE_INIT}, that work is used for + * validation, and a blank argument, like a blank configured statement, reads as no + * statement. Whether anything runs at all is the action's own configuration that decides: + * for an action the pool has not enabled, this method returns true without executing the + * statement or touching the connection. * * @return true if the connection was validated successfully. It returns true even if validation was not performed, * such as when {@link PoolConfiguration#setValidationInterval(long)} has been called with a positive @@ -1337,7 +1337,8 @@ public class PooledConnection implements PooledConnectionMBean { * the one the check itself may have started, or one a previous borrower left open. A read-only check is * ended with a rollback, never with a commit: a pool health check must not commit application work the * application itself never committed. The one exception is the {@link #VALIDATE_INIT} execution of the - * configured {@link PoolConfiguration#getInitSQL() init SQL}: that query is not a check but the pool's + * configured {@link PoolConfiguration#getInitSQL() init SQL} or + * {@link PoolConfiguration#getInitSQLs() init SQL statements}: that work is not a check but the pool's * own initialization of the session it has just established, so its transaction is ended with a commit * and the initialization persists for the connection's lifetime. When the transaction cannot be ended - * by the commit or by the rollback - the session state is unknown, so the validation is reported as @@ -1424,19 +1425,17 @@ public class PooledConnection implements PooledConnectionMBean { // connection's lifetime. The pool only ever runs the init action on a // session that connect() established moments ago, so the transaction // this execution opens is the pool's own initialization work, and - // nothing a borrower could have left behind on it. - String initSql = PoolProperties.configuredStatement(configuration.getInitSQL()); - boolean executingInitSql = validateAction == VALIDATE_INIT && initSql != null; + // nothing a borrower could have left behind on it. The statements are + // read once, so a live configuration change cannot switch from the + // single init SQL to a list (or back) midway through the work. + String[] initSQLs = PoolProperties.initStatements(configuration); + boolean executingInitSql = validateAction == VALIDATE_INIT && initSQLs.length > 0; - if (executingInitSql) { - query = initSql; - } - - if (query == null) { + if (!executingInitSql && query == null) { query = PoolProperties.configuredStatement(configuration.getValidationQuery()); } - if (query == null) { + if (!executingInitSql && query == null) { boolean transactionTerminated = false; int validationQueryTimeout = configuration.getValidationQueryTimeout(); if (validationQueryTimeout < 0) { @@ -1518,7 +1517,13 @@ public class PooledConnection implements PooledConnectionMBean { stmt.setQueryTimeout(validationQueryTimeout); } - stmt.execute(query); + if (executingInitSql) { + for (String initSql : initSQLs) { + stmt.execute(initSql); + } + } else { + stmt.execute(query); + } stmt.close(); this.lastValidated = System.currentTimeMillis(); if (executingInitSql) { diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java index de32951001..9bc371b4a6 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java @@ -16,6 +16,7 @@ package org.apache.tomcat.jdbc.pool.jmx; import java.lang.ref.WeakReference; +import java.util.Collection; import java.util.Properties; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -582,6 +583,11 @@ public class ConnectionPool extends NotificationBroadcasterSupport implements Co return getPoolProperties().getInitSQL(); } + @Override + public Collection<String> getInitSQLs() { + return getPoolProperties().getInitSQLs(); + } + /** * Returns the interceptor configuration with any credential its definitions carry masked out, so that a read of * this attribute does not hand back in cleartext the password {@link #getPassword()} exists to withhold - the @@ -938,6 +944,12 @@ public class ConnectionPool extends NotificationBroadcasterSupport implements Co } + @Override + public void setInitSQLs(Collection<String> initSQLs) { + getPoolProperties().setInitSQLs(initSQLs); + } + + /** * Refuses the write. A live interceptor change is accepted through the data source bean * ({@link org.apache.tomcat.jdbc.pool.DataSourceProxy#setJdbcInterceptors(String)}), which is the authoritative diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml index a9adb7245f..a4c9acda4c 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml @@ -216,6 +216,11 @@ type="java.lang.String" writeable="false"/> + <attribute name="initSQLs" + description="The ordered SQL statements executed once per connection, when it is established" + type="java.lang.Object" + writeable="false"/> + <attribute name="testOnConnect" description="Validate connection after connection has been established" type="java.lang.Boolean" diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/MultipleInitSqlBase.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/MultipleInitSqlBase.java new file mode 100644 index 0000000000..8db39826f9 --- /dev/null +++ b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/MultipleInitSqlBase.java @@ -0,0 +1,205 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.tomcat.jdbc.pool; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import org.apache.tomcat.jdbc.JdbcPoolBaseTest; + +/** + * Bugzilla 56779: a connection can need more than one initialization statement, + * and a single {@code initSQL} string cannot express them without relying on a + * vendor-specific multi-statement block. The collection form must run the + * statements in order, on every session the pool establishes, under the same + * transaction rules as the single-statement form. + */ +abstract class MultipleInitSqlBase extends JdbcPoolBaseTest { + + private String createTable() throws SQLException { + String table = uniqueTable(); + try (Connection admin = adminConnection(); Statement st = admin.createStatement()) { + st.execute("CREATE TABLE " + table + " (v INT)"); + } + return table; + } + + private static int rowCount(Connection connection, String table) throws SQLException { + try (Statement st = connection.createStatement(); + ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM " + table)) { + rs.next(); + return rs.getInt(1); + } + } + + private static Integer userVariable(Connection connection, String name) throws SQLException { + try (Statement st = connection.createStatement(); + ResultSet rs = st.executeQuery("SELECT @" + name)) { + rs.next(); + Object value = rs.getObject(1); + return value == null ? null : Integer.valueOf(((Number) value).intValue()); + } + } + + private DataSource poolWithStatements(Collection<String> statements) { + DataSource ds = newDataSource(); + ds.getPoolProperties().setInitSQLs(statements); + return ds; + } + + @Test + void initSQLsAreOrderedFilteredAndCopied() { + PoolProperties properties = new PoolProperties(); + List<String> input = new ArrayList<>(Arrays.asList("SET @A = 1", " ", null, "SET @A = @A + 1")); + properties.setInitSQLs(input); + + Assertions.assertEquals(Arrays.asList("SET @A = 1", "SET @A = @A + 1"), + new ArrayList<>(properties.getInitSQLs()), + "blank entries must be omitted and order preserved"); + input.set(0, "SET @A = 99"); + Assertions.assertEquals("SET @A = 1", properties.getInitSQLs().iterator().next(), + "the configured collection must be copied, not retained"); + + Assertions.assertThrows(UnsupportedOperationException.class, + () -> properties.getInitSQLs().clear(), + "the exposed collection must not be mutable"); + + properties.setInitSQLs(Collections.emptyList()); + Assertions.assertTrue(properties.getInitSQLs().isEmpty(), + "an empty collection clears the multi-statement configuration"); + } + + @Test + void theConfigurationDumpReportsInitSQLsWithoutPrintingTheStatement() { + PoolProperties properties = new PoolProperties(); + properties.setInitSQLs(Arrays.asList( + "SET @SECRET = 'credential-shaped-text'", + "SET @OTHER = 2")); + String dump = properties.toString(); + Assertions.assertTrue(dump.contains("initSQLs=<sql>"), + "the dump must report the configured statements, was: " + dump); + Assertions.assertFalse(dump.contains("credential-shaped-text"), + "the dump must not print initialization SQL text"); + } + + @Test + void statementsRunInOrder() throws Exception { + DataSource ds = poolWithStatements(Arrays.asList( + "SET @INIT_ORDER = 1", + "SET @INIT_ORDER = @INIT_ORDER * 10 + 2")); + ds.createPool(); + try (Connection c = ds.getConnection()) { + Assertions.assertEquals(Integer.valueOf(12), userVariable(c, "INIT_ORDER"), + "the second statement must observe the first statement's work"); + } + } + + @Test + void everyPhysicalConnectionRunsAllStatements() throws Exception { + DataSource ds = poolWithStatements(Collections.singletonList("SET @MULTI = 7")); + ds.getPoolProperties().setInitialSize(1); + ds.getPoolProperties().setMaxActive(2); + ds.createPool(); + try (Connection first = ds.getConnection(); Connection second = ds.getConnection()) { + Assertions.assertEquals(Integer.valueOf(7), userVariable(first, "MULTI")); + Assertions.assertEquals(Integer.valueOf(7), userVariable(second, "MULTI")); + } + } + + @Test + void allStatementsShareOneCommitWhenAutoCommitIsOff() throws Exception { + String table = createTable(); + DataSource ds = poolWithStatements(Arrays.asList( + "INSERT INTO " + table + " VALUES (1)", + "INSERT INTO " + table + " VALUES (2)")); + ds.getPoolProperties().setDefaultAutoCommit(Boolean.FALSE); + ds.createPool(); + try (Connection c = ds.getConnection()) { + Assertions.assertEquals(2, rowCount(c, table)); + } + Assertions.assertEquals(2, adminRowCount(table), + "both initialization statements must be committed before the first borrow"); + } + + @Test + void aFailureInALaterStatementRollsBackTheEarlierOnes() throws Exception { + String table = createTable(); + DataSource ds = poolWithStatements(Arrays.asList( + "INSERT INTO " + table + " VALUES (1)", + "INSERT INTO NO_SUCH_TABLE VALUES (2)")); + ds.getPoolProperties().setDefaultAutoCommit(Boolean.FALSE); + Assertions.assertThrows(SQLException.class, ds::createPool, + "a failed initialisation statement must fail the pool start"); + Assertions.assertEquals(0, adminRowCount(table), + "the earlier statement must be rolled back with the failed one"); + awaitSessions(0); + } + + @Test + void initSQLsReplaceTheValidationQueryAtConnect() throws Exception { + DataSource ds = poolWithStatements(Collections.singletonList("SET @MULTI = 9")); + ds.getPoolProperties().setTestOnConnect(true); + ds.getPoolProperties().setValidationQuery("SELECT * FROM NO_SUCH_VALIDATION_TABLE"); + ds.createPool(); + try (Connection c = ds.getConnection()) { + Assertions.assertEquals(Integer.valueOf(9), userVariable(c, "MULTI")); + } + } + + @Test + void aSingleInitSQLRemainsTheFallbackAndTheListTakesPrecedence() throws Exception { + DataSource ds = newDataSource(); + ds.getPoolProperties().setInitSQL("SET @MULTI = 1"); + ds.getPoolProperties().setInitSQLs(Collections.singletonList("SET @MULTI = 2")); + ds.createPool(); + try (Connection c = ds.getConnection()) { + Assertions.assertEquals(Integer.valueOf(2), userVariable(c, "MULTI"), + "a non-empty initSQLs collection must take precedence over initSQL"); + } + + DataSource fallback = newDataSource(); + fallback.getPoolProperties().setInitSQL("SET @MULTI = 3"); + fallback.getPoolProperties().setInitSQLs(Collections.emptyList()); + fallback.createPool(); + try (Connection c = fallback.getConnection()) { + Assertions.assertEquals(Integer.valueOf(3), userVariable(c, "MULTI"), + "an empty initSQLs collection must leave initSQL in effect"); + } + } + + @Test + void initSQLsCanBeChangedOnALivePool() throws Exception { + DataSource ds = newDataSource(); + ds.getPoolProperties().setInitialSize(0); + ds.createPool(); + ds.setInitSQLs(Arrays.asList("SET @MULTI = 11", "SET @MULTI = @MULTI + 1")); + try (Connection c = ds.getConnection()) { + Assertions.assertEquals(Integer.valueOf(12), userVariable(c, "MULTI"), + "a live initSQLs change must apply to connections established afterwards"); + } + } +} diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java index 64bca4fc82..be378e8cf8 100644 --- a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java +++ b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java @@ -38,6 +38,10 @@ class TestConnectionSetup { class InitSqlCommittedAtInitialization extends InitSqlCommittedAtInitializationBase { } + @Nested + class MultipleInitSql extends MultipleInitSqlBase { + } + @Nested class LiveDriverChange extends LiveDriverChangeBase { } diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 0f3b2f9bc3..f20e6b67f6 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -559,6 +559,14 @@ Revert pull request <pr>677</pr> which added request hints from JDBC 4.3, causing statement cache issues on many databases. (remm) </add> + <add> + Allow a connection to be initialized with more than one SQL statement + through the new <code>initSQLs</code> collection property. The statements + execute in order on every newly established connection, share one + transaction when auto commit is off, and are rolled back together if any + statement fails. The existing single <code>initSQL</code> attribute + remains available. (remm) + </add> <add> Add a <code>rollbackOnAbandon</code> attribute that rolls back the transaction of an abandoned connection before closing it, so a driver --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
