From 4aa248e82bd32742985bfe6e8ef1d51fb921463e Mon Sep 17 00:00:00 2001 From: Eduardo Jaremicki Moreira Date: Thu, 21 Dec 2017 15:37:39 -0200 Subject: [PATCH] IDEMPIERE-3586 Add pagination to Query --- .../src/org/compiere/model/Query.java | 93 ++++++++++++++++++- 1 file changed, 90 insertions(+), 3 deletions(-) diff --git a/org.adempiere.base/src/org/compiere/model/Query.java b/org.adempiere.base/src/org/compiere/model/Query.java index 0fcd883cfb..1d81022d81 100644 --- a/org.adempiere.base/src/org/compiere/model/Query.java +++ b/org.adempiere.base/src/org/compiere/model/Query.java @@ -83,6 +83,16 @@ public class Query private int queryTimeout = 0; private List joinClauseList = new ArrayList(); + /** + * Limit current query rows return. + */ + private int pageSize; + + /** + * Number of pages will be skiped on query run. + */ + private int skip; + /** * * @param table @@ -753,9 +763,86 @@ public class Query if (DB.isPostgreSQL()) sql = sql + " OF " + table.getTableName(); } - if (log.isLoggable(Level.FINEST)) log.finest("TableName = "+table.getTableName()+"... SQL = " +sql); //red1 - to assist in debugging SQL - return sql; - } + + // If have pagination + if (pageSize > 0) { + sql = appendPagination(sql); + } + + if (log.isLoggable(Level.FINEST)) + log.finest("TableName = " + table.getTableName() + "... SQL = " + sql); // red1 - to assist in debugging SQL + + return sql; + } + + /** + * Set the pagination of the query. + * + * @param pPageSize + * Limit current query rows return. + * + * @return current Query + */ + public Query setPageSize(int pPageSize) { + this.pageSize = pPageSize; + return this; + } + + /** + * Set the pagination of the query. + * + * @param pPageSize + * Limit current query rows return. + * + * @param pSkip + * Number of pages will be skiped on query run. ZERO to first page + * + * @return current Query + */ + public Query setPage(int pPageSize, int pSkip) { + this.pageSize = pPageSize; + this.skip = pSkip; + return this; + } + + /** + * If top is bigger than 0 set the pagination on query + * + * @param query + * SQL String + * @param pageSize + * number + * @param skip + * number + */ + private String appendPagination(String pQuery) { + + String query = pQuery; + + if (pageSize > 0) { + + StringBuilder sql = new StringBuilder(); + + if (DB.isOracle()) { + + sql.append("select * from ("); + sql.append(" select ROWNUM pRow, tb.* from ("); + sql.append(query); + sql.append(") tb) where pRow > "); + sql.append(pageSize * skip); + sql.append(" AND pRow <= "); + sql.append(((pageSize * skip) + pageSize)); + + return sql.toString(); + + } + else { + query = query.concat(" FETCH FIRST " + pageSize + " ROWS ONLY OFFSET " + (pageSize * skip)); + } + } + + return query; + } private final ResultSet createResultSet (PreparedStatement pstmt) throws SQLException {