All Downloads are FREE. Search and download functionalities are using the official Maven repository.

protobuf4j.orm.sql.clause.GroupByClause Maven / Gradle / Ivy

The newest version!
package protobuf4j.orm.sql.clause;

import com.google.common.collect.Lists;
import lombok.Data;
import protobuf4j.orm.sql.AbstractSqlObject;
import protobuf4j.orm.sql.Direction;
import protobuf4j.orm.sql.IExpression;
import protobuf4j.orm.sql.ISqlValue;
import protobuf4j.orm.sql.expr.Column;

import javax.annotation.Nonnull;
import java.util.List;

/**
 * author: yuanwq
 * date: 2018/7/12
 */
@Data
public class GroupByClause extends AbstractSqlObject {
  private final List groupByItems = Lists.newArrayList();

  public GroupByClause clear() {
    groupByItems.clear();
    return this;
  }

  private GroupByClause addGroupByItem(GroupByItem groupByItem) {
    this.groupByItems.add(groupByItem);
    return this;
  }

  public GroupByClause by(IExpression expr) {
    return addGroupByItem(new GroupByItem(expr));
  }

  public GroupByClause by(String column) {
    return by(Column.of(column));
  }

  public GroupByClause asc(IExpression expr) {
    return addGroupByItem(new GroupByItem(expr, Direction.ASC));
  }

  public GroupByClause asc(String column) {
    return asc(Column.of(column));
  }

  public GroupByClause desc(IExpression expr) {
    return addGroupByItem(new GroupByItem(expr, Direction.DESC));
  }

  public GroupByClause desc(String column) {
    return desc(Column.of(column));
  }

  public boolean isEmpty() {
    return groupByItems.isEmpty();
  }

  @Override
  public StringBuilder toSqlTemplate(@Nonnull StringBuilder sb) {
    if (groupByItems.isEmpty()) {
      return sb;
    }
    sb.append("GROUP BY ");
    boolean first = true;
    for (GroupByItem expr : groupByItems) {
      if (first) {
        first = false;
      } else {
        sb.append(",");
      }
      expr.toSqlTemplate(sb);
    }
    return sb;
  }

  @Override
  public StringBuilder toSolidSql(@Nonnull StringBuilder sb) {
    if (groupByItems.isEmpty()) {
      return sb;
    }
    sb.append("GROUP BY ");
    boolean first = true;
    for (GroupByItem expr : groupByItems) {
      if (first) {
        first = false;
      } else {
        sb.append(",");
      }
      expr.toSolidSql(sb);
    }
    return sb;
  }

  @Override
  public List collectSqlValue(@Nonnull List sqlValues) {
    for (GroupByItem expr : groupByItems) {
      expr.collectSqlValue(sqlValues);
    }
    return sqlValues;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy