net.sf.jsqlparser.expression.Expression Java Examples

The following examples show how to use net.sf.jsqlparser.expression.Expression. 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: BinaryExpressionConverter.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public JE toJSqlParserExpression(SE expression) {
    SQLExpression left = (SQLExpression) expression.getLeft();
    SQLExpression right = (SQLExpression) expression.getRight();

    Expression leftExp = ExpressionConverters.toJSqlParserExpression(left);
    Expression rightExp = ExpressionConverters.toJSqlParserExpression(right);

    if (jsqlparserExpressionSupplier != null) {
        JE jsqlparserExpression = jsqlparserExpressionSupplier.get(expression);
        jsqlparserExpression.setLeftExpression(leftExp);
        jsqlparserExpression.setRightExpression(rightExp);
        return jsqlparserExpression;
    } else {
        return buildJSqlParserExpression(expression, leftExp, rightExp);
    }
}
 
Example #2
Source File: AbstractSpannerExpressionVisitorAdapter.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@Override
public void visit(SignedExpression value) {
  Expression underlyingValue = value.getExpression();
  if (underlyingValue instanceof DoubleValue) {
    DoubleValue doubleValue = (DoubleValue) underlyingValue;
    doubleValue
        .setValue(value.getSign() == '-' ? -doubleValue.getValue() : doubleValue.getValue());
    visit(doubleValue);
  } else if (underlyingValue instanceof LongValue) {
    LongValue longValue = (LongValue) underlyingValue;
    longValue.setValue(value.getSign() == '-' ? -longValue.getValue() : longValue.getValue());
    visit(longValue);
  } else {
    super.visit(value);
  }
}
 
Example #3
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private void setWhereParameters(Expression where,
    com.google.cloud.spanner.Statement.Builder builder) {
  if (where != null) {
    where.accept(new ExpressionVisitorAdapter() {
      private String currentCol = null;

      @Override
      public void visit(Column col) {
        currentCol = unquoteIdentifier(col.getFullyQualifiedName());
      }

      @Override
      public void visit(JdbcParameter parameter) {
        parameter.accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
            builder.bind("p" + parameter.getIndex()), currentCol));
        currentCol = null;
      }

      @Override
      public void visit(SubSelect subSelect) {
        setSelectParameters(subSelect.getSelectBody(), builder);
      }

    });
  }
}
 
Example #4
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private Mutation createUpdateMutation(Update update, boolean generateParameterMetaData)
    throws SQLException {
  if (update.getTables().isEmpty())
    throw new CloudSpannerSQLException("No table found in update statement",
        Code.INVALID_ARGUMENT);
  if (update.getTables().size() > 1)
    throw new CloudSpannerSQLException(
        "Update statements for multiple tables at once are not supported", Code.INVALID_ARGUMENT);
  String table = unquoteIdentifier(update.getTables().get(0).getFullyQualifiedName());
  getParameterStore().setTable(table);
  List<Expression> expressions = update.getExpressions();
  WriteBuilder builder = Mutation.newUpdateBuilder(table);
  int index = 0;
  for (Column col : update.getColumns()) {
    String columnName = unquoteIdentifier(col.getFullyQualifiedName());
    expressions.get(index).accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
        builder.set(columnName), columnName));
    index++;
  }
  visitUpdateWhereClause(update.getWhere(), builder, generateParameterMetaData);

  return builder.build();
}
 
Example #5
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private Mutation createDeleteMutation(Delete delete, boolean generateParameterMetaData)
    throws SQLException {
  String table = unquoteIdentifier(delete.getTable().getFullyQualifiedName());
  getParameterStore().setTable(table);
  Expression where = delete.getWhere();
  if (where == null) {
    // Delete all
    return Mutation.delete(table, KeySet.all());
  } else {
    // Delete one
    DeleteKeyBuilder keyBuilder =
        new DeleteKeyBuilder(getConnection().getTable(table), generateParameterMetaData);
    visitDeleteWhereClause(where, keyBuilder, generateParameterMetaData);
    return Mutation.delete(table, keyBuilder.getKeyBuilder().build());
  }
}
 
