Java Code Examples for net.sf.jsqlparser.statement.delete.Delete

The following examples show how to use net.sf.jsqlparser.statement.delete.Delete. 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
@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 2
Source Project: WeBASE-Front   Source 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: 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 4
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private Mutation createDeleteMutation(Delete delete, boolean generateParameterMetaData)
    throws SQLException {
  String table = unquoteIdentifier(delete.getTable().getFullyQualifiedName());
  getParameterStore().setTable(table);
  Expression where = delete.getWhere();
  if (where == null) {
    // Delete all
    return Mutation.delete(table, KeySet.all());
  } else {
    // Delete one
    DeleteKeyBuilder keyBuilder =
        new DeleteKeyBuilder(getConnection().getTable(table), generateParameterMetaData);
    visitDeleteWhereClause(where, keyBuilder, generateParameterMetaData);
    return Mutation.delete(table, keyBuilder.getKeyBuilder().build());
  }
}
 
Example 5
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 6
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 7
Source Project: ddal   Source 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 8
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 5 votes vote down vote up
private DeleteWorker createDeleteWorker(Delete delete) throws SQLException {
  if (delete.getTable() == null
      || (delete.getTables() != null && !delete.getTables().isEmpty())) {
    throw new CloudSpannerSQLException("DELETE statement must contain only one table",
        Code.INVALID_ARGUMENT);
  }
  return new DeleteWorker(getConnection(), delete, getParameterStore(),
      getConnection().isAllowExtendedMode());
}
 
Example 9
Source Project: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preDelete(Delete delete) throws SQLException {
    // 获取线程传递参数
    Connection connection = (Connection) DTXLocalContext.cur().getResource();

    // 获取Sql Table
    if (delete.getTables().size() == 0) {
        delete.setTables(Collections.singletonList(delete.getTable()));
    }

    // Delete Sql 数据
    List<String> tables = new ArrayList<>(delete.getTables().size());
    List<String> primaryKeys = new ArrayList<>(3);
    List<String> columns = new ArrayList<>();

    for (Table table : delete.getTables()) {
        TableStruct tableStruct = globalContext.tableStruct(table.getName(),
                () -> tableStructAnalyser.analyse(connection, table.getName()));
        tableStruct.getColumns().forEach((k, v) -> columns.add(tableStruct.getTableName() + SqlUtils.DOT + k));
        tableStruct.getPrimaryKeys().forEach(primaryKey -> primaryKeys.add(tableStruct.getTableName() + SqlUtils.DOT + primaryKey));
        tables.add(tableStruct.getTableName());
    }

    // 前置准备
    try {
        DeleteImageParams deleteImageParams = new DeleteImageParams();
        deleteImageParams.setColumns(columns);
        deleteImageParams.setPrimaryKeys(primaryKeys);
        deleteImageParams.setTables(tables);
        deleteImageParams.setSqlWhere(delete.getWhere().toString());
        txcService.resolveDeleteImage(deleteImageParams);
    } catch (TxcLogicException e) {
        throw new SQLException(e.getMessage());
    }
}
 
Example 10
Source Project: evosql   Source File: TablesNamesFinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Delete delete) {
    tables.add(delete.getTable().getName());
    if (delete.getWhere() != null) {
        delete.getWhere().accept(this);
    }
}
 
Example 11
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * mysql 'delete' doesn't support alais
 */
@Override
public void visit(Delete delete) {
    if (enableLimitCheck && delete.getLimit() == null) {
        throw new IllegalStateException("no limit in sql: " + sql);
    }
    this.getStack().push(new FrameContext(StatementType.DELETE));
    visit0(delete);
    afterVisitBaseStatement();
}
 
Example 12
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");
    }
}
 
Example 13
Source Project: compass   Source File: TableRenameVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Delete delete)
{
	delete.getTable().accept(this);
    if (delete.getWhere() != null)
    {
        delete.getWhere().accept(this);
    }
}
 
Example 14
Source Project: mybatis-shard   Source File: DeleteSqlConverter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Statement doConvert(Statement statement, String tableSuffix, Pattern includePattern) {
    if (!(statement instanceof Delete)) {
        throw new IllegalArgumentException("The argument statement must is instance of Delete.");
    }
    Delete delete = (Delete) statement;

    String name = delete.getTable().getName();

    if (includePattern.matcher(name).find()) {
        delete.getTable().setName(this.convertTableName(name, tableSuffix));
    }

    return delete;
}
 
Example 15
Source Project: spanner-jdbc   Source File: DeleteWorker.java    License: MIT License 4 votes vote down vote up
public DeleteWorker(CloudSpannerConnection connection, Delete delete, ParameterStore parameters,
    boolean allowExtendedMode) throws SQLException {
  super(connection, createSelect(connection, delete), parameters, allowExtendedMode,
      DMLOperation.DELETE);
  this.delete = delete;
}
 
