Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 26bf298

Browse files
committed
Fix sql execution with order by parameter.
Replacing the order by parameter '?' with raw values from order by object. {sort: 'asc'}
1 parent a2d94a4 commit 26bf298

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎server/api-service/lowcoder-plugins/sqlBasedPlugin/src/main/java/org/lowcoder/plugin/sql/GeneralSqlExecutor.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,46 @@ private Pair<Statement, Boolean> getStatementAndExecute(Connection connection, S
148148
if (statementInput.isPreparedStatement()) {
149149
String sql = statementInput.getSql();
150150
List<Object> params = statementInput.getParams();
151+
152+
int orderByIndex = -1;
153+
String sortValue = null;
154+
for (int i = 0; i < params.size(); i++) {
155+
Object param = params.get(i);
156+
if (param instanceof Map<?, ?> map && map.containsKey("sort")) {
157+
orderByIndex = i; // Index of the ? to replace (0-based)
158+
sortValue = String.valueOf(map.get("sort")); // e.g., "ASC" or "DESC"
159+
break;
160+
}
161+
}
162+
163+
if (orderByIndex >= 0 && sortValue != null) {
164+
// Validate sortValue to prevent SQL injection
165+
if (!sortValue.equalsIgnoreCase("ASC") && !sortValue.equalsIgnoreCase("DESC")) {
166+
sortValue = "ASC"; // Default to ASC if invalid
167+
}
168+
169+
// Split the SQL at the ? placeholders
170+
String[] sqlParts = sql.split("\\?", -1);
171+
if (orderByIndex < sqlParts.length - 1) {
172+
// Rebuild the SQL, replacing the ? at orderByIndex with sortValue
173+
StringBuilder newSql = new StringBuilder();
174+
for (int i = 0; i < sqlParts.length; i++) {
175+
newSql.append(sqlParts[i]);
176+
if (i < sqlParts.length - 1) {
177+
if (i == orderByIndex) {
178+
newSql.append(sortValue); // Insert ASC or DESC
179+
} else {
180+
newSql.append("?"); // Keep other placeholders
181+
}
182+
}
183+
}
184+
sql = newSql.toString();
185+
186+
// Remove the Map from params since it's no longer a bind parameter
187+
params.remove(orderByIndex);
188+
}
189+
}
190+
151191
var statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
152192

153193
bindPreparedStatementParams(statement, params);

0 commit comments

Comments
 (0)