Java Code Examples for net.sf.jsqlparser.statement.select.Select

The following examples show how to use net.sf.jsqlparser.statement.select.Select. These examples are extracted from open source projects. 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
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
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
@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
@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: das   Source File: SqlBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Re-build the query SQL to implement paging function. The new SQL Statement will contains limit if the database
 * type is MYSQL, CET wrapped if database type is SQL Server. Note: the final SQL will contain two %s, which should
 * be replaced in run time.
 *
 * @param sql The original SQL Statement
 * @param dbType The database type
 * @return Re-build SQL which contains limit if the database type is MYSQL, CET wrapped if database type is SQL
 *         Server.
 * @throws Exception
 */
public static String pagingQuerySql(String sql, DatabaseCategory dbType, CurrentLanguage lang) throws Exception {
    String sql_content = sql.replace("@", ":");
    boolean withNolock = StringUtils.containsIgnoreCase(sql_content, "WITH (NOLOCK)");
    if (withNolock)
        sql_content = sql_content.replaceAll("(?i)WITH \\(NOLOCK\\)", "");
    StringBuilder sb = new StringBuilder();
    try {
        Select select = (Select) parserManager.parse(new StringReader(sql_content));
        PlainSelect plain = (PlainSelect) select.getSelectBody();
        if (dbType == DatabaseCategory.MySql) {
            sb.append(plain.toString());
            sb.append(lang == CurrentLanguage.Java ? mysqlPageClausePattern : mysqlCSPageClausePattern);
        } else if (dbType == DatabaseCategory.SqlServer) {
            sb.append(plain.toString());
            sb.append(lang == CurrentLanguage.Java ? sqlserverPagingClausePattern : sqlseverCSPagingClausePattern);
        } else {
            throw new Exception("Unknow database category.");
        }
    } catch (Throwable e) {
        throw e;
    }
    return sb.toString().replace(":", "@");
}
 
Example 6
Source Project: DataPermissionHelper   Source File: FromItemVisitorImpl.java    License: Apache License 2.0 6 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 7
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatement.java    License: MIT License 6 votes vote down vote up
/**
 * Determines whether the given sql statement must be executed in a single use read context. This
 * must be done for queries against the information schema. This method sets the
 * <code>forceSingleUseReadContext</code> to true if necessary.
 * 
 * @param select The sql statement to be examined.
 */
protected void determineForceSingleUseReadContext(Select select) {
  if (select.getSelectBody() != null) {
    select.getSelectBody().accept(new SelectVisitorAdapter() {
      @Override
      public void visit(PlainSelect plainSelect) {
        if (plainSelect.getFromItem() != null) {
          plainSelect.getFromItem().accept(new FromItemVisitorAdapter() {
            @Override
            public void visit(Table table) {
              if (table.getSchemaName() != null
                  && table.getSchemaName().equalsIgnoreCase("INFORMATION_SCHEMA")) {
                setForceSingleUseReadContext(true);
              }
            }
          });
        }
      }

    });
  }
}
 
Example 8
Source Project: spanner-jdbc   Source File: DeleteWorker.java    License: 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 9
Source Project: spanner-jdbc   Source 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 10
Source Project: spanner-jdbc   Source 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 11
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private InsertWorker createInsertWithSelectStatement(Insert insert, boolean forceUpdate)
    throws SQLException {
  Select select = insert.getSelect();
  if (select == null) {
    throw new CloudSpannerSQLException("Insert statement must contain a select statement",
        Code.INVALID_ARGUMENT);
  }
  boolean isDuplicate = insert.isUseDuplicate();
  InsertWorker.DMLOperation mode;
  if (forceUpdate)
    mode = DMLOperation.UPDATE;
  else if (isDuplicate)
    mode = DMLOperation.ONDUPLICATEKEYUPDATE;
  else
    mode = DMLOperation.INSERT;
  return new InsertWorker(getConnection(), select, insert, getParameterStore(),
      getConnection().isAllowExtendedMode(), mode);
}
 
