I have a fresh QueryBuilder<Card, Integer>
, and I want to orderByRaw
using a SelectArg
.
//String column is coming from unknown source
SelectArg selectArg = new SelectArg(SqlType.STRING, column);
qBuilder.selectColumns(column).groupBy(column).orderByRaw("? IS NULL ASC", selectArg);
After this I want to get the qBuilder.queryRaw()
. And something really strange happens. The raw statement returned by qBuilder
is this:
SELECT `occupation` FROM `card` GROUP BY `occupation` ORDER BY ? IS NULL ASC
The ?
is not replaced with what should be occupation
here, and as expected, nulls appear first in the ordering of the objects.
Although, if doing this:
qBuilder.selectColumns(column).groupBy(column).orderByRaw(column + " IS NULL ASC");
ordering works as expected (again using qBuilder.queryRaw()
), the nulls go last, and everything is ordered by occupation
ascending.
Debugging
protected abstract void appendStatementEnd(StringBuilder sb, List<ArgumentHolder> argList) throws SQLException;
The above method will add SelectArgs
in the argList but then, the queryRaw()
is called with just the preparedStamenteString()
and not any String... arguments
, which is natural since I called it like this in the first place using qBuilder.queryRaw()
, resulting in calling the method below:
public GenericRawResults<String[]> queryRaw() throws SQLException {
return dao.queryRaw(prepareStatementString());
}
How can I use orderByRaw
without the fear of letting a possible injection happen?
I really don't think this is a bug @venge. Your test validates the query string but the expansion of ?
into the string "testColumn"
happens when the query is executed so it won't be expanded there. You can turn on logging to see that the right query is being run. If it wasn't then we'd see problems about no column name ?
or no argument to ?
specified.
2019-11-01 18:15:16,761 [TRACE] BaseMappedStatement prepared statement arguments: [testColumn] 2019-11-01 18:15:16,781 [DEBUG] StatementExecutor query of 'SELECT
testColumn
FROMtestobject
GROUP BYtestColumn
ORDER BY? IS NULL ASC ' returned 4 results
I think the problem here is that ORDER BY... IN NULL ASC
. In reading the docs about using NULL there, I'm confused about what it should do. ASC
or DESC
doesn't seem to affect the sort order in my tests.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.