Java Code Examples for net.sf.jsqlparser.statement.insert.Insert

The following examples show how to use net.sf.jsqlparser.statement.insert.Insert. 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
@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 3
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 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: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void postInsert(StatementInformation statementInformation) throws SQLException {
    Connection connection = (Connection) DTXLocalContext.cur().getResource();
    Insert insert = (Insert) statementInformation.getAttachment();
    TableStruct tableStruct = globalContext.tableStruct(insert.getTable().getName(),
            () -> tableStructAnalyser.analyse(connection, insert.getTable().getName()));

    // 非自增主键值
    PrimaryKeyListVisitor primaryKeyListVisitor = new PrimaryKeyListVisitor(insert.getTable(),
            insert.getColumns(), tableStruct.getFullyQualifiedPrimaryKeys());
    insert.getItemsList().accept(primaryKeyListVisitor);

    try {
        InsertImageParams insertImageParams = new InsertImageParams();
        insertImageParams.setTableName(tableStruct.getTableName());
        insertImageParams.setStatement(statementInformation.getStatement());
        insertImageParams.setFullyQualifiedPrimaryKeys(tableStruct.getFullyQualifiedPrimaryKeys());
        insertImageParams.setPrimaryKeyValuesList(primaryKeyListVisitor.getPrimaryKeyValuesList());
        txcService.resolveInsertImage(insertImageParams);
    } catch (TxcLogicException e) {
        throw new SQLException(e);
    }
}
 
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: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void visit(Insert insert) {
    this.getStack().push(new FrameContext(StatementType.INSERT));
    visit0(insert);
    // route table
    List<Column> columns = insert.getColumns();
    if (columns != null) {
        ItemsList itemsList = insert.getItemsList();
        if (itemsList instanceof ExpressionList) {
            procInsertColumns(columns, (ExpressionList) itemsList);
        } else if (itemsList instanceof MultiExpressionList) {
            for (ExpressionList expressionList : ((MultiExpressionList) itemsList).getExprList()) {
                procInsertColumns(columns, expressionList);
            }
        } else {
            throw new UnsupportedSQLExpressionException(insert.toString());
        }
    }
    afterVisitBaseStatement();
}
 
Example 8
private void transform(final Insert insert, Tenant tenant) {
    /*
    insert.getColumns().add(new Column(tenant.getTenantColumn()));
    if (insert.getItemsList() != null) {
        ItemsList itemsList = insert.getItemsList();
        if (itemsList instanceof ExpressionList) {
            ((ExpressionList) insert.getItemsList()).getExpressions().add(new StringValue(tenant.getSingleTenantValues()));
        }
    }
     */
}
 
