public static SeQueryInfo parse(ISession session, PlainSelect select) throws SeException, IOException { String[] columns = null; String[] tables = null; String where = null; String orderAndOrGroupByClause = null; if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("building SeQueryInfo to reflect " + select); } // obtain needed SeQueryInfo components columns = getColumns(session, select.getSelectItems()); tables = getTables(select.getFromItems()); Expression whereClause = select.getWhere(); if (whereClause != null) { where = whereClause.toString(); } if (select.getGroupByColumnReferences() != null && select.getGroupByColumnReferences().size() > 0) { String gb = PlainSelect.getFormatedList(select.getGroupByColumnReferences(), " GROUP BY "); orderAndOrGroupByClause = gb; } if (select.getOrderByElements() != null && select.getOrderByElements().size() > 0) { String ob = PlainSelect.orderByToString(select.getOrderByElements()); if (orderAndOrGroupByClause == null) { orderAndOrGroupByClause = ""; } orderAndOrGroupByClause += " " + ob; } // build SeQueryInfo SeQueryInfo qinfo = new SeQueryInfo(); qinfo.setColumns(columns); SeSqlConstruct sqlConstruct = new SeSqlConstruct(); sqlConstruct.setTables(tables); if (where != null) { sqlConstruct.setWhere(where); } qinfo.setConstruct(sqlConstruct); if (orderAndOrGroupByClause != null) { qinfo.setByClause(orderAndOrGroupByClause); } return qinfo; }
/** * convert to order by sql * * @param sql * @param orderBy * @return */ public static String converToOrderBySql(String sql, String orderBy) { // 解析SQL Statement stmt = null; try { stmt = CCJSqlParserUtil.parse(sql); Select select = (Select) stmt; SelectBody selectBody = select.getSelectBody(); // 处理body-去最外层order by List<OrderByElement> orderByElements = extraOrderBy(selectBody); String defaultOrderBy = PlainSelect.orderByToString(orderByElements); if (defaultOrderBy.indexOf('?') != -1) { throw new RuntimeException("原SQL[" + sql + "]中的order by包含参数,因此不能使用OrderBy插件进行修改!"); } // 新的sql sql = select.toString(); } catch (Throwable e) { e.printStackTrace(); } return sql + " order by " + orderBy; }
public String toString() { String selects = ""; String allDistinct = ""; if (isAll()) { allDistinct = "ALL "; } else if (isDistinct()) { allDistinct = "DISTINCT "; } for (int i = 0; i < plainSelects.size(); i++) { selects += "(" + plainSelects.get(i) + ((i < plainSelects.size() - 1) ? ") UNION " + allDistinct : ")"); } return selects + ((orderByElements != null) ? PlainSelect.orderByToString(orderByElements) : "") + ((limit != null) ? limit + "" : ""); }