Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:APIJSON APIJSON ResultSet to Map Transformation

From Leeroopedia
Knowledge Sources
Domains SQL_Execution, Optimization, JDBC
Last Updated 2026-10-11 00:00 GMT

Overview

JDBC ResultSet-to-JSON-Map transformation with adaptive capacity sizing, join-aware column routing, and database-specific metadata handling that converts relational query results into APIJSON's hierarchical JSON response structure.

Description

The AbstractSQLExecutor.execute() method transforms a JDBC ResultSet into a List<Map<String, Object>> (one map per row). This transformation involves several non-obvious optimizations and database-specific workarounds:

Adaptive capacity sizing: Before iterating rows, the executor attempts rs.last() / rs.getRow() / rs.beforeFirst() to get the exact row count for ArrayList pre-sizing. If the JDBC driver doesn't support scrollable ResultSets, it falls back to a heuristic capacity estimate based on:

  • id condition → capacity 1
  • id{} IN list → capacity = list size
  • Otherwise → capacity = config.getCount(), then reduced by a formula accounting for WHERE conditions, GROUP BY, HAVING, and OR/NOT clauses

Column-to-join routing: For JOIN queries, the executor must determine which columns belong to the main table vs. joined tables. When rsmd.getTableName(i) returns empty (Presto, some functions), it uses the JOIN config's column lists to locate the correct table. QuestDB-specific handling renames duplicate columns (e.g., id1 → id).

Database-specific key extraction:

  • Hive: Strips table name prefix from column labels (table.column → column)
  • QuestDB: Uses keyMap to reverse auto-renamed columns
  • KingbaseES Oracle: Hides pagination RN column
  • Columns starting with _ are always hidden

Value type handling: The getValue() method converts JDBC types to JSON-compatible types: Year → int, Month → int, DayOfWeek → int, TemporalAccessor → formatted string, BigDecimal → scaled number.

Null handling: By default (ENABLE_OUTPUT_NULL_COLUMN = false), null columns are skipped — except the main table must put at least one entry (even if null) to prevent empty result maps.

Usage

Use this heuristic when:

  • Debugging unexpected empty results or missing columns in APIJSON responses
  • Adding support for a new database with non-standard JDBC metadata behavior
  • Tuning performance for large result sets (capacity sizing)
  • Handling JOIN queries where columns may be misplaced between main and vice tables

The Insight (Rule of Thumb)

  • Action: Override getKey(), getValue(), isHideColumn(), or onPutColumn() in AbstractSQLExecutor subclass to customize ResultSet transformation.
  • Value: Default behavior: use rsmd.getColumnLabel() for keys, rs.getObject() for values, hide _-prefixed columns, skip nulls.
  • Trade-off: rs.last() for capacity sizing requires a scrollable ResultSet; the fallback heuristic avoids this but may over-allocate or under-allocate.
  • Compatibility: Each database may need specific handling in getKey() for column label quirks.

Reasoning

The core challenge is that JDBC metadata is inconsistent across databases:

  • rsmd.getTableName() may return empty (Presto, SQL functions)
  • Column labels may include table prefixes (Hive)
  • Some databases auto-rename duplicate columns (QuestDB)
  • Pagination may inject synthetic columns (KingbaseES Oracle RN)

The capacity-sizing optimization matters because ArrayList reallocation (System.arrayCopy) is expensive for large result sets. Getting the exact count via rs.last() is ideal, but not all drivers support it. The fallback formula estimates capacity by reducing config.getCount() based on the number of WHERE conditions (more conditions → fewer expected rows), GROUP BY columns, and HAVING conditions — using a logarithmic decay formula (capacity / Math.pow(1.5, ...)).

The null-skipping behavior (ENABLE_OUTPUT_NULL_COLUMN = false) reduces response size but requires special handling for the main table: if all columns are null, the map would be empty, causing downstream code to treat it as a non-existent row. The fix: if (value != null || ENABLE_OUTPUT_NULL_COLUMN || (join == null && table.isEmpty())) ensures at least one entry.

Code Evidence

Capacity estimation fallback in `AbstractSQLExecutor.java:320-375`:

try {
    rs.last();  // 移到最后一行
    resultList = new ArrayList<>(rs.getRow());
    rs.beforeFirst();
} catch (Throwable e) {
    // ... fallback to heuristic capacity estimation
    capacity = config.getCount() <= 0 ? AbstractParser.MAX_QUERY_COUNT : config.getCount();
    if (capacity > MIN_OPTIMIZE_CAPACITY) {
        // Reduce capacity based on WHERE, GROUP BY, HAVING conditions
        double cap = capacity / Math.pow(1.5, Math.log10(capacity)/8
            + andCondCount
            + ((orCondCount <= 0 ? 0 : 2.0d/orCondCount)
            + (notCondCount/5.0d)
            + (groupCount <= 0 ? 0 : 10.0d/Math.min(5, groupCount)))
            + havingCount);
    }
}

Hive column label stripping in `AbstractSQLExecutor.java:1054-1063`:

if (config.isHive()) {
    String tableName = config.getTable();
    String realTableName = AbstractSQLConfig.TABLE_KEY_MAP.get(tableName);
    String pattern = "^" + (StringUtil.isEmpty(realTableName, true) ? tableName : realTableName) + "\\." + "[a-zA-Z]+$";
    boolean isMatch = Pattern.matches(pattern, key);
    if (isMatch) {
        key = key.split("\\.")[1];
    }
}

KingbaseES RN column hiding in `AbstractSQLExecutor.java:1022-1028`:

if (config.isKingBaseOracle() && config.getCount() > 0
        && columnIndex == rsmd.getColumnCount() && "RN".equalsIgnoreCase(columnName)) {
    return true;
}
return columnName.startsWith("_");

Null column handling in `AbstractSQLExecutor.java:1000-1002`:

if (value != null || ENABLE_OUTPUT_NULL_COLUMN || (join == null && table.isEmpty())) {
    table.put(label, value);
}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment