net.sf.jsqlparser.parser.CCJSqlParserUtil Java Examples

The following examples show how to use net.sf.jsqlparser.parser.CCJSqlParserUtil. 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: FromItemVisitorImpl.java    From DataPermissionHelper with Apache License 2.0 7 votes vote down vote up
@Override
public void visit(Table table) {
    String tableName = table.getName();
    //关键点:解析到需要进行数据权限控制的表时进行拼装,可以从当前线程获取表数据
    //需要进行的数据权限控制的表数据
    Map<String, IdsAndColumn> tables = DPHelper.getLocalDataPermissions().getTables();
    if (tables.containsKey(tableName)) {
        IdsAndColumn idsAndColumn = tables.get(tableName);
        List<String> ids = idsAndColumn.getIds();
        List<String> columns = idsAndColumn.getColumns();

        SubSelect subSelect = new SubSelect();
        String subSql = SqlSpliceUtils.spliceIdAndColumn(tableName, ids, columns);
        try {
            subSelect.setSelectBody(((Select) (CCJSqlParserUtil.parse(subSql))).getSelectBody());
        } catch (JSQLParserException e) {
            logger.error("数据权限sql解析异常");
        }
        //TODO:采用随机别名不能避免重名
        subSelect.setAlias(table.getAlias() != null ? table.getAlias() : new Alias("DP" + UUID.randomUUID()
                .toString().replace("-", "")));
        this.subSelect = subSelect;
    }
}
 
Example #2
Source File: JsqlParsertests.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void instrmentOrderBy(String sql) throws Throwable {
    Statement statement = CCJSqlParserUtil.parse(sql);
    if (statement instanceof Select) {
        Select select = (Select) statement;
        System.out.println("print parsed sql statement:");
        System.out.println(select.toString());
        System.out.println("show tables:");
        TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
        List<String> tableNames = tablesNamesFinder.getTableList(select);
        for (String tableName : tableNames) {
            System.out.println(tableName);
        }

        SQLStatementInstrumentor instrumentor = new SQLStatementInstrumentor();
        String orderBySql = instrumentor.instrumentOrderBySql(sql, SqlStyleOrderByBuilder.DEFAULT.build("name asc, age desc"));

        System.out.println("print instrumented sql:");
        System.out.println(orderBySql);

        System.out.println("====================================");
    }
}
 
Example #3
Source File: SqlTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Test
public void testWithNolock(){
    String sql = "SELECT * FROM A WITH(NOLOCK) INNER JOIN B WITH(NOLOCK) ON A.TypeId = B.Id";
    System.out.println(sql);
    sql = sql.replaceAll("((?i)\\s*(\\w?)\\s*with\\s*\\(nolock\\))", " $2_PAGEWITHNOLOCK");
    System.out.println(sql);
    //解析SQL
    Statement stmt = null;
    try {
        stmt = CCJSqlParserUtil.parse(sql);
    } catch (Throwable e) {
        e.printStackTrace();
        return;
    }
    Select select = (Select) stmt;
    SelectBody selectBody = select.getSelectBody();
    sql = selectBody.toString();

    sql = sql.replaceAll("\\s*(\\w*?)_PAGEWITHNOLOCK", " $1 WITH(NOLOCK)");

    System.out.println(sql);
}
 
Example #4
Source File: OrderByParser.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 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 PageException("原SQL[" + sql + "]中的order by包含参数,因此不能使用OrderBy插件进行修改!");
        }
        //新的sql
        sql = select.toString();
    } catch (Throwable e) {
        log.warn("处理排序失败: " + e + ",降级为直接拼接 order by 参数");
    }
    return sql + " order by " + orderBy;
}
 
Example #5
Source File: SqlServerParser.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 转换为分页语句
 *
 * @param sql
 * @param offset
 * @param limit
 * @return
 */
