Java Code Examples for net.sf.jsqlparser.statement.update.Update

The following examples show how to use net.sf.jsqlparser.statement.update.Update. 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: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private Mutation createUpdateMutation(Update update, boolean generateParameterMetaData)
    throws SQLException {
  if (update.getTables().isEmpty())
    throw new CloudSpannerSQLException("No table found in update statement",
        Code.INVALID_ARGUMENT);
  if (update.getTables().size() > 1)
    throw new CloudSpannerSQLException(
        "Update statements for multiple tables at once are not supported", Code.INVALID_ARGUMENT);
  String table = unquoteIdentifier(update.getTables().get(0).getFullyQualifiedName());
  getParameterStore().setTable(table);
  List<Expression> expressions = update.getExpressions();
  WriteBuilder builder = Mutation.newUpdateBuilder(table);
  int index = 0;
  for (Column col : update.getColumns()) {
    String columnName = unquoteIdentifier(col.getFullyQualifiedName());
    expressions.get(index).accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
        builder.set(columnName), columnName));
    index++;
  }
  visitUpdateWhereClause(update.getWhere(), builder, generateParameterMetaData);

  return builder.build();
}
 
Example 3
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 4
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 5
Source Project: evosql   Source File: TablesNamesFinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Update update) {
    for (Table table : update.getTables()) {
        tables.add(table.getName());
    }
    if (update.getExpressions() != null) {
        for (Expression expression : update.getExpressions()) {
            expression.accept(this);
        }
    }

    if (update.getFromItem() != null) {
        update.getFromItem().accept(this);
    }

    if (update.getJoins() != null) {
        for (Join join : update.getJoins()) {
            join.getRightItem().accept(this);
        }
    }

    if (update.getWhere() != null) {
        update.getWhere().accept(this);
    }
}
 
Example 6
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 7
Source Project: WeBASE-Front   Source 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 8
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatement.java    License: MIT License 5 votes vote down vote up
/**
 * Transform the given UPDATE-statement into an "INSERT INTO TAB1 (...) SELECT ... FROM TAB1 WHERE
 * ... ON DUPLICATE KEY UPDATE"
 * 
 * @param update The UPDATE-statement
 * @return An SQL-statement equal to the UPDATE-statement but in INSERT form
 * @throws SQLException if a database exception occurs while getting the table meta data or if the
 *         statement tries to update the primary key value
 */
protected String createInsertSelectOnDuplicateKeyUpdateStatement(Update update)
    throws SQLException {
  String tableName = unquoteIdentifier(update.getTables().get(0).getName());
  TableKeyMetaData table = getConnection().getTable(tableName);
  List<String> keyColumns = table.getKeyColumns();
  List<String> updateColumns = update.getColumns().stream().map(Column::getColumnName)
      .map(String::toUpperCase).collect(Collectors.toList());
  List<String> quotedKeyColumns =
      keyColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> quotedAndQualifiedKeyColumns =
      keyColumns.stream().map(x -> quoteIdentifier(tableName) + "." + quoteIdentifier(x))
          .collect(Collectors.toList());

  List<String> quotedUpdateColumns =
      updateColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> expressions =
      update.getExpressions().stream().map(Object::toString).collect(Collectors.toList());
  if (updateColumns.stream().anyMatch(keyColumns::contains)) {
    String invalidCols =
        updateColumns.stream().filter(keyColumns::contains).collect(Collectors.joining());
    throw new CloudSpannerSQLException(
        "UPDATE of a primary key value is not allowed, cannot UPDATE the column(s) "
            + invalidCols,
        Code.INVALID_ARGUMENT);
  }

  StringBuilder res = new StringBuilder();
  res.append("INSERT INTO ").append(quoteIdentifier(tableName)).append("\n(");
  res.append(String.join(", ", quotedKeyColumns)).append(", ");
  res.append(String.join(", ", quotedUpdateColumns)).append(")");
  res.append("\nSELECT ").append(String.join(", ", quotedAndQualifiedKeyColumns)).append(", ");
  res.append(String.join(", ", expressions));
  res.append("\nFROM ").append(quoteIdentifier(tableName));
  if (update.getWhere() != null)
    res.append("\n").append("WHERE ").append(update.getWhere().toString());
  res.append("\nON DUPLICATE KEY UPDATE");

  return res.toString();
}
 
Example 9
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatementTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCreateInsertSelectOnDuplicateKeyUpdateStatement()
    throws JSQLParserException, SQLException {
  String sql = "UPDATE FOO SET BAR=2 WHERE VALUE=1";
  Update update = (Update) CCJSqlParserUtil.parse(sql);
  String insert = subject.createInsertSelectOnDuplicateKeyUpdateStatement(update);
  assertEquals("INSERT INTO `FOO`\n" + "(`ID`, `BAR`)\n" + "SELECT `FOO`.`ID`, 2\n"
      + "FROM `FOO`\n" + "WHERE VALUE = 1\n" + "ON DUPLICATE KEY UPDATE", insert);
}
 
