OrderWriter { public void write(QueryStatement queryStatement, List<IObject> sortMessage) throws QueryBuildException { try { Writer writer = queryStatement.getBodyWriter(); writer.write("ORDER BY"); Iterator<IObject> sortObjects = sortMessage.iterator(); while (sortObjects.hasNext()) { IObject sortObject = sortObjects.next(); Iterator<Map.Entry<IFieldName, Object>> sortEntries = sortObject.iterator(); while (sortEntries.hasNext()) { Map.Entry<IFieldName, Object> entry = sortEntries.next(); FieldPath fieldPath = PostgresFieldPath.fromString(String.valueOf(entry.getKey())); String sortDirection = resolveSortDirection(entry.getValue()); writer.write("("); writer.write(fieldPath.toSQL()); writer.write(")"); writer.write(sortDirection); if (sortObjects.hasNext() || sortEntries.hasNext()) { writer.write(","); } } } } catch (QueryBuildException qbe) { throw qbe; } catch (Exception e) { throw new QueryBuildException("Error while writing ORDER BY clause", e); } }  void write(QueryStatement queryStatement, List<IObject> sortMessage);  }
@Test public void should_WritesORDERClauseIntoQueryStatement() throws Exception { IObject criteriaMessage = new DSObject("{ \"sort\": [ { \"testField\": \"desc\" }, { \"anotherTestField\": \"asc\" } ] }"); List<IObject> sortMessage = (List<IObject>) criteriaMessage.getValue(new FieldName("sort")); orderWriter.write(query, sortMessage); assertEquals("ORDER BY(document#>'{testField}')DESC,(document#>'{anotherTestField}')ASC", body.toString()); verify(query, times(0)).pushParameterSetter(any()); }
@Test(expected = QueryBuildException.class) public void should_FailOnWrongDirection() throws Exception { IObject criteriaMessage = new DSObject("{ \"sort\": [ { \"testField\": 1 } ] }"); List<IObject> sortMessage = (List<IObject>) criteriaMessage.getValue(new FieldName("sort")); orderWriter.write(query, sortMessage); fail(); }