shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.walker.db.page;
 
import java.util.Locale;
 
/**
 * 描述:分页工具,根据不同数据库生成不同sql分页语句
 * @author 时克英
 * @date 2020年7月23日 下午6:22:35
 */
 
public class PageUtils {
 
    public static final String getLimitStringForMysql(String sql, boolean hasOffset){
        return sql + (hasOffset ? " limit ?, ?" : " limit ?");
    }
    
    public static final String getLimitStringForOracle(String sql, boolean hasOffset){
        sql = sql.trim();
        String forUpdateClause = null;
        boolean isForUpdate = false;
        int forUpdateIndex = sql.toLowerCase(Locale.ROOT).lastIndexOf("for update");
        if (forUpdateIndex > -1) {
            forUpdateClause = sql.substring(forUpdateIndex);
            sql = sql.substring(0, forUpdateIndex - 1);
            isForUpdate = true;
        }
 
        StringBuilder pagingSelect = new StringBuilder(sql.length() + 100);
        if (hasOffset) {
            pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
        } else {
            pagingSelect.append("select * from ( ");
        }
 
        pagingSelect.append(sql);
        if (hasOffset) {
            pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
        } else {
            pagingSelect.append(" ) where rownum <= ?");
        }
 
        if (isForUpdate) {
            pagingSelect.append(" ");
            pagingSelect.append(forUpdateClause);
        }
 
        return pagingSelect.toString();
    }
    
    public static final String getLimitStringForSQLServer(String querySelect, int offset, int limit) {
        if (offset > 0) {
            throw new UnsupportedOperationException("query result offset is not supported");
        } else {
            return (new StringBuilder(querySelect.length() + 8)).append(querySelect).insert(getAfterSelectInsertPoint(querySelect), " top " + limit).toString();
        }
    }
    
    static int getAfterSelectInsertPoint(String sql) {
        int selectIndex = sql.toLowerCase(Locale.ROOT).indexOf("select");
        int selectDistinctIndex = sql.toLowerCase(Locale.ROOT).indexOf("select distinct");
        return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6);
    }
}