Example #6
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private void visitDeleteWhereClause(Expression where, DeleteKeyBuilder keyBuilder,
    boolean generateParameterMetaData) throws SQLException {
  if (where != null) {
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        keyBuilder.set(columnName);
        expression.accept(
            new KeyBuilderExpressionVisitorAdapter(getParameterStore(), columnName, keyBuilder));
      }

    };
    where.accept(whereClauseVisitor);
    if (!generateParameterMetaData && !whereClauseVisitor.isValid()) {
      throw new CloudSpannerSQLException(INVALID_WHERE_CLAUSE_DELETE_MESSAGE,
          Code.INVALID_ARGUMENT);
    }
  }
}
 
Example #7
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private boolean isSingleRowWhereClause(TableKeyMetaData table, Expression where) {
  if (where != null) {
    SingleRowWhereClauseValidator validator = new SingleRowWhereClauseValidator(table);
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        validator.set(columnName);
        expression.accept(new SingleRowWhereClauseValidatorExpressionVisitorAdapter(
            getParameterStore(), validator));
      }

    };
    where.accept(whereClauseVisitor);
    return whereClauseVisitor.isValid() && validator.isValid();
  }
  return false;
}
 
Example #8
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private void visitUpdateWhereClause(Expression where, WriteBuilder builder,
    boolean generateParameterMetaData) throws SQLException {
  if (where != null) {
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        expression.accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
            builder.set(columnName), columnName));
      }

    };
    where.accept(whereClauseVisitor);
    if (!generateParameterMetaData && !whereClauseVisitor.isValid()) {
      throw new CloudSpannerSQLException(INVALID_WHERE_CLAUSE_UPDATE_MESSAGE,
          Code.INVALID_ARGUMENT);
    }
  } else {
    throw new SQLException(INVALID_WHERE_CLAUSE_UPDATE_MESSAGE);
  }
}
 
Example #9
Source File: SQLCommandInfoHolder.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
public SQLCommandInfoHolder(SQLCommandType sqlCommandType, Expression whereClause, boolean isDistinct, boolean isCountAll, boolean isTotalGroup, FromHolder from, long limit, long offset, List<SelectItem> selectItems, List<Join> joins, List<String> groupBys, List<OrderByElement> orderByElements, AliasHolder aliasHolder, Expression havingClause) {
    this.sqlCommandType = sqlCommandType;
    this.whereClause = whereClause;
    this.isDistinct = isDistinct;
    this.isCountAll = isCountAll;
    this.isTotalGroup = isTotalGroup;
    this.from = from;
    this.limit = limit;
    this.offset = offset;
    this.selectItems = selectItems;
    this.joins = joins;
    this.groupBys = groupBys;
    this.havingClause = havingClause;
    this.orderByElements = orderByElements;
    this.aliasHolder = aliasHolder;
}
 
Example #10
Source File: SQLCommandInfoHolder.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
private AliasHolder generateHashAliasFromSelectItems(List<SelectItem> selectItems) {
	HashMap<String,String> aliasFromFieldHash = new HashMap<String,String>();
	HashMap<String,String> fieldFromAliasHash = new HashMap<String,String>();
	for(SelectItem sitem: selectItems) {
		if(!(sitem instanceof AllColumns)) {
			if(sitem instanceof SelectExpressionItem) {
 			SelectExpressionItem seitem = (SelectExpressionItem) sitem;
 			if(seitem.getAlias() != null) {
  			Expression selectExp = seitem.getExpression();
  			selectExp.accept(new ExpVisitorEraseAliasTableBaseBuilder(this.from.getBaseAliasTable()));
  			String expStr = selectExp.toString();
  			String aliasStr = seitem.getAlias().getName();
 				aliasFromFieldHash.put( expStr, aliasStr);
 				fieldFromAliasHash.put( aliasStr, expStr);
 			}
			}
		}
	}
	return new AliasHolder(aliasFromFieldHash, fieldFromAliasHash);
}
 
