|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.apache.texera.dao |
| 21 | + |
| 22 | +import com.zaxxer.hikari.{HikariConfig, HikariDataSource} |
| 23 | +import org.jooq.impl.DSL |
| 24 | +import org.scalatest.flatspec.AnyFlatSpec |
| 25 | +import org.scalatest.matchers.should.Matchers |
| 26 | +import org.scalatest.{BeforeAndAfterAll} |
| 27 | + |
| 28 | +class SqlServerSpec extends AnyFlatSpec with Matchers with BeforeAndAfterAll with MockTexeraDB { |
| 29 | + |
| 30 | + override def beforeAll(): Unit = initializeDBAndReplaceDSLContext() |
| 31 | + override def afterAll(): Unit = shutdownDB() |
| 32 | + |
| 33 | + // ------------------------------------------------------------------------- |
| 34 | + // SqlServer.withTransaction |
| 35 | + // |
| 36 | + // getDSLContext is backed by the embedded Postgres DataSource, so each |
| 37 | + // top-level query borrows a connection from the pool. withTransaction |
| 38 | + // binds a single connection for the duration of the block, making rollback |
| 39 | + // and commit behaviour fully observable. |
| 40 | + // ------------------------------------------------------------------------- |
| 41 | + |
| 42 | + "SqlServer.withTransaction" should "return the value produced by the block" in { |
| 43 | + val result = SqlServer.withTransaction(getDSLContext) { _ => 42 } |
| 44 | + result shouldBe 42 |
| 45 | + } |
| 46 | + |
| 47 | + it should "commit the block's work so subsequent queries observe the changes" in { |
| 48 | + // SELECT 1 is a lightweight live query; completing without error confirms |
| 49 | + // the transaction committed and the connection was returned cleanly. |
| 50 | + val result = SqlServer.withTransaction(getDSLContext) { ctx => |
| 51 | + ctx.selectOne().fetchOne().value1() |
| 52 | + } |
| 53 | + result shouldBe 1 |
| 54 | + } |
| 55 | + |
| 56 | + it should "re-throw the exception when the block throws" in { |
| 57 | + val boom = new RuntimeException("intentional failure") |
| 58 | + val thrown = intercept[RuntimeException] { |
| 59 | + SqlServer.withTransaction(getDSLContext) { _ => throw boom } |
| 60 | + } |
| 61 | + thrown.getMessage should include("intentional failure") |
| 62 | + } |
| 63 | + |
| 64 | + it should "roll back all DML in the block when an exception is thrown" in { |
| 65 | + // A permanent (non-TEMP) table is used so every connection from the pool |
| 66 | + // can see it; TEMP tables are session-scoped and would be invisible across |
| 67 | + // pool connections. |
| 68 | + val dsl = getDSLContext |
| 69 | + dsl.execute("CREATE TABLE IF NOT EXISTS _txn_rollback_test (v INT)") |
| 70 | + try { |
| 71 | + intercept[RuntimeException] { |
| 72 | + SqlServer.withTransaction(dsl) { ctx => |
| 73 | + ctx.execute("INSERT INTO _txn_rollback_test VALUES (99)") |
| 74 | + throw new RuntimeException("force rollback") |
| 75 | + } |
| 76 | + } |
| 77 | + // The INSERT was inside the rolled-back transaction, so the table must |
| 78 | + // still be empty. |
| 79 | + dsl.fetchCount(DSL.table(DSL.name("_txn_rollback_test"))) shouldBe 0 |
| 80 | + } finally { |
| 81 | + dsl.execute("DROP TABLE IF EXISTS _txn_rollback_test") |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + it should "support nested return types beyond Int" in { |
| 86 | + val result = SqlServer.withTransaction(getDSLContext) { ctx => |
| 87 | + ctx.selectOne().fetchOne().value1().toString |
| 88 | + } |
| 89 | + result shouldBe "1" |
| 90 | + } |
| 91 | + |
| 92 | + // ------------------------------------------------------------------------- |
| 93 | + // HikariCP pool lifecycle and configuration |
| 94 | + // |
| 95 | + // These tests create their own HikariDataSource against the embedded Postgres |
| 96 | + // instance so they can drive the pool directly, independently of the |
| 97 | + // DSLContext replacement that MockTexeraDB applies for its own queries. |
| 98 | + // ------------------------------------------------------------------------- |
| 99 | + |
| 100 | + private def buildPool( |
| 101 | + maxSize: Int = 5, |
| 102 | + minIdle: Int = 1, |
| 103 | + poolName: String = "spec-pool" |
| 104 | + ): HikariDataSource = { |
| 105 | + // Use the default "postgres" database so no schema setup is needed. |
| 106 | + val jdbcUrl = getDBInstance.getJdbcUrl("postgres", "postgres") |
| 107 | + val cfg = new HikariConfig() |
| 108 | + cfg.setJdbcUrl(jdbcUrl) |
| 109 | + cfg.setUsername("postgres") |
| 110 | + cfg.setPassword("") |
| 111 | + cfg.setPoolName(poolName) |
| 112 | + cfg.setMaximumPoolSize(maxSize) |
| 113 | + cfg.setMinimumIdle(minIdle) |
| 114 | + cfg.setConnectionTimeout(5000) |
| 115 | + new HikariDataSource(cfg) |
| 116 | + } |
| 117 | + |
| 118 | + "HikariCP pool" should "provide a usable connection that can execute queries" in { |
| 119 | + val ds = buildPool() |
| 120 | + try { |
| 121 | + val conn = ds.getConnection |
| 122 | + try { |
| 123 | + val rs = conn.prepareStatement("SELECT 1").executeQuery() |
| 124 | + rs.next() shouldBe true |
| 125 | + rs.getInt(1) shouldBe 1 |
| 126 | + } finally conn.close() |
| 127 | + } finally ds.close() |
| 128 | + } |
| 129 | + |
| 130 | + it should "apply the configured pool name" in { |
| 131 | + val ds = buildPool(poolName = "my-named-pool") |
| 132 | + try { |
| 133 | + ds.getHikariConfigMXBean.getPoolName shouldBe "my-named-pool" |
| 134 | + } finally ds.close() |
| 135 | + } |
| 136 | + |
| 137 | + it should "apply the configured maximum pool size" in { |
| 138 | + val ds = buildPool(maxSize = 7) |
| 139 | + try { |
| 140 | + ds.getHikariConfigMXBean.getMaximumPoolSize shouldBe 7 |
| 141 | + } finally ds.close() |
| 142 | + } |
| 143 | + |
| 144 | + it should "apply the configured minimum idle connections" in { |
| 145 | + val ds = buildPool(minIdle = 2) |
| 146 | + try { |
| 147 | + ds.getHikariConfigMXBean.getMinimumIdle shouldBe 2 |
| 148 | + } finally ds.close() |
| 149 | + } |
| 150 | + |
| 151 | + it should "count a borrowed connection as active" in { |
| 152 | + val ds = buildPool() |
| 153 | + try { |
| 154 | + val conn = ds.getConnection |
| 155 | + try { |
| 156 | + ds.getHikariPoolMXBean.getActiveConnections should be >= 1 |
| 157 | + } finally conn.close() |
| 158 | + } finally ds.close() |
| 159 | + } |
| 160 | + |
| 161 | + it should "decrement active count and increment idle count once a connection is returned" in { |
| 162 | + val ds = buildPool() |
| 163 | + try { |
| 164 | + val conn = ds.getConnection |
| 165 | + conn.close() |
| 166 | + ds.getHikariPoolMXBean.getActiveConnections shouldBe 0 |
| 167 | + ds.getHikariPoolMXBean.getIdleConnections should be >= 1 |
| 168 | + } finally ds.close() |
| 169 | + } |
| 170 | + |
| 171 | + it should "allow up to the maximum pool size connections to be borrowed concurrently" in { |
| 172 | + val ds = buildPool(maxSize = 3) |
| 173 | + try { |
| 174 | + val c1 = ds.getConnection |
| 175 | + val c2 = ds.getConnection |
| 176 | + val c3 = ds.getConnection |
| 177 | + ds.getHikariPoolMXBean.getActiveConnections shouldBe 3 |
| 178 | + c1.close(); c2.close(); c3.close() |
| 179 | + } finally ds.close() |
| 180 | + } |
| 181 | + |
| 182 | + it should "report isClosed as false while open and true after close" in { |
| 183 | + val ds = buildPool() |
| 184 | + ds.isClosed shouldBe false |
| 185 | + ds.close() |
| 186 | + ds.isClosed shouldBe true |
| 187 | + } |
| 188 | + |
| 189 | + it should "reject getConnection after the pool has been closed" in { |
| 190 | + val ds = buildPool() |
| 191 | + ds.close() |
| 192 | + // HikariCP throws an SQLException (wrapped as RuntimeException by the pool) |
| 193 | + // when a caller tries to borrow from a closed pool. |
| 194 | + assertThrows[Exception](ds.getConnection) |
| 195 | + } |
| 196 | + |
| 197 | + // ------------------------------------------------------------------------- |
| 198 | + // SqlServer.close() |
| 199 | + // |
| 200 | + // The instance's private HikariDataSource is the only resource that needs |
| 201 | + // explicit release; close() guards it against double-close. These tests |
| 202 | + // construct a fresh SqlServer via initConnection (the only public entry |
| 203 | + // point — the class constructor is private) and assert against the |
| 204 | + // underlying pool via reflection, which avoids broadening the class API |
| 205 | + // just to make this branch observable. |
| 206 | + // ------------------------------------------------------------------------- |
| 207 | + |
| 208 | + private def datasourceOf(instance: SqlServer): HikariDataSource = { |
| 209 | + val field = classOf[SqlServer].getDeclaredField("dataSource") |
| 210 | + field.setAccessible(true) |
| 211 | + field.get(instance).asInstanceOf[HikariDataSource] |
| 212 | + } |
| 213 | + |
| 214 | + "SqlServer.close" should "shut down the underlying HikariDataSource and be idempotent" in { |
| 215 | + val jdbcUrl = getDBInstance.getJdbcUrl("postgres", "postgres") |
| 216 | + // Replaces the singleton — initConnection internally calls close() on the |
| 217 | + // prior instance, which is itself an exercise of the same path. The trait |
| 218 | + // holds its own DSLContext separately, so other tests' database access is |
| 219 | + // unaffected by this replacement. |
| 220 | + SqlServer.initConnection(jdbcUrl, "postgres", "") |
| 221 | + val instance = SqlServer.getInstance() |
| 222 | + val ds = datasourceOf(instance) |
| 223 | + |
| 224 | + ds.isClosed shouldBe false |
| 225 | + instance.close() |
| 226 | + ds.isClosed shouldBe true |
| 227 | + |
| 228 | + // Second close() must take the `dataSource.isClosed` branch and return |
| 229 | + // without throwing. Calling Hikari's close() twice would itself be safe |
| 230 | + // today, but the guard is what this assertion pins. |
| 231 | + noException should be thrownBy instance.close() |
| 232 | + ds.isClosed shouldBe true |
| 233 | + } |
| 234 | +} |
0 commit comments