001package io.ebean.config.dbplatform.sqlserver;
002
003import io.ebean.config.dbplatform.SqlLimitRequest;
004import io.ebean.config.dbplatform.SqlLimitResponse;
005import io.ebean.config.dbplatform.SqlLimiter;
006
007/**
008 * Use ANSI offset rows syntax or top n - SQL Server 2012 onwards.
009 */
010public class SqlServerSqlLimiter implements SqlLimiter {
011
012  public SqlServerSqlLimiter() {
013  }
014
015  @Override
016  public SqlLimitResponse limit(SqlLimitRequest request) {
017
018    String dbSql = request.getDbSql();
019    StringBuilder sb = new StringBuilder(50 + dbSql.length());
020
021    int firstRow = request.getFirstRow();
022    int maxRows = request.getMaxRows();
023
024    if (firstRow < 1) {
025      // just use top n
026      sb.append("select ");
027      if (request.isDistinct()) {
028        sb.append("distinct ");
029      }
030      sb.append("top ").append(maxRows).append(" ");
031      sb.append(dbSql);
032      return new SqlLimitResponse(sb.toString());
033    }
034
035    sb.append("select ");
036    if (request.isDistinct()) {
037      sb.append("distinct ");
038    }
039
040    sb.append(dbSql);
041    sb.append(" ").append("offset");
042    sb.append(" ").append(firstRow).append(" rows");
043    if (maxRows > 0) {
044      sb.append(" fetch next ").append(maxRows).append(" rows only");
045    }
046    return new SqlLimitResponse(sb.toString());
047  }
048
049}