public String convertToPageSql(String sql, Integer offset, Integer limit) {
    //解析SQL
    Statement stmt;
    try {
        stmt = CCJSqlParserUtil.parse(sql);
    } catch (Throwable e) {
        throw new PageException("不支持该SQL转换为分页查询!", e);
    }
    if (!(stmt instanceof Select)) {
        throw new PageException("分页语句必须是Select查询!");
    }
    //获取分页查询的select
    Select pageSelect = getPageSelect((Select) stmt);
    String pageSql = pageSelect.toString();
    //缓存移到外面了,所以不替换参数
    if (offset != null) {
        pageSql = pageSql.replace(START_ROW, String.valueOf(offset));
    }
    if (limit != null) {
        pageSql = pageSql.replace(PAGE_SIZE, String.valueOf(limit));
    }
    return pageSql;
}
 
Example #6
Source File: TableRenameUtil.java    From compass with Apache License 2.0 6 votes vote down vote up
public static String modifyTableNames(String sql,TableRenamer tableRenamer) 
{

	if(sql == null)
	{
		throw new IllegalArgumentException("sql is null");
	}
	
	Statement statement = null;
	try
	{
		statement = CCJSqlParserUtil.parse(sql);
	} 
	catch (JSQLParserException e) 
	{
		throw new IllegalArgumentException("Error when parsing sql:[" + sql+"]",e);
	}
	
	TableRenameVisitor tableRenameVisitor=new TableRenameVisitor(tableRenamer);
	statement.accept(tableRenameVisitor);
	return statement.toString();
}
 
Example #7
Source File: SqlServer.java    From genericdao with Artistic License 2.0 6 votes vote down vote up
/**
 * 转换为分页语句
 *
 * @param sql
 * @param offset
 * @param limit
 * @param orderBy
 * @return
 */
public String convertToPageSql(String sql, int offset, int limit, String orderBy) {
    StringBuilder key = new StringBuilder(sql.length() + 40);
    key.append(sql);
    key.append(orderBy);
    String pageSql = CACHE.get(key.toString());
    if (pageSql == null) {
        //解析SQL
        Statement stmt;
        try {
            stmt = CCJSqlParserUtil.parse(sql);
        } catch (JSQLParserException e) {
            throw new RuntimeException("不支持该SQL转换为分页查询!");
        }
        if (!(stmt instanceof Select)) {
            throw new RuntimeException("分页语句必须是Select查询!");
        }
        //获取分页查询的select
        Select pageSelect = getPageSelect((Select) stmt, orderBy);
        pageSql = pageSelect.toString();
        CACHE.put(key.toString(), pageSql);
    }
    pageSql = pageSql.replace(START_ROW, String.valueOf(offset));
    pageSql = pageSql.replace(PAGE_SIZE, String.valueOf(limit));
    return pageSql;
}
 
Example #8
Source File: JSQLParserAdapter.java    From ddal with Apache License 2.0 6 votes vote down vote up
public JSQLParserAdapter(String sql, ShardRouter shardRouter, boolean enableLimitCheck) {
    this.sql = sql;
    this.shardRouter = shardRouter;
    this.enableLimitCheck = enableLimitCheck;
    try {
        this.statement = CCJSqlParserUtil.parse(sql);
    } catch (Throwable e) {
        throw new SQLSyntaxErrorException("sql is [" + sql + "]", e);
    }
    if (statement instanceof Select //
        || statement instanceof Update//
        || statement instanceof Insert//
        || statement instanceof Delete) {
        // ok
    } else {
        throw new UnsupportedSQLExpressionException(
                                                    "Sql ["
                                                            + sql
                                                            + "] is not supported in shard sql. Only support 'select' 'insert' 'update' and 'delete' sql statement");
    }
}
 
Example #9
Source File: MockedSchemaExtractor.java    From evosql with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, TableSchema> getTablesFromQuery(String pathToBeTested) {
    Map<String, TableSchema> tableSchemas = new HashMap<String, TableSchema>();

    // Get a list of table names from the query
    Statement stmt;
    try {
        stmt = CCJSqlParserUtil.parse(pathToBeTested);
    } catch (JSQLParserException e) {
        e.printStackTrace();
        return null;
    }

    if (!(stmt instanceof Select)) {
        return null;
    }
    List<String> tableList = new TablesNamesFinder().getTableList(stmt);

    for (String tableName : tableList) {
        tableName = tableName.replaceAll("^\"|\"$", ""); // Remove quotes around tablenames
        tableSchemas.put(tableName,	this.extract(tableName));
    }

    return tableSchemas;
}
 
Example #10
Source File: SchemaExtractor.java    From evosql with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, TableSchema> getTablesFromQuery(String pathToBeTested) {
    Map<String, TableSchema> tableSchemas = new HashMap<>();

    // Get a list of table names from the query
    Statement stmt;
    try {
        stmt = CCJSqlParserUtil.parse(pathToBeTested);
    } catch (JSQLParserException e) {
        e.printStackTrace();
        return null;
    }

    if (!(stmt instanceof Select)) {
        return null;
    }
    List<String> tableList = new TablesNamesFinder().getTableList(stmt);

    for (String tableName : tableList) {
        tableName = tableName.replaceAll("^\"|\"$", ""); // Remove quotes around tablenames
        tableSchemas.put(tableName, this.extract(tableName));
    }

    return tableSchemas;
}
 
Example #11
Source File: OrderByParser.java    From OrderByHelper with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: TxcJdbcEventListener.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
@Override
public String onBeforeAnyExecute(StatementInformation statementInformation) throws SQLException {
    String sql = statementInformation.getSqlWithValues();

    // 当前业务链接
    DTXLocalContext.cur().setResource(statementInformation.getStatement().getConnection());

    // 拦截处理
    try {
        Statement statement = CCJSqlParserUtil.parse(sql);
        log.debug("statement > {}", statement);
        statementInformation.setAttachment(statement);
        if (statement instanceof Update) {
            sqlExecuteInterceptor.preUpdate((Update) statement);
        } else if (statement instanceof Delete) {
            sqlExecuteInterceptor.preDelete((Delete) statement);
        } else if (statement instanceof Insert) {
            sqlExecuteInterceptor.preInsert((Insert) statement);
        } else if (statement instanceof Select) {
            sqlExecuteInterceptor.preSelect(new LockableSelect((Select) statement));
        }
    } catch (JSQLParserException e) {
        throw new SQLException(e);
    }
    return sql;
}
 
Example #13
Source File: OrderByParser.java    From FastSQL with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@Override
public CloudSpannerParameterMetaData getParameterMetaData() throws SQLException {
  // parse the SQL statement without executing it
  try {
    if (isDDLStatement()) {
      throw new CloudSpannerSQLException("Cannot get parameter meta data for DDL statement",
          Code.INVALID_ARGUMENT);
    }
    Statement statement = CCJSqlParserUtil.parse(sanitizeSQL(sql));
    if (statement instanceof Insert || statement instanceof Update
        || statement instanceof Delete) {
      // Create mutation, but don't do anything with it. This
      // initializes column names of the parameter store.
      createMutations(sql, false, true);
    } else if (statement instanceof Select) {
      // Create select builder, but don't do anything with it. This
      // initializes column names of the parameter store.
      createSelectBuilder(statement, sql);
    }
  } catch (JSQLParserException | TokenMgrException e) {
    throw new CloudSpannerSQLException(PARSE_ERROR + sql + ": " + e.getLocalizedMessage(),
        Code.INVALID_ARGUMENT, e);
  }
  return new CloudSpannerParameterMetaData(this);
}
 
Example #15
Source File: JsqlParsertests.java    From sqlhelper with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void instrmentTenant(String sql) throws Throwable {
    Statement statement = CCJSqlParserUtil.parse(sql);
    if (statement instanceof Select) {
        Select select = (Select) statement;
        System.out.println("print parsed sql statement:");
        System.out.println(select.toString());
        System.out.println("show tables:");
        TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
        List<String> tableNames = tablesNamesFinder.getTableList(select);
        for (String tableName : tableNames) {
            System.out.println(tableName);
        }

        SQLStatementInstrumentor instrumentor = new SQLStatementInstrumentor();
        /*
        String tenantSql = instrumentor.instrumentTenantSql(sql, AndTenantBuilder.DEFAULT
                .column("tenant")
                .value("1")
                .build());
        System.out.println("print instrumented sql:");
        System.out.println(tenantSql);
        */
        System.out.println("====================================");
    }
}
 
Example #16
Source File: DeleteWorker.java    From spanner-jdbc with MIT License 6 votes vote down vote up
private static Select createSelect(CloudSpannerConnection connection, Delete delete)
    throws SQLException {
  TableKeyMetaData table =
      connection.getTable(CloudSpannerDriver.unquoteIdentifier(delete.getTable().getName()));
  List<String> keyCols = table.getKeyColumns().stream()
      .map(x -> CloudSpannerDriver.quoteIdentifier(delete.getTable().getName()) + "."
          + CloudSpannerDriver.quoteIdentifier(x))
      .collect(Collectors.toList());
  StringBuilder sql = new StringBuilder();
  sql.append("SELECT ").append(String.join(", ", keyCols));
  sql.append("\nFROM ").append(CloudSpannerDriver.quoteIdentifier(delete.getTable().getName()));
  sql.append("\nWHERE ").append(delete.getWhere().toString());

  try {
    return (Select) CCJSqlParserUtil.parse(sql.toString());
  } catch (JSQLParserException e) {
    throw new CloudSpannerSQLException("Could not parse generated SELECT statement: " + sql,
        Code.INVALID_ARGUMENT);
  }
}
 
Example #17
Source File: CRUDParseUtils.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
public static void parseRemove(String sql, Table table, Condition condition)
        throws JSQLParserException, FrontException {
    Statement statement = CCJSqlParserUtil.parse(sql);
    Delete delete = (Delete) statement;

    // parse table name
    net.sf.jsqlparser.schema.Table sqlTable = delete.getTable();
    table.setTableName(sqlTable.getName());

    // parse where clause
    Expression where = delete.getWhere();
    if (where != null) {
        BinaryExpression expr = (BinaryExpression) (where);
        handleExpression(condition, expr);
    }
    Limit limit = delete.getLimit();
    parseLimit(condition, limit);
}
 
Example #18
Source File: SqlParser.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
/**
 * The main method to parse the SQL statement into an NNA-understandable query.
 *
 * @param statement The SQL statement.
 * @throws JSQLParserException - if sql is unreadable
 */
public void parse(String statement) throws JSQLParserException {
  Statements statements = CCJSqlParserUtil.parseStatements(statement);
  INodeSqlStatementVisitor inodeVisitor = new INodeSqlStatementVisitor();
  statements.accept(inodeVisitor);
  set = inodeVisitor.set.toLowerCase();
  filters = String.join(",", inodeVisitor.filters);
  sum = inodeVisitor.sum;
  find = inodeVisitor.find;
  type = inodeVisitor.type;
  limit = inodeVisitor.limit;
  sortAscending = inodeVisitor.sortAscending;
  sortDescending = inodeVisitor.sortDescending;
  parentDirDepth = inodeVisitor.parentDirDepth;
  timeRange = inodeVisitor.timeRange;
}
 
