class 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()));     // TODO: convert using IOC
                    String sortDirection = resolveSortDirection(entry.getValue());      // TODO: convert using IOC
                    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);
        }
    }

}