net.sf.jsqlparser.statement.Statement Java Examples

The following examples show how to use net.sf.jsqlparser.statement.Statement. 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: sqlhelper   Author: fangjinuo   File: JsqlParsertests.java    License: 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 #2
Source Project: sqlhelper   Author: fangjinuo   File: JsqlParsertests.java    License: 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 Project: sqlhelper   Author: fangjinuo   File: JSqlParserOrderByTransformer.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public SqlStatementWrapper<Statement> transform(@NonNull SqlStatementWrapper<Statement> sw, @NonNull TransformConfig config) {
    Preconditions.checkNotNull(sw);
    Preconditions.checkNotNull(config);
    OrderBy orderBy = Preconditions.checkNotNull(config.getOrderBy());
    final Statement statement = sw.get();
    Preconditions.checkNotNull(statement, "statement is null");
    Preconditions.checkTrue(statement instanceof Select, new Supplier<Object[], String>() {
        @Override
        public String get(Object[] input) {
            return StringTemplates.formatWithPlaceholder("statement is not a select statement: {}", statement.toString());
        }
    });

    tranaform((Select) statement, orderBy);
    sw.setChanged(true);
    return sw;
}
 
Example #4
Source Project: sqlhelper   Author: fangjinuo   File: JSqlParserWhereTransformer.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public SqlStatementWrapper<Statement> transform(SqlStatementWrapper<Statement> statementWrapper, TransformConfig config) {
    if (Emptys.isEmpty(statementWrapper) || Emptys.isEmpty(config)) {
        return statementWrapper;
    }
    Statement statement = statementWrapper.get();
    List<WhereTransformConfig> expressionConfigs = config.getWhereInstrumentConfigs();
    if (Emptys.isEmpty(statement) || Emptys.isEmpty(expressionConfigs)) {
        return statementWrapper;
    }
    if (!JSqlParsers.isDML(statement)) {
        return statementWrapper;
    }

    if (Reflects.isSubClassOrEquals(Select.class, statement.getClass())) {
        transform((Select) statement, false, expressionConfigs);
    } else if (Reflects.isSubClassOrEquals(Update.class, statement.getClass())) {
        transform((Update) statement, expressionConfigs);
    } else if (Reflects.isSubClassOrEquals(Delete.class, statement.getClass())) {
        transform((Delete) statement, expressionConfigs);
    } else if (Reflects.isSubClassOrEquals(Insert.class, statement.getClass())) {
        transform((Insert) statement, config.getTenant());
    }

    return statementWrapper;
}
 
Example #5
Source Project: WeBASE-Front   Author: WeBankFinTech   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 #6
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: 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 Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: 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 #8
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: 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 #9
Source Project: FastSQL   Author: fast-sql   File: OrderByParser.java    License: 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 #10
Source Project: tx-lcn   Author: codingapi   File: TxcJdbcEventListener.java    License: 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 #11
Source Project: OrderByHelper   Author: abel533   File: OrderByParser.java    License: 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 Project: evosql   Author: SERG-Delft   File: SchemaExtractor.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<>();

    // 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 #13