Example #19
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with MIT License 6 votes vote down vote up
@Override
public ResultSet executeQuery() throws SQLException {
  CustomDriverStatement custom = getCustomDriverStatement(sqlTokens);
  if (custom != null && custom.isQuery()) {
    return custom.executeQuery(sqlTokens);
  }
  Statement statement;
  try {
    statement = CCJSqlParserUtil.parse(sanitizeSQL(sql));
  } catch (JSQLParserException | TokenMgrException e) {
    throw new CloudSpannerSQLException(PARSE_ERROR + sql + ": " + e.getLocalizedMessage(),
        Code.INVALID_ARGUMENT, e);
  }
  if (statement instanceof Select) {
    determineForceSingleUseReadContext((Select) statement);
    com.google.cloud.spanner.Statement.Builder builder = createSelectBuilder(statement, sql);
    try (ReadContext context = getReadContext()) {
      com.google.cloud.spanner.ResultSet rs = context.executeQuery(builder.build());
      return new CloudSpannerResultSet(this, rs, sql);
    }
  }
  throw new CloudSpannerSQLException(
      "SQL statement not suitable for executeQuery. Expected SELECT-statement.",
      Code.INVALID_ARGUMENT);
}
 
Example #20
Source File: ElasticSearchSqlServiceImpl.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
/**
 * 查询替换为别名进行
 *
 * @param sql
 * @return
 * @throws JSQLParserException
 */
private String replaceTableName(String sql) throws JSQLParserException {
    Statement statement = CCJSqlParserUtil.parse(sql);
    Select select = (Select) statement;

    StringBuilder buffer = new StringBuilder();
    ExpressionDeParser expressionDeParser = new ExpressionDeParser();

    TableNameParser tableNameParser = new TableNameParser(expressionDeParser, buffer);

    expressionDeParser.setSelectVisitor(tableNameParser);
    expressionDeParser.setBuffer(buffer);
    select.getSelectBody().accept(tableNameParser);
    return select.toString();
}
 
Example #21
Source File: FunctionCountTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
public static Select select(String sql) {
    Statement stmt = null;
    try {
        stmt = CCJSqlParserUtil.parse(sql);
    } catch (JSQLParserException e) {
        throw new RuntimeException(e);
    }
    if (stmt instanceof Select) {
        return (Select) stmt;
    }
    throw new RuntimeException("仅支持Select查询");
}
 
Example #22
Source File: JSqlParser.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public JSqlParserStatementWrapper parse(String sql) throws SQLParseException {
    try {
        Statement statement = CCJSqlParserUtil.parse(sql);
        JSqlParserStatementWrapper result = new JSqlParserStatementWrapper(statement);
        result.setOriginalSql(sql);
        return result;
    } catch (JSQLParserException ex) {
        throw new SQLParseException(ex);
    }
}
 
Example #23
Source File: SQLUtils.java    From nimble-orm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 往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 #24
Source File: SqlParser.java    From genericdao with Artistic License 2.0 5 votes vote down vote up
/**
 * 获取智能的countSql
 *
 * @param sql
 * @return
 */
public String getSmartCountSql(String sql) {
    //校验是否支持该sql
    isSupportedSql(sql);
    if (CACHE.get(sql) != null) {
        return CACHE.get(sql);
    }
    //解析SQL
    Statement stmt = null;
    try {
        stmt = CCJSqlParserUtil.parse(sql);
    } catch (JSQLParserException e) {
        //无法解析的用一般方法返回count语句
        String countSql = getSimpleCountSql(sql);
        CACHE.put(sql, countSql);
        return countSql;
    }
    Select select = (Select) stmt;
    SelectBody selectBody = select.getSelectBody();
    //处理body
    processSelectBody(selectBody);
    //处理with
    processWithItemsList(select.getWithItemsList());
    //处理为count查询
    sqlToCount(select);
    String result = select.toString();
    CACHE.put(sql, result);
    return result;
}
 
Example #25
Source File: SqlUtils.java    From sql-to-mongo-db-query-converter with Apache License 2.0 5 votes vote down vote up
public static Expression cloneExpression(Expression expression) {
	if(expression == null) {
		return null;
	}
	try {
		return CCJSqlParserUtil.parseCondExpression(expression.toString());
	} catch (JSQLParserException e) {
		// Never exception because clone
		e.printStackTrace();
		return null;
	}
}
 
