This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9448-04bce08d75fee3189aa97f2f47da2aac6cc0ff38 in repository https://gitbox.apache.org/repos/asf/texera.git
commit 4b4a0c386d81a247bd1d49b7f686fc93e509e2f9 Author: Xinyuan Lin <[email protected]> AuthorDate: Mon Nov 16 02:27:59 2026 +0000 refactor(workflow-operator): share SQL source cursor logic (#9448) ### What changes were proposed in this PR? Share row iteration, cached tuples and progressive batch limits across the JDBC and AsterixDB SQL sources. Each adapter retains its own cursor operation and query. Reuse the MySQL and PostgreSQL descriptor and executor fixtures, and share the AsterixDB HTTP fixture across its suites. The diff removes 365 net lines. ### Any related issues, documentation, discussions? Closes #9447. ### How was this PR tested? All 204 tests in 11 SQL suites passed on main and on this change, with identical test names, order and outcomes within each suite. ```bash sql=org.apache.texera.amber.operator.source.sql sbt "WorkflowOperator/testOnly $sql.SQLSourceOpDescSpec $sql.SQLSourceOpExecSpec $sql.asterixdb.AsterixDBConnUtilSpec $sql.asterixdb.AsterixDBSourceOpDescSpec $sql.asterixdb.AsterixDBSourceOpExecSpec $sql.mysql.MySQLConnUtilSpec $sql.mysql.MySQLSourceOpDescSpec $sql.mysql.MySQLSourceOpExecSpec $sql.postgresql.PostgreSQLConnUtilSpec $sql.postgresql.PostgreSQLSourceOpDescSpec $sql.postgresql.PostgreSQLSourceOpExecSpec" sbt "WorkflowOperator/scalafmtCheck" "WorkflowOperator/Test/scalafmtCheck" \ "WorkflowOperator/scalafix --check" "WorkflowOperator/Test/scalafix --check" ``` ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Codex (GPT-6) and Claude Code (Claude Opus 5.5) --- .../operator/source/sql/SQLSourceOpExec.scala | 73 +++-- .../sql/asterixdb/AsterixDBSourceOpExec.scala | 103 ++----- .../source/sql/mysql/MySQLSourceOpExec.scala | 25 +- .../sql/postgresql/PostgreSQLSourceOpExec.scala | 31 +-- .../source/sql/JdbcSourceOpDescBehaviors.scala | 110 ++++++++ .../source/sql/JdbcSourceOpExecTestHarness.scala | 302 +++++++++++++++++++++ .../operator/source/sql/SQLSourceOpExecSpec.scala | 125 ++++----- .../sql/asterixdb/AsterixDBConnUtilSpec.scala | 70 +---- .../sql/asterixdb/AsterixDBSourceOpDescSpec.scala | 123 ++------- .../sql/asterixdb/AsterixDBSourceOpExecSpec.scala | 49 +--- .../source/sql/asterixdb/AsterixDBTestServer.scala | 97 +++++++ .../source/sql/mysql/MySQLSourceOpDescSpec.scala | 85 +----- .../source/sql/mysql/MySQLSourceOpExecSpec.scala | 284 ++----------------- .../postgresql/PostgreSQLSourceOpDescSpec.scala | 87 +----- .../postgresql/PostgreSQLSourceOpExecSpec.scala | 285 ++----------------- 15 files changed, 742 insertions(+), 1107 deletions(-) diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala index 9931f98890..e113466616 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExec.scala @@ -49,7 +49,35 @@ abstract class SQLSourceOpExec(descString: String) extends SourceOperatorExecuto * * @return Iterator[TupleLike] */ - override def produceTuple(): Iterator[TupleLike] = { + override def produceTuple(): Iterator[TupleLike] = + iterateRows[ResultSet](curResultSet, _.next())(fetchNextJdbcResult, clearJdbcResult) + + private def fetchNextJdbcResult(): Boolean = { + curQuery = getNextQuery + curQuery match { + case Some(query) => + curResultSet = Option(query.executeQuery) + true + case None => + curResultSet = None + false + } + } + + private def clearJdbcResult(): Unit = { + curResultSet.foreach(_.close()) + curQuery.foreach(_.close()) + curResultSet = None + curQuery = None + } + + protected final def iterateRows[R]( + currentRows: => Option[R], + advanceRow: R => Boolean + )( + fetchNextResult: () => Boolean, + clearResult: () => Unit + ): Iterator[TupleLike] = { new Iterator[TupleLike]() { override def hasNext: Boolean = { cachedTuple match { @@ -85,9 +113,9 @@ abstract class SQLSourceOpExec(descString: String) extends SourceOperatorExecuto while (true) { breakable { - curResultSet match { - case Some(resultSet) => - if (resultSet.next()) { + currentRows match { + case Some(rows) => + if (advanceRow(rows)) { // manually skip until the offset position in order to adapt to progressive batches curOffset.foreach(offset => { @@ -111,23 +139,10 @@ abstract class SQLSourceOpExec(descString: String) extends SourceOperatorExecuto }) return tuple } else { - // close the current resultSet and query - curResultSet.foreach(resultSet => resultSet.close()) - curQuery.foreach(query => query.close()) - curResultSet = None - curQuery = None - break() + clearResult() } case None => - curQuery = getNextQuery - curQuery match { - case Some(query) => - curResultSet = Option(query.executeQuery) - break() - case None => - curResultSet = None - return null - } + if (!fetchNextResult()) return null } } @@ -383,8 +398,28 @@ abstract class SQLSourceOpExec(descString: String) extends SourceOperatorExecuto @throws[SQLException] protected def loadTableNames(): Unit + protected final def collectTableNames(preparedStatement: PreparedStatement): Unit = { + val resultSet = preparedStatement.executeQuery() + while (resultSet.next()) tableNames += resultSet.getString(1) + resultSet.close() + preparedStatement.close() + } + protected def addFilterConditions(queryBuilder: StringBuilder): Unit + protected final def addJdbcKeywordCondition(queryBuilder: StringBuilder, column: String)( + enabled: => Boolean, + typeForColumn: => AttributeType + )(conditionFor: String => String): Unit = { + if (enabled) { + val columnType = typeForColumn + if (columnType != AttributeType.STRING) + throw new RuntimeException("Can't do keyword search on type " + columnType.toString) + // in sql prepared statement, column name cannot be inserted using PreparedStatement.setString either + queryBuilder ++= conditionFor(column) + } + } + /** * generate sql query string using the info provided by user. One of following * select * from TableName where 1 = 1 AND MATCH (ColumnName) AGAINST ( ? IN BOOLEAN MODE) LIMIT ?; diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExec.scala index c08c79b2aa..e6251abded 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExec.scala @@ -46,7 +46,6 @@ class AsterixDBSourceOpExec private[asterixdb] ( private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC)) - private var curQueryString: Option[String] = None private var curResultIterator: Option[Iterator[AnyRef]] = None override def open(): Unit = { @@ -55,86 +54,26 @@ class AsterixDBSourceOpExec private[asterixdb] ( super.open() } - /** - * A generator of a Tuple, which converted from a CSV row of fields from AsterixDB - * - * @return Iterator[TupleLike] - */ - override def produceTuple(): Iterator[TupleLike] = { - new Iterator[TupleLike]() { - override def hasNext: Boolean = { - - cachedTuple match { - // if existing Tuple in cache, means there exist next Tuple. - case Some(_) => true - case None => - // cache the next Tuple - cachedTuple = Option(next()) - cachedTuple.isDefined - } - } - - override def next(): Tuple = { - // if has the next Tuple in cache, return it and clear the cache - cachedTuple.foreach(tuple => { - cachedTuple = None - return tuple - }) - - // otherwise, send query to fetch for the next Tuple - - while (true) { - breakable { - curResultIterator match { - case Some(resultSet) => - if (resultSet.hasNext) { - - // manually skip until the offset position in order to adapt to progressive batches - curOffset.foreach(offset => { - if (offset > 0) { - curOffset = Option(offset - 1) - break() - } - }) - - // construct Tuple from the next result. - val tuple = buildTupleFromRow - - if (tuple == null) - break() - - // update the limit in order to adapt to progressive batches - curLimit.foreach(limit => { - if (limit > 0) { - curLimit = Option(limit - 1) - } - }) - return tuple - } else { - // close the current resultSet and query - curResultIterator = None - curQueryString = None - break() - } - case None => - curQueryString = if (hasNextQuery) generateSqlQuery else None - curQueryString match { - case Some(query) => - curResultIterator = queryAsterixDB(desc.host, desc.port, query) - break() - case None => - curResultIterator = None - return null - } - } - } - } - null - - } + override def produceTuple(): Iterator[TupleLike] = + iterateRows[Iterator[AnyRef]](curResultIterator, _.hasNext)( + fetchNextHttpResult, + clearHttpResult + ) + + private def fetchNextHttpResult(): Boolean = { + val query = if (hasNextQuery) generateSqlQuery else None + query match { + case Some(sql) => + curResultIterator = queryAsterixDB(desc.host, desc.port, sql) + true + case None => + curResultIterator = None + false } } + private def clearHttpResult(): Unit = curResultIterator = None + /** * Build a Tuple from a row of curResultIterator * @@ -182,13 +121,7 @@ class AsterixDBSourceOpExec private[asterixdb] ( } - /** - * close curResultIterator, curQueryString - */ - override def close(): Unit = { - curResultIterator = None - curQueryString = None - } + override def close(): Unit = clearHttpResult() /** * add naive support for full text search. diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExec.scala index bd494a940b..e0c45789dc 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.source.sql.mysql -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.source.sql.SQLSourceOpExec import org.apache.texera.amber.operator.source.sql.mysql.MySQLConnUtil.connect import org.apache.texera.amber.util.JSONUtils.objectMapper @@ -43,16 +42,11 @@ class MySQLSourceOpExec private[mysql] ( @throws[RuntimeException] override def addFilterConditions(queryBuilder: StringBuilder): Unit = { val keywordSearchByColumn = desc.keywordSearchByColumn.orNull - if ( - desc.keywordSearch.getOrElse(false) && keywordSearchByColumn != null && desc.keywords != null - ) { - val columnType = schema.getAttribute(keywordSearchByColumn).getType - - if (columnType == AttributeType.STRING) - // in sql prepared statement, column name cannot be inserted using PreparedStatement.setString either - queryBuilder ++= " AND MATCH(" + keywordSearchByColumn + ") AGAINST (? IN BOOLEAN MODE)" - else - throw new RuntimeException("Can't do keyword search on type " + columnType.toString) + addJdbcKeywordCondition(queryBuilder, keywordSearchByColumn)( + desc.keywordSearch.getOrElse(false) && keywordSearchByColumn != null && desc.keywords != null, + schema.getAttribute(keywordSearchByColumn).getType + ) { column => + " AND MATCH(" + column + ") AGAINST (? IN BOOLEAN MODE)" } } @@ -60,13 +54,6 @@ class MySQLSourceOpExec private[mysql] ( override protected def loadTableNames(): Unit = { val preparedStatement = connection.prepareStatement(FETCH_TABLE_NAMES_SQL) preparedStatement.setString(1, desc.database) - val resultSet = preparedStatement.executeQuery - while ({ - resultSet.next - }) { - tableNames += resultSet.getString(1) - } - resultSet.close() - preparedStatement.close() + collectTableNames(preparedStatement) } } diff --git a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExec.scala b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExec.scala index 4ce3a34cdd..fd0c5909fd 100644 --- a/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExec.scala +++ b/common/workflow-operator/src/main/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.source.sql.postgresql -import org.apache.texera.amber.core.tuple.AttributeType import org.apache.texera.amber.operator.source.sql.SQLSourceOpExec import org.apache.texera.amber.operator.source.sql.postgresql.PostgreSQLConnUtil.connect import org.apache.texera.amber.util.JSONUtils.objectMapper @@ -41,33 +40,19 @@ class PostgreSQLSourceOpExec private[postgresql] (descString: String) @throws[RuntimeException] override def addFilterConditions(queryBuilder: StringBuilder): Unit = { val keywordSearchByColumn = desc.keywordSearchByColumn.orNull - if ( - desc.keywordSearch.getOrElse(false) && keywordSearchByColumn != null && desc.keywords != null - ) { - val columnType = schema.getAttribute(keywordSearchByColumn).getType - - if (columnType == AttributeType.STRING) { - // in sql prepared statement, column name cannot be inserted using PreparedStatement.setString either - queryBuilder ++= " AND " + keywordSearchByColumn + " @@ to_tsquery(?)" - - // OPTIMIZE: no fulltext index is required, having a built fulltext index can help performance on large dataset. - - // OPTIMIZE: limited support on the default language, english. equivalent `to_tsquery('english', ?)` - } else - throw new RuntimeException("Can't do keyword search on type " + columnType.toString) + addJdbcKeywordCondition(queryBuilder, keywordSearchByColumn)( + desc.keywordSearch.getOrElse(false) && keywordSearchByColumn != null && desc.keywords != null, + schema.getAttribute(keywordSearchByColumn).getType + ) { column => + // PostgreSQL can run this search without a full-text index. + // to_tsquery uses the database's default language configuration. + " AND " + column + " @@ to_tsquery(?)" } } @throws[SQLException] override protected def loadTableNames(): Unit = { val preparedStatement = connection.prepareStatement(FETCH_TABLE_NAMES_SQL) - val resultSet = preparedStatement.executeQuery - while ({ - resultSet.next - }) { - tableNames += resultSet.getString(1) - } - resultSet.close() - preparedStatement.close() + collectTableNames(preparedStatement) } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpDescBehaviors.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpDescBehaviors.scala new file mode 100644 index 0000000000..530ce29adc --- /dev/null +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpDescBehaviors.scala @@ -0,0 +1,110 @@ +/* + * 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.texera.amber.operator.source.sql + +import org.apache.texera.amber.core.executor.OpExecWithClassName +import org.apache.texera.amber.core.workflow.WorkflowContext.{ + DEFAULT_EXECUTION_ID, + DEFAULT_WORKFLOW_ID +} +import org.apache.texera.amber.operator.LogicalOp +import org.apache.texera.amber.operator.metadata.OperatorGroupConstants +import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import scala.reflect.ClassTag + +trait JdbcSourceOpDescBehaviors extends AnyFlatSpec with Matchers { + protected final def jdbcSourceContract[D <: SQLSourceOpDesc: ClassTag]( + databaseName: String, + operatorType: String, + executorClassName: String, + newDescriptor: => D + ): Unit = { + val descriptorName = implicitly[ClassTag[D]].runtimeClass.getSimpleName + + s"$descriptorName.operatorInfo" should + s"advertise the $databaseName source in the Database Connector group with no input and one output" in { + val info = (newDescriptor).operatorInfo + info.userFriendlyName shouldBe s"$databaseName Source" + info.operatorDescription shouldBe s"Read data from a $databaseName instance" + info.operatorGroupName shouldBe OperatorGroupConstants.DATABASE_GROUP + info.inputPorts shouldBe empty + info.outputPorts should have length 1 + } + + descriptorName should "default its connection and query fields" in { + val d = newDescriptor + d.host shouldBe null + d.port shouldBe null + d.database shouldBe null + d.table shouldBe null + d.limit shouldBe None + d.offset shouldBe None + d.keywordSearch shouldBe Some(false) + d.progressive shouldBe Some(false) + d.interval shouldBe 0L + } + + s"$descriptorName.sourceSchema" should "prompt for connection details before a connection is configured" in { + val ex = intercept[IllegalArgumentException]((newDescriptor).sourceSchema()) + ex.getMessage should include("host") + } + + s"$descriptorName.getPhysicalOp" should + s"wire the $databaseName exec as a source op with no input port and one output port" in { + val d = newDescriptor + val physical = d.getPhysicalOp(DEFAULT_WORKFLOW_ID, DEFAULT_EXECUTION_ID) + physical.opExecInitInfo match { + case OpExecWithClassName(className, _) => + className shouldBe executorClassName + case other => fail(s"expected OpExecWithClassName, got $other") + } + physical.inputPorts.keySet shouldBe empty + physical.outputPorts.keySet shouldBe d.operatorInfo.outputPorts.map(_.id).toSet + } + + descriptorName should "round-trip its config fields through the polymorphic base" in { + val d = newDescriptor + d.host = "localhost" + d.database = "db" + d.table = "t" + d.username = "secret-user" + d.password = "secret-pass" + d.limit = Some(5L) + val json = objectMapper.writeValueAsString(d) + json should include(s"""\"operatorType\":\"$operatorType\"""") + // Unlike AsterixDBSourceOpDesc (which drops credentials via @JsonIgnoreProperties), the SQL + // base persists username/password in plaintext; pin that behavior so any future change is visible. + json should include("secret-user") + json should include("secret-pass") + val restored = objectMapper.readValue(json, classOf[LogicalOp]) + restored shouldBe a[D] + val r = restored.asInstanceOf[D] + r.host shouldBe "localhost" + r.database shouldBe "db" + r.table shouldBe "t" + r.username shouldBe "secret-user" + r.password shouldBe "secret-pass" + r.limit shouldBe Some(5L) + } + } +} diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpExecTestHarness.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpExecTestHarness.scala new file mode 100644 index 0000000000..0f52ec793c --- /dev/null +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/JdbcSourceOpExecTestHarness.scala @@ -0,0 +1,302 @@ +/* + * 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.texera.amber.operator.source.sql + +import org.apache.texera.amber.core.tuple.Tuple +import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.scalamock.scalatest.MockFactory +import org.scalatest.BeforeAndAfterAll +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers + +import java.sql.{ + Connection, + DatabaseMetaData, + Driver, + DriverManager, + DriverPropertyInfo, + PreparedStatement, + ResultSet, + SQLException, + SQLFeatureNotSupportedException +} +import java.util.Properties +import java.util.logging.Logger +import scala.collection.mutable + +private[sql] trait JdbcSourceOpExecTestHarness extends MockFactory with BeforeAndAfterAll { + this: AnyFlatSpec with Matchers => + + protected def jdbcUrlPrefix: String + protected def tableListingSql: String + protected def listingDatabase: Option[String] = None + + /** Returns pre-armed connections for the dialect’s test URL prefix. */ + protected final class StubDriver extends Driver { + private val armed = mutable.Queue.empty[Connection] + var lastUrl: String = _ + var lastProperties: Properties = _ + + def arm(connection: Connection): Unit = armed.enqueue(connection) + + override def connect(url: String, info: Properties): Connection = { + if (!acceptsURL(url)) return null + lastUrl = url + lastProperties = info + if (armed.isEmpty) throw new SQLException("stub driver: no connection armed for " + url) + armed.dequeue() + } + + override def acceptsURL(url: String): Boolean = url != null && url.startsWith(jdbcUrlPrefix) + override def getPropertyInfo(url: String, info: Properties): Array[DriverPropertyInfo] = + Array.empty + override def getMajorVersion: Int = 1 + override def getMinorVersion: Int = 0 + override def jdbcCompliant(): Boolean = false + override def getParentLogger: Logger = throw new SQLFeatureNotSupportedException() + } + + protected lazy val stubDriver = new StubDriver + + override def beforeAll(): Unit = { + super.beforeAll() + DriverManager.registerDriver(stubDriver) + } + + override def afterAll(): Unit = { + DriverManager.deregisterDriver(stubDriver) + super.afterAll() + } + + /** A connection answering the `sourceSchema()` JDBC-metadata probe run in the constructor. */ + protected final def schemaConn(columns: Seq[(String, Int)]): Connection = { + val conn = mock[Connection] + val metaData = mock[DatabaseMetaData] + val columnsRs = mock[ResultSet] + // once inside the dialect’s connect method, once inside SQLSourceOpDesc.querySchema + (conn.setReadOnly _).expects(true).twice() + (conn.getMetaData _).expects().returning(metaData) + (metaData + .getColumns(_: String, _: String, _: String, _: String)) + .expects(null, null, "tbl", null) + .returning(columnsRs) + inSequence { + columns.foreach { + case (name, jdbcType) => + (columnsRs.next _).expects().returning(true) + (columnsRs.getString(_: String)).expects("COLUMN_NAME").returning(name) + (columnsRs.getInt(_: String)).expects("DATA_TYPE").returning(jdbcType) + } + (columnsRs.next _).expects().returning(false) + } + (conn.close _).expects() + conn + } + + /** Stubs the `information_schema` probe that `loadTableNames` issues. */ + protected final def expectTableListing(conn: Connection, tables: Seq[String]): Unit = { + val statement = mock[PreparedStatement] + val resultSet = mock[ResultSet] + (conn.prepareStatement(_: String)).expects(tableListingSql).returning(statement) + listingDatabase.foreach(database => (statement.setString _).expects(1, database)) + (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + inSequence { + tables.foreach(_ => (resultSet.next _).expects().returning(true)) + (resultSet.next _).expects().returning(false) + } + inSequence { + tables.foreach(table => (resultSet.getString(_: Int)).expects(1).returning(table)) + } + (resultSet.close _).expects() + (statement.close _).expects() + } + + protected final def configuredDescriptorJson[D <: SQLSourceOpDesc]( + desc: D, + host: String, + port: String + )(configure: D => Unit): String = { + desc.host = host + desc.port = port + desc.database = "db" + desc.table = "tbl" + desc.username = "u" + desc.password = "p" + configure(desc) + objectMapper.writeValueAsString(desc) + } + + protected final def connectionForOpen(tables: Seq[String]): Connection = { + val conn = mock[Connection] + (conn.setReadOnly _).expects(true) + expectTableListing(conn, tables) + conn + } + + protected val baseSelect = "\nSELECT * FROM tbl where 1 = 1" + + protected trait QueryAccess { + def loadTables(): Unit + def filterClause: String + def sqlQuery: Option[String] + } + + protected final def verifyReconnect(expectedUrl: String)(reconnect: => Connection): Unit = { + stubDriver.lastUrl shouldBe expectedUrl + val connection = mock[Connection] + (connection.setReadOnly _).expects(true) + stubDriver.arm(connection) + reconnect should be theSameInstanceAs connection + stubDriver.lastUrl shouldBe expectedUrl + stubDriver.lastProperties.getProperty("user") shouldBe "u" + stubDriver.lastProperties.getProperty("password") shouldBe "p" + } + + protected final def verifyTableListing( + exec: SQLSourceOpExec with QueryAccess, + tables: Seq[String] + ): Unit = { + val conn = mock[Connection] + expectTableListing(conn, tables) + exec.connection = conn + exec.loadTables() + exec.tableNames.toList shouldBe tables.toList + } + + protected final def verifyOpen(exec: SQLSourceOpExec): Unit = { + val conn = connectionForOpen(Seq("other", "tbl")) + stubDriver.arm(conn) + exec.open() + exec.connection should be theSameInstanceAs conn + exec.tableNames.toList shouldBe List("other", "tbl") + exec.batchByAttribute shouldBe None + } + + protected final def verifyMissingTable(exec: SQLSourceOpExec): Unit = { + stubDriver.arm(connectionForOpen(Seq("other"))) + intercept[RuntimeException](exec.open()).getMessage shouldBe "Can't find the given table `tbl`." + } + + protected final def keywordGuardCases( + keyword: String, + expectedClause: String, + placeholderName: String + )(newExec: (SQLSourceOpDesc => Unit) => SQLSourceOpExec with QueryAccess): Unit = { + it should "add nothing when keyword search is switched off" in { + val exec = newExec { desc => + desc.keywordSearch = Option(false) + desc.keywordSearchByColumn = Option("name") + desc.keywords = Option(keyword) + } + exec.filterClause shouldBe "" + } + + it should "add nothing when no search column is configured" in { + val exec = newExec { desc => + desc.keywordSearch = Option(true) + desc.keywords = Option(keyword) + } + exec.filterClause shouldBe "" + } + + it should s"still emit the $placeholderName placeholder when the keywords are missing" in { + val exec = newExec { desc => + desc.keywordSearch = Option(true) + desc.keywordSearchByColumn = Option("name") + } + // The query keeps the placeholder for None, while JDBC parameter binding skips it. + exec.desc.keywords shouldBe None + exec.filterClause shouldBe expectedClause + exec.sqlQuery shouldBe Some(baseSelect + expectedClause + ";") + } + + it should "refuse a keyword search on a non-string column" in { + val exec = newExec { desc => + desc.keywordSearch = Option(true) + desc.keywordSearchByColumn = Option("id") + desc.keywords = Option("42") + } + intercept[RuntimeException](exec.filterClause).getMessage shouldBe + "Can't do keyword search on type integer" + } + + it should "refuse a keyword search on a column that is not in the schema" in { + val exec = newExec { desc => + desc.keywordSearch = Option(true) + desc.keywordSearchByColumn = Option("nope") + desc.keywords = Option("x") + } + intercept[RuntimeException](exec.filterClause).getMessage shouldBe + "nope is not contained in the schema" + } + } + + protected final def verifyRenderedQuery( + exec: SQLSourceOpExec with QueryAccess, + expectedClause: String + ): Unit = { + exec.sqlQuery shouldBe Some(baseSelect + expectedClause + ";") + exec.curLimit = Some(3L) + exec.curOffset = Some(2L) + exec.sqlQuery shouldBe Some(baseSelect + expectedClause + " LIMIT ? OFFSET ?;") + } + + protected final def verifyKeywordRows( + exec: SQLSourceOpExec, + expectedClause: String, + keyword: String, + expectedName: String + ): Unit = { + val conn = connectionForOpen(Seq("tbl")) + val queryStatement = mock[PreparedStatement] + val rows = mock[ResultSet] + + (conn + .prepareStatement(_: String)) + .expects(baseSelect + expectedClause + ";") + .returning(queryStatement) + (queryStatement.setString _).expects(1, keyword) + (queryStatement.executeQuery: () => ResultSet).expects().returning(rows) + inSequence { + (rows.next _).expects().returning(true) + (rows.next _).expects().returning(false) + } + (rows.getObject(_: String)).expects("id").returning(Int.box(7)) + (rows.getObject(_: String)).expects("name").returning(expectedName) + (rows.close _).expects() + (queryStatement.close _).expects() + + stubDriver.arm(conn) + exec.open() + val tuples = exec.produceTuple().map(_.asInstanceOf[Tuple]).toList + + tuples should have size 1 + tuples.head.getField[Any]("id") shouldBe 7 + tuples.map(_.getField[Any]("name")) shouldBe List(expectedName) + } + + protected final def verifyClose(exec: SQLSourceOpExec): Unit = { + val conn = connectionForOpen(Seq("tbl")) + (conn.close _).expects() + stubDriver.arm(conn) + exec.open() + exec.close() + } +} diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExecSpec.scala index f947ba284d..e8a8a202ed 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/SQLSourceOpExecSpec.scala @@ -23,6 +23,7 @@ import org.apache.texera.amber.core.tuple.AttributeTypeUtils.parseTimestamp import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple} import org.apache.texera.amber.operator.source.sql.postgresql.PostgreSQLSourceOpDesc import org.apache.texera.amber.util.JSONUtils.objectMapper +import org.scalamock.matchers.MockParameter import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -138,6 +139,18 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { exec } + private def queryMocks( + sql: MockParameter[String], + conn: Connection = mock[Connection] + )(bind: PreparedStatement => Unit = _ => ()): (Connection, PreparedStatement, ResultSet) = { + val statement = mock[PreparedStatement] + val resultSet = mock[ResultSet] + (conn.prepareStatement(_: String)).expects(sql).returning(statement) + bind(statement) + (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + (conn, statement, resultSet) + } + /** * A connection answering the `SELECT MIN/MAX(col) FROM tbl;` boundary probes. * `sides` narrows it to the probes the executor is expected to actually issue. @@ -149,13 +162,7 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { ): Connection = { val conn = mock[Connection] sides.foreach { side => - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn - .prepareStatement(_: String)) - .expects(s"SELECT $side($column) FROM tbl;") - .returning(statement) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (_, statement, resultSet) = queryMocks(s"SELECT $side($column) FROM tbl;", conn)() (resultSet.next _).expects().returning(true) stub(resultSet, side) (resultSet.close _).expects() @@ -394,25 +401,20 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { exec.tableNames should contain("tbl") } - it should "reject progressive mode without min and max boundaries" in { - val exec = new TestSQLSourceOpExec(progressiveJson("big", None, None, 30L)) - val thrown = intercept[IllegalArgumentException](exec.open()) - thrown.getMessage should startWith("Missing required progressive configuration") - } - - it should "reject progressive mode with a lower but no upper boundary" in { - val exec = new TestSQLSourceOpExec(progressiveJson("big", Option("0"), None, 30L)) - val thrown = intercept[IllegalArgumentException](exec.open()) - thrown.getMessage should startWith("Missing required progressive configuration") - } - - it should "reject progressive mode with an upper but no lower boundary" in { - // the mirror of the case above: without this one, dropping the min check from the - // configuration guard would go unnoticed and desc.min.get would raise a bare - // NoSuchElementException instead of this message - val exec = new TestSQLSourceOpExec(progressiveJson("big", None, Option("100"), 30L)) - val thrown = intercept[IllegalArgumentException](exec.open()) - thrown.getMessage should startWith("Missing required progressive configuration") + // Include both one-sided configurations. Dropping the min check would let + // the upper-only case reach desc.min.get and throw a bare NoSuchElementException + // instead of reporting the missing progressive configuration. + Seq( + ("reject progressive mode without min and max boundaries", None, None), + ("reject progressive mode with a lower but no upper boundary", Option("0"), None), + ("reject progressive mode with an upper but no lower boundary", None, Option("100")) + ).foreach { + case (name, min, max) => + it should name in { + val exec = new TestSQLSourceOpExec(progressiveJson("big", min, max, 30L)) + val thrown = intercept[IllegalArgumentException](exec.open()) + thrown.getMessage should startWith("Missing required progressive configuration") + } } it should "reject a non-auto upper bound on a column that is neither LONG nor TIMESTAMP" in { @@ -479,14 +481,7 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { } it should "reject an auto boundary probe on an unsupported column type" in { - val conn = mock[Connection] - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn - .prepareStatement(_: String)) - .expects("SELECT MIN(name) FROM tbl;") - .returning(statement) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (conn, statement, resultSet) = queryMocks("SELECT MIN(name) FROM tbl;")() (resultSet.next _).expects().returning(true) // the probe currently throws before closing; allow (but don't require) the close-out so a // later fix that releases the ResultSet/PreparedStatement on this path won't break the spec @@ -508,12 +503,7 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { } "SQLSourceOpExec.produceTuple" should "stream every row of the single non-progressive query" in { - val resultSet = mock[ResultSet] - val statement = mock[PreparedStatement] - val conn = mock[Connection] - - (conn.prepareStatement(_: String)).expects(BASE + ";").returning(statement) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (conn, statement, resultSet) = queryMocks(BASE + ";")() inSequence { (resultSet.next _).expects().returning(true) (resultSet.next _).expects().returning(true) @@ -540,18 +530,12 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { } it should "bind the keyword, limit and offset parameters and skip the offset rows" in { - val resultSet = mock[ResultSet] - val statement = mock[PreparedStatement] - val conn = mock[Connection] - - (conn - .prepareStatement(_: String)) - .expects(BASE + " AND name @@ to_tsquery(?) LIMIT ? OFFSET ?;") - .returning(statement) - (statement.setString _).expects(1, "foo") - (statement.setLong _).expects(2, 2L) - (statement.setLong _).expects(3, 1L) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (conn, statement, resultSet) = + queryMocks(BASE + " AND name @@ to_tsquery(?) LIMIT ? OFFSET ?;") { statement => + (statement.setString _).expects(1, "foo") + (statement.setLong _).expects(2, 2L) + (statement.setLong _).expects(3, 1L) + } inSequence { (resultSet.next _).expects().returning(true) // consumed by the manual offset skip (resultSet.next _).expects().returning(true) @@ -583,20 +567,14 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { } it should "bind no fixed offset in progressive mode" in { - val resultSet = mock[ResultSet] - val statement = mock[PreparedStatement] - val conn = mock[Connection] - // the limit is present so that progressive-ness and "has a limit" are distinguishable - // here, and so that the clause order (sliding window ahead of LIMIT) is pinned - (conn - .prepareStatement(_: String)) - .expects(BASE + " AND big >= 0 AND big < 30 LIMIT ?;") - .returning(statement) - // only the limit is bound, at index 1: progressive mode carries its offset in the - // sliding window, and the strict mock rejects any further setLong, i.e. any offset - (statement.setLong _).expects(1, 2L) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) +// here, and so that the clause order (sliding window ahead of LIMIT) is pinned + val (conn, statement, resultSet) = queryMocks(BASE + " AND big >= 0 AND big < 30 LIMIT ?;") { + statement => + // only the limit is bound, at index 1: progressive mode carries its offset in the + // sliding window, and the strict mock rejects any further setLong, i.e. any offset + (statement.setLong _).expects(1, 2L) + } inSequence { (resultSet.next _).expects().returning(true) // consumed by the manual offset skip (resultSet.next _).expects().returning(true) @@ -649,11 +627,7 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { /** A connection answering one query with the given (id, name) rows, then exhausting. */ private def rowsConn(rows: Seq[(Any, Any)]): Connection = { - val conn = mock[Connection] - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn.prepareStatement(_: String)).expects(*).returning(statement) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (conn, statement, resultSet) = queryMocks(*)() inSequence { rows.foreach { case (id, name) => @@ -705,13 +679,10 @@ class SQLSourceOpExecSpec extends AnyFlatSpec with Matchers with MockFactory { keywords: Option[String], expectBinding: Boolean ): Unit = { - val conn = mock[Connection] - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn.prepareStatement(_: String)).expects(*).returning(statement) - if (expectBinding) (statement.setString _).expects(1, keywords.get) - else (statement.setString _).expects(*, *).never() - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) + val (conn, statement, resultSet) = queryMocks(*) { statement => + if (expectBinding) (statement.setString _).expects(1, keywords.get) + else (statement.setString _).expects(*, *).never() + } (resultSet.next _).expects().returning(false) (resultSet.close _).expects() (statement.close _).expects() diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBConnUtilSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBConnUtilSpec.scala index f670d46641..1b65398b3f 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBConnUtilSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBConnUtilSpec.scala @@ -19,14 +19,11 @@ package org.apache.texera.amber.operator.source.sql.asterixdb -import com.sun.net.httpserver.{HttpExchange, HttpServer} import kong.unirest.json.JSONException import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import java.net.{InetSocketAddress, URLDecoder} -import java.nio.charset.StandardCharsets import java.util.concurrent.atomic.AtomicInteger import scala.collection.mutable @@ -49,67 +46,24 @@ class AsterixDBConnUtilSpec private val versionHits = new AtomicInteger(0) @volatile private var versionStatus: Int = 200 - @volatile private var versionBody: String = versionJson("0.9.9") + @volatile private var versionBody: String = AsterixDBTestServer.versionJson("0.9.9") // Responds to POST /query/service based on the submitted statement. @volatile private var queryResponder: String => (Int, String) = _ => (200, """{"results":[]}""") // Decoded form fields of every /query/service request, in arrival order. private val recordedQueries = mutable.Buffer[Map[String, String]]() - private val server: HttpServer = HttpServer.create(new InetSocketAddress(0), 0) - server.createContext( - "/admin/version", - (exchange: HttpExchange) => { - versionHits.incrementAndGet() - respond(exchange, versionStatus, versionBody) - } - ) - server.createContext( - "/query/service", - (exchange: HttpExchange) => { - val is = exchange.getRequestBody - val body = - try new String(is.readAllBytes(), StandardCharsets.UTF_8) - finally is.close() - val form = parseForm(body) - recordedQueries.synchronized { recordedQueries += form } - val (status, responseBody) = queryResponder(form.getOrElse("statement", "")) - respond(exchange, status, responseBody) - } - ) + private val server = AsterixDBTestServer.bind(version = { + versionHits.incrementAndGet() + (versionStatus, versionBody) + }) { form => + recordedQueries.synchronized { recordedQueries += form } + queryResponder(form.getOrElse("statement", "")) + } private val host = "127.0.0.1" private def port: String = server.getAddress.getPort.toString - private def versionJson(version: String): String = - s"""{"git.build.version":"$version"}""" - - private def respond(exchange: HttpExchange, status: Int, body: String): Unit = { - if (status == 204) { - // 204 must not carry a body; length -1 signals a bodyless response. - exchange.sendResponseHeaders(204, -1) - exchange.close() - } else { - val bytes = body.getBytes(StandardCharsets.UTF_8) - exchange.getResponseHeaders.add("Content-Type", "application/json") - exchange.sendResponseHeaders(status, bytes.length.toLong) - val os = exchange.getResponseBody - try os.write(bytes) - finally os.close() - } - } - - private def parseForm(body: String): Map[String, String] = - body - .split("&") - .filter(_.contains("=")) - .map { pair => - val idx = pair.indexOf('=') - URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8) -> - URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8) - } - .toMap - private def lastQueryField(name: String): String = recordedQueries.synchronized { recordedQueries.last(name) } @@ -137,7 +91,7 @@ class AsterixDBConnUtilSpec AsterixDBConnUtil.asterixDBVersionMapping -= host versionHits.set(0) versionStatus = 200 - versionBody = versionJson("0.9.9") + versionBody = AsterixDBTestServer.versionJson("0.9.9") queryResponder = _ => (200, """{"results":[]}""") recordedQueries.synchronized { recordedQueries.clear() } } @@ -173,7 +127,7 @@ class AsterixDBConnUtilSpec // --------------------------------------------------------------------------- it should "send the default format `csv` unprefixed when the server version is 0.9.5" in { - versionBody = versionJson("0.9.5") + versionBody = AsterixDBTestServer.versionJson("0.9.5") AsterixDBConnUtil.queryAsterixDB(host, port, "SELECT 1;") lastQueryField("format") shouldBe "csv" } @@ -301,7 +255,7 @@ class AsterixDBConnUtilSpec "AsterixDBConnUtil.updateAsterixDBVersionMapping" should "store git.build.version for the host on HTTP 200" in { - versionBody = versionJson("1.0.0-SNAPSHOT") + versionBody = AsterixDBTestServer.versionJson("1.0.0-SNAPSHOT") AsterixDBConnUtil.updateAsterixDBVersionMapping(host, port) AsterixDBConnUtil.asterixDBVersionMapping.get(host) shouldBe Some("1.0.0-SNAPSHOT") } @@ -314,7 +268,7 @@ class AsterixDBConnUtilSpec it should "overwrite an existing entry for the host on a later successful probe" in { AsterixDBConnUtil.asterixDBVersionMapping += (host -> "0.9.5") - versionBody = versionJson("0.9.9") + versionBody = AsterixDBTestServer.versionJson("0.9.9") AsterixDBConnUtil.updateAsterixDBVersionMapping(host, port) AsterixDBConnUtil.asterixDBVersionMapping.get(host) shouldBe Some("0.9.9") } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpDescSpec.scala index 2898acf64f..86d8563970 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpDescSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.source.sql.asterixdb -import com.sun.net.httpserver.{HttpExchange, HttpServer} import org.apache.texera.amber.core.executor.OpExecWithClassName import org.apache.texera.amber.core.tuple.{AttributeType, Schema} import org.apache.texera.amber.core.workflow.WorkflowContext.{ @@ -33,8 +32,6 @@ import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import java.net.{InetSocketAddress, URLDecoder} -import java.nio.charset.StandardCharsets import scala.collection.mutable import scala.util.Try @@ -56,33 +53,14 @@ class AsterixDBSourceOpDescSpec extends AnyFlatSpec with Matchers with BeforeAnd /** Decoded `statement` form field of every /query/service request, in order. */ private val recordedStatements = mutable.Buffer[String]() - private val server: HttpServer = HttpServer.create(new InetSocketAddress(0), 0) - server.createContext( - "/admin/version", - (exchange: HttpExchange) => respond(exchange, """{"git.build.version":"0.9.9"}""") - ) - server.createContext( - "/query/service", - (exchange: HttpExchange) => { - val is = exchange.getRequestBody - val body = - try new String(is.readAllBytes(), StandardCharsets.UTF_8) - finally is.close() - val statement = formField(body, "statement") - recordedStatements.synchronized { recordedStatements += statement } - respond(exchange, responseFor(statement)) - } - ) + private val server = AsterixDBTestServer.forStatements(recordedStatements)(responseFor) private val host = "localhost" private def port: String = server.getAddress.getPort.toString private def responseFor(statement: String): String = if (statement.contains("Metadata.`Datatype`")) { - val fields = datatypeFields - .map { case (name, tpe) => s"""{"FieldName":"$name","FieldType":"$tpe"}""" } - .mkString(",") - s"""{"results":[{"Fields":[$fields]}]}""" + AsterixDBTestServer.datatypeResult(datatypeFields) } else if (statement.contains("Metadata.`Dataset`")) { """{"results":[{"DatatypeName":"tweetType"}]}""" } else { @@ -92,27 +70,6 @@ class AsterixDBSourceOpDescSpec extends AnyFlatSpec with Matchers with BeforeAnd """{"results":[]}""" } - private def respond(exchange: HttpExchange, body: String): Unit = { - val bytes = body.getBytes(StandardCharsets.UTF_8) - exchange.getResponseHeaders.add("Content-Type", "application/json") - exchange.sendResponseHeaders(200, bytes.length.toLong) - val os = exchange.getResponseBody - try os.write(bytes) - finally os.close() - } - - private def formField(body: String, name: String): String = - body - .split("&") - .filter(_.contains("=")) - .map { pair => - val idx = pair.indexOf('=') - URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8) -> - URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8) - } - .toMap - .getOrElse(name, "") - override protected def beforeAll(): Unit = { super.beforeAll() server.start() @@ -243,25 +200,14 @@ class AsterixDBSourceOpDescSpec extends AnyFlatSpec with Matchers with BeforeAnd it should "be applied by sourceSchema before it issues any query" in { // sourceSchema resolves `default` to 19002; stand up a minimal stub there so // the test doesn't depend on an external AsterixDB process. - val defaultPortServer = Try(HttpServer.create(new InetSocketAddress(19002), 0)).getOrElse { + val defaultPortServer = Try( + AsterixDBTestServer.bind(port = 19002) { form => + (200, responseFor(form.getOrElse("statement", ""))) + } + ).getOrElse { cancel("port 19002 is unavailable; cannot verify updatePort integration without a local stub") } try { - defaultPortServer.createContext( - "/admin/version", - (exchange: HttpExchange) => respond(exchange, """{"git.build.version":"0.9.9"}""") - ) - defaultPortServer.createContext( - "/query/service", - (exchange: HttpExchange) => { - val is = exchange.getRequestBody - val body = - try new String(is.readAllBytes(), StandardCharsets.UTF_8) - finally is.close() - val statement = formField(body, "statement") - respond(exchange, responseFor(statement)) - } - ) defaultPortServer.start() val d = configured() @@ -292,46 +238,21 @@ class AsterixDBSourceOpDescSpec extends AnyFlatSpec with Matchers with BeforeAnd "requirement failed: Please enter a valid host name for AsterixDB." } - it should "name the port when the port is missing" in { - val d = configured() - d.port = null - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid port for AsterixDB." - } - - it should "name the port when the port is only whitespace" in { - val d = configured() - d.port = " " - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid port for AsterixDB." - } - - it should "name the database when the database is missing" in { - val d = configured() - d.database = null - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid database name for AsterixDB." - } - - it should "name the database when the database is only whitespace" in { - val d = configured() - d.database = " " - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid database name for AsterixDB." - } - - it should "name the table when the table is missing" in { - val d = configured() - d.table = null - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid table name for AsterixDB." - } - - it should "name the table when the table is only whitespace" in { - val d = configured() - d.table = " " - intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe - "requirement failed: Please enter a valid table name for AsterixDB." + Seq[(String, String, (AsterixDBSourceOpDesc, String) => Unit)]( + ("port", "port", (d, value) => d.port = value), + ("database", "database name", (d, value) => d.database = value), + ("table", "table name", (d, value) => d.table = value) + ).foreach { + case (field, label, setField) => + Seq[(String, String)]("missing" -> null, "only whitespace" -> " ").foreach { + case (description, value) => + it should s"name the $field when the $field is $description" in { + val d = configured() + setField(d, value) + intercept[IllegalArgumentException](d.sourceSchema()).getMessage shouldBe + s"requirement failed: Please enter a valid $label for AsterixDB." + } + } } it should "name the first unset field, checking host, port, database, then table" in { diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExecSpec.scala index b1023437de..8e19e3f5ae 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBSourceOpExecSpec.scala @@ -19,7 +19,6 @@ package org.apache.texera.amber.operator.source.sql.asterixdb -import com.sun.net.httpserver.{HttpExchange, HttpServer} import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Tuple} import org.apache.texera.amber.operator.filter.{ComparisonType, FilterPredicate} import org.apache.texera.amber.util.JSONUtils.objectMapper @@ -27,8 +26,6 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach} -import java.net.{InetSocketAddress, URLDecoder} -import java.nio.charset.StandardCharsets import java.sql.Timestamp import scala.collection.mutable @@ -76,33 +73,14 @@ class AsterixDBSourceOpExecSpec // Decoded `statement` form field of every /query/service request, in order. private val recordedStatements = mutable.Buffer[String]() - private val server: HttpServer = HttpServer.create(new InetSocketAddress(0), 0) - server.createContext( - "/admin/version", - (exchange: HttpExchange) => respond(exchange, """{"git.build.version":"0.9.9"}""") - ) - server.createContext( - "/query/service", - (exchange: HttpExchange) => { - val is = exchange.getRequestBody - val body = - try new String(is.readAllBytes(), StandardCharsets.UTF_8) - finally is.close() - val statement = formField(body, "statement") - recordedStatements.synchronized { recordedStatements += statement } - respond(exchange, responseFor(statement)) - } - ) + private val server = AsterixDBTestServer.forStatements(recordedStatements)(responseFor) private val host = "localhost" private def port: String = server.getAddress.getPort.toString private def responseFor(statement: String): String = if (statement.contains("Metadata.`Datatype`")) { - val fields = datatypeFields - .map { case (name, tpe) => s"""{"FieldName":"$name","FieldType":"$tpe"}""" } - .mkString(",") - s"""{"results":[{"Fields":[$fields]}]}""" + AsterixDBTestServer.datatypeResult(datatypeFields) } else if (statement.contains("SELECT DatatypeName FROM Metadata.`Dataset`")) { """{"results":[{"DatatypeName":"tweetType"}]}""" } else if (statement.contains("select `DatasetName` from Metadata.`Dataset`")) { @@ -120,27 +98,6 @@ class AsterixDBSourceOpExecSpec .replace("\"", "\\\"") .replace("\n", "\\n") + "\"" - private def respond(exchange: HttpExchange, body: String): Unit = { - val bytes = body.getBytes(StandardCharsets.UTF_8) - exchange.getResponseHeaders.add("Content-Type", "application/json") - exchange.sendResponseHeaders(200, bytes.length.toLong) - val os = exchange.getResponseBody - try os.write(bytes) - finally os.close() - } - - private def formField(body: String, name: String): String = - body - .split("&") - .filter(_.contains("=")) - .map { pair => - val idx = pair.indexOf('=') - URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8) -> - URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8) - } - .toMap - .getOrElse(name, "") - /** Statements the executor issued that are not metadata bookkeeping. */ private def dataStatements: Seq[String] = recordedStatements.synchronized { @@ -775,7 +732,7 @@ class AsterixDBSourceOpExecSpec // NOT covered here, on purpose: this drives next() directly, so `cachedTuple` // is empty by the time close() runs. The engine's own loop is // `while (it.hasNext) it.next()`, i.e. hasNext always peeks first, and - // close() clears curResultIterator/curQueryString but not the inherited + // close() clears the HTTP result iterator but not the inherited // cachedTuple (neither does SQLSourceOpExec.close()) - so a peeked but // unconsumed row is still handed out after close(). That is left unpinned on // purpose: asserting it would cement what looks like a leak, and asserting diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBTestServer.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBTestServer.scala new file mode 100644 index 0000000000..e6e7160b06 --- /dev/null +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/asterixdb/AsterixDBTestServer.scala @@ -0,0 +1,97 @@ +/* + * 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.texera.amber.operator.source.sql.asterixdb + +import com.sun.net.httpserver.{HttpExchange, HttpServer} + +import java.net.{InetSocketAddress, URLDecoder} +import java.nio.charset.StandardCharsets +import scala.collection.mutable + +private[asterixdb] object AsterixDBTestServer { + def versionJson(version: String): String = + s"""{"git.build.version":"$version"}""" + + def datatypeResult(fields: Seq[(String, String)]): String = { + val entries = fields + .map { case (name, tpe) => s"""{"FieldName":"$name","FieldType":"$tpe"}""" } + .mkString(",") + s"""{"results":[{"Fields":[$entries]}]}""" + } + + def forStatements(recorded: mutable.Buffer[String], port: Int = 0)( + response: String => String + ): HttpServer = + bind(port) { form => + val statement = form.getOrElse("statement", "") + recorded.synchronized { recorded += statement } + (200, response(statement)) + } + + def bind(port: Int = 0, version: => (Int, String) = (200, versionJson("0.9.9")))( + query: Map[String, String] => (Int, String) + ): HttpServer = { + val server = HttpServer.create(new InetSocketAddress(port), 0) + server.createContext( + "/admin/version", + (exchange: HttpExchange) => { + val (status, body) = version + respond(exchange, status, body) + } + ) + server.createContext( + "/query/service", + (exchange: HttpExchange) => { + val is = exchange.getRequestBody + val body = + try new String(is.readAllBytes(), StandardCharsets.UTF_8) + finally is.close() + val (status, responseBody) = query(parseForm(body)) + respond(exchange, status, responseBody) + } + ) + server + } + + private def respond(exchange: HttpExchange, status: Int, body: String): Unit = { + if (status == 204) { + // A 204 response is bodyless. + exchange.sendResponseHeaders(204, -1) + exchange.close() + } else { + val bytes = body.getBytes(StandardCharsets.UTF_8) + exchange.getResponseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(status, bytes.length.toLong) + val os = exchange.getResponseBody + try os.write(bytes) + finally os.close() + } + } + + private def parseForm(body: String): Map[String, String] = + body + .split("&") + .filter(_.contains("=")) + .map { pair => + val idx = pair.indexOf('=') + URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8) -> + URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8) + } + .toMap +} diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpDescSpec.scala index 618cebc22f..0544e50010 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpDescSpec.scala @@ -19,87 +19,18 @@ package org.apache.texera.amber.operator.source.sql.mysql -import org.apache.texera.amber.core.executor.OpExecWithClassName -import org.apache.texera.amber.core.workflow.WorkflowContext.{ - DEFAULT_EXECUTION_ID, - DEFAULT_WORKFLOW_ID -} -import org.apache.texera.amber.operator.LogicalOp -import org.apache.texera.amber.operator.metadata.OperatorGroupConstants -import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers +import org.apache.texera.amber.operator.source.sql.JdbcSourceOpDescBehaviors import scala.annotation.nowarn // MySQLSourceOpDesc is @deprecated (no longer executable) but retained so legacy // workflows still deserialize; the coverage below pins that backward-compatible contract. @nowarn("cat=deprecation") -class MySQLSourceOpDescSpec extends AnyFlatSpec with Matchers { - - "MySQLSourceOpDesc.operatorInfo" should - "advertise the MySQL source in the Database Connector group with no input and one output" in { - val info = (new MySQLSourceOpDesc).operatorInfo - info.userFriendlyName shouldBe "MySQL Source" - info.operatorDescription shouldBe "Read data from a MySQL instance" - info.operatorGroupName shouldBe OperatorGroupConstants.DATABASE_GROUP - info.inputPorts shouldBe empty - info.outputPorts should have length 1 - } - - "MySQLSourceOpDesc" should "default its connection and query fields" in { - val d = new MySQLSourceOpDesc - d.host shouldBe null - d.port shouldBe null - d.database shouldBe null - d.table shouldBe null - d.limit shouldBe None - d.offset shouldBe None - d.keywordSearch shouldBe Some(false) - d.progressive shouldBe Some(false) - d.interval shouldBe 0L - } - - "MySQLSourceOpDesc.sourceSchema" should "prompt for connection details before a connection is configured" in { - val ex = intercept[IllegalArgumentException]((new MySQLSourceOpDesc).sourceSchema()) - ex.getMessage should include("host") - } - - "MySQLSourceOpDesc.getPhysicalOp" should - "wire the MySQL exec as a source op with no input port and one output port" in { - val d = new MySQLSourceOpDesc - val physical = d.getPhysicalOp(DEFAULT_WORKFLOW_ID, DEFAULT_EXECUTION_ID) - physical.opExecInitInfo match { - case OpExecWithClassName(className, _) => - className shouldBe "org.apache.texera.amber.operator.source.sql.mysql.MySQLSourceOpExec" - case other => fail(s"expected OpExecWithClassName, got $other") - } - physical.inputPorts.keySet shouldBe empty - physical.outputPorts.keySet shouldBe d.operatorInfo.outputPorts.map(_.id).toSet - } - - "MySQLSourceOpDesc" should "round-trip its config fields through the polymorphic base" in { - val d = new MySQLSourceOpDesc - d.host = "localhost" - d.database = "db" - d.table = "t" - d.username = "secret-user" - d.password = "secret-pass" - d.limit = Some(5L) - val json = objectMapper.writeValueAsString(d) - json should include("\"operatorType\":\"MySQLSource\"") - // Unlike AsterixDBSourceOpDesc (which drops credentials via @JsonIgnoreProperties), the SQL - // base persists username/password in plaintext; pin that behavior so any future change is visible. - json should include("secret-user") - json should include("secret-pass") - val restored = objectMapper.readValue(json, classOf[LogicalOp]) - restored shouldBe a[MySQLSourceOpDesc] - val r = restored.asInstanceOf[MySQLSourceOpDesc] - r.host shouldBe "localhost" - r.database shouldBe "db" - r.table shouldBe "t" - r.username shouldBe "secret-user" - r.password shouldBe "secret-pass" - r.limit shouldBe Some(5L) - } +class MySQLSourceOpDescSpec extends JdbcSourceOpDescBehaviors { + jdbcSourceContract( + "MySQL", + "MySQLSource", + "org.apache.texera.amber.operator.source.sql.mysql.MySQLSourceOpExec", + new MySQLSourceOpDesc + ) } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExecSpec.scala index c81ebe291f..a29778d041 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/mysql/MySQLSourceOpExecSpec.scala @@ -19,91 +19,37 @@ package org.apache.texera.amber.operator.source.sql.mysql -import org.apache.texera.amber.core.tuple.{AttributeType, Tuple} -import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalamock.scalatest.MockFactory -import org.scalatest.BeforeAndAfterAll +import org.apache.texera.amber.core.tuple.AttributeType +import org.apache.texera.amber.operator.source.sql.JdbcSourceOpExecTestHarness import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import java.sql.{ - Connection, - DatabaseMetaData, - Driver, - DriverManager, - DriverPropertyInfo, - PreparedStatement, - ResultSet, - SQLException, - SQLFeatureNotSupportedException, - Types -} -import java.util.Properties -import java.util.logging.Logger +import java.sql.{SQLException, Types} import scala.annotation.nowarn -import scala.collection.mutable // MySQLSourceOpExec is @deprecated (no longer executable) but retained so legacy workflows keep // working; the coverage below pins the dialect-specific SQL it still produces. @nowarn("cat=deprecation") -class MySQLSourceOpExecSpec - extends AnyFlatSpec - with Matchers - with MockFactory - with BeforeAndAfterAll { +class MySQLSourceOpExecSpec extends AnyFlatSpec with Matchers with JdbcSourceOpExecTestHarness { private val HOST = "127.0.0.1" // Port 1 is never served: no MySQL driver ships on this classpath, and if one ever did it would // be refused instantly and DriverManager would fall through to the stub driver below. private val PORT = "1" private val JDBC_URL = "jdbc:mysql://127.0.0.1:1/db?autoReconnect=true&useSSL=true" - private val BASE = "\nSELECT * FROM tbl where 1 = 1" private val FETCH_TABLES = "SELECT table_name FROM information_schema.tables WHERE table_schema = ?;" private val MATCH_CLAUSE = " AND MATCH(name) AGAINST (? IN BOOLEAN MODE)" - /** - * A JDBC driver that hands out pre-armed connections for `jdbc:mysql://` URLs. It lets the - * executor be built through the real `MySQLConnUtil` code path without a MySQL server. - */ - private class StubDriver extends Driver { - private val armed = mutable.Queue.empty[Connection] - var lastUrl: String = _ - var lastProperties: Properties = _ - - def arm(connection: Connection): Unit = armed.enqueue(connection) - - override def connect(url: String, info: Properties): Connection = { - if (!acceptsURL(url)) return null - lastUrl = url - lastProperties = info - if (armed.isEmpty) throw new SQLException("stub driver: no connection armed for " + url) - armed.dequeue() - } - - override def acceptsURL(url: String): Boolean = url != null && url.startsWith("jdbc:mysql://") - override def getPropertyInfo(url: String, info: Properties): Array[DriverPropertyInfo] = - Array.empty - override def getMajorVersion: Int = 1 - override def getMinorVersion: Int = 0 - override def jdbcCompliant(): Boolean = false - override def getParentLogger: Logger = throw new SQLFeatureNotSupportedException() - } - - private val stubDriver = new StubDriver - - override def beforeAll(): Unit = { - super.beforeAll() - DriverManager.registerDriver(stubDriver) - } - - override def afterAll(): Unit = { - DriverManager.deregisterDriver(stubDriver) - super.afterAll() - } + override protected def jdbcUrlPrefix: String = "jdbc:mysql://" + override protected def tableListingSql: String = FETCH_TABLES + // The MySQL listing binds the database name, while PostgreSQL has no parameters. + override protected def listingDatabase: Option[String] = Some("db") /** Re-exposes the protected query-building surface of the dialect executor. */ - private class TestMySQLSourceOpExec(descString: String) extends MySQLSourceOpExec(descString) { + private class TestMySQLSourceOpExec(descString: String) + extends MySQLSourceOpExec(descString) + with QueryAccess { def fetchTableNamesSql: String = FETCH_TABLE_NAMES_SQL def loadTables(): Unit = loadTableNames() def sqlQuery: Option[String] = generateSqlQuery @@ -114,17 +60,8 @@ class MySQLSourceOpExecSpec } } - private def descJson(configure: MySQLSourceOpDesc => Unit = _ => ()): String = { - val desc = new MySQLSourceOpDesc - desc.host = HOST - desc.port = PORT - desc.database = "db" - desc.table = "tbl" - desc.username = "u" - desc.password = "p" - configure(desc) - objectMapper.writeValueAsString(desc) - } + private def descJson(configure: MySQLSourceOpDesc => Unit = _ => ()): String = + configuredDescriptorJson(new MySQLSourceOpDesc, HOST, PORT)(configure) private val keywordJson = descJson { desc => desc.keywordSearch = Option(true) @@ -132,31 +69,6 @@ class MySQLSourceOpExecSpec desc.keywords = Option("sore throat") } - /** A connection answering the `sourceSchema()` JDBC-metadata probe run in the constructor. */ - private def schemaConn(columns: Seq[(String, Int)]): Connection = { - val conn = mock[Connection] - val metaData = mock[DatabaseMetaData] - val columnsRs = mock[ResultSet] - // once inside MySQLConnUtil.connect, once inside SQLSourceOpDesc.querySchema - (conn.setReadOnly _).expects(true).twice() - (conn.getMetaData _).expects().returning(metaData) - (metaData - .getColumns(_: String, _: String, _: String, _: String)) - .expects(null, null, "tbl", null) - .returning(columnsRs) - inSequence { - columns.foreach { - case (name, jdbcType) => - (columnsRs.next _).expects().returning(true) - (columnsRs.getString(_: String)).expects("COLUMN_NAME").returning(name) - (columnsRs.getInt(_: String)).expects("DATA_TYPE").returning(jdbcType) - } - (columnsRs.next _).expects().returning(false) - } - (conn.close _).expects() - conn - } - private def newExec( json: String = descJson(), columns: Seq[(String, Int)] = Seq("id" -> Types.INTEGER, "name" -> Types.VARCHAR) @@ -165,25 +77,6 @@ class MySQLSourceOpExecSpec new TestMySQLSourceOpExec(json) } - /** Stubs the `information_schema` probe that `loadTableNames` issues. */ - private def expectTableListing(conn: Connection, tables: Seq[String]): Unit = { - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn.prepareStatement(_: String)).expects(FETCH_TABLES).returning(statement) - // MySQL scopes the listing to the configured database via a bound parameter - (statement.setString _).expects(1, "db") - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) - inSequence { - tables.foreach(_ => (resultSet.next _).expects().returning(true)) - (resultSet.next _).expects().returning(false) - } - inSequence { - tables.foreach(table => (resultSet.getString(_: Int)).expects(1).returning(table)) - } - (resultSet.close _).expects() - (statement.close _).expects() - } - "MySQLSourceOpExec" should "deserialize a MySQLSourceOpDesc and derive the schema from JDBC metadata" in { val exec = newExec(columns = Seq("id" -> Types.INTEGER, "name" -> Types.VARCHAR, "created" -> Types.TIMESTAMP) @@ -201,17 +94,7 @@ class MySQLSourceOpExecSpec "MySQLSourceOpExec.establishConn" should "dial the MySQL JDBC URL built from the descriptor" in { val exec = newExec() - stubDriver.lastUrl shouldBe JDBC_URL - - val reconnected = mock[Connection] - // MySQLConnUtil.connect flips the fresh connection to read-only - (reconnected.setReadOnly _).expects(true) - stubDriver.arm(reconnected) - - exec.establishConn() should be theSameInstanceAs reconnected - stubDriver.lastUrl shouldBe JDBC_URL - stubDriver.lastProperties.getProperty("user") shouldBe "u" - stubDriver.lastProperties.getProperty("password") shouldBe "p" + verifyReconnect(JDBC_URL)(exec.establishConn()) } it should "propagate the SQLException when the server refuses the connection" in { @@ -221,49 +104,19 @@ class MySQLSourceOpExecSpec } "MySQLSourceOpExec.loadTableNames" should "list information_schema tables scoped to the database" in { - val exec = newExec() - val conn = mock[Connection] - expectTableListing(conn, Seq("tbl", "other")) - - exec.connection = conn - exec.loadTables() - - exec.tableNames.toList shouldBe List("tbl", "other") + verifyTableListing(newExec(), Seq("tbl", "other")) } it should "leave the table list empty when the database exposes no tables" in { - val exec = newExec() - val conn = mock[Connection] - expectTableListing(conn, Seq.empty) - - exec.connection = conn - exec.loadTables() - - exec.tableNames shouldBe empty + verifyTableListing(newExec(), Seq.empty) } "MySQLSourceOpExec.open" should "connect and accept a table present in the MySQL listing" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("other", "tbl")) - stubDriver.arm(conn) - - exec.open() - - exec.connection should be theSameInstanceAs conn - exec.tableNames.toList shouldBe List("other", "tbl") - exec.batchByAttribute shouldBe None + verifyOpen(newExec()) } it should "reject a table missing from the MySQL listing" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("other")) - stubDriver.arm(conn) - - intercept[RuntimeException](exec.open()).getMessage shouldBe "Can't find the given table `tbl`." + verifyMissingTable(newExec()) } "MySQLSourceOpExec.addFilterConditions" should @@ -274,112 +127,21 @@ class MySQLSourceOpExecSpec exec.filterClause should not include "sore throat" } - it should "add nothing when keyword search is switched off" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(false) - desc.keywordSearchByColumn = Option("name") - desc.keywords = Option("sore throat") - }) - exec.filterClause shouldBe "" - } - - it should "add nothing when no search column is configured" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywords = Option("sore throat") - }) - exec.filterClause shouldBe "" - } - - it should "still emit the MATCH placeholder when the keywords are missing" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("name") - }) - // The guard reads `desc.keywords != null`, but `keywords` is an Option, so it is never null and - // the empty case slips through. Pin the behavior as it stands: the clause keeps its bind - // placeholder even though SQLSourceOpExec.getNextQuery (which unwraps with `.orNull`) binds - // nothing for it, so the statement would fail at execution time. - exec.desc.keywords shouldBe None - exec.filterClause shouldBe MATCH_CLAUSE - exec.sqlQuery shouldBe Some(BASE + MATCH_CLAUSE + ";") - } - - it should "refuse a keyword search on a non-string column" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("id") - desc.keywords = Option("42") - }) - intercept[RuntimeException](exec.filterClause).getMessage shouldBe - "Can't do keyword search on type integer" - } - - it should "refuse a keyword search on a column that is not in the schema" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("nope") - desc.keywords = Option("x") - }) - intercept[RuntimeException](exec.filterClause).getMessage shouldBe - "nope is not contained in the schema" - } + keywordGuardCases("sore throat", MATCH_CLAUSE, "MATCH")(configure => newExec(descJson(configure))) "MySQLSourceOpExec.generateSqlQuery" should "splice the MATCH clause into the full statement" in { - val exec = newExec(keywordJson) - exec.sqlQuery shouldBe Some(BASE + MATCH_CLAUSE + ";") - - exec.curLimit = Some(3L) - exec.curOffset = Some(2L) - exec.sqlQuery shouldBe Some(BASE + MATCH_CLAUSE + " LIMIT ? OFFSET ?;") + verifyRenderedQuery(newExec(keywordJson), MATCH_CLAUSE) } it should "produce a plain statement when no keyword search is configured" in { - newExec().sqlQuery shouldBe Some(BASE + ";") + newExec().sqlQuery shouldBe Some(baseSelect + ";") } "MySQLSourceOpExec.produceTuple" should "run the MATCH query and bind the keyword parameter" in { - val exec = newExec(keywordJson) - val conn = mock[Connection] - val queryStatement = mock[PreparedStatement] - val rows = mock[ResultSet] - - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("tbl")) - - (conn - .prepareStatement(_: String)) - .expects(BASE + MATCH_CLAUSE + ";") - .returning(queryStatement) - (queryStatement.setString _).expects(1, "sore throat") - (queryStatement.executeQuery: () => ResultSet).expects().returning(rows) - inSequence { - (rows.next _).expects().returning(true) - (rows.next _).expects().returning(false) - } - (rows.getObject(_: String)).expects("id").returning(Int.box(7)) - (rows.getObject(_: String)).expects("name").returning("a sore throat") - (rows.close _).expects() - (queryStatement.close _).expects() - - stubDriver.arm(conn) - exec.open() - val tuples = exec.produceTuple().map(_.asInstanceOf[Tuple]).toList - - tuples should have size 1 - tuples.head.getField[Any]("id") shouldBe 7 - tuples.head.getField[Any]("name") shouldBe "a sore throat" + verifyKeywordRows(newExec(keywordJson), MATCH_CLAUSE, "sore throat", "a sore throat") } "MySQLSourceOpExec.close" should "close the connection established by open" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("tbl")) - (conn.close _).expects() - stubDriver.arm(conn) - - exec.open() - exec.close() + verifyClose(newExec()) } } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpDescSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpDescSpec.scala index d32f087d7e..18911f6bf5 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpDescSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpDescSpec.scala @@ -19,82 +19,13 @@ package org.apache.texera.amber.operator.source.sql.postgresql -import org.apache.texera.amber.core.executor.OpExecWithClassName -import org.apache.texera.amber.core.workflow.WorkflowContext.{ - DEFAULT_EXECUTION_ID, - DEFAULT_WORKFLOW_ID -} -import org.apache.texera.amber.operator.LogicalOp -import org.apache.texera.amber.operator.metadata.OperatorGroupConstants -import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalatest.flatspec.AnyFlatSpec -import org.scalatest.matchers.should.Matchers - -class PostgreSQLSourceOpDescSpec extends AnyFlatSpec with Matchers { - - "PostgreSQLSourceOpDesc.operatorInfo" should - "advertise the PostgreSQL source in the Database Connector group with no input and one output" in { - val info = (new PostgreSQLSourceOpDesc).operatorInfo - info.userFriendlyName shouldBe "PostgreSQL Source" - info.operatorDescription shouldBe "Read data from a PostgreSQL instance" - info.operatorGroupName shouldBe OperatorGroupConstants.DATABASE_GROUP - info.inputPorts shouldBe empty - info.outputPorts should have length 1 - } - - "PostgreSQLSourceOpDesc" should "default its connection and query fields" in { - val d = new PostgreSQLSourceOpDesc - d.host shouldBe null - d.port shouldBe null - d.database shouldBe null - d.table shouldBe null - d.limit shouldBe None - d.offset shouldBe None - d.keywordSearch shouldBe Some(false) - d.progressive shouldBe Some(false) - d.interval shouldBe 0L - } - - "PostgreSQLSourceOpDesc.sourceSchema" should "prompt for connection details before a connection is configured" in { - val ex = intercept[IllegalArgumentException]((new PostgreSQLSourceOpDesc).sourceSchema()) - ex.getMessage should include("host") - } - - "PostgreSQLSourceOpDesc.getPhysicalOp" should - "wire the PostgreSQL exec as a source op with no input port and one output port" in { - val d = new PostgreSQLSourceOpDesc - val physical = d.getPhysicalOp(DEFAULT_WORKFLOW_ID, DEFAULT_EXECUTION_ID) - physical.opExecInitInfo match { - case OpExecWithClassName(className, _) => - className shouldBe "org.apache.texera.amber.operator.source.sql.postgresql.PostgreSQLSourceOpExec" - case other => fail(s"expected OpExecWithClassName, got $other") - } - physical.inputPorts.keySet shouldBe empty - physical.outputPorts.keySet shouldBe d.operatorInfo.outputPorts.map(_.id).toSet - } - - "PostgreSQLSourceOpDesc" should "round-trip its config fields through the polymorphic base" in { - val d = new PostgreSQLSourceOpDesc - d.host = "localhost" - d.database = "db" - d.table = "t" - d.username = "secret-user" - d.password = "secret-pass" - d.limit = Some(5L) - val json = objectMapper.writeValueAsString(d) - json should include("\"operatorType\":\"PostgreSQLSource\"") - // Unlike AsterixDBSourceOpDesc (which drops credentials via @JsonIgnoreProperties), the SQL - // base persists username/password in plaintext; pin that behavior so any future change is visible. - json should include("secret-user") - json should include("secret-pass") - val restored = objectMapper.readValue(json, classOf[LogicalOp]) - restored shouldBe a[PostgreSQLSourceOpDesc] - val r = restored.asInstanceOf[PostgreSQLSourceOpDesc] - r.host shouldBe "localhost" - r.database shouldBe "db" - r.table shouldBe "t" - r.username shouldBe "secret-user" - r.password shouldBe "secret-pass" - r.limit shouldBe Some(5L) - } +import org.apache.texera.amber.operator.source.sql.JdbcSourceOpDescBehaviors + +class PostgreSQLSourceOpDescSpec extends JdbcSourceOpDescBehaviors { + jdbcSourceContract( + "PostgreSQL", + "PostgreSQLSource", + "org.apache.texera.amber.operator.source.sql.postgresql.PostgreSQLSourceOpExec", + new PostgreSQLSourceOpDesc + ) } diff --git a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExecSpec.scala b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExecSpec.scala index 9186b8cafa..e3b12469a9 100644 --- a/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExecSpec.scala +++ b/common/workflow-operator/src/test/scala/org/apache/texera/amber/operator/source/sql/postgresql/PostgreSQLSourceOpExecSpec.scala @@ -19,34 +19,17 @@ package org.apache.texera.amber.operator.source.sql.postgresql -import org.apache.texera.amber.core.tuple.{AttributeType, Tuple} -import org.apache.texera.amber.util.JSONUtils.objectMapper -import org.scalamock.scalatest.MockFactory -import org.scalatest.BeforeAndAfterAll +import org.apache.texera.amber.core.tuple.AttributeType +import org.apache.texera.amber.operator.source.sql.JdbcSourceOpExecTestHarness import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import java.sql.{ - Connection, - DatabaseMetaData, - Driver, - DriverManager, - DriverPropertyInfo, - PreparedStatement, - ResultSet, - SQLException, - SQLFeatureNotSupportedException, - Types -} -import java.util.Properties -import java.util.logging.Logger -import scala.collection.mutable +import java.sql.{SQLException, Types} class PostgreSQLSourceOpExecSpec extends AnyFlatSpec with Matchers - with MockFactory - with BeforeAndAfterAll { + with JdbcSourceOpExecTestHarness { private val HOST = "127.0.0.1" // Port 1 is never served. The real pgjdbc driver is on the test classpath and is offered the URL @@ -54,56 +37,17 @@ class PostgreSQLSourceOpExecSpec // through to the stub driver below. private val PORT = "1" private val JDBC_URL = "jdbc:postgresql://127.0.0.1:1/db" - private val BASE = "\nSELECT * FROM tbl where 1 = 1" private val FETCH_TABLES = "SELECT table_name FROM information_schema.tables WHERE table_type='BASE TABLE';" private val TSQUERY_CLAUSE = " AND name @@ to_tsquery(?)" - /** - * A JDBC driver that hands out pre-armed connections for `jdbc:postgresql://` URLs. It lets the - * executor be built through the real `PostgreSQLConnUtil` code path without a live server. - */ - private class StubDriver extends Driver { - private val armed = mutable.Queue.empty[Connection] - var lastUrl: String = _ - var lastProperties: Properties = _ - - def arm(connection: Connection): Unit = armed.enqueue(connection) - - override def connect(url: String, info: Properties): Connection = { - if (!acceptsURL(url)) return null - lastUrl = url - lastProperties = info - if (armed.isEmpty) throw new SQLException("stub driver: no connection armed for " + url) - armed.dequeue() - } - - // deliberately narrow: only the unserved sentinel endpoint used by this spec - override def acceptsURL(url: String): Boolean = - url != null && url.startsWith("jdbc:postgresql://" + HOST + ":" + PORT + "/") - override def getPropertyInfo(url: String, info: Properties): Array[DriverPropertyInfo] = - Array.empty - override def getMajorVersion: Int = 1 - override def getMinorVersion: Int = 0 - override def jdbcCompliant(): Boolean = false - override def getParentLogger: Logger = throw new SQLFeatureNotSupportedException() - } - - private val stubDriver = new StubDriver - - override def beforeAll(): Unit = { - super.beforeAll() - DriverManager.registerDriver(stubDriver) - } - - override def afterAll(): Unit = { - DriverManager.deregisterDriver(stubDriver) - super.afterAll() - } + override protected def jdbcUrlPrefix: String = "jdbc:postgresql://" + HOST + ":" + PORT + "/" + override protected def tableListingSql: String = FETCH_TABLES /** Re-exposes the protected query-building surface of the dialect executor. */ private class TestPostgreSQLSourceOpExec(descString: String) - extends PostgreSQLSourceOpExec(descString) { + extends PostgreSQLSourceOpExec(descString) + with QueryAccess { def fetchTableNamesSql: String = FETCH_TABLE_NAMES_SQL def loadTables(): Unit = loadTableNames() def sqlQuery: Option[String] = generateSqlQuery @@ -114,17 +58,8 @@ class PostgreSQLSourceOpExecSpec } } - private def descJson(configure: PostgreSQLSourceOpDesc => Unit = _ => ()): String = { - val desc = new PostgreSQLSourceOpDesc - desc.host = HOST - desc.port = PORT - desc.database = "db" - desc.table = "tbl" - desc.username = "u" - desc.password = "p" - configure(desc) - objectMapper.writeValueAsString(desc) - } + private def descJson(configure: PostgreSQLSourceOpDesc => Unit = _ => ()): String = + configuredDescriptorJson(new PostgreSQLSourceOpDesc, HOST, PORT)(configure) private val keywordJson = descJson { desc => desc.keywordSearch = Option(true) @@ -132,31 +67,6 @@ class PostgreSQLSourceOpExecSpec desc.keywords = Option("sore & throat") } - /** A connection answering the `sourceSchema()` JDBC-metadata probe run in the constructor. */ - private def schemaConn(columns: Seq[(String, Int)]): Connection = { - val conn = mock[Connection] - val metaData = mock[DatabaseMetaData] - val columnsRs = mock[ResultSet] - // once inside PostgreSQLConnUtil.connect, once inside SQLSourceOpDesc.querySchema - (conn.setReadOnly _).expects(true).twice() - (conn.getMetaData _).expects().returning(metaData) - (metaData - .getColumns(_: String, _: String, _: String, _: String)) - .expects(null, null, "tbl", null) - .returning(columnsRs) - inSequence { - columns.foreach { - case (name, jdbcType) => - (columnsRs.next _).expects().returning(true) - (columnsRs.getString(_: String)).expects("COLUMN_NAME").returning(name) - (columnsRs.getInt(_: String)).expects("DATA_TYPE").returning(jdbcType) - } - (columnsRs.next _).expects().returning(false) - } - (conn.close _).expects() - conn - } - private def newExec( json: String = descJson(), columns: Seq[(String, Int)] = Seq("id" -> Types.INTEGER, "name" -> Types.VARCHAR) @@ -165,27 +75,6 @@ class PostgreSQLSourceOpExecSpec new TestPostgreSQLSourceOpExec(json) } - /** - * Stubs the `information_schema` probe that `loadTableNames` issues. The statement mock is - * strict, so an unexpected `setString` would fail the test: that is what pins PostgreSQL's - * parameterless listing (unlike MySQL, which binds the database name). - */ - private def expectTableListing(conn: Connection, tables: Seq[String]): Unit = { - val statement = mock[PreparedStatement] - val resultSet = mock[ResultSet] - (conn.prepareStatement(_: String)).expects(FETCH_TABLES).returning(statement) - (statement.executeQuery: () => ResultSet).expects().returning(resultSet) - inSequence { - tables.foreach(_ => (resultSet.next _).expects().returning(true)) - (resultSet.next _).expects().returning(false) - } - inSequence { - tables.foreach(table => (resultSet.getString(_: Int)).expects(1).returning(table)) - } - (resultSet.close _).expects() - (statement.close _).expects() - } - "PostgreSQLSourceOpExec" should "deserialize a PostgreSQLSourceOpDesc and derive the schema from JDBC metadata" in { val exec = newExec(columns = @@ -207,17 +96,7 @@ class PostgreSQLSourceOpExecSpec "PostgreSQLSourceOpExec.establishConn" should "dial the PostgreSQL JDBC URL built from the descriptor" in { val exec = newExec() - stubDriver.lastUrl shouldBe JDBC_URL - - val reconnected = mock[Connection] - // PostgreSQLConnUtil.connect flips the fresh connection to read-only - (reconnected.setReadOnly _).expects(true) - stubDriver.arm(reconnected) - - exec.establishConn() should be theSameInstanceAs reconnected - stubDriver.lastUrl shouldBe JDBC_URL - stubDriver.lastProperties.getProperty("user") shouldBe "u" - stubDriver.lastProperties.getProperty("password") shouldBe "p" + verifyReconnect(JDBC_URL)(exec.establishConn()) } it should "propagate the SQLException when the server refuses the connection" in { @@ -228,49 +107,19 @@ class PostgreSQLSourceOpExecSpec "PostgreSQLSourceOpExec.loadTableNames" should "list every base table without binding a database parameter" in { - val exec = newExec() - val conn = mock[Connection] - expectTableListing(conn, Seq("tbl", "other")) - - exec.connection = conn - exec.loadTables() - - exec.tableNames.toList shouldBe List("tbl", "other") + verifyTableListing(newExec(), Seq("tbl", "other")) } it should "leave the table list empty when the database exposes no base tables" in { - val exec = newExec() - val conn = mock[Connection] - expectTableListing(conn, Seq.empty) - - exec.connection = conn - exec.loadTables() - - exec.tableNames shouldBe empty + verifyTableListing(newExec(), Seq.empty) } "PostgreSQLSourceOpExec.open" should "connect and accept a table present in the listing" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("other", "tbl")) - stubDriver.arm(conn) - - exec.open() - - exec.connection should be theSameInstanceAs conn - exec.tableNames.toList shouldBe List("other", "tbl") - exec.batchByAttribute shouldBe None + verifyOpen(newExec()) } it should "reject a table missing from the listing" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("other")) - stubDriver.arm(conn) - - intercept[RuntimeException](exec.open()).getMessage shouldBe "Can't find the given table `tbl`." + verifyMissingTable(newExec()) } "PostgreSQLSourceOpExec.addFilterConditions" should @@ -283,115 +132,25 @@ class PostgreSQLSourceOpExecSpec exec.filterClause should not include "MATCH" } - it should "add nothing when keyword search is switched off" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(false) - desc.keywordSearchByColumn = Option("name") - desc.keywords = Option("sore & throat") - }) - exec.filterClause shouldBe "" - } - - it should "add nothing when no search column is configured" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywords = Option("sore & throat") - }) - exec.filterClause shouldBe "" - } - - it should "still emit the to_tsquery placeholder when the keywords are missing" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("name") - }) - // The guard reads `desc.keywords != null`, but `keywords` is an Option, so it is never null and - // the empty case slips through. Pin the behavior as it stands: the clause keeps its bind - // placeholder even though SQLSourceOpExec.getNextQuery (which unwraps with `.orNull`) binds - // nothing for it, so the statement would fail at execution time. - exec.desc.keywords shouldBe None - exec.filterClause shouldBe TSQUERY_CLAUSE - exec.sqlQuery shouldBe Some(BASE + TSQUERY_CLAUSE + ";") - } - - it should "refuse a keyword search on a non-string column" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("id") - desc.keywords = Option("42") - }) - intercept[RuntimeException](exec.filterClause).getMessage shouldBe - "Can't do keyword search on type integer" - } - - it should "refuse a keyword search on a column that is not in the schema" in { - val exec = newExec(descJson { desc => - desc.keywordSearch = Option(true) - desc.keywordSearchByColumn = Option("nope") - desc.keywords = Option("x") - }) - intercept[RuntimeException](exec.filterClause).getMessage shouldBe - "nope is not contained in the schema" - } + keywordGuardCases("sore & throat", TSQUERY_CLAUSE, "to_tsquery")(configure => + newExec(descJson(configure)) + ) "PostgreSQLSourceOpExec.generateSqlQuery" should "splice the to_tsquery clause into the full statement" in { - val exec = newExec(keywordJson) - exec.sqlQuery shouldBe Some(BASE + TSQUERY_CLAUSE + ";") - - exec.curLimit = Some(3L) - exec.curOffset = Some(2L) - exec.sqlQuery shouldBe Some(BASE + TSQUERY_CLAUSE + " LIMIT ? OFFSET ?;") + verifyRenderedQuery(newExec(keywordJson), TSQUERY_CLAUSE) } it should "produce a plain statement when no keyword search is configured" in { - newExec().sqlQuery shouldBe Some(BASE + ";") + newExec().sqlQuery shouldBe Some(baseSelect + ";") } "PostgreSQLSourceOpExec.produceTuple" should "run the to_tsquery statement and bind the keyword parameter" in { - val exec = newExec(keywordJson) - val conn = mock[Connection] - val queryStatement = mock[PreparedStatement] - val rows = mock[ResultSet] - - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("tbl")) - - (conn - .prepareStatement(_: String)) - .expects(BASE + TSQUERY_CLAUSE + ";") - .returning(queryStatement) - (queryStatement.setString _).expects(1, "sore & throat") - (queryStatement.executeQuery: () => ResultSet).expects().returning(rows) - inSequence { - (rows.next _).expects().returning(true) - (rows.next _).expects().returning(false) - } - (rows.getObject(_: String)).expects("id").returning(Int.box(7)) - (rows.getObject(_: String)).expects("name").returning(null) - (rows.close _).expects() - (queryStatement.close _).expects() - - stubDriver.arm(conn) - exec.open() - val tuples = exec.produceTuple().map(_.asInstanceOf[Tuple]).toList - - tuples should have size 1 - tuples.head.getField[Any]("id") shouldBe 7 - // a SQL NULL surfaces as a null field rather than being dropped - tuples.map(_.getField[Any]("name")) shouldBe List(null) + verifyKeywordRows(newExec(keywordJson), TSQUERY_CLAUSE, "sore & throat", null) } "PostgreSQLSourceOpExec.close" should "close the connection established by open" in { - val exec = newExec() - val conn = mock[Connection] - (conn.setReadOnly _).expects(true) - expectTableListing(conn, Seq("tbl")) - (conn.close _).expects() - stubDriver.arm(conn) - - exec.open() - exec.close() + verifyClose(newExec()) } }