Example 12
Source Project: tx-lcn   Source 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 13
Source Project: evosql   Source 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 14
Source Project: evosql   Source 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 15
Source Project: dal   Source File: SqlBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Re-build the query SQL to implement paging function. The new SQL Statement will contains limit if the database
 * type is MYSQL, CET wrapped if database type is SQL Server. Note: the final SQL will contain two %s, which should
 * be replaced in run time.
 *
 * @param sql The original SQL Statement
 * @param dbType The database type
 * @return Re-build SQL which contains limit if the database type is MYSQL, CET wrapped if database type is SQL
 *         Server.
 * @throws Exception
 */
public static String pagingQuerySql(String sql, DatabaseCategory dbType, CurrentLanguage lang) throws Exception {
    String sql_content = sql.replace("@", ":");
    boolean withNolock = StringUtils.containsIgnoreCase(sql_content, "WITH (NOLOCK)");
    if (withNolock)
        sql_content = sql_content.replaceAll("(?i)WITH \\(NOLOCK\\)", "");
    StringBuilder sb = new StringBuilder();
    try {
        Select select = (Select) parserManager.parse(new StringReader(sql_content));
        PlainSelect plain = (PlainSelect) select.getSelectBody();
        if (dbType == DatabaseCategory.MySql) {
            sb.append(plain.toString());
            sb.append(lang == CurrentLanguage.Java ? mysqlPageClausePattern : mysqlCSPageClausePattern);
        } else if (dbType == DatabaseCategory.SqlServer) {
            sb.append(plain.toString());
            sb.append(lang == CurrentLanguage.Java ? sqlserverPagingClausePattern : sqlseverCSPagingClausePattern);
        } else {
            throw new Exception("Unknow database category.");
        }
    } catch (Throwable e) {
        throw e;
    }
    return sb.toString().replace(":", "@");
}
 
Example 16
Source Project: hasor   Source File: SqlServer2012Dialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BoundSql getCountSql(FxQuery fxSql, Map<String, Object> paramMap) {
    String buildSqlString = fxSql.buildQueryString(paramMap);
    List<Object> paramArrays = fxSql.buildParameterSource(paramMap);
    //
    // .含有 order by 去掉它
    if (buildSqlString.toLowerCase().contains("order by")) {
        Select selectStatement = parseSelect(buildSqlString, fxSql);
        PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody();
        if (plainSelect.getOrderByElements() != null) {
            List<OrderByElement> orderByElements = plainSelect.getOrderByElements();
            plainSelect.setOrderByElements(null);
            buildSqlString = selectStatement.toString();
            plainSelect.setOrderByElements(orderByElements);
        }
    }
    // .拼 count 语句
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("SELECT COUNT(*) FROM (");
    sqlBuilder.append(buildSqlString);
    sqlBuilder.append(") as TEMP_T");
    return new BoundSql(sqlBuilder.toString(), paramArrays.toArray());
}
 
Example 17
Source Project: hasor   Source File: SqlServer2012Dialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public BoundSql getPageSql(FxQuery fxSql, Map<String, Object> paramMap, int start, int limit) {
    String buildSqlString = fxSql.buildQueryString(paramMap);
    List<Object> paramArrays = fxSql.buildParameterSource(paramMap);
    //
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append(buildSqlString);
    //
    if (buildSqlString.toLowerCase().contains("order by")) {
        Select selectStatement = parseSelect(buildSqlString, fxSql);
        PlainSelect plainSelect = (PlainSelect) selectStatement.getSelectBody();
        if (plainSelect.getOrderByElements() == null) {
            sqlBuilder.append(" ORDER BY CURRENT_TIMESTAMP");
        }
    } else {
        sqlBuilder.append(" ORDER BY CURRENT_TIMESTAMP");
    }
    //
    sqlBuilder.append(" offset ? rows fetch next ? rows only ");
    paramArrays.add(start);
    paramArrays.add(limit);
    //
    buildSqlString = sqlBuilder.toString();
    return new BoundSql(buildSqlString, paramArrays.toArray());
}
 
