001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.dao.orm.hibernate;
016    
017    import com.liferay.portal.kernel.util.StringBundler;
018    import com.liferay.portal.kernel.util.StringPool;
019    import com.liferay.portal.kernel.util.StringUtil;
020    
021    import org.hibernate.dialect.SQLServerDialect;
022    
023    /**
024     * @author Steven Cao
025     */
026    public class SQLServer2008Dialect extends SQLServerDialect {
027    
028            public String getLimitString(String sql, int offset, int limit) {
029                    String lowerCaseSql = sql.toLowerCase();
030    
031                    int lastOrderByPos = lowerCaseSql.lastIndexOf("order by");
032    
033                    if ((lastOrderByPos < 0) || (offset == 0) ||
034                            StringUtil.endsWith(sql, StringPool.CLOSE_PARENTHESIS)) {
035    
036                            return super.getLimitString(sql, 0, limit);
037                    }
038                    else {
039                            int fromPos = lowerCaseSql.indexOf("from");
040    
041                            String orderBy = sql.substring(lastOrderByPos, sql.length());
042    
043                            String selectFrom = sql.substring(0, fromPos);
044    
045                            String selectFromWhere = sql.substring(fromPos, lastOrderByPos);
046    
047                            StringBundler sb = new StringBundler(10);
048    
049                            sb.append("select * from (");
050                            sb.append(selectFrom);
051                            sb.append(", _page_row_num = row_number() over(");
052                            sb.append(orderBy);
053                            sb.append(")");
054                            sb.append(selectFromWhere);
055                            sb.append(" ) temp where _page_row_num between ");
056                            sb.append(offset + 1);
057                            sb.append(" and ");
058                            sb.append(limit);
059    
060                            return sb.toString();
061                    }
062            }
063    
064            public boolean supportsLimitOffset() {
065                    return _SUPPORTS_LIMIT_OFFSET;
066            }
067    
068            private static final boolean _SUPPORTS_LIMIT_OFFSET = true;
069    
070    }