Source Project: evosql   Author: SERG-Delft   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 #14
Source Project: genericdao   Author: lp895876294   File: SqlServer.java    License: 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 #15
Source Project: compass   Author: sogou-biztech   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 #16
Source Project: DDF   Author: ddf-project   File: TableNameReplacerTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void BatchTestArithOps() {
    String[] arithOps = {"+", "-", "*", "/", "%", "&", "|", "^"};
    String sqlcmd = "select ddf://adatao/a.id %s ddf://adatao/a.id2 from ddf://adatao/a";
    TableNameReplacer tableNameReplacer = new TableNameReplacer(this.manager);
    for (String arithOp : arithOps) {
        String newSqlCmd = String.format(sqlcmd, arithOp);
        Statement statement = null;
        try {
            statement = this.testFullURISingle(newSqlCmd);
            // System.out.println(statement);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example #17
Source Project: DDF   Author: ddf-project   File: TableVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @brief Visit the statement. This is the function that should be called
 * in the first place.
 * @param statement A SQL statement.
 */
public void visit(Statement statement) throws Exception {
    if (statement instanceof Select) {
        Select select = (Select) statement;
        if (select.getWithItemsList() != null) {
            for (WithItem withItem : ((Select) statement).getWithItemsList()) {
                withItem.accept(this);
            }
        }
        if (select.getSelectBody() != null) {
            select.getSelectBody().accept(this);
        }
    } else if (statement instanceof DescribeTable) {
        ((DescribeTable)statement).accept(this);
    }
    // TODO: Add more type support here.
}
 
Example #18
Source Project: Mybatis-PageHelper   Author: pagehelper   File: SqlServerParser.java    License: 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 #19
Source Project: Mybatis-PageHelper   Author: pagehelper   File: OrderByParser.java    License: 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 #20
Source Project: Mybatis-PageHelper   Author: 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 #21
Source Project: sqlhelper   Author: fangjinuo   File: JSqlParser.java    License: 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 #22
Source Project: WeBASE-Front   Author: WeBankFinTech   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 #23
Source Project: elasticsearch-sql   Author: noobgod   File: ElasticSearchSqlServiceImpl.java    License: 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 #24
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerStatement.java    License: MIT License 5 votes vote down vote up
@Override
public ResultSet executeQuery(String sql) throws SQLException {
  String[] sqlTokens = getTokens(sql);
  CustomDriverStatement custom = getCustomDriverStatement(sqlTokens);
  if (custom != null && custom.isQuery()) {
    return custom.executeQuery(sqlTokens);
  }
  try (ReadContext context = getReadContext()) {
    com.google.cloud.spanner.ResultSet rs =
        context.executeQuery(com.google.cloud.spanner.Statement.of(sql));
    return new CloudSpannerResultSet(this, rs, sql);
  }
}
 
Example #25
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerStatement.java    License: MIT License 5 votes vote down vote up
private boolean moveToNextResult(int current) throws SQLException {
  if (current != java.sql.Statement.KEEP_CURRENT_RESULT && currentResultSets != null
      && currentResultSets.size() > currentResultSetIndex
      && currentResultSets.get(currentResultSetIndex) != null) {
    currentResultSets.get(currentResultSetIndex).close();
  }
  if (currentResultSets != null && currentResultSets.size() > currentResultSetIndex
      && currentResultSets.get(currentResultSetIndex) != null) {
    currentResultSets.set(currentResultSetIndex, null);
  }
  currentResultSetIndex++;
  lastUpdateCount = -1;

  return currentResultSets != null && currentResultSetIndex < currentResultSets.size();
}
 
Example #26
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatement.java    License: MIT License 5 votes vote down vote up
private com.google.cloud.spanner.Statement.Builder createSelectBuilder(Statement statement,
    String sql) {
  String namedSql = convertPositionalParametersToNamedParameters(sql);
  com.google.cloud.spanner.Statement.Builder builder =
      com.google.cloud.spanner.Statement.newBuilder(namedSql);
  setSelectParameters(((Select) statement).getSelectBody(), builder);

  return builder;
}
 
Example #27
Source Project: spanner-jdbc   Author: olavloite   File: CloudSpannerPreparedStatementTest.java    License: 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 #28
Source Project: aceql-http   Author: kawansoft   File: JSQLParserTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * @param args
    */
   public static void main(String[] args) throws Exception {

Statement statement = CCJSqlParserUtil.parse("SELECT * from public.CUSTOMER");
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder.getTableList(statement);
System.out.println(tableList);

if (statement instanceof Commit) {
    Commit commit = (Commit) statement;
	System.out.println(commit.getClass());
}
   }
 
Example #29
Source Project: aceql-http   Author: kawansoft   File: JSQLParserTest.java    License: 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 Project: sql-to-mongo-db-query-converter   Author: vincentrussell   File: SQLCommandInfoHolder.java    License: Apache License 2.0 5 votes vote down vote up
public Builder setStatement(Statement statement) throws com.github.vincentrussell.query.mongodb.sql.converter.ParseException, ParseException {
    
    if (Select.class.isAssignableFrom(statement.getClass())) {
        sqlCommandType = SQLCommandType.SELECT;
        SelectBody selectBody = ((Select) statement).getSelectBody();

        if (SetOperationList.class.isInstance(selectBody)) {
            SetOperationList setOperationList = (SetOperationList)selectBody;
            if (setOperationList.getSelects() != null
                    && setOperationList.getSelects().size() == 1
                    && PlainSelect.class.isInstance(setOperationList.getSelects().get(0))) {
                return setPlainSelect((PlainSelect) setOperationList.getSelects().get(0));
            }
        } else if (PlainSelect.class.isInstance(selectBody)) {
            return setPlainSelect((PlainSelect) selectBody);
        }

        throw new ParseException("No supported sentence");


    } else if (Delete.class.isAssignableFrom(statement.getClass())) {
        sqlCommandType = SQLCommandType.DELETE;
        Delete delete = (Delete)statement;
        return setDelete(delete); 
    } else {
    	throw new ParseException("No supported sentence");
    }
}