Java Code Examples for net.sf.jsqlparser.parser.CCJSqlParserUtil#parse()

The following examples show how to use net.sf.jsqlparser.parser.CCJSqlParserUtil#parse() . 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 Project: ddal   File: JSQLParserAdapter.java    License: 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 2
Source Project: WeBASE-Front   File: CRUDParseUtils.java    License: 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 3
Source Project: evosql   File: MockedSchemaExtractor.java    License: 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 4
Source Project: Mybatis-PageHelper   File: SqlTest.java    License: 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 5
@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 6
Source Project: compass   File: TableRenameUtil.java    License: 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
@Test
public void testCreateInsertSelectOnDuplicateKeyUpdateStatementWithParametersAndUpdateOnPartOfKeyLowerCase()
    throws JSQLParserException, SQLException {
  String sql = "UPDATE BAR SET id1=?, col1=? WHERE id2=? AND col2=?";
  Update update = (Update) CCJSqlParserUtil.parse(sql);
  thrown.expect(CloudSpannerSQLException.class);
  thrown.expectMessage(
      "UPDATE of a primary key value is not allowed, cannot UPDATE the column(s) ID1");
  subject.createInsertSelectOnDuplicateKeyUpdateStatement(update);
}
 
Example 8
/**
    * @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 9
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());
}
 
Example 10
@Test
public void testCreateInsertSelectOnDuplicateKeyUpdateStatement()
    throws JSQLParserException, SQLException {
  String sql = "UPDATE FOO SET BAR=2 WHERE VALUE=1";
  Update update = (Update) CCJSqlParserUtil.parse(sql);
  String insert = subject.createInsertSelectOnDuplicateKeyUpdateStatement(update);
  assertEquals("INSERT INTO `FOO`\n" + "(`ID`, `BAR`)\n" + "SELECT `FOO`.`ID`, 2\n"
      + "FROM `FOO`\n" + "WHERE VALUE = 1\n" + "ON DUPLICATE KEY UPDATE", insert);
}
 
Example 11
Source Project: WeBASE-Front   File: CRUDParseUtils.java    License: 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 12
@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 13
@Test
public void testCreateInsertSelectOnDuplicateKeyUpdateStatementWithParametersAndUpdateOnPartOfKey()
    throws JSQLParserException, SQLException {
  String sql = "UPDATE BAR SET ID1=?, COL1=? WHERE ID2=? AND COL2=?";
  Update update = (Update) CCJSqlParserUtil.parse(sql);
  thrown.expect(CloudSpannerSQLException.class);
  thrown.expectMessage(
      "UPDATE of a primary key value is not allowed, cannot UPDATE the column(s) ID1");
  subject.createInsertSelectOnDuplicateKeyUpdateStatement(update);
}
 
Example 14
Source Project: Mybatis-PageHelper   File: FunctionCountTest.java    License: 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 15
Source Project: genericdao   File: SqlParser.java    License: 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 16
private AbstractTablePartWorker createWorker(String sql, ParameterStore parameters)
    throws JSQLParserException {
  CloudSpannerConnection connection = mock(CloudSpannerConnection.class);
  Select select = (Select) CCJSqlParserUtil.parse(sql);
  DMLOperation operation = DMLOperation.INSERT;
  AbstractTablePartWorker worker = mock(AbstractTablePartWorker.class,
      withSettings().useConstructor(connection, select, parameters, true, operation)
          .defaultAnswer(CALLS_REAL_METHODS));
  return worker;
}
 
Example 17
Source Project: WeBASE-Front   File: CRUDParseUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean parseInsert(String sql, Table table, Entry entry)
        throws JSQLParserException, FrontException {
    Statement statement = CCJSqlParserUtil.parse(sql);
    Insert insert = (Insert) statement;

    if (insert.getSelect() != null) {
        throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR, "The insert select clause is not supported.");
    }
    // parse table name
    String tableName = insert.getTable().getName();
    table.setTableName(tableName);

    // parse columns
    List<Column> columns = insert.getColumns();
    ItemsList itemsList = insert.getItemsList();
    String items = itemsList.toString();
    String[] rawItem = items.substring(1, items.length() - 1).split(",");
    String[] itemArr = new String[rawItem.length];
    for (int i = 0; i < rawItem.length; i++) {
        itemArr[i] = rawItem[i].trim();
    }
    if (columns != null) {
        if (columns.size() != itemArr.length) {
            throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR, "Column count doesn't match value count.");
        }
        List<String> columnNames = new ArrayList<>();
        for (Column column : columns) {
            String columnName = trimQuotes(column.toString());
            if (columnNames.contains(columnName)) {
                throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR,
                        "Please provide the field '" + columnName + "' only once.");
            } else {
                columnNames.add(columnName);
            }
        }
        for (int i = 0; i < columnNames.size(); i++) {
            entry.put(columnNames.get(i), trimQuotes(itemArr[i]));
        }
        return false;
    } else {
        for (int i = 0; i < itemArr.length; i++) {
            entry.put(i + "", trimQuotes(itemArr[i]));
        }
        return true;
    }
}
 
Example 18
Source Project: spanner-jdbc   File: CloudSpannerStatement.java    License: MIT License 4 votes vote down vote up
@Override
public boolean execute(String sql) throws SQLException {
  String[] sqlTokens = getTokens(sql);
  CustomDriverStatement custom = getCustomDriverStatement(sqlTokens);
  if (custom != null)
    return custom.execute(sqlTokens);
  Statement statement = null;
  boolean ddl = isDDLStatement(sqlTokens);
  if (!ddl) {
    try {
      statement = CCJSqlParserUtil.parse(sanitizeSQL(sql));
    } catch (JSQLParserException | TokenMgrException e) {
      throw new CloudSpannerSQLException(
          "Error while parsing sql statement " + sql + ": " + e.getLocalizedMessage(),
          Code.INVALID_ARGUMENT, e);
    }
  }
  if (!ddl && statement instanceof Select) {
    determineForceSingleUseReadContext((Select) statement);
    if (!isForceSingleUseReadContext() && getConnection().isBatchReadOnly()) {
      List<Partition> partitions = partitionQuery(com.google.cloud.spanner.Statement.of(sql));
      currentResultSets = new ArrayList<>(partitions.size());
      for (Partition p : partitions) {
        currentResultSets
            .add(new CloudSpannerPartitionResultSet(this, getBatchReadOnlyTransaction(), p, sql));
      }
    } else {
      try (ReadContext context = getReadContext()) {
        com.google.cloud.spanner.ResultSet rs =
            context.executeQuery(com.google.cloud.spanner.Statement.of(sql));
        currentResultSets = Arrays.asList(new CloudSpannerResultSet(this, rs, sql));
        currentResultSetIndex = 0;
        lastUpdateCount = -1;
      }
    }
    return true;
  } else {
    lastUpdateCount = executeUpdate(sql);
    currentResultSetIndex = 0;
    currentResultSets = null;
    return false;
  }
}
 
Example 19
private String getTestCount(String sql, long batchSize) throws JSQLParserException {
  Select select = (Select) CCJSqlParserUtil.parse(sql);
  return createWorker(select.toString()).createCountQuery(select, batchSize);
}
 
Example 20
Source Project: spanner-jdbc   File: SqlParserTest.java    License: MIT License 3 votes vote down vote up
/**
 * This test should not throw an exception, but it does as the SQL parser is not able to parse a
 * boolean expression. The workaround is to wrap the boolean expression in a case when ... then
 * expression.
 * 
 * @throws JSQLParserException
 */
@Test(expected = JSQLParserException.class)
public void testIfStatement() throws JSQLParserException {
  String sql = "SELECT IF(select 2>1, 'A', 'B') FROM notifications";
  Statement statement = CCJSqlParserUtil.parse(sql);
  assertNotNull(statement);
}