Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
* @author Jimmy Praet
* @author Duyeor Kim
* @author WooSeung Kim
* @author Jinhui Kim
* @since 2.0
*/
public class JdbcPagingItemReader<T> extends AbstractPagingItemReader<T> implements InitializingBean {
Expand Down Expand Up @@ -325,8 +326,68 @@ private List<Object> getParameterList(@Nullable Map<String, Object> values,
return parameterList;
}

/**
* The result set column label of a sort key, and whether the sort key named that
* column with an ANSI double-quoted identifier.
*
* @param label the column label, with identifier quoting removed
* @param quoted whether the last identifier of the sort key was quoted
* @param plain whether the sort key is the column label itself, without quoting or a
* qualifier
*/
record SortKeyLabel(String label, boolean quoted, boolean plain) {
}

/**
* Return the column label of the last identifier in the given sort key, dropping
* identifier quoting. For example both {@code "A"} and {@code t."A"} yield the label
* {@code A}, the first as a quoted key. Leading and trailing spaces on the sort key
* are ignored, while spaces inside a quoted identifier are preserved. Only ANSI
* double quotes ({@code "}) delimit an identifier: identifiers quoted with backticks
* or brackets are out of scope, because those databases may still compare them case
* insensitively.
* @param key the configured sort key
* @return the column label of the sort key
*/
static SortKeyLabel getSortKeyLabel(String key) {
String trimmedKey = key.trim();
StringBuilder label = new StringBuilder();
boolean inQuotedIdentifier = false;
boolean quoted = false;
for (int i = 0; i < trimmedKey.length(); i++) {
char c = trimmedKey.charAt(i);
if (c == '"') {
if (inQuotedIdentifier && i + 1 < trimmedKey.length() && trimmedKey.charAt(i + 1) == '"') {
// Escaped double quote inside a delimited identifier
label.append('"');
i++;
}
else {
inQuotedIdentifier = !inQuotedIdentifier;
if (inQuotedIdentifier) {
quoted = true;
}
}
}
else if (c == '.' && !inQuotedIdentifier) {
// Start a new identifier segment
label.setLength(0);
quoted = false;
}
else {
label.append(c);
}
}
String labelString = label.toString();
return new SortKeyLabel(labelString, quoted, labelString.equals(trimmedKey));
}

private class PagingRowMapper implements RowMapper<T> {

private static final int NOT_FOUND = -1;

private static final int AMBIGUOUS = -2;

private final Map<String, Integer> sortKeyColumns = new LinkedHashMap<>();

private @Nullable Map<String, Object> sortKeyValues;
Expand Down Expand Up @@ -354,27 +415,47 @@ private int findSortKeyColumn(ResultSet rs, String key) throws SQLException {
return rs.findColumn(key);
}
catch (SQLException original) {
int separator = key.lastIndexOf('.');
if (separator < 0) {
SortKeyLabel sortKeyLabel = getSortKeyLabel(key);
if (sortKeyLabel.plain()) {
// A plain label needs no metadata scan: findColumn already looked
// up exactly this label.
throw original;
}
String label = key.substring(separator + 1);
ResultSetMetaData metadata = rs.getMetaData();
int match = -1;
for (int i = 1; i <= metadata.getColumnCount(); i++) {
if (label.equalsIgnoreCase(JdbcUtils.lookupColumnName(metadata, i))) {
if (match != -1) {
// Do not silently choose between duplicate output labels.
throw original;
}
match = i;
}
}
if (match == -1) {
// The sort key is a SQL column reference (which may be quoted or
// qualified), while findColumn expects a result set column label.
// A quoted identifier is case sensitive, so it may only match the
// exact label; an unquoted key may match a unique label that differs
// in case. The single pass matters: an exact match tried first would
// let an unquoted key such as p.id bind to a quoted "id" column while
// the unquoted id column is also in the result set.
int column = findColumnIndex(rs, sortKeyLabel.label(), !sortKeyLabel.quoted());
if (column < 0) {
throw original;
}
return match;
return column;
}
}

/**
* Return the index of the only column whose label matches the given label.
* @return the column index, {@code NOT_FOUND} if no label matches, or
* {@code AMBIGUOUS} if more than one label matches
*/
private int findColumnIndex(ResultSet rs, String label, boolean ignoreCase) throws SQLException {
ResultSetMetaData metadata = rs.getMetaData();
int match = NOT_FOUND;
for (int i = 1; i <= metadata.getColumnCount(); i++) {
String columnLabel = JdbcUtils.lookupColumnName(metadata, i);
boolean matches = ignoreCase ? label.equalsIgnoreCase(columnLabel) : label.equals(columnLabel);
if (matches) {
if (match != NOT_FOUND) {
// Do not silently choose between duplicate output labels.
return AMBIGUOUS;
}
match = i;
}
}
return match;
}

}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2006-2024 the original author or authors.
* Copyright 2006-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -52,6 +52,7 @@
* @author Mahmoud Ben Hassine
* @author Benjamin Hetz
* @author Stefano Cordio
* @author Jinhui Kim
* @since 2.0
*/
public abstract class AbstractSqlPagingQueryProvider implements PagingQueryProvider {
Expand Down Expand Up @@ -162,12 +163,31 @@ public boolean isUsingNamedParameters() {

/**
* The sort key placeholder will vary depending on whether named parameters or
* traditional placeholders are used in query strings.
* traditional placeholders are used in query strings. A sort key can be a quoted or
* qualified SQL column reference, such as {@code "A"} or {@code t."A"}. As the quote
* characters are not valid in a plain named parameter, such a key is wrapped in the
* {@code :{...}} form, in which the braces delimit the parameter name.
* @return placeholder for sortKey.
*/
@Override
public String getSortKeyPlaceHolder(String keyName) {
return usingNamedParameters ? ":_" + keyName : "?";
if (!usingNamedParameters) {
return "?";
}
String parameterName = "_" + keyName;
// A sort key can be a quoted or qualified column reference (for example "A"
// or t."A"), which is not a valid unquoted named parameter name
return isPlainParameterName(parameterName) ? ":" + parameterName : ":{" + parameterName + "}";
}

private static boolean isPlainParameterName(String parameterName) {
for (int i = 0; i < parameterName.length(); i++) {
char c = parameterName.charAt(i);
if (!Character.isLetterOrDigit(c) && c != '_' && c != '.') {
return false;
}
}
return true;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* Copyright 2026-present the original author or authors.
*
* Licensed 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
*
* https://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.springframework.batch.infrastructure.item.database;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.postgresql.ds.PGSimpleDataSource;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;

import org.springframework.batch.infrastructure.item.ExecutionContext;
import org.springframework.batch.infrastructure.item.database.support.PostgresPagingQueryProvider;
import org.springframework.jdbc.core.JdbcTemplate;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
* Sort keys that are quoted column references, as required for upper case or mixed case
* column names in PostgreSQL. PostgreSQL folds unquoted identifiers to lower case, so a
* column named {@code "A"} must be referenced and sorted with quotes, while the result
* set column label stays {@code A}.
*
* @author Jinhui Kim
*/
@Testcontainers(disabledWithoutDocker = true)
class JdbcPagingItemReaderPostgresQuotedSortKeyIntegrationTests {

private static final DockerImageName POSTGRESQL_IMAGE = DockerImageName.parse("postgres:17.5");

@Container
public static PostgreSQLContainer postgres = new PostgreSQLContainer(POSTGRESQL_IMAGE);

private PGSimpleDataSource dataSource;

@BeforeEach
void setUp() {
this.dataSource = new PGSimpleDataSource();
this.dataSource.setURL(postgres.getJdbcUrl());
this.dataSource.setUser(postgres.getUsername());
this.dataSource.setPassword(postgres.getPassword());
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
jdbcTemplate.execute("DROP TABLE IF EXISTS records");
jdbcTemplate.execute("CREATE TABLE records (\"A\" BIGINT PRIMARY KEY, \"group\" INTEGER)");
for (long id = 1; id <= 5; id++) {
jdbcTemplate.update("INSERT INTO records VALUES (?, ?)", id, (id - 1) / 2);
}
}

@Test
void readWithQuotedSortKeyAndNamedParameters() throws Exception {
assertEquals(List.of(1L, 2L, 3L, 4L, 5L), readAll("\"A\", \"group\"", Map.of("\"A\"", Order.ASCENDING), true));
}

@Test
void restartWithQuotedSortKey() throws Exception {
ExecutionContext executionContext = new ExecutionContext();
JdbcPagingItemReader<Long> reader = reader("\"A\", \"group\"", Map.of("\"A\"", Order.ASCENDING), false);
try {
reader.open(executionContext);
assertEquals(1L, reader.read());
assertEquals(2L, reader.read());
reader.update(executionContext);
assertEquals(Map.of("\"A\"", 2L), executionContext.get("reader.start.after"));
}
finally {
reader.close();
}

JdbcPagingItemReader<Long> restartedReader = reader("\"A\", \"group\"", Map.of("\"A\"", Order.ASCENDING),
false);
assertEquals(List.of(3L, 4L, 5L), readAll(restartedReader, executionContext));
}

private List<Long> readAll(String selectClause, Map<String, Order> sortKeys, boolean namedParameters)
throws Exception {
return readAll(reader(selectClause, sortKeys, namedParameters), new ExecutionContext());
}

private List<Long> readAll(JdbcPagingItemReader<Long> reader, ExecutionContext executionContext) throws Exception {
try {
reader.open(executionContext);
List<Long> items = new ArrayList<>();
Long item;
while ((item = reader.read()) != null) {
items.add(item);
}
return items;
}
finally {
reader.close();
}
}

private JdbcPagingItemReader<Long> reader(String selectClause, Map<String, Order> sortKeys, boolean namedParameters)
throws Exception {
PostgresPagingQueryProvider queryProvider = new PostgresPagingQueryProvider();
queryProvider.setSelectClause(selectClause);
queryProvider.setFromClause("records p");
queryProvider.setWhereClause(namedParameters ? "1 = :enabled" : "1 = ?");
queryProvider.setSortKeys(sortKeys);
JdbcPagingItemReader<Long> reader = new JdbcPagingItemReader<>(this.dataSource, queryProvider);
reader.setName("reader");
reader.setPageSize(2);
reader.setParameterValues(Map.of(namedParameters ? "enabled" : "0", 1));
reader.setRowMapper((rs, rowNum) -> rs.getLong(1));
reader.afterPropertiesSet();
return reader;
}

}
Loading