Skip to content

Fix sql execution with orderby parameter. #1563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 5, 2025
Merged
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 @@ -148,6 +148,46 @@ private Pair<Statement, Boolean> getStatementAndExecute(Connection connection, S
if (statementInput.isPreparedStatement()) {
String sql = statementInput.getSql();
List<Object> params = statementInput.getParams();

int orderByIndex = -1;
String sortValue = null;
for (int i = 0; i < params.size(); i++) {
Object param = params.get(i);
if (param instanceof Map<?, ?> map && map.containsKey("sort")) {
orderByIndex = i; // Index of the ? to replace (0-based)
sortValue = String.valueOf(map.get("sort")); // e.g., "ASC" or "DESC"
break;
}
}

if (orderByIndex >= 0 && sortValue != null) {
// Validate sortValue to prevent SQL injection
if (!sortValue.equalsIgnoreCase("ASC") && !sortValue.equalsIgnoreCase("DESC")) {
sortValue = "ASC"; // Default to ASC if invalid
}

// Split the SQL at the ? placeholders
String[] sqlParts = sql.split("\\?", -1);
if (orderByIndex < sqlParts.length - 1) {
// Rebuild the SQL, replacing the ? at orderByIndex with sortValue
StringBuilder newSql = new StringBuilder();
for (int i = 0; i < sqlParts.length; i++) {
newSql.append(sqlParts[i]);
if (i < sqlParts.length - 1) {
if (i == orderByIndex) {
newSql.append(sortValue); // Insert ASC or DESC
} else {
newSql.append("?"); // Keep other placeholders
}
}
}
sql = newSql.toString();

// Remove the Map from params since it's no longer a bind parameter
params.remove(orderByIndex);
}
}

var statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

bindPreparedStatementParams(statement, params);
Expand Down
Loading