jdaugherty commented on code in PR #15453:
URL: https://github.com/apache/grails-core/pull/15453#discussion_r2853377238


##########
grails-testing-support-dbcleanup-core/src/main/groovy/org/apache/grails/testing/cleanup/core/DatabaseCleanupContext.groovy:
##########
@@ -0,0 +1,220 @@
+/*
+ *  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
+ *
+ *    https://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.grails.testing.cleanup.core
+
+import javax.sql.DataSource
+
+import groovy.transform.CompileStatic
+import groovy.util.logging.Slf4j
+
+import org.springframework.context.ApplicationContext
+
+/**
+ * Context that holds the discovered {@link DatabaseCleaner} implementations 
and
+ * provides access to the application's data sources for cleanup operations.
+ *
+ * <p>Multiple cleaners can be registered (one per database type). When 
performing cleanup,
+ * the context matches each datasource to an appropriate cleaner using either 
an explicit
+ * database type from the {@link DatasourceCleanupMapping} or auto-discovery 
via
+ * {@link DatabaseCleaner#supports(DataSource)}. If a datasource is marked for 
cleanup
+ * but no matching cleaner is found, an error is thrown.</p>
+ */
+@Slf4j
+@CompileStatic
+class DatabaseCleanupContext {
+
+    private ApplicationContext applicationContext
+    private final Map<String, DatabaseCleaner> cleanersByType
+
+    DatabaseCleanupContext(List<DatabaseCleaner> cleaners) {
+        cleanersByType = createCleanersMap(cleaners)
+    }
+
+    private static Map<String, DatabaseCleaner> 
createCleanersMap(List<DatabaseCleaner> cleaners) {
+        def typeMap = [:] as Map<String, DatabaseCleaner>
+        cleaners.each {
+            def type = it.databaseType()?.trim()
+            if (!type) {
+                throw new IllegalStateException(
+                        "DatabaseCleaner implementation $it.class.name " +
+                        'returned a null or empty databaseType()'
+                )
+            }
+            def existing = typeMap[type]
+            if (existing) {
+                throw new IllegalStateException(
+                        "Duplicate databaseType '$type' declared by both " +
+                        "$existing.class.name and $it.class.name. " +
+                        'Each DatabaseCleaner must declare a unique 
databaseType.'
+                )
+            }
+
+            typeMap[type] = it
+            log.debug(
+                    'Discovered DatabaseCleaner implementation: {} (type: {})',
+                    it.class.name,
+                    type
+            )
+        }
+        typeMap.asImmutable()
+    }
+
+    /**
+     * @return the Spring {@link ApplicationContext}, or null if not yet 
resolved
+     */
+    ApplicationContext getApplicationContext() {
+        applicationContext
+    }
+
+    /**
+     * Sets the application context. Called by the interceptor when the test's
+     * Spring context becomes available.
+     */
+    void setApplicationContext(ApplicationContext applicationContext) {
+        this.applicationContext = applicationContext
+    }
+
+    /**
+     * Performs cleanup on data sources found in the application context using 
the
+     * provided mapping from the {@link DatabaseCleanup} annotation.
+     *
+     * <p>If the mapping specifies explicit database types for data sources, 
those types
+     * are used to look up the cleaner directly. Otherwise, auto-discovery via
+     * {@link DatabaseCleaner#supports(DataSource)} is used.</p>
+     *
+     * @param mapping the parsed annotation value describing which data 
sources to clean
+     *        and optionally which cleaner types to use
+     * @return a list of {@link DatabaseCleanupStats}, one per datasource 
cleaned
+     * @throws IllegalStateException if a datasource marked for cleanup has no
+     *         matching {@link DatabaseCleaner} on the classpath, if an 
explicitly
+     *         specified database type has no matching cleaner, or if a 
specified
+     *         datasource bean does not exist in the application context
+     */
+    List<DatabaseCleanupStats> performCleanup(DatasourceCleanupMapping 
mapping) {
+        if (!applicationContext) {
+            throw new IllegalStateException(
+                    'Cannot perform database cleanup: ApplicationContext is 
not available'
+            )
+        }
+        if (!cleanersByType) {
+            throw new IllegalStateException(
+                    'Cannot perform database cleanup: no DatabaseCleaner 
implementations found'
+            )
+        }
+
+        def allDataSources = applicationContext.getBeansOfType(DataSource)
+        def allStats = [] as List<DatabaseCleanupStats>
+
+        if (mapping.cleanAll) {
+            // Clean all data sources using auto-discovery
+            allDataSources.each { beanName, dataSource ->
+                def cleaner = findCleanerFor(dataSource)
+                if (!cleaner) {
+                    throw new IllegalStateException(
+                            'No DatabaseCleaner implementation found that 
supports ' +
+                            "datasource '$beanName'. Ensure that a 
database-specific " +
+                            'cleanup library (e.g., 
grails-testing-support-dbcleanup-h2) ' +
+                            'is on the classpath for each database type used 
in your tests. ' +
+                            "Available cleaners: 
${cleanersByType.values()*.databaseType()}"
+                    )
+                }
+
+                log.debug(
+                        'Cleaning up datasource: {} (using {} cleaner)',
+                        beanName,
+                        cleaner.databaseType()
+                )
+                def stats = cleaner.cleanup(applicationContext, dataSource)
+                stats.datasourceName = beanName
+                if (stats.tableRowCounts) {
+                    log.debug(
+                            'Cleaned {} tables from datasource {}',
+                            stats.tableRowCounts.size(),
+                            beanName
+                    )
+                }
+                allStats << stats
+            }
+        } else {
+            // Clean specific data sources per the mapping entries
+            mapping.entries.each {

Review Comment:
   Why not leave this as `for`



##########
grails-testing-support-dbcleanup-core/src/main/groovy/org/apache/grails/testing/cleanup/core/DatabaseCleanupInterceptor.groovy:
##########
@@ -119,41 +132,43 @@ class DatabaseCleanupInterceptor extends 
AbstractMethodInterceptor {
             return
         }
 
-        ApplicationContext appCtx = resolver.resolve(invocation)
+        def appCtx = resolver.resolve(invocation)
         if (appCtx) {
             context.applicationContext = appCtx
         }
         else {
             throw new IllegalStateException(
-                'Could not resolve ApplicationContext from test instance. 
Ensure the spec is annotated with @Integration.')
+                'Could not resolve ApplicationContext from test instance. ' +
+                'Ensure the spec is annotated with @Integration.'
+            )
         }
     }
 
     /**
      * Logs cleanup statistics and overall timing information for the cleanup 
operation.
      *
-     * @param statsList the list of cleanup statistics from individual 
datasources
+     * @param statsList the list of cleanup statistics from individual data 
sources
      * @param overallStartTime the overall start time of the cleanup operation
      */
     private static void logStats(List<DatabaseCleanupStats> statsList, long 
overallStartTime) {
         if (DatabaseCleanupStats.debugEnabled) {
             long overallEndTime = System.currentTimeMillis()
             long overallDuration = overallEndTime - overallStartTime
 
-            String separator = 
'=========================================================='
-            String startTimeFormatted = 
DatabaseCleanupStats.formatTime(overallStartTime)
-            String endTimeFormatted = 
DatabaseCleanupStats.formatTime(overallEndTime)
+            def separator = 
'=========================================================='
+            def startTimeFormatted = 
DatabaseCleanupStats.formatTime(overallStartTime)
+            def endTimeFormatted = 
DatabaseCleanupStats.formatTime(overallEndTime)
 
-            System.out.println(separator)
-            System.out.println('Overall Cleanup Timing')
-            System.out.println("Start Time: ${startTimeFormatted}")
-            System.out.println("End Time:   ${endTimeFormatted}")
-            System.out.println("Duration:   ${overallDuration} ms")
-            System.out.println(separator)
+            println(separator)
+            println('Overall Cleanup Timing')
+            println("Start Time: $startTimeFormatted")
+            println("End Time:   $endTimeFormatted")
+            println("Duration:   $overallDuration ms")
+            println(separator)
 
-            for (DatabaseCleanupStats stats : statsList) {
-                if (stats.tableRowCounts) {
-                    System.out.println(stats.toFormattedReport())
+            statsList.each {

Review Comment:
   `for`



##########
grails-testing-support-dbcleanup-h2/src/main/groovy/org/apache/grails/testing/cleanup/h2/H2DatabaseCleaner.groovy:
##########
@@ -57,53 +55,36 @@ class H2DatabaseCleaner implements DatabaseCleaner {
 
     @Override
     boolean supports(DataSource dataSource) {
-        Connection connection = null
-        try {
-            connection = dataSource.getConnection()
-            DatabaseMetaData metaData = connection.getMetaData()
-            String url = metaData.getURL()
-            return url && url.startsWith('jdbc:h2:')
-        }
-        catch (Exception e) {
+        try (def con = dataSource.connection) {

Review Comment:
   Doesn't this break groovydoc?



##########
grails-testing-support-dbcleanup-postgresql/src/main/groovy/org/apache/grails/testing/cleanup/postgresql/PostgresDatabaseCleanupHelper.groovy:
##########
@@ -16,67 +16,52 @@
  *  specific language governing permissions and limitations
  *  under the License.
  */
-
 package org.apache.grails.testing.cleanup.postgresql
 
-import java.sql.Connection
-import java.sql.DatabaseMetaData
-
 import javax.sql.DataSource
 
 import groovy.transform.CompileStatic
 import groovy.util.logging.Slf4j
 
 /**
- * Helper utility for PostgreSQL database cleanup operations. Provides 
PostgreSQL-specific logic such as
- * resolving the current schema from a {@link DataSource} by inspecting JDBC 
connection metadata
- * and parsing PostgreSQL JDBC URLs.
+ * Helper utility for PostgreSQL database cleanup operations.
+ * Provides PostgreSQL-specific logic such as resolving the
+ * current schema from a {@link DataSource} by inspecting
+ * JDBC connection metadata and parsing PostgreSQL JDBC URLs.
  */
 @Slf4j
 @CompileStatic
 class PostgresDatabaseCleanupHelper {
 
     /**
-     * Resolves the current schema for the given PostgreSQL datasource by 
inspecting the JDBC connection metadata.
-     * If the JDBC URL contains a `currentSchema` parameter, returns that 
schema.
+     * Resolves the current schema for the given PostgreSQL datasource
+     * by inspecting the JDBC connection metadata. If the JDBC URL
+     * contains a `currentSchema` parameter, returns that schema.
      * Otherwise, returns the connection's current schema.
      *
      * @param dataSource the datasource to resolve the schema for
      * @return the schema name, or {@code null} if it cannot be determined
      */
     static String resolveCurrentSchema(DataSource dataSource) {
-        Connection connection = null
-        try {
-            connection = dataSource.getConnection()
-            String schema = connection.getSchema()
+        try (def con = dataSource.connection) {
+            def schema = con.getSchema()
             if (schema) {
                 log.debug('Resolved current schema from connection: {}', 
schema)
                 return schema
             }
 
-            // Fallback: try to get the schema from the database metadata URL
-            DatabaseMetaData metaData = connection.getMetaData()
-            String url = metaData.getURL()
+            def url = con.metaData.URL
             if (url) {
                 schema = extractCurrentSchemaFromUrl(url)
-                if (schema) {
-                    log.debug('Resolved current schema from URL {}: {}', url, 
schema)
-                    return schema
-                }
-            }
-        }
-        finally {
-            if (connection) {
-                try {
-                    connection.close()
-                }
-                catch (Exception ignored) {
-                    // ignore
-                }
+                log.debug('Resolved current schema from URL {}: {}', url, 
schema)
+                return schema
             }
         }
-
-        throw new IllegalStateException("Because postgres defaults to the 
search_path when currentSchema isn't defined, a schema should always be found")
+        throw new IllegalStateException(
+                'Because postgres defaults to the search_path ' +

Review Comment:
   Isn't string concatenation historically slow?   It probably doesn't matter 
b/c we're exceptioning, but this seems harder to read since we then also have 
to escape the apostrophe



##########
grails-testing-support-dbcleanup-core/src/main/groovy/org/apache/grails/testing/cleanup/core/DatabaseCleanupContext.groovy:
##########
@@ -0,0 +1,220 @@
+/*
+ *  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
+ *
+ *    https://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.grails.testing.cleanup.core
+
+import javax.sql.DataSource
+
+import groovy.transform.CompileStatic
+import groovy.util.logging.Slf4j
+
+import org.springframework.context.ApplicationContext
+
+/**
+ * Context that holds the discovered {@link DatabaseCleaner} implementations 
and
+ * provides access to the application's data sources for cleanup operations.
+ *
+ * <p>Multiple cleaners can be registered (one per database type). When 
performing cleanup,
+ * the context matches each datasource to an appropriate cleaner using either 
an explicit
+ * database type from the {@link DatasourceCleanupMapping} or auto-discovery 
via
+ * {@link DatabaseCleaner#supports(DataSource)}. If a datasource is marked for 
cleanup
+ * but no matching cleaner is found, an error is thrown.</p>
+ */
+@Slf4j
+@CompileStatic
+class DatabaseCleanupContext {
+
+    private ApplicationContext applicationContext
+    private final Map<String, DatabaseCleaner> cleanersByType
+
+    DatabaseCleanupContext(List<DatabaseCleaner> cleaners) {
+        cleanersByType = createCleanersMap(cleaners)
+    }
+
+    private static Map<String, DatabaseCleaner> 
createCleanersMap(List<DatabaseCleaner> cleaners) {
+        def typeMap = [:] as Map<String, DatabaseCleaner>
+        cleaners.each {

Review Comment:
   In cases like this, I actually prefer keeping the `for` 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to