001/*
002 * Copyright 2006-2012 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.batch.item.database.support;
018
019import org.springframework.util.StringUtils;
020
021/**
022 * Postgres implementation of a  {@link org.springframework.batch.item.database.PagingQueryProvider} using database specific features.
023 * 
024 * When using the groupClause, this implementation expects all select fields not used in aggregate functions to be included in the 
025 * groupClause (the provider does not add them for you).
026 *
027 * @author Thomas Risberg
028 * @author Michael Minella
029 * @since 2.0
030 */
031public class PostgresPagingQueryProvider extends AbstractSqlPagingQueryProvider {
032
033        @Override
034        public String generateFirstPageQuery(int pageSize) {
035                return SqlPagingQueryUtils.generateLimitSqlQuery(this, false, buildLimitClause(pageSize));
036        }
037
038        @Override
039        public String generateRemainingPagesQuery(int pageSize) {
040                if(StringUtils.hasText(getGroupClause())) {
041                        return SqlPagingQueryUtils.generateLimitGroupedSqlQuery(this, true, buildLimitClause(pageSize));
042                }
043                else {
044                        return SqlPagingQueryUtils.generateLimitSqlQuery(this, true, buildLimitClause(pageSize));
045                }
046        }
047
048        private String buildLimitClause(int pageSize) {
049                return new StringBuilder().append("LIMIT ").append(pageSize).toString();
050        }
051        
052        @Override
053        public String generateJumpToItemQuery(int itemIndex, int pageSize) {
054                int page = itemIndex / pageSize;
055                int offset = (page * pageSize) - 1;
056                offset = offset<0 ? 0 : offset;
057                String limitClause = new StringBuilder().append("LIMIT 1 OFFSET ").append(offset).toString();
058                return SqlPagingQueryUtils.generateLimitJumpToQuery(this, limitClause);
059        }
060
061}