Example #11
Source File: QueryConverter.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
/**
  * Erase table base alias and get where part of main table when joins
  * @param exp
  * @param tholder
  * @return
  */
 private Expression preprocessWhere(Expression exp, FromHolder tholder){
 	if(sqlCommandInfoHolder.getJoins()!=null && !sqlCommandInfoHolder.getJoins().isEmpty()) {
 		ExpressionHolder partialWhereExpHolder = new ExpressionHolder(null);
 		MutableBoolean haveOrExpression = new MutableBoolean(false);
exp.accept(new WhereVisitorMatchAndLookupPipelineMatchBuilder(tholder.getBaseAliasTable(), partialWhereExpHolder, haveOrExpression));
if(haveOrExpression.booleanValue()) {
	return null;//with or exp we can't use match first step
}
exp = partialWhereExpHolder.getExpression();
     }
 	if(exp != null) {
 		exp.accept(new ExpVisitorEraseAliasTableBaseBuilder(tholder.getBaseAliasTable()));
 	}
 	return exp;
 }
 
Example #12
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
public static Object getValue(Expression incomingExpression, Expression otherSide,
                              FieldType defaultFieldType,
                              Map<String, FieldType> fieldNameToFieldTypeMapping) throws ParseException {
    FieldType fieldType = otherSide !=null ? firstNonNull(fieldNameToFieldTypeMapping.get(getStringValue(otherSide)),
            defaultFieldType) : FieldType.UNKNOWN;
    if (LongValue.class.isInstance(incomingExpression)) {
        return normalizeValue((((LongValue)incomingExpression).getValue()),fieldType);
    } else if (SignedExpression.class.isInstance(incomingExpression)) {
        return normalizeValue((((SignedExpression)incomingExpression).toString()),fieldType);
    } else if (StringValue.class.isInstance(incomingExpression)) {
        return normalizeValue((((StringValue)incomingExpression).getValue()),fieldType);
    } else if (Column.class.isInstance(incomingExpression)) {
        return normalizeValue(getStringValue(incomingExpression),fieldType);
    } else {
        throw new ParseException("can not parseNaturalLanguageDate: " + incomingExpression.toString());
    }
}
 
Example #13
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
public static Object parseFunctionArguments(final ExpressionList parameters,
                                            final FieldType defaultFieldType,
                                            final Map<String, FieldType> fieldNameToFieldTypeMapping) {
    if (parameters == null) {
        return null;
    } else if (parameters.getExpressions().size()==1) {
        return getStringValue(parameters.getExpressions().get(0));
    } else {
        return Lists.newArrayList(Lists.transform(parameters.getExpressions(),
                new com.google.common.base.Function<Expression, Object>() {
                    @Override
                    public Object apply(Expression expression) {
                        try {
                            return getValue(expression, null, defaultFieldType,
                                    fieldNameToFieldTypeMapping);
                        } catch (ParseException e) {
                            return getStringValue(expression);
                        }
                    }
                }));
    }
}
 
Example #14
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
public static DateFunction isDateFunction(Expression incomingExpression) throws ParseException {
    if (ComparisonOperator.class.isInstance(incomingExpression)) {
        ComparisonOperator comparisonOperator = (ComparisonOperator)incomingExpression;
        String rightExpression = getStringValue(comparisonOperator.getRightExpression());
        if (Function.class.isInstance(comparisonOperator.getLeftExpression())) {
            Function function = ((Function)comparisonOperator.getLeftExpression());
            if ("date".equals(function.getName().toLowerCase())
                    && (function.getParameters().getExpressions().size()==2)
                    && StringValue.class.isInstance(function.getParameters().getExpressions().get(1))) {
                String column = getStringValue(function.getParameters().getExpressions().get(0));
                DateFunction dateFunction = null;
                try {
                    dateFunction = new DateFunction(((StringValue)(function.getParameters().getExpressions().get(1))).getValue(),rightExpression,column);
                    dateFunction.setComparisonFunction(comparisonOperator);
                } catch (IllegalArgumentException e) {
                    throw new ParseException(e.getMessage());
                }
                return dateFunction;
            }

        }
    }
    return null;
}
 