Example 16
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 4 votes vote down vote up
private Mutations createMutations(String sql, boolean forceUpdate,
    boolean generateParameterMetaData) throws SQLException {
  try {
    if (getConnection().isReadOnly()) {
      throw new CloudSpannerSQLException(NO_MUTATIONS_IN_READ_ONLY_MODE_EXCEPTION,
          Code.FAILED_PRECONDITION);
    }
    if (isDDLStatement()) {
      throw new CloudSpannerSQLException(
          "Cannot create mutation for DDL statement. Expected INSERT, UPDATE or DELETE",
          Code.INVALID_ARGUMENT);
    }
    Statement statement = CCJSqlParserUtil.parse(sanitizeSQL(sql));
    if (statement instanceof Insert) {
      Insert insertStatement = (Insert) statement;
      if (generateParameterMetaData || insertStatement.getSelect() == null)
        return new Mutations(createInsertMutation(insertStatement, generateParameterMetaData));
      return new Mutations(createInsertWithSelectStatement(insertStatement, forceUpdate));
    } else if (statement instanceof Update) {
      Update updateStatement = (Update) statement;
      if (updateStatement.getSelect() != null)
        throw new CloudSpannerSQLException(
            "UPDATE statement using SELECT is not supported. Try to re-write the statement as an INSERT INTO ... SELECT A, B, C FROM TABLE WHERE ... ON DUPLICATE KEY UPDATE",
            Code.INVALID_ARGUMENT);
      if (updateStatement.getTables().size() > 1)
        throw new CloudSpannerSQLException(
            "UPDATE statement using multiple tables is not supported. Try to re-write the statement as an INSERT INTO ... SELECT A, B, C FROM TABLE WHERE ... ON DUPLICATE KEY UPDATE",
            Code.INVALID_ARGUMENT);

      if (generateParameterMetaData || isSingleRowWhereClause(
          getConnection()
              .getTable(unquoteIdentifier(updateStatement.getTables().get(0).getName())),
          updateStatement.getWhere()))
        return new Mutations(createUpdateMutation(updateStatement, generateParameterMetaData));
      // Translate into an 'INSERT ... SELECT ... ON DUPLICATE KEY
      // UPDATE'-statement
      String insertSQL = createInsertSelectOnDuplicateKeyUpdateStatement(updateStatement);
      return createMutations(insertSQL, true, false);
    } else if (statement instanceof Delete) {
      Delete deleteStatement = (Delete) statement;
      if (generateParameterMetaData || deleteStatement.getWhere() == null
          || isSingleRowWhereClause(
              getConnection().getTable(unquoteIdentifier(deleteStatement.getTable().getName())),
              deleteStatement.getWhere()))
        return new Mutations(createDeleteMutation(deleteStatement, generateParameterMetaData));
      return new Mutations(createDeleteWorker(deleteStatement));
    } else {
      throw new CloudSpannerSQLException(
          "Unrecognized or unsupported SQL-statment: Expected one of INSERT, UPDATE or DELETE. Please note that batching of prepared statements is not supported for SELECT-statements.",
          Code.INVALID_ARGUMENT);
    }
  } catch (JSQLParserException | IllegalArgumentException | TokenMgrException e) {
    throw new CloudSpannerSQLException(PARSE_ERROR + sql + ": " + e.getLocalizedMessage(),
        Code.INVALID_ARGUMENT, e);
  }
}
 
Example 17
Source Project: jobson   Source File: AllColumnRefsFinder.java    License: Apache License 2.0 4 votes vote down vote up
public void visit(Delete delete) {
    throw new UnsupportedSQLFeatureException("Feature Delete not supported");
}
 
Example 18
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 4 votes vote down vote up
protected void visit0(Delete delete) {
    super.visit(delete);
}
 
Example 19
public Builder setDelete(Delete delete) throws com.github.vincentrussell.query.mongodb.sql.converter.ParseException, ParseException {
	SqlUtils.isTrue(delete.getTables().size() == 0, "there should only be on table specified for deletes");
    from = generateFromHolder(new FromHolder(this.defaultFieldType,this.fieldNameToFieldTypeMapping),delete.getTable(),null);
    whereClause = delete.getWhere();
    return this;
}
 
Example 20
Source Project: foxtrot   Source File: SqlElementVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visit(Delete delete) {
    //supported construct
}
 
Example 21
Source Project: mybatis-shard   Source File: SqlConverterFactory.java    License: Eclipse Public License 1.0 4 votes vote down vote up
private void register() {
    converterMap.put(Select.class.getName(), new SelectSqlConverter());
    converterMap.put(Insert.class.getName(), new InsertSqlConverter());
    converterMap.put(Update.class.getName(), new UpdateSqlConverter());
    converterMap.put(Delete.class.getName(), new DeleteSqlConverter());
}
 
Example 22
Source Project: tx-lcn   Source File: SqlExecuteInterceptor.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 程序业务{@code delete} 语句执行前植入事务操作
 *
 * @param delete SQL
 * @throws SQLException 事务判断资源锁定、不支持此SQL时抛出
 */
void preDelete(Delete delete) throws SQLException;
 
Example 23
Source Project: DDF   Source File: TableVisitor.java    License: Apache License 2.0 2 votes vote down vote up
@Override
public void visit(Delete delete) throws Exception {

}