Example 10
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatementTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCreateInsertSelectOnDuplicateKeyUpdateStatementWithParameters()
    throws JSQLParserException, SQLException {
  String sql = "UPDATE FOO SET BAR=? WHERE ID=? AND VALUE=?";
  Update update = (Update) CCJSqlParserUtil.parse(sql);
  String insert = subject.createInsertSelectOnDuplicateKeyUpdateStatement(update);
  assertEquals("INSERT INTO `FOO`\n" + "(`ID`, `BAR`)\n" + "SELECT `FOO`.`ID`, ?\n"
      + "FROM `FOO`\n" + "WHERE ID = ? AND VALUE = ?\n" + "ON DUPLICATE KEY UPDATE", insert);
}
 
Example 11
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatementTest.java    License: 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 12
Source Project: spanner-jdbc   Source File: AbstractCloudSpannerStatementTest.java    License: 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 13
Source Project: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void preUpdate(Update update) throws SQLException {
    // 获取线程传递参数
    Connection connection = (Connection) DTXLocalContext.cur().getResource();

    // Update相关数据准备
    List<String> columns = new ArrayList<>(update.getColumns().size());
    List<String> primaryKeys = new ArrayList<>(3);
    List<String> tables = new ArrayList<>(update.getTables().size());
    update.getColumns().forEach(column -> {
        column.setTable(update.getTables().get(0));
        columns.add(column.getFullyQualifiedName());
    });
    for (Table table : update.getTables()) {
        tables.add(table.getName());
        TableStruct tableStruct = globalContext.tableStruct(table.getName(),
                () -> tableStructAnalyser.analyse(connection, table.getName()));
        tableStruct.getPrimaryKeys().forEach(key -> primaryKeys.add(table.getName() + "." + key));
    }

    // 前置准备
    try {
        UpdateImageParams updateImageParams = new UpdateImageParams();
        updateImageParams.setColumns(columns);
        updateImageParams.setPrimaryKeys(primaryKeys);
        updateImageParams.setTables(tables);
        updateImageParams.setWhereSql(update.getWhere() == null ? "1=1" : update.getWhere().toString());
        txcService.resolveUpdateImage(updateImageParams);
    } catch (TxcLogicException e) {
        throw new SQLException(e.getMessage());
    }
}
 
Example 14
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Update update) {
    if (enableLimitCheck && update.getLimit() == null) {
        throw new IllegalStateException("no limit in sql: " + sql);
    }
    this.getStack().push(new FrameContext(StatementType.UPDATE));
    visit0(update);
    afterVisitBaseStatement();
}
 
Example 15
Source Project: compass   Source File: TableRenameVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Update update)
{
    for (Table table : update.getTables())
    {
    	table.accept(this);
    }
    if (update.getExpressions() != null)
    {
        for (Expression expression : update.getExpressions())
        {
            expression.accept(this);
        }
    }

    if (update.getFromItem() != null)
    {
        update.getFromItem().accept(this);
    }

    if (update.getJoins() != null)
    {
        for (Join join : update.getJoins())
        {
            join.getRightItem().accept(this);
        }
    }

    if (update.getWhere() != null)
    {
        update.getWhere().accept(this);
    }
}
 
Example 16
Source Project: mybatis-shard   Source File: UpdateSqlConverter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected Statement doConvert(Statement statement, String suffix, Pattern includePattern) {
    if (!(statement instanceof Update)) {
        throw new IllegalArgumentException("The argument statement must is instance of Update.");
    }
    Update update = (Update) statement;
    String name = update.getTable().getName();

    if (includePattern.matcher(name).find()) {
        update.getTable().setName(this.convertTableName(name, suffix));
    }
    return update;
}
 
Example 17
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 18
Source Project: dynamic-add-date   Source File: AddDateInterceptor.java    License: MIT License 4 votes vote down vote up
private void updateValueWithIndex(int modifyDateColumnIndex, String currentDate, Update update) {
    update.getExpressions().set(modifyDateColumnIndex, new QuotationTimestampValue(currentDate));
}
 
Example 19
Source Project: dynamic-add-date   Source File: AddDateInterceptor.java    License: MIT License 4 votes vote down vote up
private void updateValue(String updateDateColumnName, String currentDate, Update update) {
    // 添加列
    update.getColumns().add(new Column(updateDateColumnName));
    update.getExpressions().add(new QuotationTimestampValue(currentDate));
}
 
Example 20
Source Project: jobson   Source File: AllColumnRefsFinder.java    License: Apache License 2.0 4 votes vote down vote up
public void visit(Update update) {
    throw new UnsupportedSQLFeatureException("Feature Update not supported");
}
 
Example 21
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 4 votes vote down vote up
protected void visit0(Update update) {
    super.visit(update);
}
 
Example 22
Source Project: foxtrot   Source File: SqlElementVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visit(Update update) {
    //supported construct
}
 
Example 23
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 24
Source Project: tx-lcn   Source File: SqlExecuteInterceptor.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 程序业务{@code update} 语句执行前植入事务操作
 *
 * @param update SQL
 * @throws SQLException 事务判断资源锁定、不支持此SQL时抛出
 */
void preUpdate(Update update) throws SQLException;
 
Example 25
Source Project: DDF   Source File: TableVisitor.java    License: Apache License 2.0 2 votes vote down vote up
@Override
public void visit(Update update) throws Exception {

}