Example 18
Source Project: Mybatis-PageHelper   Source File: FunctionCountTest.java    License: MIT License 6 votes vote down vote up
@Test
public void test() {
    Select select = select("select max(name),code,min(aa),nvl(ab,0),heh from user where a > 100");
    List<SelectItem> selectItems = ((PlainSelect) select.getSelectBody()).getSelectItems();
    for (SelectItem item : selectItems) {
        if (item instanceof SelectExpressionItem) {
            Expression exp = ((SelectExpressionItem) item).getExpression();
            if (exp instanceof Function) {
                System.out.println("Function:" + item.toString());
            } else {
                System.out.println("Not a function:" + exp.toString());
            }
        } else {
            System.out.println("Not a function:" + item.toString());
        }
    }
}
 
Example 19
Source Project: Mybatis-PageHelper   Source 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 20
@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 21
/**
 * 查询替换为别名进行
 *
 * @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 22
Source Project: spanner-jdbc   Source File: CloudSpannerResultSetMetaData.java    License: MIT License 5 votes vote down vote up
private void initColumns(Select select) {
  columns = new ArrayList<>();
  aliases = new ArrayList<>();
  select.getSelectBody().accept(new SelectVisitorAdapter() {
    @Override
    public void visit(PlainSelect plainSelect) {
      for (SelectItem selectItem : plainSelect.getSelectItems()) {
        selectItem.accept(new SelectItemVisitor() {
          private boolean foundColumn = false;

          @Override
          public void visit(SelectExpressionItem selectExpressionItem) {
            selectExpressionItem.getExpression().accept(new ExpressionVisitorAdapter() {
              @Override
              public void visit(Column column) {
                registerColumn(column, selectExpressionItem.getAlias());
                foundColumn = true;
              }
            });
            if (!foundColumn) {
              registerColumn(null, selectExpressionItem.getAlias());
            }
          }

          @Override
          public void visit(AllTableColumns allTableColumns) {
            registerAllTableColumns(allTableColumns.getTable());
          }

          @Override
          public void visit(AllColumns allColumns) {
            for (Table table : tables) {
              registerAllTableColumns(table);
            }
          }
        });
      }
    }
  });
}
 
Example 23
Source Project: spanner-jdbc   Source File: AbstractTablePartWorker.java    License: MIT License 5 votes vote down vote up
AbstractTablePartWorker(CloudSpannerConnection connection, Select select,
    ParameterStore parameters, boolean allowExtendedMode, DMLOperation operation) {
  this.connection = connection;
  this.select = select;
  this.parameters = parameters;
  this.allowExtendedMode = allowExtendedMode;
  this.operation = operation;
}
 
Example 24
Source Project: spanner-jdbc   Source File: AbstractTablePartWorker.java    License: MIT License 5 votes vote down vote up
private long isRecordCountGreaterThan(Select select, long batchSize) throws SQLException {
  if (estimatedRecordCount == -1) {
    PreparedStatement ps = connection.prepareStatement(createCountQuery(select, batchSize));
    for (int i = 1; i <= parameters.getHighestIndex(); i++) {
      setParameter(i, ps);
    }
    try (ResultSet count = ps.executeQuery()) {
      if (count.next())
        estimatedRecordCount = count.getLong(1);
    }
  }
  return estimatedRecordCount;
}
 
Example 25
Source Project: spanner-jdbc   Source 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 26
Source Project: spanner-jdbc   Source File: AbstractTablePartWorkerTest.java    License: MIT License 5 votes vote down vote up
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 27
/**
    * @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 28
Source Project: nimble-orm   Source File: SQLUtils.java    License: 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 29
Source Project: DDF   Source File: TableNameReplacer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @brief Run the replacer.
 * @param statement The SQL statement.
 * @brief The new statement.
 */
public Statement run(Statement statement) throws Exception {
    // Clear the with table names in case that we run several sql command.
    this.withTableNameList.clear();
    if (statement instanceof Select) {
        visit(statement);
    } else if (statement instanceof DescribeTable){
        ((DescribeTable)statement).accept(this);
    }
    return statement;
}
 
Example 30
Source Project: Mybatis-PageHelper   Source 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查询");
}