net.sf.jsqlparser.JSQLParserException Java Examples

The following examples show how to use net.sf.jsqlparser.JSQLParserException. 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: SqlTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Test
public void testSqlParser11() throws JSQLParserException {
    CountSqlParser countSqlParser = new CountSqlParser();
    System.out.println(countSqlParser.getSmartCountSql(
            "select so.id,so.address,so.area_code,so.area_id,so.del_flag,so.email," +
                    "so.fax,so.grade,so.icon,so.master, so.name,so.parent_id,so.parent_ids," +
                    "so.phone,so.remarks,so.type,so.zip_code " +
                    "from sys_organization so " +
                    "LEFT JOIN sys_user_organization suo ON (suo.org_id = so.id or FIND_IN_SET(suo.org_id,so.parent_ids)) " +
                    "where suo.user_id = ? group by so.id LIMIT ? "));

    System.out.println(countSqlParser.getSmartCountSql(
            "select so.id,so.address,so.area_code,so.area_id,so.del_flag,so.email," +
                    "so.fax,so.grade,so.icon,so.master, so.name,so.parent_id,so.parent_ids," +
                    "so.phone,so.remarks,so.type,so.zip_code " +
                    "from sys_organization so " +
                    "LEFT JOIN sys_user_organization suo ON (suo.org_id = so.id or FIND_IN_SET(suo.org_id,so.parent_ids)) " +
                    "where suo.user_id = ?"));
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Test
public void testSql386() throws JSQLParserException {
    String originalSql = " select a.Guid,\n" +
        "               ProManager,\n" +
        "               WorkOrderType,\n" +
        "               a.Name,\n" +
        "               WorkNote,\n" +
        "               b.Name                             TeamName,\n" +
        "               ConstructionSite,\n" +
        "               iif(a.MaterialGuid is null, 0, 1) as IsMaterial,\n" +
        "               a.MaterialGuid,\n" +
        "               c.Code                          as MaterialCode,\n" +
        "               c.FullName                         MaterialName,\n" +
        "               d.FullName                         MatStdSortName\n" +
        "        from RMC_WorkOrder a\n" +
        "                 left join dbo.SYS_OrgFrame b on a.TeamGuid = b.Code and b.ParentGuid is null\n" +
        "                 left join dbo.BAS_Material c on a.MaterialGuid = c.Guid\n" +
        "                 left join BAS_MatStdSort d on a.MatStdSortGuid = d.Guid\n" +
        "        where a.ConfirmUser is null\n" +
        "          and b.Guid = 1\n" +
        "        order by a.ContractBillNO desc";
    System.out.println(sqlServer.convertToPageSql(originalSql, 1, 10));
}
 
Example #11
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
@Test
public void testSql66() throws JSQLParserException {
    String originalSql = "SELECT *\n" +
        "FROM\n" +
        "forum_post_info a with(nolock)\n" +
        "LEFT JOIN forum_carcase_tags as b with(nolock) on a.id = b.carcase_id where b.tag_id = 127";
    ReplaceSql replaceSql = new RegexWithNolockReplaceSql();
    String replace = replaceSql.replace(originalSql);
    String pageSql = sqlServer.convertToPageSql(replace, 1, 10);


    CountSqlParser countSqlParser = new CountSqlParser();
    String smartCountSql = countSqlParser.getSmartCountSql(replace);
    smartCountSql = replaceSql.restore(smartCountSql);
    System.out.println(smartCountSql);


    String result = replaceSql.restore(pageSql);
    System.out.println(result);
}
 
Example #12
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 #13
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 #14
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 #15
Source File: SqlTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSqlParser() throws JSQLParserException {
    CountSqlParser countSqlParser = new CountSqlParser();
    System.out.println(countSqlParser.getSmartCountSql("with " +
        "cr as " +
        "( " +
        "    select UserRegionCode from person.UserRegion where Name like 'C%' order by name" +
        ") " +
        " " +
        "select * from person.StateProvince where UserRegionCode in (select * from cr)"));

    System.out.println(countSqlParser.getSmartCountSql("with cr as " +
            " (select aaz093 from aa10 where aaa100 like 'AAB05%' order by aaz093 desc) " +
            "select count(1) from aa10 where aaz093 in (select * from cr)"));


    System.out.println(countSqlParser.getSmartCountSql("select a.aac001,a.aac030,b.aaa103 " +
            "  from ac02 a " +
            "  left join aa10 b " +
            "    on b.aaa100 = 'AAC031' " +
            "   and b.aaa102 = a.aac031 " +
            "   order by a.aac001"));

    System.out.println(countSqlParser.getSmartCountSql("select * from aa10 WHERE aaa100 LIKE 'AAB05%' " +
            "union " +
            "select * from aa10 where aaa100 = 'AAC031'"));

    System.out.println(countSqlParser.getSmartCountSql("select * from (select * from aa10 WHERE aaa100 LIKE 'AAB05%' " +
            "union " +
            "select * from aa10 where aaa100 = 'AAC031')"));

    System.out.println(countSqlParser.getSmartCountSql("select so.id,so.address,so.area_code,so.area_id,so.del_flag,so.email,so.fax,so.grade,so.icon,so.master, so.name,so.parent_id,so.parent_ids,so.phone,so.remarks,so.type,so.zip_code from sys_organization so LEFT JOIN sys_user_organization suo ON (suo.org_id = so.id or FIND_IN_SET(suo.org_id,so.parent_ids)) where suo.user_id = ? group by so.id LIMIT ? "));
}
 
Example #16
Source File: SqlConverterFactory.java    From mybatis-shard with Eclipse Public License 1.0 5 votes vote down vote up
/**
     * 修改sql语句
     * 
     * @param sql
     * @param suffix
     * @return 修改后的sql
     */
    public String convert(String sql, String suffix, String includePattern) {

        Statement statement = null;
        try {
            statement = pm.parse(new StringReader(sql));
        } catch (JSQLParserException e) {
            log.error(e.getMessage(), e);
            Throwables.propagate(e);
        }

        SqlConverter converter = this.converterMap.get(statement.getClass().getName());

        if (converter != null) {
            return converter.convert(statement, suffix, includePattern);
        }
        return sql;
        
//        try {
//
//            SQLStatement statement = SQLParserDelegate.parse(sql);
//
//            statement.accept(new TableReplaceVisitor(suffix, includePattern));
//
//            MySQLOutputASTVisitor sqlGen = new MySQLOutputASTVisitor(new StringBuilder());
//            statement.accept(sqlGen);
//
//            return sqlGen.getSql();
//
//        } catch (SQLSyntaxErrorException e) {
//            Throwables.propagate(e);
//        }
//
//        return sql;
    }
 
Example #17
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSqlUnion2() throws JSQLParserException {
    String originalSql = "select name,code from ( " +
        "\tselect name,py code from user where id >170 " +
        "\tunion all " +
        "\tselect name,py code from user where id < 10 " +
        ") as temp " +
        "order by code";
    System.out.println(sqlServer.convertToPageSql(originalSql, 1, 10));
}
 
Example #18
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSql345() throws JSQLParserException {
    String originalSql = "Select CC.ClinicID, CC.CaseHistoryNum, CC.CaseHistoryID, CC.DoctorID, CC.ClientRegisterID\n" +
        "From Client CC With(Nolock)\n" +
        "Left Outer Join Register CR With(Nolock) On CC.ClientRegisterID = CR.ClientRegisterID\n" +
        "Where CC.ClientID = 14374";
    ReplaceSql replaceSql = new RegexWithNolockReplaceSql();
    String replace = replaceSql.replace(originalSql);
    String pageSql = sqlServer.convertToPageSql(replace, 1, 10);
    String result = replaceSql.restore(pageSql);
    System.out.println(result);
}
 
Example #19
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSql306() throws JSQLParserException {
    String originalSql = "Select * FROM table1 t1 with(nolock)\n" +
        "left join table2 t2 with(nolock) on t1.id=t2.id\n" +
        "left join table3 t3 with(nolock) on t1.id=t3.id";
    ReplaceSql replaceSql = new RegexWithNolockReplaceSql();
    String replace = replaceSql.replace(originalSql);
    String pageSql = sqlServer.convertToPageSql(replace, 1, 10);
    String result = replaceSql.restore(pageSql);
    System.out.println(result);
}
 
Example #20
Source File: SqlServerTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSql398() throws JSQLParserException {
    String originalSql = "Select AUS.ScheduleID, AUS.SystemID, AUS.ClinicID, AUS.DoctorID, AUS.ScheduleDate, \n" +
        "\tAUS.StartTime, AUS.EndTime, AUS.Status, AUS.BookBy, AUS.Note, AUS.Remark, AUS.SourceType, CM.CompanyName,\n" +
        "\tAU.UserName As DoctorName, AU.UserNumber As DoctorNumber, CC.CodeDesc As ClinicName, CD.Lat, CD.Lng,\n" +
        "\tCD.ContactTel, CD.Address, CR.ConsultationStatusID, CR.RegisterStatus,A1.CodeDesc as AreaLevel1, A2.CodeDesc as AreaLevel2\n" +
        "\tFrom ACM_User_Schedule AUS with(nolock)\n" +
        "\tLeft Join Client_Register CR with(nolock) On AUS.BookBy=CR.ClientID And CR.SourceType='F' And AUS.ClientRegisterNum=CR.ClientRegisterNum \n" +
        "\tInner Join ACM_User AU with(nolock) On AU.UserID = AUS.DoctorID \n" +
        "\tInner Join Code_Clinic CC with(nolock) On AUS.ClinicID=CC.CodeID\n" +
        "\tInner Join Clinic_Detail CD with(nolock) On CC.CodeID = CD.ClinicID\n" +
        "\tInner Join Code_Area A1 with(nolock) On CD.AreaLevel1ID=A1.CodeID\n" +
        "\tInner Join Code_Area A2 with(nolock) On CD.AreaLevel2ID=A2.CodeID\n" +
        "\tInner Join Company_Master CM with(nolock) On CC.SystemID = CM.SystemID\n" +
        "\tWhere BookBy=1";
    ReplaceSql replaceSql = new RegexWithNolockReplaceSql();
    String replace = replaceSql.replace(originalSql);
    String pageSql = sqlServer.convertToPageSql(replace, 1, 10);


    CountSqlParser countSqlParser = new CountSqlParser();
    String smartCountSql = countSqlParser.getSmartCountSql(replace);
    smartCountSql = replaceSql.restore(smartCountSql);
    System.out.println(smartCountSql);


    String result = replaceSql.restore(pageSql);
    System.out.println(result);
}
 
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: SqlServerTest.java    From Mybatis-PageHelper with MIT License 5 votes vote down vote up
@Test
public void testSqlUnion() throws JSQLParserException {
    String originalSql = "select name,py code from user where id >170 " +
        "union all " +
        "select name,py code from user where id < 10 order by code";
    System.out.println(sqlServer.convertToPageSql(originalSql, 1, 10));
}
 
Example #24
Source File: AbstractCloudSpannerStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@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 #25
Source File: AbstractCloudSpannerStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@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 #26
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());
}
 
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 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 #28
Source File: JSQLParserAdapter.java    From ddal with Apache License 2.0 5 votes vote down vote up
/**
 * To make ddal-jsqlparser work well, JSqlParser should include the feature of 'support getting jdbc parameter index'.
 * And this feature is provided on the version of {@link <a href="https://github.com/JSQLParser/JSqlParser/releases/tag/jsqlparser-0.9.7">0.9.7</a>}.
 * This method is designed to check the necessary feature.
 */