Example #15
Source File: ObjPD.java    From openprodoc with GNU Affero General Public License v3.0 6 votes vote down vote up
private int EvalExprType(Expression where)
{
if (where instanceof AndExpression)
    return (EXPR_AND);
else if (where instanceof OrExpression)
    return (EXPR_OR);
else if (where instanceof BinaryExpression)
    return(EXPR_BASIC);
else if (where instanceof Function)
    return(EXPR_FUNCT);
else if (where instanceof Parenthesis)
    return (EXPR_PAR);
else if (where instanceof InExpression) 
    return (EXPR_IN);
else if (where instanceof NotExpression) 
    return (EXPR_NOT);
return(-1);
}
 
Example #16
Source File: CTEToNestedQueryConverter.java    From quetzal with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void visit(Function function) {
	clear();
	boolean tmpLeftTableFound = false;
	boolean tmpRightTableFound = false;
	boolean tmpWhereOnlyExpFound = false;
	boolean prevIsTopVal = isTopLevel;
	isTopLevel = false;
	if (function.getParameters()!=null) {
		for (Expression e: function.getParameters().getExpressions()) {
			e.accept(this);
			tmpLeftTableFound |= leftTableFound;
			tmpRightTableFound |= rightTableFound;
			tmpWhereOnlyExpFound |= whereOnlyExpFound;
		}
	}
	leftTableFound = tmpLeftTableFound;
	rightTableFound = tmpRightTableFound;
	whereOnlyExpFound = tmpWhereOnlyExpFound;
	isTopLevel = prevIsTopVal;
	defaultTopLevelProcessing(function);
}
 
Example #17
Source File: FunctionCountTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@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 #18
Source File: MyTenantHandler.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 租户Id
 *
 * @return
 */
@Override
public Expression getTenantId() {
    // 从当前系统上下文中取出当前请求的服务商ID,通过解析器注入到SQL中。
    Long tenantId = apiContext.getCurrentTenantId();
    log.debug("当前租户为{}", tenantId);
    if (tenantId == null) {
        return new NullValue();
    }
    return new LongValue(tenantId);
}
 
Example #19
Source File: JSqlParsers.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean expressionEquals(Expression expr1, Expression expr2) {
    if (expr1 == null && expr2 == null) {
        return true;
    }
    if (expr1 == null || expr2 == null) {
        return false;
    }

    if (expr1 instanceof Column && expr2 instanceof Column) {
        return columnEquals((Column) expr1, (Column) expr2);
    }
    return expr1.toString().equalsIgnoreCase(expr2.toString());
}
 
Example #20
Source File: ExpressionConverterRegistry.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void registry(ExpressionConverter converter) {
    Class<? extends SQLExpression> standardExpressionClass = converter.getStandardExpressionClass();
    Class<? extends Expression> jSqlParserExpressionClass = converter.getJSqlParserExpressionClass();
    Preconditions.checkNotNull(standardExpressionClass);
    Preconditions.checkNotNull(jSqlParserExpressionClass);
    standardExpressionConverterMap.put(standardExpressionClass, converter);
    jsqlparserExpressionConverterMap.put(jSqlParserExpressionClass, converter);
}
 
Example #21
Source File: ExpressionConverters.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ExpressionList toJSqlParserExpressionList(final ListExpression expression) {
    List<Expression> expressions = Pipeline.of(expression.getExpressions()).map(new Function<SQLExpression, Expression>() {
        @Override
        public Expression apply(SQLExpression input) {
            return toJSqlParserExpression(expression);
        }
    }).asList();
    ExpressionList result = new ExpressionList();
    result.setExpressions(expressions);
    return result;
}
 
Example #22
Source File: TenantAutoConfigure.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Bean
public TenantHandler tenantHandler() {
    return new TenantHandler() {
        /**
         * 获取租户id
         */
        @Override
        public Expression getTenantId(boolean where) {
            String tenant = TenantContextHolder.getTenant();
            if (tenant != null) {
                return new StringValue(TenantContextHolder.getTenant());
            }
            return new NullValue();
        }

        /**
         * 获取租户列名
         */
        @Override
        public String getTenantIdColumn() {
            return "tenant_id";
        }

        /**
         * 过滤不需要根据租户隔离的表
         * @param tableName 表名
         */
        @Override
        public boolean doTableFilter(String tableName) {
            return tenantProperties.getIgnoreTables().stream().anyMatch(
                    (e) -> e.equalsIgnoreCase(tableName)
            );
        }
    };
}
 
