2022-07-20 13:18:57 +02:00
|
|
|
package fr.pandacube.lib.db;
|
2021-03-21 12:41:43 +01:00
|
|
|
|
|
|
|
import java.util.ArrayList;
|
|
|
|
import java.util.List;
|
2022-07-10 00:55:56 +02:00
|
|
|
import java.util.stream.Collectors;
|
2021-03-21 12:41:43 +01:00
|
|
|
|
|
|
|
public class SQLOrderBy<E extends SQLElement<E>> {
|
|
|
|
|
2022-07-10 00:55:56 +02:00
|
|
|
private final List<OBField> orderByFields = new ArrayList<>();
|
2021-03-21 12:41:43 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Construit une nouvelle clause ORDER BY
|
|
|
|
*/
|
|
|
|
private SQLOrderBy() {}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ajoute un champ dans la clause ORDER BY en construction
|
|
|
|
*
|
|
|
|
* @param field le champ SQL à ordonner
|
|
|
|
* @param d le sens de tri (croissant ASC ou décroissant DESC)
|
|
|
|
* @return l'objet courant (permet de chainer les ajouts de champs)
|
|
|
|
*/
|
|
|
|
private SQLOrderBy<E> add(SQLField<E, ?> field, Direction d) {
|
|
|
|
orderByFields.add(new OBField(field, d));
|
|
|
|
return this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ajoute un champ dans la clause ORDER BY en construction avec pour direction ASC
|
|
|
|
*
|
|
|
|
* @param field le champ SQL à ordonner
|
|
|
|
* @return l'objet courant (permet de chainer les ajouts de champs)
|
|
|
|
*/
|
|
|
|
public SQLOrderBy<E> thenAsc(SQLField<E, ?> field) {
|
|
|
|
return add(field, Direction.ASC);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Ajoute un champ dans la clause ORDER BY en construction avec pour direction DESC
|
|
|
|
*
|
|
|
|
* @param field le champ SQL à ordonner
|
|
|
|
* @return l'objet courant (permet de chainer les ajouts de champs)
|
|
|
|
*/
|
|
|
|
public SQLOrderBy<E> thenDesc(SQLField<E, ?> field) {
|
|
|
|
return add(field, Direction.DESC);
|
|
|
|
}
|
|
|
|
|
|
|
|
/* package */ String toSQL() {
|
2022-07-10 00:55:56 +02:00
|
|
|
return orderByFields.stream()
|
|
|
|
.map(f -> "`" + f.field.getName() + "` " + f.direction.name())
|
|
|
|
.collect(Collectors.joining(", "));
|
2021-03-21 12:41:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public String toString() {
|
|
|
|
return toSQL();
|
|
|
|
}
|
|
|
|
|
|
|
|
private class OBField {
|
|
|
|
public final SQLField<E, ?> field;
|
|
|
|
public final Direction direction;
|
|
|
|
|
|
|
|
public OBField(SQLField<E, ?> f, Direction d) {
|
|
|
|
field = f;
|
|
|
|
direction = d;
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
private enum Direction {
|
2022-07-10 00:55:56 +02:00
|
|
|
ASC, DESC
|
2021-03-21 12:41:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
public static <E extends SQLElement<E>> SQLOrderBy<E> asc(SQLField<E, ?> field) {
|
|
|
|
return new SQLOrderBy<E>().thenAsc(field);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static <E extends SQLElement<E>> SQLOrderBy<E> desc(SQLField<E, ?> field) {
|
|
|
|
return new SQLOrderBy<E>().thenDesc(field);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|