net.sf.jsqlparser.statement.select.PlainSelect Java Examples
The following examples show how to use
net.sf.jsqlparser.statement.select.PlainSelect.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SqlBuilder.java From das with Apache License 2.0 | 6 votes |
/** * Re-build the query SQL to implement paging function. The new SQL Statement will contains limit if the database * type is MYSQL, CET wrapped if database type is SQL Server. Note: the final SQL will contain two %s, which should * be replaced in run time. * * @param sql The original SQL Statement * @param dbType The database type * @return Re-build SQL which contains limit if the database type is MYSQL, CET wrapped if database type is SQL * Server. * @throws Exception */ public static String pagingQuerySql(String sql, DatabaseCategory dbType, CurrentLanguage lang) throws Exception { String sql_content = sql.replace("@", ":"); boolean withNolock = StringUtils.containsIgnoreCase(sql_content, "WITH (NOLOCK)"); if (withNolock) sql_content = sql_content.replaceAll("(?i)WITH \\(NOLOCK\\)", ""); StringBuilder sb = new StringBuilder(); try { Select select = (Select) parserManager.parse(new StringReader(sql_content)); PlainSelect plain = (PlainSelect) select.getSelectBody(); if (dbType == DatabaseCategory.MySql) { sb.append(plain.toString()); sb.append(lang == CurrentLanguage.Java ? mysqlPageClausePattern : mysqlCSPageClausePattern); } else if (dbType == DatabaseCategory.SqlServer) { sb.append(plain.toString()); sb.append(lang == CurrentLanguage.Java ? sqlserverPagingClausePattern : sqlseverCSPagingClausePattern); } else { throw new Exception("Unknow database category."); } } catch (Throwable e) { throw e; } return sb.toString().replace(":", "@"); }
Example #2
Source File: FunctionCountTest.java From Mybatis-PageHelper with MIT License | 6 votes |
@Test public void test() { Select select = select("select max(name),code,min(aa),nvl(ab,0),heh from user where a > 100"); List<SelectItem> selectItems = ((PlainSelect) select.getSelectBody()).getSelectItems(); for (SelectItem item : selectItems) { if (item instanceof SelectExpressionItem) { Expression exp = ((SelectExpressionItem) item).getExpression(); if (exp instanceof Function) { System.out.println("Function:" + item.toString()); } else { System.out.println("Not a function:" + exp.toString()); } } else { System.out.println("Not a function:" + item.toString()); } } }
Example #3
Source File: CTEToNestedQueryConverter.java From quetzal with Eclipse Public License 2.0 | 6 votes |
protected int getNumberNonPlaceHolderFromItem(PlainSelect plainSelect) { int ret = 0; if (useExplicitJoinSyntax) { for (Join join: plainSelect.getJoins()) { if (join.getRightItem()!=null) { if ( (join.getRightItem() instanceof Table)) { String tableName = ((Table) join.getRightItem()).getFullyQualifiedName(); if (!placeHolderTables.contains(tableName)) { ret++; } } else { ret++; } } } } return ret; }
Example #4
Source File: AbstractCloudSpannerStatement.java From spanner-jdbc with MIT License | 6 votes |
/** * Determines whether the given sql statement must be executed in a single use read context. This * must be done for queries against the information schema. This method sets the * <code>forceSingleUseReadContext</code> to true if necessary. * * @param select The sql statement to be examined. */ protected void determineForceSingleUseReadContext(Select select) { if (select.getSelectBody() != null) { select.getSelectBody().accept(new SelectVisitorAdapter() { @Override public void visit(PlainSelect plainSelect) { if (plainSelect.getFromItem() != null) { plainSelect.getFromItem().accept(new FromItemVisitorAdapter() { @Override public void visit(Table table) { if (table.getSchemaName() != null && table.getSchemaName().equalsIgnoreCase("INFORMATION_SCHEMA")) { setForceSingleUseReadContext(true); } } }); } } }); } }
Example #5
Source File: CTEToNestedQueryConverter.java From quetzal with Eclipse Public License 2.0 | 6 votes |
@Override public String toString() { StringBuilder buf = new StringBuilder(); for (int i = 0; i < getPlainSelects().size(); i++) { if (i != 0) { buf.append(" ") .append(getOperations().get(i - 1).toString()) .append(" "); } buf.append(getPlainSelects().get(i).toString()); } if (getOrderByElements() != null) { buf.append(PlainSelect.orderByToString(getOrderByElements())); } if (getLimit() != null) { buf.append(getLimit().toString()); } return buf.toString(); }
Example #6
Source File: FromHolder.java From sql-to-mongo-db-query-converter with Apache License 2.0 | 6 votes |
private void addToSQLHolderMap(FromItem from) throws com.github.vincentrussell.query.mongodb.sql.converter.ParseException, ParseException { if (from instanceof Table) { Table table = (Table)from; fromToSQLHolder.put(table, new SQLTableInfoHolder(table.getName())); } else if(from instanceof SubSelect){ SubSelect subselect = (SubSelect) from; fromToSQLHolder.put(from, SQLCommandInfoHolder.Builder .create(defaultFieldType, fieldNameToFieldTypeMapping) .setPlainSelect((PlainSelect)subselect.getSelectBody()) .build()); } else {//Not happen SubJoin, not supported previously return; } }
Example #7
Source File: SqlBuilder.java From dal with Apache License 2.0 | 6 votes |
/** * Re-build the query SQL to implement paging function. The new SQL Statement will contains limit if the database * type is MYSQL, CET wrapped if database type is SQL Server. Note: the final SQL will contain two %s, which should * be replaced in run time. * * @param sql The original SQL Statement * @param dbType The database type * @return Re-build SQL which contains limit if the database type is MYSQL, CET wrapped if database type is SQL * Server. * @throws Exception */ public static String pagingQuerySql(String sql, DatabaseCategory dbType, CurrentLanguage lang) throws Exception { String sql_content = sql.replace("@", ":"); boolean withNolock = StringUtils.containsIgnoreCase(sql_content, "WITH (NOLOCK)"); if (withNolock) sql_content = sql_content.replaceAll("(?i)WITH \\(NOLOCK\\)", ""); StringBuilder sb = new StringBuilder(); try { Select select = (Select) parserManager.parse(new StringReader(sql_content)); PlainSelect plain = (PlainSelect) select.getSelectBody(); if (dbType == DatabaseCategory.MySql) { sb.append(plain.toString()); sb.append(lang == CurrentLanguage.Java ? mysqlPageClausePattern : mysqlCSPageClausePattern); } else if (dbType == DatabaseCategory.SqlServer) { sb.append(plain.toString()); sb.append(lang == CurrentLanguage.Java ? sqlserverPagingClausePattern : sqlseverCSPagingClausePattern); } else { throw new Exception("Unknow database category."); } } catch (Throwable e) { throw e; } return sb.toString().replace(":", "@"); }
Example #8
Source File: SqlServer2012Dialect.java From hasor with Apache License 2.0 | 6 votes |
@Override public BoundSql getPageSql(FxQuery fxSql, Map<String, Object> paramMap, int start, int limit) { String buildSqlString = fxSql.buildQueryString(paramMap); List<Object> paramArrays = fxSql.buildParameterSource(paramMap); // StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append(buildSqlString); // if (buildSqlString.toLowerCase().contains("order by")) { Select selectStatement = parseSelect(buildSqlString, fxSql); PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody(); if (plainSelect.getOrderByElements() == null) { sqlBuilder.append(" ORDER BY CURRENT_TIMESTAMP"); } } else { sqlBuilder.append(" ORDER BY CURRENT_TIMESTAMP"); } // sqlBuilder.append(" offset ? rows fetch next ? rows only "); paramArrays.add(start); paramArrays.add(limit); // buildSqlString = sqlBuilder.toString(); return new BoundSql(buildSqlString, paramArrays.toArray()); }
Example #9
Source File: SqlServer2012Dialect.java From hasor with Apache License 2.0 | 6 votes |
@Override public BoundSql getCountSql(FxQuery fxSql, Map<String, Object> paramMap) { String buildSqlString = fxSql.buildQueryString(paramMap); List<Object> paramArrays = fxSql.buildParameterSource(paramMap); // // .含有 order by 去掉它 if (buildSqlString.toLowerCase().contains("order by")) { Select selectStatement = parseSelect(buildSqlString, fxSql); PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody(); if (plainSelect.getOrderByElements() != null) { List<OrderByElement> orderByElements = plainSelect.getOrderByElements(); plainSelect.setOrderByElements(null); buildSqlString = selectStatement.toString(); plainSelect.setOrderByElements(orderByElements); } } // .拼 count 语句 StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("SELECT COUNT(*) FROM ("); sqlBuilder.append(buildSqlString); sqlBuilder.append(") as TEMP_T"); return new BoundSql(sqlBuilder.toString(), paramArrays.toArray()); }
Example #10
Source File: FunctionCountTest.java From Mybatis-PageHelper with MIT License | 5 votes |
@Test public void test2() { Select select = select("select distinct(name) from user where a > 100"); List<SelectItem> selectItems = ((PlainSelect) select.getSelectBody()).getSelectItems(); for (SelectItem item : selectItems) { if (item instanceof Function) { System.out.println("Function:" + item.toString()); } else { System.out.println("Not a function:" + item.toString()); } } }
Example #11
Source File: SQLUtils.java From nimble-orm with GNU General Public License v2.0 | 5 votes |
/** * 往where sql里面插入AND关系的表达式。 * * 例如:whereSql为 where a!=3 or a!=2 limit 1 * condExpress为 deleted=0 * 那么返回:where (deleted=0 and (a!=3 or a!=2)) limit 1 * * @param whereSql 从where起的sql子句,如果有where必须带上where关键字。 * @param condExpression 例如a=? 不带where或and关键字。 * @return 注意返回字符串前面没有空格 * @throws JSQLParserException */ public static String insertWhereAndExpression(String whereSql, String condExpression) throws JSQLParserException { if(condExpression == null || condExpression.trim().isEmpty()) { return whereSql == null ? "" : whereSql; } if(whereSql == null || whereSql.trim().isEmpty()) { return "WHERE " + condExpression; } whereSql = whereSql.trim(); if(!whereSql.toUpperCase().startsWith("WHERE ")) { return "WHERE " + condExpression + " " + whereSql; } // 为解决JSqlParse对复杂的condExpression不支持的问题,这里用替换的形式来达到目的 String magic = "A" + UUID.randomUUID().toString().replace("-", ""); String selectSql = "select * from dual "; // 辅助where sql解析用 Statement statement = CCJSqlParserUtil.parse(selectSql + whereSql); Select selectStatement = (Select) statement; PlainSelect plainSelect = (PlainSelect)selectStatement.getSelectBody(); Expression ce = CCJSqlParserUtil.parseCondExpression(magic); Expression oldWhere = plainSelect.getWhere(); Expression newWhere = new FixedAndExpression(oldWhere, ce); plainSelect.setWhere(newWhere); String result = plainSelect.toString().substring(selectSql.length()); return result.replace(magic, condExpression); }
Example #12
Source File: AddDateInterceptor.java From dynamic-add-date with MIT License | 5 votes |
@Override public void visit(PlainSelect plainSelect) { if (index != -1) { plainSelect.getSelectItems().set(index, new SelectExpressionItem(new QuotationTimestampValue(columnValue))); } else { plainSelect.getSelectItems().add(new SelectExpressionItem(new QuotationTimestampValue(columnValue))); } }
Example #13
Source File: CloudSpannerResultSetMetaData.java From spanner-jdbc with MIT License | 5 votes |
private void initColumns(Select select) { columns = new ArrayList<>(); aliases = new ArrayList<>(); select.getSelectBody().accept(new SelectVisitorAdapter() { @Override public void visit(PlainSelect plainSelect) { for (SelectItem selectItem : plainSelect.getSelectItems()) { selectItem.accept(new SelectItemVisitor() { private boolean foundColumn = false; @Override public void visit(SelectExpressionItem selectExpressionItem) { selectExpressionItem.getExpression().accept(new ExpressionVisitorAdapter() { @Override public void visit(Column column) { registerColumn(column, selectExpressionItem.getAlias()); foundColumn = true; } }); if (!foundColumn) { registerColumn(null, selectExpressionItem.getAlias()); } } @Override public void visit(AllTableColumns allTableColumns) { registerAllTableColumns(allTableColumns.getTable()); } @Override public void visit(AllColumns allColumns) { for (Table table : tables) { registerAllTableColumns(table); } } }); } } }); }
Example #14
Source File: ObjPD.java From openprodoc with GNU Affero General Public License v3.0 | 4 votes |
/** * Search in ANY object using SQL Syntax subset, similar to CMIS SQL * @param SQL complete query * @return and opened @Cursor * @throws PDException In any Error */ public Cursor SearchSelect(String SQL) throws PDException { if (PDLog.isDebug()) PDLog.Debug("ObjPD.SearchSelect>:"+SQL); Query QBE=null; try { Select ParsedSQL = (Select) CCJSqlParserUtil.parse(SQL); //-- Calculate Table Names ------------ TablesNamesFinder tablesNamesFinder = new TablesNamesFinder(); List<String> TableListSQL = tablesNamesFinder.getTableList(ParsedSQL); Vector <String> OPDTabs=CalculateTabs(TableListSQL); //-- Calculate Fields ------------- List<SelectItem> selectItems = ((PlainSelect)ParsedSQL.getSelectBody()).getSelectItems(); Vector<String> Fields=new Vector<String>(); if (!( selectItems.get(0) instanceof AllColumns)) for (int i = 0; i < selectItems.size(); i++) Fields.add(((SelectExpressionItem)selectItems.get(i)).getExpression().toString()); Record Rec=CalculateRec(Fields, OPDTabs); //-- Calculate Conds in Select ------------ Expression When = ((PlainSelect)ParsedSQL.getSelectBody()).getWhere(); Conditions CondSel=EvalExpr(When); //-- Check Additional-Security Conditions ---- Conditions FinalConds; Conditions AddedConds=NeededMoreConds(TableListSQL, OPDTabs); if (AddedConds==null) FinalConds=CondSel; else { FinalConds=new Conditions(); FinalConds.addCondition(AddedConds); FinalConds.addCondition(CondSel); } //-- Calculate Order ------------ Vector <String> Order=new Vector<String>(); Vector <Boolean> OrderAsc=new Vector<Boolean>(); List<OrderByElement> orderByElements = ((PlainSelect)ParsedSQL.getSelectBody()).getOrderByElements(); if (orderByElements!=null) for (int i = 0; i < orderByElements.size(); i++) { Order.add(orderByElements.get(i).getExpression().toString()); OrderAsc.add(orderByElements.get(i).isAsc()); } //-- Create Query -------------- QBE=new Query(OPDTabs, Rec, FinalConds, Order, OrderAsc); if (PDLog.isDebug()) PDLog.Debug("ObjPD.SearchSelect <"); } catch (Exception Ex) { Ex.printStackTrace(); PDException.GenPDException("Processing_SQL", Ex.getLocalizedMessage()); } return(getDrv().OpenCursor(QBE)); }
Example #15
Source File: SqlBuilder.java From dal with Apache License 2.0 | 4 votes |
private static String plainSelectToStringAppendWithNoLock(PlainSelect plain) { StringBuilder sql = new StringBuilder("SELECT "); if (plain.getDistinct() != null) sql.append(plain.getDistinct()).append(" "); if (plain.getTop() != null) sql.append(plain.getTop()).append(" "); sql.append(PlainSelect.getStringList(plain.getSelectItems())); if (plain.getFromItem() != null) { sql.append(" FROM ").append(plain.getFromItem()).append(" WITH (NOLOCK) "); if (plain.getJoins() != null) { Iterator<Join> it = plain.getJoins().iterator(); while (it.hasNext()) { Join join = it.next(); if (join.isSimple()) { sql.append(", ").append(join).append(" WITH (NOLOCK) "); } else { String temp = join.toString().replace(join.getRightItem().toString(), join.getRightItem().toString() + " WITH (NOLOCK) "); sql.append(" ").append(temp); } } } if (plain.getWhere() != null) sql.append(" WHERE ").append(plain.getWhere()); if (plain.getOracleHierarchical() != null) sql.append(plain.getOracleHierarchical().toString()); sql.append(PlainSelect.getFormatedList(plain.getGroupByColumnReferences(), "GROUP BY")); if (plain.getHaving() != null) sql.append(" HAVING ").append(plain.getHaving()); sql.append(PlainSelect.orderByToString(plain.isOracleSiblings(), plain.getOrderByElements())); if (plain.getLimit() != null) sql.append(plain.getLimit()); } return sql.toString(); }
Example #16
Source File: CTEToNestedQueryConverter.java From quetzal with Eclipse Public License 2.0 | 4 votes |
public List<PlainSelect> getPlainSelects() { return setOp.getPlainSelects(); }
Example #17
Source File: CTEToNestedQueryConverter.java From quetzal with Eclipse Public License 2.0 | 4 votes |
public void setOpsAndSelects(List<PlainSelect> select, List<SetOperation> ops) { setOp.setOpsAndSelects(select, ops); }
Example #18
Source File: CTEToNestedQueryConverter.java From quetzal with Eclipse Public License 2.0 | 4 votes |
@Override public void visit(PlainSelect plainSelect) { FromItem fromItem =plainSelect.getFromItem(); ReplacementFromItemVisitor visitor = new ReplacementFromItemVisitor(cteName2Def,placeHolderTables); if (fromItem!=null) { fromItem.accept(visitor); //if (visitor.getResult()!=fromItem) { FromItem res = visitor.getResult(); if (res instanceof SubSelect) { SubSelect sub = (SubSelect) res; if (sub.getSelectBody() instanceof SetOperationList) { SetOperationListNoParenthesisWrapper setOp = new SetOperationListNoParenthesisWrapper((SetOperationList) sub.getSelectBody()); sub.setSelectBody(setOp); } } if (res.getAlias()!=null) { res.getAlias().setUseAs(useASInTableAlias); } plainSelect.setFromItem(res); } } //order by if (plainSelect.getOrderByElements()!=null) { List<OrderByElement> newOrderBy = new LinkedList<OrderByElement>(); for (OrderByElement oe: plainSelect.getOrderByElements()) { if (oe.getExpression() instanceof Parenthesis) { OrderByElement noe =new OrderByElement(); noe.setExpression( ((Parenthesis)oe.getExpression()).getExpression()); noe.setAsc(oe.isAsc()); newOrderBy.add(noe); } else { newOrderBy.add(oe); } } plainSelect.setOrderByElements(newOrderBy); } if (plainSelect.getJoins()!=null) { int nonPlaceHolderTables =getNumberNonPlaceHolderFromItem(plainSelect); for (Join join: plainSelect.getJoins()) { if (join.getRightItem()!=null) { join.getRightItem().accept(visitor); //if (visitor.getResult()!=join.getRightItem()) { FromItem res = visitor.getResult(); if (res instanceof SubSelect) { SubSelect sub = (SubSelect) res; if (sub.getSelectBody() instanceof SetOperationList) { SetOperationListNoParenthesisWrapper setOp = new SetOperationListNoParenthesisWrapper((SetOperationList) sub.getSelectBody()); sub.setSelectBody(setOp); } } if (res.getAlias()!=null) { res.getAlias().setUseAs(useASInTableAlias); } join.setRightItem(res); } if (join.isSimple() && useExplicitJoinSyntax) { join.setSimple(false); if (nonPlaceHolderTables>2 && plainSelect.getWhere()!=null) { throw new RuntimeException("3 way join or more not implemented yet!\n"+plainSelect); } else if (plainSelect.getWhere()!=null ) { String tableName = null; if (join.getRightItem() instanceof Table) { tableName = ((Table) join.getRightItem()).getFullyQualifiedName(); } if (tableName == null || !placeHolderTables.contains(tableName)) { Table leftTable; if (plainSelect.getFromItem() instanceof Table) { leftTable = (Table) plainSelect.getFromItem(); } else { assert plainSelect.getFromItem().getAlias()!=null; leftTable = new Table(plainSelect.getFromItem().getAlias().getName()); } Table rightTable; if (join.getRightItem() instanceof Table) { rightTable = (Table) join.getRightItem(); } else { assert join.getRightItem().getAlias()!=null; rightTable = new Table(join.getRightItem().getAlias().getName()); } SplitOnAndWhereExpression split = new SplitOnAndWhereExpression(leftTable, rightTable); plainSelect.getWhere().accept(split); join.setOnExpression(split.getOnExp()); plainSelect.setWhere(split.getWhereExp()); } } } } } } }
Example #19
Source File: SelectVisitorImpl.java From DataPermissionHelper with Apache License 2.0 | 4 votes |
@Override public void visit(PlainSelect plainSelect) { // 访问 select if (plainSelect.getSelectItems() != null) { for (SelectItem item : plainSelect.getSelectItems()) { item.accept(new SelectItemVisitorImpl()); } } // 访问from FromItem fromItem = plainSelect.getFromItem(); FromItemVisitorImpl fromItemVisitorImpl = new FromItemVisitorImpl(); fromItem.accept(fromItemVisitorImpl); if (fromItemVisitorImpl.getSubSelect() != null) { plainSelect.setFromItem(fromItemVisitorImpl.getSubSelect()); if (!DPHelper.getChangeTable()) { DPHelper.setChangeTable(true); } } // 访问where if (plainSelect.getWhere() != null) { plainSelect.getWhere().accept(new ExpressionVisitorImpl()); } // 访问join if (plainSelect.getJoins() != null) { for (Join join : plainSelect.getJoins()) { FromItemVisitorImpl fromItemVisitorImplTemp = new FromItemVisitorImpl(); join.getRightItem().accept(fromItemVisitorImplTemp); if (fromItemVisitorImplTemp.getSubSelect() != null) { join.setRightItem(fromItemVisitorImplTemp.getSubSelect()); if (!DPHelper.getChangeTable()) { DPHelper.setChangeTable(true); } } } } // 访问 order by if (plainSelect.getOrderByElements() != null) { for (OrderByElement orderByElement : plainSelect .getOrderByElements()) { orderByElement.getExpression().accept( new ExpressionVisitorImpl()); } } // 访问group by having if (plainSelect.getHaving() != null) { plainSelect.getHaving().accept(new ExpressionVisitorImpl()); } }
Example #20
Source File: SqlBuilder.java From das with Apache License 2.0 | 4 votes |
private static String plainSelectToStringAppendWithNoLock(PlainSelect plain) { StringBuilder sql = new StringBuilder("SELECT "); if (plain.getDistinct() != null) sql.append(plain.getDistinct()).append(" "); if (plain.getTop() != null) sql.append(plain.getTop()).append(" "); sql.append(PlainSelect.getStringList(plain.getSelectItems())); if (plain.getFromItem() != null) { sql.append(" FROM ").append(plain.getFromItem()).append(" WITH (NOLOCK) "); if (plain.getJoins() != null) { Iterator<Join> it = plain.getJoins().iterator(); while (it.hasNext()) { Join join = it.next(); if (join.isSimple()) { sql.append(", ").append(join).append(" WITH (NOLOCK) "); } else { String temp = join.toString().replace(join.getRightItem().toString(), join.getRightItem().toString() + " WITH (NOLOCK) "); sql.append(" ").append(temp); } } } if (plain.getWhere() != null) sql.append(" WHERE ").append(plain.getWhere()); if (plain.getOracleHierarchical() != null) sql.append(plain.getOracleHierarchical().toString()); sql.append(PlainSelect.getFormatedList(plain.getGroupByColumnReferences(), "GROUP BY")); if (plain.getHaving() != null) sql.append(" HAVING ").append(plain.getHaving()); sql.append(PlainSelect.orderByToString(plain.isOracleSiblings(), plain.getOrderByElements())); if (plain.getLimit() != null) sql.append(plain.getLimit()); } return sql.toString(); }