Example #23
Source File: PreTenantHandler.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 租户Id
 *
 * @return
 */
@Override
public Expression getTenantId(boolean where) {
    Long tenantId = PreTenantContextHolder.getCurrentTenantId();
    log.debug("当前租户为{}", tenantId);
    if (tenantId == null) {
        return new NullValue();
    }
    return new LongValue(tenantId);
}
 
Example #24
Source File: ItemsListVisitorImpl.java    From DataPermissionHelper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void visit(ExpressionList el) {
    List<Expression> list = el.getExpressions();
    if (list != null && list.size() > 0) {
        for (Expression expr : list) {
            expr.accept(new ExpressionVisitorImpl());
        }
    }
}
 
Example #25
Source File: PrimaryKeyListVisitor.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> newKeyValues(List<Expression> expressions) {
    Map<String, Object> keyValues = new HashMap<>();
    for (int i = 0; i < columns.size(); i++) {
        columns.get(i).setTable(table);
        if (primaryKeys.contains(columns.get(i).getFullyQualifiedName())) {
            Object expression = expressions.get(i).getASTNode().jjtGetValue();
            keyValues.put(columns.get(i).getFullyQualifiedName(),
                    Reflection.invokeN(expression.getClass(), "getValue", expression, new Object[0]));
        }
    }
    return keyValues;
}
 
Example #26
Source File: SQLRecordPredicate.java    From herddb with Apache License 2.0 5 votes vote down vote up
static boolean isConstant(Expression exp) {
    return exp instanceof StringValue
            || exp instanceof LongValue
            || exp instanceof NullValue
            || exp instanceof TimestampValue
            || exp instanceof JdbcParameter;
}
 
Example #27
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 5 votes vote down vote up
public static String getStringValue(Expression expression) {
    if (StringValue.class.isInstance(expression)) {
        return ((StringValue)expression).getValue();
    } else if (Column.class.isInstance(expression)) {
        String columnName = expression.toString();
        Matcher matcher = SURROUNDED_IN_QUOTES.matcher(columnName);
        if (matcher.matches()) {
            return matcher.group(1);
        }
        return columnName;
    }
    return expression.toString();
}
 
Example #28
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 5 votes vote down vote up
public static boolean isSpecialtyFunction(Expression incomingExpression) {
    if (incomingExpression == null) {
        return false;
    }

    if (Function.class.isInstance(incomingExpression) && containsIgnoreCase(SPECIALTY_FUNCTIONS, ((Function)incomingExpression).getName())) {
        return true;
    }

    return false;
}
 
Example #29
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 5 votes vote down vote up
public static List<String> getGroupByColumnReferences(PlainSelect plainSelect) {
    if (plainSelect.getGroupBy()==null) {
        return Collections.emptyList();
    }

    return Lists.transform(plainSelect.getGroupBy().getGroupByExpressions(),
            new com.google.common.base.Function<Expression, String>() {
        @Override
        public String apply(@Nonnull  Expression expression) {
            return SqlUtils.getStringValue(expression);
        }
    });
}
 
Example #30
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 5 votes vote down vote up
public static String getFieldFromFunction(Function function) throws ParseException{
	 List<String> parameters = function.getParameters()== null ? Collections.<String>emptyList() : Lists.transform(function.getParameters().getExpressions(), new com.google.common.base.Function<Expression, String>() {
           @Override
           public String apply(@Nonnull Expression expression) {
               return SqlUtils.getStringValue(expression);
           }
       });
       if (parameters.size() > 1) {
           throw new ParseException(function.getName()+" function can only have one parameter");
       }
       return parameters.size() > 0 ? Iterables.get(parameters, 0) : null;
}