Example 9
Source Project: tx-lcn   Source File: TxcJdbcEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterExecute(PreparedStatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
    if (statementInformation.getAttachment() instanceof Insert) {
        try {
            sqlExecuteInterceptor.postInsert(statementInformation);
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
Example 10
Source Project: tx-lcn   Source File: TxcJdbcEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterExecute(StatementInformation statementInformation, long timeElapsedNanos, String sql, SQLException e) {
    if (statementInformation.getAttachment() instanceof Insert) {
        try {
            sqlExecuteInterceptor.postInsert(statementInformation);
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
Example 11
Source Project: tx-lcn   Source File: TxcJdbcEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterExecuteUpdate(PreparedStatementInformation statementInformation, long timeElapsedNanos, int rowCount, SQLException e) {
    if (statementInformation.getAttachment() instanceof Insert) {
        try {
            sqlExecuteInterceptor.postInsert(statementInformation);
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
Example 12
Source Project: tx-lcn   Source File: TxcJdbcEventListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterExecuteUpdate(StatementInformation statementInformation, long timeElapsedNanos, String sql, int rowCount, SQLException e) {
    if (statementInformation.getAttachment() instanceof Insert) {
        try {
            sqlExecuteInterceptor.postInsert(statementInformation);
        } catch (SQLException e1) {
            throw new RuntimeException(e1);
        }
    }
}
 
Example 13
Source Project: evosql   Source File: TablesNamesFinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Insert insert) {
    tables.add(insert.getTable().getName());
    if (insert.getItemsList() != null) {
        insert.getItemsList().accept(this);
    }
    if (insert.getSelect() != null) {
        visit(insert.getSelect());
    }
}
 
Example 14
Source Project: compass   Source File: TableRenameVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void visit(Insert insert)
{
    insert.getTable().accept(this);
    
    if (insert.getItemsList() != null)
    {
        insert.getItemsList().accept(this);
    }
    if (insert.getSelect() != null)
    {
        visit(insert.getSelect());
    }
}
 
Example 15
Source Project: mybatis-shard   Source File: InsertSqlConverter.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 Insert)) {
        throw new IllegalArgumentException("The argument statement must is instance of Insert.");
    }
    Insert insert = (Insert) statement;

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

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

    return insert;
}
 
Example 16
Source Project: WeBASE-Front   Source File: CRUDParseUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean parseInsert(String sql, Table table, Entry entry)
        throws JSQLParserException, FrontException {
    Statement statement = CCJSqlParserUtil.parse(sql);
    Insert insert = (Insert) statement;

    if (insert.getSelect() != null) {
        throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR, "The insert select clause is not supported.");
    }
    // parse table name
    String tableName = insert.getTable().getName();
    table.setTableName(tableName);

    // parse columns
    List<Column> columns = insert.getColumns();
    ItemsList itemsList = insert.getItemsList();
    String items = itemsList.toString();
    String[] rawItem = items.substring(1, items.length() - 1).split(",");
    String[] itemArr = new String[rawItem.length];
    for (int i = 0; i < rawItem.length; i++) {
        itemArr[i] = rawItem[i].trim();
    }
    if (columns != null) {
        if (columns.size() != itemArr.length) {
            throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR, "Column count doesn't match value count.");
        }
        List<String> columnNames = new ArrayList<>();
        for (Column column : columns) {
            String columnName = trimQuotes(column.toString());
            if (columnNames.contains(columnName)) {
                throw new FrontException(PrecompiledUtils.CRUD_SQL_ERROR,
                        "Please provide the field '" + columnName + "' only once.");
            } else {
                columnNames.add(columnName);
            }
        }
        for (int i = 0; i < columnNames.size(); i++) {
            entry.put(columnNames.get(i), trimQuotes(itemArr[i]));
        }
        return false;
    } else {
        for (int i = 0; i < itemArr.length; i++) {
            entry.put(i + "", trimQuotes(itemArr[i]));
        }
        return true;
    }
}
 
Example 17
Source Project: spanner-jdbc   Source File: InsertWorker.java    License: MIT License 4 votes vote down vote up
public InsertWorker(CloudSpannerConnection connection, Select select, Insert insert,
    ParameterStore parameters, boolean allowExtendedMode, DMLOperation operation) {
  super(connection, select, parameters, allowExtendedMode, operation);
  this.insert = insert;
}
 
Example 18
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 19
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 4 votes vote down vote up
private Mutation createInsertMutation(Insert insert, boolean generateParameterMetaData)
    throws SQLException {
  ItemsList items = insert.getItemsList();
  if (generateParameterMetaData && items == null && insert.getSelect() != null) {
    // Just initialize the parameter meta data of the select statement
    createSelectBuilder(insert.getSelect(), insert.getSelect().toString());
    return null;
  }
  if (!(items instanceof ExpressionList)) {
    throw new CloudSpannerSQLException("Insert statement must specify a list of values",
        Code.INVALID_ARGUMENT);
  }
  if (insert.getColumns() == null || insert.getColumns().isEmpty()) {
    throw new CloudSpannerSQLException("Insert statement must specify a list of column names",
        Code.INVALID_ARGUMENT);
  }
  List<Expression> expressions = ((ExpressionList) items).getExpressions();
  String table = unquoteIdentifier(insert.getTable().getFullyQualifiedName());
  getParameterStore().setTable(table);
  WriteBuilder builder;
  if (insert.isUseDuplicate()) {
    /**
     * Do an insert-or-update. BUT: Cloud Spanner does not support supplying different values for
     * the insert and update statements, meaning that only the values specified in the INSERT part
     * of the statement will be considered. Anything specified in the 'ON DUPLICATE KEY UPDATE
     * ...' statement will be ignored.
     */
    if (this.forceUpdate)
      builder = Mutation.newUpdateBuilder(table);
    else
      builder = Mutation.newInsertOrUpdateBuilder(table);
  } else {
    /**
     * Just do an insert and throw an error if a row with the specified key alread exists.
     */
    builder = Mutation.newInsertBuilder(table);
  }
  int index = 0;
  for (Column col : insert.getColumns()) {
    String columnName = unquoteIdentifier(col.getFullyQualifiedName());
    expressions.get(index).accept(new ValueBinderExpressionVisitorAdapter<>(getParameterStore(),
        builder.set(columnName), columnName));
    index++;
  }
  return builder.build();
}
 
Example 20
Source Project: tx-lcn   Source File: TxcSqlExecuteInterceptor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void preInsert(Insert insert) {
}
 
Example 21
Source Project: jobson   Source File: AllColumnRefsFinder.java    License: Apache License 2.0 4 votes vote down vote up
public void visit(Insert insert) {
    throw new UnsupportedSQLFeatureException("Feature Insert not supported");
}
 
Example 22
Source Project: ddal   Source File: JSQLParserAdapter.java    License: Apache License 2.0 4 votes vote down vote up
protected void visit0(Insert insert) {
    super.visit(insert);
}
 
Example 23
Source Project: foxtrot   Source File: SqlElementVisitor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void visit(Insert insert) {
    //supported construct
}
 
Example 24
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 25
Source Project: tx-lcn   Source File: SqlExecuteInterceptor.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 程序业务{@code insert} 语句执行前植入事务操作
 *
 * @param insert SQL
 * @throws SQLException 不支持此SQL时抛出
 */
void preInsert(Insert insert) throws SQLException;
 
Example 26
Source Project: DDF   Source File: TableVisitor.java    License: Apache License 2.0 2 votes vote down vote up
@Override
public void visit(Insert insert) throws Exception {

}