package fr.pandacube.lib.db; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * A SQL {@code ORDER BY} expression builder. * @param the table type. */ public class SQLOrderBy> { /** * Creates a new SQL {@code ORDER BY} expression builder with the provided field to sort in the ascending order. * @param field le field to order. * @return a new SQL {@code ORDER BY} expression builder. * @param the type of the table declaring the field. */ public static > SQLOrderBy asc(SQLField field) { return new SQLOrderBy().thenAsc(field); } /** * Creates a new SQL {@code ORDER BY} expression builder with the provided field to sort in the descending order. * @param field le field to order. * @return a new SQL {@code ORDER BY} expression builder. * @param the type of the table declaring the field. */ public static > SQLOrderBy desc(SQLField field) { return new SQLOrderBy().thenDesc(field); } private final List> orderByFields = new ArrayList<>(); private SQLOrderBy() {} private SQLOrderBy add(SQLField field, Direction d) { orderByFields.add(new OBField<>(field, d)); return this; } /** * Adds the provided field to sort in the ascending order, in this {@code ORDER BY} expression builder. * @param field le field to order. * @return this. */ public SQLOrderBy thenAsc(SQLField field) { return add(field, Direction.ASC); } /** * Adds the provided field to sort in the descending order, in this {@code ORDER BY} expression builder. * @param field le field to order. * @return this. */ public SQLOrderBy thenDesc(SQLField field) { return add(field, Direction.DESC); } /* package */ String toSQL() { return orderByFields.stream() .map(f -> "`" + f.field.getName() + "` " + f.direction.name()) .collect(Collectors.joining(", ")); } @Override public String toString() { return toSQL(); } private record OBField>(SQLField field, Direction direction) { } private enum Direction { ASC, DESC } }