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-9476-99a8ced7251a02556ed1be5c7e790d2883633984
in repository https://gitbox.apache.org/repos/asf/texera.git

commit 0796c47de4c14287b147eaa2b8d416f3e1371086
Author: Xinyuan Lin <[email protected]>
AuthorDate: Mon Nov 16 23:42:18 2026 +0000

    refactor(amber): simplify dashboard database queries (#9476)
    
    ### What changes were proposed in this PR?
    
    Remove redundant database work from three Amber REST resources.
    **+84/−176 lines.**
    
    - User settings read only the requested columns, upsert by `(uid, key)`,
    and delete directly by that key. The separate existence checks and their
    private DAO helpers become unnecessary.
    - User quota sums result and console-log bytes per execution with two
    correlated subqueries in one query. This avoids reading both child
    collections for every execution and preserves zero for missing or null
    sizes.
    - Administrator execution listing computes the access flag in the
    paginated query from `WorkflowAccess.accessibleWids`, the same
    owner-or-grant rule it used before. The total drops two joins guaranteed
    by foreign keys.
    
    The REST response fields, user scoping, and pagination are preserved.
    
    ### Any related issues, documentation, discussions?
    
    Closes #9475.
    
    ### How was this PR tested?
    
    All 58 existing cases and nine local PostgreSQL probe cases passed on
    both main and the PR branch. The probes covered empty and null values,
    quota totals beyond the signed 64-bit range, grant removal, sorting, and
    page boundaries. The four-execution quota request went from nine SQL
    statements to one. The administrator probes went from 32 statements to
    17. Strict Scala compilation of the three touched resources, the scoped
    Scalafmt check, and `git diff --check` passed.
    
    After review, all 58 cases in the four specs passed again with the
    correlated quota sums and the shared access rule. A local probe also
    covered null and missing sizes, another user's rows, and a quota sum
    past the signed 64-bit range. The Scalafmt and Scalafix checks for
    `WorkflowExecutionService` passed.
    
    The existing cases were run directly with ScalaTest on JDK 17 and local
    PostgreSQL. They can also be run from the repository root:
    
    ```text
    sbt "WorkflowExecutionService/testOnly *UserConfigResourceSpec 
*UserQuotaResourceSpec *AdminUserResourceSpec *AdminExecutionResourceSpec"
    ```
    
    ### Was this PR authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-6), Claude Code (Claude Opus 5.5)
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .../texera/web/resource/UserConfigResource.scala   | 137 ++++++---------------
 .../admin/execution/AdminExecutionResource.scala   |  50 +++-----
 .../dashboard/user/quota/UserQuotaResource.scala   |  73 +++++------
 3 files changed, 84 insertions(+), 176 deletions(-)

diff --git 
a/amber/src/main/scala/org/apache/texera/web/resource/UserConfigResource.scala 
b/amber/src/main/scala/org/apache/texera/web/resource/UserConfigResource.scala
index 3e36adf934..87f32a3f53 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/resource/UserConfigResource.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/resource/UserConfigResource.scala
@@ -23,53 +23,46 @@ import io.dropwizard.auth.Auth
 import org.apache.texera.auth.SessionUser
 import org.apache.texera.dao.SqlServer
 import org.apache.texera.dao.jooq.generated.Tables.USER_CONFIG
-import org.apache.texera.dao.jooq.generated.tables.daos.UserConfigDao
-import org.apache.texera.dao.jooq.generated.tables.pojos.{User, UserConfig}
 
 import javax.annotation.security.RolesAllowed
 import javax.ws.rs._
 import javax.ws.rs.core._
-import scala.jdk.CollectionConverters.CollectionHasAsScala
+import scala.jdk.CollectionConverters.MapHasAsScala
 
 /**
   * This class handles requests to read and write the user dictionary,
   * an abstract collection of (key, value) string pairs that is unique for 
each user
-  * This is accomplished using a mysql table called user_dictionary.
-  * The details of user_dictionary can be found in /sql/texera_ddl.sql
+  * This is accomplished using a table called user_config.
+  * The details of user_config can be found in /sql/texera_ddl.sql
   */
 @Path("/user/config")
 @RolesAllowed(Array("REGULAR", "ADMIN"))
 @Consumes(Array(MediaType.TEXT_PLAIN))
 class UserConfigResource {
-  private def userDictionaryDao =
-    new UserConfigDao(
-      SqlServer
-        .getInstance()
-        .createDSLContext()
-        .configuration
-    )
+  private def context = SqlServer.getInstance().createDSLContext()
+
+  private def requireValidKey(key: String): Unit =
+    if (key == null || key.trim.isEmpty) {
+      throw new BadRequestException("key cannot be null or empty")
+    }
 
   @GET
   @Produces(Array(MediaType.APPLICATION_JSON))
   def getAllDict(@Auth sessionUser: SessionUser): Map[String, String] = {
-    val user = sessionUser.getUser
-    getDict(user)
+    getDict(sessionUser.getUid)
   }
 
   /**
     * This method retrieves all of a user's dictionary entries in
-    * the user_dictionary table as a json object
+    * the user_config table as a json object
     */
-  private def getDict(user: User): Map[String, String] = {
-    SqlServer
-      .getInstance()
-      .createDSLContext()
-      .select()
+  private def getDict(uid: Integer): Map[String, String] = {
+    context
+      .select(USER_CONFIG.KEY, USER_CONFIG.VALUE)
       .from(USER_CONFIG)
-      .where(USER_CONFIG.UID.eq(user.getUid))
-      .fetchInto(classOf[UserConfig])
+      .where(USER_CONFIG.UID.eq(uid))
+      .fetchMap(USER_CONFIG.KEY, USER_CONFIG.VALUE)
       .asScala
-      .map { entry => (entry.getKey, entry.getValue) }
       .toMap
   }
 
@@ -77,34 +70,12 @@ class UserConfigResource {
   @Produces(Array(MediaType.TEXT_PLAIN))
   @Path("/{key}")
   def getEntry(@PathParam("key") key: String, @Auth sessionUser: SessionUser): 
String = {
-    val user = sessionUser.getUser
-
-    if (key == null || key.trim.isEmpty) {
-      throw new BadRequestException("key cannot be null or empty")
-    }
-    if (!dictEntryExists(user, key)) {
-      null
-    } else {
-      getValueByKey(user, key)
-    }
-  }
-
-  /**
-    * This method retrieves a value from the user_dictionary table
-    * given a user's uid and key. each tuple (uid, key) is a primary key
-    * in user_dictionary, and should uniquely identify one value
-    *
-    * @return String or null if entry doesn't exist
-    */
-  private def getValueByKey(user: User, key: String): String = {
-    SqlServer
-      .getInstance()
-      .createDSLContext()
-      .fetchOne(
-        USER_CONFIG,
-        USER_CONFIG.UID.eq(user.getUid).and(USER_CONFIG.KEY.eq(key))
-      )
-      .getValue
+    requireValidKey(key)
+    context
+      .select(USER_CONFIG.VALUE)
+      .from(USER_CONFIG)
+      
.where(USER_CONFIG.UID.eq(sessionUser.getUid).and(USER_CONFIG.KEY.eq(key)))
+      .fetchOne(USER_CONFIG.VALUE)
   }
 
   /**
@@ -118,65 +89,27 @@ class UserConfigResource {
       value: String,
       @Auth sessionUser: SessionUser
   ): Unit = {
-    val user = sessionUser.getUser
-    if (key == null || key.trim.isEmpty) {
-      throw new BadRequestException("key cannot be null or empty")
-    }
-    if (dictEntryExists(user, key)) {
-      userDictionaryDao.update(new UserConfig(user.getUid, key, value))
-    } else {
-      userDictionaryDao.insert(new UserConfig(user.getUid, key, value))
-    }
-  }
-
-  /**
-    * This method checks if a given entry exists
-    * each tuple (uid, key) is a primary key in user_dictionary,
-    * and should uniquely identify one value
-    */
-  private def dictEntryExists(user: User, key: String): Boolean = {
-    userDictionaryDao.existsById(
-      SqlServer
-        .getInstance()
-        .createDSLContext()
-        .newRecord(USER_CONFIG.UID, USER_CONFIG.KEY)
-        .values(user.getUid, key)
-    )
+    requireValidKey(key)
+    context
+      .insertInto(USER_CONFIG, USER_CONFIG.UID, USER_CONFIG.KEY, 
USER_CONFIG.VALUE)
+      .values(sessionUser.getUid, key, value)
+      .onConflict(USER_CONFIG.UID, USER_CONFIG.KEY)
+      .doUpdate()
+      .set(USER_CONFIG.VALUE, value)
+      .execute()
   }
 
   /**
     * This method deletes a key-value pair from the current in-session user's 
dictionary based on
     * the "key" attribute of the DeleteRequest
-    *
-    * @return
-    * 401 unauthorized -
-    * 400 bad request -
-    * 422 Unprocessable Entity - payload: "no such entry" (if no entry exists 
for provided key)
     */
   @DELETE
   @Path("/{key}")
   def deleteEntry(@PathParam("key") key: String, @Auth sessionUser: 
SessionUser): Unit = {
-    val user = sessionUser.getUser
-    if (key == null || key.trim.isEmpty) {
-      throw new BadRequestException("key cannot be null or empty")
-    }
-    if (dictEntryExists(user, key)) {
-      deleteDictEntry(user, key)
-    }
-  }
-
-  /**
-    * This method deletes a single entry
-    * each tuple (uid, key) is a primary key in user_dictionary,
-    * and should uniquely identify one value
-    */
-  private def deleteDictEntry(user: User, key: String): Unit = {
-    userDictionaryDao.deleteById(
-      SqlServer
-        .getInstance()
-        .createDSLContext()
-        .newRecord(USER_CONFIG.UID, USER_CONFIG.KEY)
-        .values(user.getUid, key)
-    )
+    requireValidKey(key)
+    context
+      .deleteFrom(USER_CONFIG)
+      
.where(USER_CONFIG.UID.eq(sessionUser.getUid).and(USER_CONFIG.KEY.eq(key)))
+      .execute()
   }
 }
diff --git 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala
 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala
index 4a62d20462..7a50c7ba3a 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/admin/execution/AdminExecutionResource.scala
@@ -100,15 +100,11 @@ class AdminExecutionResource {
   def getTotalWorkflows: Int = {
     context
       .select(
-        DSL.countDistinct(WORKFLOW.WID)
+        DSL.countDistinct(WORKFLOW_VERSION.WID)
       )
       .from(WORKFLOW_EXECUTIONS)
       .join(WORKFLOW_VERSION)
       .on(WORKFLOW_EXECUTIONS.VID.eq(WORKFLOW_VERSION.VID))
-      .join(USER)
-      .on(WORKFLOW_EXECUTIONS.UID.eq(USER.UID))
-      .join(WORKFLOW)
-      .on(WORKFLOW.WID.eq(WORKFLOW_VERSION.WID))
       .fetchOne(0, classOf[Int])
   }
 
@@ -129,6 +125,10 @@ class AdminExecutionResource {
   ): List[dashboardExecution] = {
     val filter_status = filter.asScala.map(mapToStatus).toSeq.filter(_ != 
-1).asJava
 
+    val hasAccessField = DSL
+      
.field(WORKFLOW_VERSION.WID.in(WorkflowAccess.accessibleWids(current_user.getUid)))
+      .as("has_access")
+
     // Base query that retrieves latest execution info for each workflow 
without sorting and filtering.
     // Only retrieving executions in current page according to pageSize and 
pageIndex parameters.
     val executions_base_query = context
@@ -141,7 +141,8 @@ class AdminExecutionResource {
         WORKFLOW_EXECUTIONS.STARTING_TIME,
         WORKFLOW_EXECUTIONS.LAST_UPDATE_TIME,
         WORKFLOW_EXECUTIONS.STATUS,
-        WORKFLOW_EXECUTIONS.NAME
+        WORKFLOW_EXECUTIONS.NAME,
+        hasAccessField
       )
       .from(WORKFLOW_EXECUTIONS)
       .join(WORKFLOW_VERSION)
@@ -169,42 +170,29 @@ class AdminExecutionResource {
     }
 
     // Apply sorting if user specified.
-    var executions_apply_order =
-      executions_apply_filter.limit(page_size).offset(page_index * page_size)
-    if (sortField != "NO_SORTING") {
-      executions_apply_order = executions_apply_filter
-        .orderBy(
-          if (sortDirection == "desc") sortFieldMapping.getOrElse(sortField, 
WORKFLOW.NAME).desc()
-          else sortFieldMapping.getOrElse(sortField, WORKFLOW.NAME).asc()
-        )
-        .limit(page_size)
-        .offset(page_index * page_size)
-    }
+    val executions_apply_order =
+      (if (sortField != "NO_SORTING") {
+         executions_apply_filter.orderBy(
+           if (sortDirection == "desc") sortFieldMapping.getOrElse(sortField, 
WORKFLOW.NAME).desc()
+           else sortFieldMapping.getOrElse(sortField, WORKFLOW.NAME).asc()
+         )
+       } else {
+         executions_apply_filter
+       }).limit(page_size).offset(page_index * page_size)
 
     val executions = executions_apply_order.fetch()
 
-    // Retrieve the id of each workflow that the user has access to.
-    val availableWorkflowIds = context
-      .fetch(WorkflowAccess.accessibleWids(current_user.getUid))
-      .getValues(0, classOf[Integer])
-      .asScala
-      .toSet
-
     // Calculate the statistics needed for each execution.
     executions
       .map(workflowRecord => {
         val startingTime =
           workflowRecord.get(WORKFLOW_EXECUTIONS.STARTING_TIME).getTime
 
-        var lastUpdateTime: Long = 0
-        if (workflowRecord.get(WORKFLOW_EXECUTIONS.LAST_UPDATE_TIME) == null) {
-          lastUpdateTime = 0
-        } else {
-          lastUpdateTime = 
workflowRecord.get(WORKFLOW_EXECUTIONS.LAST_UPDATE_TIME).getTime
-        }
+        val lastUpdateTime =
+          
Option(workflowRecord.get(WORKFLOW_EXECUTIONS.LAST_UPDATE_TIME)).fold(0L)(_.getTime)
 
         val timeDifferenceSeconds = (lastUpdateTime - startingTime) / 1000.0
-        val hasAccess = 
availableWorkflowIds.contains(workflowRecord.get(WORKFLOW_VERSION.WID))
+        val hasAccess = 
java.lang.Boolean.TRUE.equals(workflowRecord.get(hasAccessField))
         dashboardExecution(
           workflowRecord.get(WORKFLOW.NAME),
           workflowRecord.get(WORKFLOW_VERSION.WID),
diff --git 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala
 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala
index bf1869c57f..2e43e4fe72 100644
--- 
a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala
+++ 
b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/quota/UserQuotaResource.scala
@@ -27,6 +27,7 @@ import org.apache.texera.dao.jooq.generated.Tables._
 import 
org.apache.texera.web.resource.dashboard.user.dataset.utils.DatasetStatisticsUtils.getUserCreatedDatasets
 import org.apache.texera.web.resource.dashboard.user.quota.UserQuotaResource._
 import 
org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource
+import org.jooq.impl.DSL
 
 import java.util
 import javax.annotation.security.RolesAllowed
@@ -67,7 +68,6 @@ object UserQuotaResource {
   def getUserCreatedWorkflow(uid: Integer): List[Workflow] = {
     val userWorkflowEntries = context
       .select(
-        WORKFLOW_OF_USER.UID,
         WORKFLOW_OF_USER.WID,
         WORKFLOW.NAME,
         WORKFLOW.CREATION_TIME,
@@ -90,7 +90,7 @@ object UserQuotaResource {
     userWorkflowEntries
       .map(workflowRecord => {
         Workflow(
-          workflowRecord.get(WORKFLOW_OF_USER.UID),
+          uid,
           workflowRecord.get(WORKFLOW_OF_USER.WID),
           workflowRecord.get(WORKFLOW.NAME),
           workflowRecord.get(WORKFLOW.CREATION_TIME).getTime,
@@ -106,12 +106,26 @@ object UserQuotaResource {
   }
 
   def getUserQuotaSize(uid: Integer): Array[QuotaStorage] = {
-    val executions = context
+    val resultTotal = DSL.field(
+      DSL
+        .select(DSL.sum(OPERATOR_PORT_EXECUTIONS.RESULT_SIZE))
+        .from(OPERATOR_PORT_EXECUTIONS)
+        
.where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(WORKFLOW_EXECUTIONS.EID))
+    )
+    val logTotal = DSL.field(
+      DSL
+        .select(DSL.sum(OPERATOR_EXECUTIONS.CONSOLE_MESSAGES_SIZE))
+        .from(OPERATOR_EXECUTIONS)
+        
.where(OPERATOR_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(WORKFLOW_EXECUTIONS.EID))
+    )
+    context
       .select(
         WORKFLOW_EXECUTIONS.EID,
         WORKFLOW_EXECUTIONS.RUNTIME_STATS_SIZE,
         WORKFLOW.WID,
-        WORKFLOW.NAME
+        WORKFLOW.NAME,
+        resultTotal,
+        logTotal
       )
       .from(WORKFLOW_EXECUTIONS)
       .leftJoin(WORKFLOW_VERSION)
@@ -121,47 +135,20 @@ object UserQuotaResource {
       .where(WORKFLOW_EXECUTIONS.UID.eq(uid))
       .orderBy(WORKFLOW_EXECUTIONS.EID.desc)
       .fetch()
-
-    if (executions == null || executions.isEmpty) {
-      return Array.empty
-    }
-
-    executions.asScala.map { record =>
-      val eid = record.get(WORKFLOW_EXECUTIONS.EID)
-      val wid = record.get(WORKFLOW.WID)
-      val workflowName = record.get(WORKFLOW.NAME)
-      val runTimeStatsSize =
-        
Option(record.get(WORKFLOW_EXECUTIONS.RUNTIME_STATS_SIZE)).map(_.toLong).getOrElse(0L)
-
-      val resultSize = context
-        .select(OPERATOR_PORT_EXECUTIONS.RESULT_SIZE)
-        .from(OPERATOR_PORT_EXECUTIONS)
-        .where(OPERATOR_PORT_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid))
-        .fetch()
-        .asScala
-        .map(r => 
Option(r.get(OPERATOR_PORT_EXECUTIONS.RESULT_SIZE)).map(_.toLong).getOrElse(0L))
-        .sum
-
-      val logSize = context
-        .select(OPERATOR_EXECUTIONS.CONSOLE_MESSAGES_SIZE)
-        .from(OPERATOR_EXECUTIONS)
-        .where(OPERATOR_EXECUTIONS.WORKFLOW_EXECUTION_ID.eq(eid))
-        .fetch()
-        .asScala
-        .map(r =>
-          
Option(r.get(OPERATOR_EXECUTIONS.CONSOLE_MESSAGES_SIZE)).map(_.toLong).getOrElse(0L)
+      .asScala
+      .map(record =>
+        QuotaStorage(
+          record.get(WORKFLOW_EXECUTIONS.EID),
+          record.get(WORKFLOW.WID),
+          record.get(WORKFLOW.NAME),
+          Option(record.get(resultTotal)).map(_.longValue()).getOrElse(0L),
+          Option(record.get(WORKFLOW_EXECUTIONS.RUNTIME_STATS_SIZE))
+            .map(_.longValue())
+            .getOrElse(0L),
+          Option(record.get(logTotal)).map(_.longValue()).getOrElse(0L)
         )
-        .sum
-
-      QuotaStorage(
-        eid,
-        wid,
-        workflowName,
-        resultSize,
-        runTimeStatsSize,
-        logSize
       )
-    }.toArray
+      .toArray
   }
 
   def deleteExecutionCollection(eid: Integer): Unit = {

Reply via email to