Example #26
Source File: CRUDParseUtils.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
public static void parseUpdate(String sql, Table table, Entry entry, Condition condition)
        throws JSQLParserException, FrontException {
    Statement statement = CCJSqlParserUtil.parse(sql);
    Update update = (Update) statement;

    // parse table name
    List<net.sf.jsqlparser.schema.Table> tables = update.getTables();
    String tableName = tables.get(0).getName();
    table.setTableName(tableName);

    // parse cloumns
    List<Column> columns = update.getColumns();
    List<Expression> expressions = update.getExpressions();
    int size = expressions.size();
    String[] values = new String[size];
    for (int i = 0; i < size; i++) {
        values[i] = expressions.get(i).toString();
    }
    for (int i = 0; i < columns.size(); i++) {
        entry.put(trimQuotes(columns.get(i).toString()), trimQuotes(values[i]));
    }

    // parse where clause
    Expression where = update.getWhere();
    if (where != null) {
        BinaryExpression expr2 = (BinaryExpression) (where);
        handleExpression(condition, expr2);
    }
    Limit limit = update.getLimit();
    parseLimit(condition, limit);
}
 
Example #27
Source File: ScaffoldCommandRegister.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
private Generator tableGenerator(String sql, DataSource ds) {
    try {
        CreateTable stmt = (CreateTable) CCJSqlParserUtil.parse("CREATE TABLE " + sql);
        return new Generator()
                .writing("migration", g -> g.task(
                        new FlywayTask("src/main/java", stmt.getTable().getName(), "CREATE TABLE " + sql)));
    } catch (JSQLParserException e) {
        throw new IllegalArgumentException("Statement generating a table is wrong syntax.", e);
    }
}
 
Example #28
Source File: DataPermissionInterceptor.java    From DataPermissionHelper with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object[] args = invocation.getArgs();
    MappedStatement mappedStatement = (MappedStatement) args[0];
    Object parameter = args[1];
    //从当前线程获取需要进行数据权限控制的业务
    DataPermission dataPermission = DPHelper.getLocalDataPermissions();
    //判断有没有进行数据权限控制,是不是最高权限的管理员(这里指的是数据权限的白名单用户)
    if (dataPermission != null && dataPermission.getAdmin() == false) {
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        String sql = boundSql.getSql();
        //获得方法类型
        Select select = (Select) CCJSqlParserUtil.parse(sql);
        select.getSelectBody().accept(new SelectVisitorImpl());
        //判断当前sql是否被修改
        if (DPHelper.getChangeTable()) {
            //访问各个visitor
            //TODO:解析动态sql会失败
            BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), select.toString(), boundSql
                    .getParameterMappings(), parameter);
            String newMsId = mappedStatement.getId() + DATA_PERMISSION;
            MappedStatement newMs = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql), newMsId);
            args[0] = newMs;
            DPHelper.clearChangeTable();
        }
    }
    return invocation.proceed();
}
 
Example #29
Source File: JSQLParserTest.java    From aceql-http with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * @throws JSQLParserException
    */
   public static void selectTest() throws JSQLParserException {
Statement statement = CCJSqlParserUtil.parse("SELECT * FROM customer where toto = 'titi' ");

Select selectStatement = (Select) statement;
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder.getTableList(selectStatement);
System.out.println(tableList);
   }
 
Example #30
Source File: CloudSpannerPreparedStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private static void testCreateTableStatement(String sql) throws SQLException {
  boolean isDDL = isDDLStatement(sql);
  Assert.assertTrue(isDDL);
  Statement statement = null;
  try {
    statement = CCJSqlParserUtil.parse(sql);
  } catch (JSQLParserException e) {
    throw new CloudSpannerSQLException("Could not parse SQL statement", Code.INVALID_ARGUMENT, e);
  }
  Assert.assertNotNull(statement);
  Assert.assertEquals(CreateTable.class, statement.getClass());
}