Direct Answer
When groovy.sql.Sql is constructed with a javax.sql.DataSource, it does not acquire a connection per operation. Instead, it lazily obtains a single Connection from the DataSource on the first query execution and retains that connection for the entire lifespan of the Sql instance. Every subsequent statement reuses the same underlying connection.
Calling Sql.close() releases that held connection. If the DataSource is a pooled implementation—such as HikariCP, Apache Commons DBCP, or a container-managed pool—the connection is returned to the pool and becomes available to other borrowers. If the DataSource is a plain, non-pooled driver DataSource, close() physically terminates the JDBC connection.
Confirmed Behavior vs. Version-Dependent Details
The single-connection retention model is a well-established characteristic of groovy.sql.Sql across modern Groovy lines. What is less certain without checking your specific build is the exact timing of the lazy acquisition and any auto-close or error-handling differences introduced between Groovy 2.x and Groovy 3.x/4.x. Treat the "first operation triggers checkout" rule as the expected pattern, but verify against your Groovy version if your code depends on precise transaction boundaries or connection timing.
Practical Steps for This Case
- Scope the
Sql instance tightly. Use try-with-resources or Groovy's withCloseable so close() always runs. A leaked Sql instance holds a pooled connection indefinitely.
- Do not share one
Sql across threads. Because the instance retains a single connection, concurrent use causes contention and interleaved transaction state. Create one Sql per request or task.
- Confirm pool return behavior. If you use a pool, capture the pool's active connection count immediately before and after
close() to verify the connection is returned rather than leaked.
Verification Pattern
A minimal, safe check is to wrap a Sql instance around your existing DataSource, execute one trivial query, and inspect pool metrics. For example, with HikariCP you can log hikariPool.getActiveConnections() before creation, after the query, and after close(). If the count returns to the baseline after close(), the pool is receiving the connection back. If it remains elevated, the Sql instance or the pool wrapper is retaining it.
One Diagnostic Detail That Changes the Recommendation
What is your Groovy version and the concrete DataSource implementation? If you are on an older Groovy 2.x line, auto-close and exception-path behavior may differ. If your DataSource is non-pooled, calling close() is destructive and any downstream code still expecting that connection will fail. Confirming these two facts determines whether you need explicit connection management or can rely on Sql.close() alone.