diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReader.java index 681fbc2043..0ea50976a5 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReader.java @@ -77,6 +77,7 @@ * @author Jimmy Praet * @author Duyeor Kim * @author WooSeung Kim + * @author Jinhui Kim * @since 2.0 */ public class JdbcPagingItemReader extends AbstractPagingItemReader implements InitializingBean { @@ -325,8 +326,68 @@ private List getParameterList(@Nullable Map 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 { + private static final int NOT_FOUND = -1; + + private static final int AMBIGUOUS = -2; + private final Map sortKeyColumns = new LinkedHashMap<>(); private @Nullable Map sortKeyValues; @@ -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; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProvider.java index 0ac423bc89..e25c3372a6 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProvider.java @@ -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. @@ -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 { @@ -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; } /** diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderPostgresQuotedSortKeyIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderPostgresQuotedSortKeyIntegrationTests.java new file mode 100644 index 0000000000..c5f609da71 --- /dev/null +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderPostgresQuotedSortKeyIntegrationTests.java @@ -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 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 restartedReader = reader("\"A\", \"group\"", Map.of("\"A\"", Order.ASCENDING), + false); + assertEquals(List.of(3L, 4L, 5L), readAll(restartedReader, executionContext)); + } + + private List readAll(String selectClause, Map sortKeys, boolean namedParameters) + throws Exception { + return readAll(reader(selectClause, sortKeys, namedParameters), new ExecutionContext()); + } + + private List readAll(JdbcPagingItemReader reader, ExecutionContext executionContext) throws Exception { + try { + reader.open(executionContext); + List items = new ArrayList<>(); + Long item; + while ((item = reader.read()) != null) { + items.add(item); + } + return items; + } + finally { + reader.close(); + } + } + + private JdbcPagingItemReader reader(String selectClause, Map 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 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; + } + +} diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyLabelTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyLabelTests.java new file mode 100644 index 0000000000..8ddb6c9a3b --- /dev/null +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyLabelTests.java @@ -0,0 +1,81 @@ +/* + * 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 org.junit.jupiter.api.Test; + +import org.springframework.batch.infrastructure.item.database.JdbcPagingItemReader.SortKeyLabel; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Unit tests for the resolution of a sort key to a result set column label, covering the + * cases that a database round trip cannot easily reach. + * + * @author Jinhui Kim + */ +class JdbcPagingItemReaderSortKeyLabelTests { + + @Test + void unquotedQualifiedKey() { + assertSortKeyLabel("p.id", new SortKeyLabel("id", false, false)); + } + + @Test + void plainKey() { + assertSortKeyLabel("id", new SortKeyLabel("id", false, true)); + } + + @Test + void plainKeyWithOuterSpaces() { + assertSortKeyLabel(" id ", new SortKeyLabel("id", false, true)); + } + + @Test + void quotedKeyWithOuterSpaces() { + assertSortKeyLabel(" \"A\" ", new SortKeyLabel("A", true, false)); + } + + @Test + void quotedKeyContainingDot() { + assertSortKeyLabel("\"a.b\"", new SortKeyLabel("a.b", true, false)); + } + + @Test + void quotedKeyContainingEscapedQuote() { + assertSortKeyLabel("\"A\"\"B\"", new SortKeyLabel("A\"B", true, false)); + } + + @Test + void quotedQualifierWithUnquotedColumn() { + assertSortKeyLabel("\"t\".id", new SortKeyLabel("id", false, false)); + } + + @Test + void fullyQuotedQualifiedKey() { + assertSortKeyLabel("\"t\".\"A\"", new SortKeyLabel("A", true, false)); + } + + @Test + void quotedKeyContainingSpaces() { + assertSortKeyLabel("\" A \"", new SortKeyLabel(" A ", true, false)); + } + + private void assertSortKeyLabel(String key, SortKeyLabel expected) { + assertEquals(expected, JdbcPagingItemReader.getSortKeyLabel(key)); + } + +} diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyTests.java index 8bf4f0e4ec..0af06e38e9 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/JdbcPagingItemReaderSortKeyTests.java @@ -38,7 +38,14 @@ import static org.junit.jupiter.api.Assertions.assertThrows; /** + * Sort keys that are column references, including qualified and quoted (delimited) ones. + * A quoted sort key reaches the upper case or mixed case column names of databases that + * use ANSI double quotes ({@code "}) to delimit identifiers, such as PostgreSQL, H2 and + * HSQLDB. Identifiers delimited with backticks or brackets are out of scope, because + * those databases may still compare quoted identifiers case insensitively. + * * @author Mahmoud Ben Hassine + * @author Jinhui Kim */ class JdbcPagingItemReaderSortKeyTests { @@ -53,10 +60,11 @@ void setUp() { .build(); JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); jdbcTemplate.execute("SET MODE DB2"); - jdbcTemplate.execute("CREATE TABLE records (id BIGINT PRIMARY KEY, group_id INTEGER)"); + jdbcTemplate + .execute("CREATE TABLE records (id BIGINT PRIMARY KEY, group_id INTEGER, \"A\" BIGINT, \"group\" INTEGER)"); jdbcTemplate.execute("CREATE TABLE related (id BIGINT PRIMARY KEY)"); for (long id = 1; id <= 5; id++) { - jdbcTemplate.update("INSERT INTO records VALUES (?, ?)", id, (id - 1) / 2); + jdbcTemplate.update("INSERT INTO records VALUES (?, ?, ?, ?)", id, (id - 1) / 2, id, (id - 1) / 2); jdbcTemplate.update("INSERT INTO related VALUES (?)", id + 100); } } @@ -120,6 +128,24 @@ void readWithSchemaQualifiedSortKey() throws Exception { assertEquals(List.of(1L, 2L, 3L, 4L, 5L), readAll(reader, new ExecutionContext())); } + @Test + void rejectUnquotedSortKeyThatMatchesAQuotedColumn() throws Exception { + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + jdbcTemplate.execute("ALTER TABLE records ADD COLUMN \"id\" BIGINT"); + jdbcTemplate.update("UPDATE records SET \"id\" = \"A\" * 10"); + // The result set holds the labels ID and id. An unquoted key must not bind to + // the quoted column, which would store its values as the restart checkpoint and + // skip rows 3 to 5 on the next page. + JdbcPagingItemReader reader = reader("p.id, p.\"id\"", FROM, Map.of("p.id", Order.ASCENDING), false); + try { + reader.open(new ExecutionContext()); + assertThrows(BadSqlGrammarException.class, reader::read); + } + finally { + reader.close(); + } + } + @Test void rejectAmbiguousOutputLabels() throws Exception { JdbcPagingItemReader reader = reader("p.id, r.id", FROM, Map.of("r.id", Order.ASCENDING), false); @@ -144,6 +170,86 @@ void rejectMissingUnqualifiedOutputLabel() throws Exception { } } + @ParameterizedTest + @ValueSource(booleans = { true, false }) + void readWithQuotedSortKey(boolean namedParameters) throws Exception { + JdbcPagingItemReader reader = reader("\"A\", \"group\"", FROM, Map.of("\"A\"", Order.ASCENDING), + namedParameters); + + assertEquals(List.of(1L, 2L, 3L, 4L, 5L), readAll(reader, new ExecutionContext())); + } + + @ParameterizedTest + @ValueSource(booleans = { true, false }) + void restartWithQualifiedQuotedSortKey(boolean namedParameters) throws Exception { + assertRestart("p.\"A\", p.\"group\"", Map.of("p.\"A\"", Order.ASCENDING), namedParameters, List.of(1L, 2L), + List.of(3L, 4L, 5L), Map.of("p.\"A\"", 2L)); + } + + @ParameterizedTest + @ValueSource(booleans = { true, false }) + void restartWithCompositeQuotedSortKeys(boolean namedParameters) throws Exception { + Map sortKeys = new LinkedHashMap<>(); + sortKeys.put("\"group\"", Order.ASCENDING); + sortKeys.put("\"A\"", Order.DESCENDING); + + assertRestart("\"A\", \"group\"", sortKeys, namedParameters, List.of(2L, 1L), List.of(4L, 3L, 5L), + Map.of("\"group\"", 0, "\"A\"", 1L)); + } + + @Test + void readWithQuotedSortKeyContainingSpaces() throws Exception { + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + jdbcTemplate.execute("ALTER TABLE records ADD COLUMN \" A \" BIGINT"); + jdbcTemplate.update("UPDATE records SET \" A \" = \"A\" * 10"); + JdbcPagingItemReader reader = reader("\" A \"", FROM, Map.of("\" A \"", Order.ASCENDING), false); + + assertEquals(List.of(10L, 20L, 30L, 40L, 50L), readAll(reader, new ExecutionContext())); + } + + @Test + void preferExactLabelOverLabelDifferingOnlyInCase() throws Exception { + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + jdbcTemplate.execute("ALTER TABLE records ADD COLUMN \"a\" BIGINT"); + jdbcTemplate.update("UPDATE records SET \"a\" = \"A\" * 100"); + JdbcPagingItemReader reader = reader("\"A\", \"a\"", FROM, Map.of("\"A\"", Order.ASCENDING), false); + + assertEquals(List.of(1L, 2L, 3L, 4L, 5L), readAll(reader, new ExecutionContext())); + } + + @Test + void rejectQuotedSortKeyThatOnlyMatchesAnotherColumnInCase() throws Exception { + JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); + jdbcTemplate.execute("ALTER TABLE records ADD COLUMN \"a\" BIGINT"); + jdbcTemplate.update("UPDATE records SET \"a\" = \"A\" * 100"); + // "a" is a different column: a quoted sort key that is missing from the select + // clause must not fall back to it, which would silently store the wrong values + // as the restart checkpoint. + JdbcPagingItemReader reader = reader("\"a\"", FROM, Map.of("\"A\"", Order.ASCENDING), false); + try { + reader.open(new ExecutionContext()); + assertThrows(BadSqlGrammarException.class, reader::read); + } + finally { + reader.close(); + } + } + + @Test + void rejectAmbiguousQuotedOutputLabels() throws Exception { + // Both sides of the join output a column labeled A, so the guard must reject the + // sort key instead of silently picking one of them. + JdbcPagingItemReader reader = reader("p.\"A\", q.\"A\"", "records p, records q", + Map.of("p.\"A\"", Order.ASCENDING), false); + try { + reader.open(new ExecutionContext()); + assertThrows(BadSqlGrammarException.class, reader::read); + } + finally { + reader.close(); + } + } + private void assertRestart(String selectClause, Map sortKeys, boolean namedParameters, List firstItems, List remainingItems, Map expectedKeys) throws Exception { ExecutionContext executionContext = new ExecutionContext(); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProviderSortKeyPlaceHolderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProviderSortKeyPlaceHolderTests.java new file mode 100644 index 0000000000..c903124115 --- /dev/null +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/infrastructure/item/database/support/AbstractSqlPagingQueryProviderSortKeyPlaceHolderTests.java @@ -0,0 +1,70 @@ +/* + * 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.support; + +import java.util.Map; + +import javax.sql.DataSource; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.springframework.batch.infrastructure.item.database.Order; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; + +/** + * Tests the sort key placeholder of {@link AbstractSqlPagingQueryProvider}. The + * placeholder does not depend on the database dialect, so a single concrete provider is + * enough and no embedded database is needed: {@code init} only records whether the query + * uses named parameters. + * + * @author Jinhui Kim + */ +class AbstractSqlPagingQueryProviderSortKeyPlaceHolderTests { + + private final Db2PagingQueryProvider pagingQueryProvider = new Db2PagingQueryProvider(); + + @BeforeEach + void setUp() { + this.pagingQueryProvider.setSelectClause("id, name, age"); + this.pagingQueryProvider.setFromClause("foo"); + this.pagingQueryProvider.setSortKeys(Map.of("id", Order.ASCENDING)); + } + + @Test + void sortKeyPlaceHolderWithNamedParameters() throws Exception { + this.pagingQueryProvider.setWhereClause("bar = :bar"); + this.pagingQueryProvider.init(mock(DataSource.class)); + + assertEquals(":_id", this.pagingQueryProvider.getSortKeyPlaceHolder("id")); + assertEquals(":_p.id", this.pagingQueryProvider.getSortKeyPlaceHolder("p.id")); + // A quoted or qualified column reference is not a valid unquoted parameter name + assertEquals(":{_\"A\"}", this.pagingQueryProvider.getSortKeyPlaceHolder("\"A\"")); + assertEquals(":{_p.\"A\"}", this.pagingQueryProvider.getSortKeyPlaceHolder("p.\"A\"")); + } + + @Test + void sortKeyPlaceHolderWithPositionalParameters() throws Exception { + this.pagingQueryProvider.setWhereClause("bar = ?"); + this.pagingQueryProvider.init(mock(DataSource.class)); + + assertEquals("?", this.pagingQueryProvider.getSortKeyPlaceHolder("id")); + assertEquals("?", this.pagingQueryProvider.getSortKeyPlaceHolder("\"A\"")); + } + +}