public static void checkJSqlParserFeature() throws JSQLParserException {
    CCJSqlParserManager parserManager = new CCJSqlParserManager();
    String sql = "SELECT * FROM tab_1 WHERE tab_1.col_1 = ? AND col_2 IN (SELECT DISTINCT col_2 FROM tab_2 WHERE col_3 LIKE ? AND col_4 > ?) LIMIT ?, ?";
    Select select = (Select) parserManager.parse(new StringReader(sql));
    PlainSelect selectBody = (PlainSelect) select.getSelectBody();
    //
    AndExpression andExpression = (AndExpression) selectBody.getWhere();
    EqualsTo equalsTo = (EqualsTo) andExpression.getLeftExpression();
    JdbcParameter jdbcParameter = (JdbcParameter) equalsTo.getRightExpression();
    Integer index1 = jdbcParameter.getIndex();
    if (index1 != 1) {
        throw new IllegalStateException("Current version of JSQLParser doesn't support the feature of 'support "
                                        + "get jdbc parameter index'");
    }
    //
    InExpression inExpression = (InExpression) andExpression.getRightExpression();
    SubSelect subSelect = (SubSelect) inExpression.getRightItemsList();
    PlainSelect subSelectBody = (PlainSelect) subSelect.getSelectBody();
    AndExpression subAndExpression = (AndExpression) subSelectBody.getWhere();
    LikeExpression likeExpression = (LikeExpression) subAndExpression.getLeftExpression();
    if (((JdbcParameter) likeExpression.getRightExpression()).getIndex() != 2) {
        throw new IllegalStateException(
                                        "Current version of JSQLParser doesn't support the feature of 'support get jdbc parameter index'");
    }
    //
    GreaterThan greaterThan = (GreaterThan) subAndExpression.getRightExpression();
    if (((JdbcParameter) greaterThan.getRightExpression()).getIndex() != 3) {
        throw new IllegalStateException(
                                        "Current version of JSQLParser doesn't support the feature of 'support get jdbc parameter index'");
    }
    //
    Expression offset = selectBody.getLimit().getOffset();
    Expression rowCount = selectBody.getLimit().getRowCount();
    if (((JdbcParameter) offset).getIndex() != 4 || ((JdbcParameter) rowCount).getIndex() != 5) {
        throw new IllegalStateException(
                                        "Current version of JSQLParser doesn't support the feature of 'support get jdbc parameter index'");
    }
}
 
Example #29
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 #30
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);
   }