001package io.ebean.config.dbplatform;
002
003/**
004 * Adds LIMIT OFFSET clauses to a SQL query.
005 */
006public class LimitOffsetSqlLimiter implements SqlLimiter {
007
008  /**
009   * LIMIT keyword.
010   */
011  private static final String LIMIT = "limit";
012
013  /**
014   * OFFSET keyword.
015   */
016  private static final String OFFSET = "offset";
017
018  @Override
019  public SqlLimitResponse limit(SqlLimitRequest request) {
020
021    String dbSql = request.getDbSql();
022
023    StringBuilder sb = new StringBuilder(50 + dbSql.length());
024    sb.append("select ");
025    if (request.isDistinct()) {
026      sb.append("distinct ");
027    }
028
029    sb.append(dbSql);
030
031    int firstRow = request.getFirstRow();
032    int maxRows = request.getMaxRows();
033
034    if (maxRows > 0 || firstRow > 0) {
035      sb.append(" ").append(LIMIT).append(" ").append(maxRows);
036      if (firstRow > 0) {
037        sb.append(" ").append(OFFSET).append(" ");
038        sb.append(firstRow);
039      }
040    }
041
042    String sql = request.getDbPlatform().completeSql(sb.toString(), request.getOrmQuery());
043    return new SqlLimitResponse(sql);
044  }
045
046}