/*
(non-Javadoc)

@see com.impetus.kundera.query.QueryImpl#onExecuteUpdate()
498817
@Override
    protected int onExecuteUpdate() {
        if (kunderaQuery.isDeleteUpdate()) {
            List result = getResultList();
            return result != null ? result.size() : 0;
        }

        return 0;

    }
577734
@Override
    public synchronized int update(T dto) throws Exception {
        return db.update(transformer.getTableName(), transformer.transform(dto),transformer.getWhereClause(dto), null);
    }
309029
public int executeUpdate(String query) throws Exception {
        int returnVal = 0;
        Statement queryStatement = null;

        try (Connection sqlConnection = getConnection()) {
            queryStatement = sqlConnection.createStatement();
            returnVal = queryStatement.executeUpdate(query);
        } catch (Exception e) {
        } finally {
            try {
                if (queryStatement != null) {
                    queryStatement.close();
                }
            } catch (Exception e) {
            }
        }

        return returnVal;
    }
255225
@Override
    public synchronized int executeUpdate(String query) throws DatabaseEngineException {
        String[] split = query.split(Constants.UNIT_SEPARATOR_CHARACTER + "");
        int i = -1;
        for (String s : split) {
            if (StringUtils.isNotBlank(s)) {
                i = super.executeUpdate(s);
            }
        }

        return i;
    }
916573
protected int update (final String query)
        throws PersistenceException
    {
        return executeUpdate(new Operation<Integer>() {
            public Integer invoke (Connection conn, DatabaseLiaison liaison)
                throws SQLException, PersistenceException
            {
                Statement stmt = null;
                try {
                    stmt = conn.createStatement();
                    return stmt.executeUpdate(query);
                } finally {
                    JDBCUtil.close(stmt);
                }
            }
        });
    }
754175
public static SQLExecuteCallback<Integer> getPreparedUpdateSQLExecuteCallback(final DatabaseType databaseType, final boolean isExceptionThrown) {
        return new SQLExecuteCallback<Integer>(databaseType, isExceptionThrown) {
            
            @Override
            protected Integer executeSQL(final RouteUnit routeUnit, final Statement statement, final ConnectionMode connectionMode) throws SQLException {
                return ((PreparedStatement) statement).executeUpdate();
            }
        };
    }
453556
public int executeUpdate() throws SQLException {
        final boolean isExceptionThrown = ExecutorExceptionHandler.isExceptionThrown();
        SQLExecuteCallback<Integer> executeCallback = SQLExecuteCallbackFactory.getPreparedUpdateSQLExecuteCallback(getDatabaseType(), isExceptionThrown);
        List<Integer> results = executeCallback(executeCallback);
        if (isAccumulate()) {
            return accumulate(results);
        } else {
            return results.get(0);
        }
    }
1185626
public boolean execute(final OneSelect _onesel)
        throws EFapsException
    {
        this.hasResult = executeOneCompleteStmt(createSQLStatement(_onesel), getAllSelects());
        if (this.hasResult) {
            for (final OneSelect onesel :  getAllSelects()) {
                if (onesel.getFromSelect() != null && !onesel.getFromSelect().equals(this)) {
                    onesel.getFromSelect().execute(onesel);
                }
            }
        }
        return this.hasResult;
    }
1092861
List onExecuteQuery(RedisQueryInterpreter queryParameter, Class entityClazz)
    {
        /**
         * Find a list of id's and then call findById for each!
         */
        Object connection = null;
        List<Object> results = new ArrayList<Object>();
        try
        {
            connection = getConnection();
            Set<String> rowKeys = new HashSet<String>();
            EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
            String printQuery = null;

            if (showQuery)
            {
                printQuery = "Fetching primary key from " + entityMetadata.getTableName() + " corresponding to ";
            }

            if (queryParameter.getClause() != null && !queryParameter.isByRange())
            {
                String destStore = entityClazz.getSimpleName() + System.currentTimeMillis();

                Map<String, Object> fieldSets = queryParameter.getFields();

                Set<String> keySets = new HashSet<String>(fieldSets.size());
                // byte[][] keys = new byte[][fieldSets.size()];
                for (String column : fieldSets.keySet())
                {
                    String valueAsStr = PropertyAccessorHelper.getString(fieldSets.get(column));
                    String key = getHashKey(entityMetadata.getTableName(), getHashKey(column, valueAsStr));
                    keySets.add(key);
                    if (showQuery)
                    {
                        printQuery = printQuery + key + " and ";
                    }
                }

                if (showQuery)
                {
                    printQuery = printQuery.substring(0, printQuery.lastIndexOf(" and "));
                }

                if (queryParameter.getClause().equals(Clause.INTERSECT))
                {
                    KunderaCoreUtils.printQuery(printQuery, showQuery);

                    if (resource != null && resource.isActive())
                    {
                        ((Transaction) connection).zinterstore(destStore, keySets.toArray(new String[] {}));
                    }
                    else
                    {
                        ((Jedis) connection).zinterstore(destStore, keySets.toArray(new String[] {}));
                    }
                }
                else
                {
                    if (showQuery)
                    {
                        KunderaCoreUtils.printQuery(printQuery.replaceAll("and", "or"), showQuery);
                    }

                    if (resource != null && resource.isActive())
                    {
                        ((Transaction) connection).zunionstore(destStore, keySets.toArray(new String[] {}));
                    }
                    else
                    {
                        ((Jedis) connection).zunionstore(destStore, keySets.toArray(new String[] {}));
                    }
                }

                if (resource != null && resource.isActive())
                {
                    Response response = ((Transaction) connection).zrange(destStore, 0, -1);
                    // ((Transaction) connection).exec();
                    ((RedisTransaction) resource).onExecute(((Transaction) connection));

                    rowKeys = (Set<String>) response.get();
                    // connection = reInitialize(connection, rowKeys);
                    //
                    // ((Transaction) connection).del(destStore);

                }
                else
                {
                    rowKeys = ((Jedis) connection).zrange(destStore, 0, -1);
                    ((Jedis) connection).del(destStore);
                }

                // delete intermediate store after find.
                //
                // means it is a query over sorted set.
            }
            else if (queryParameter.isByRange())
            {
                // means query over a single sorted set with range
                Map<String, Double> minimum = queryParameter.getMin();
                Map<String, Double> maximum = queryParameter.getMax();

                String column = minimum.keySet().iterator().next();
                KunderaCoreUtils.printQuery(printQuery + column + " between " + minimum + " and " + maximum, showQuery);
                if (resource != null && resource.isActive())
                {
                    Response response = ((Transaction) connection)
                            .zrangeByScore(getHashKey(entityMetadata.getTableName(), column), minimum.get(column),
                                    maximum.get(column));
                    // ((Transaction) connection).exec();
                    ((RedisTransaction) resource).onExecute(((Transaction) connection));

                    rowKeys = (Set<String>) response.get();
                    // connection = reInitialize(connection, rowKeys);
                }
                else
                {
                    rowKeys = ((Jedis) connection).zrangeByScore(getHashKey(entityMetadata.getTableName(), column),
                            minimum.get(column), maximum.get(column));
                }
            }
            else if (queryParameter.isById())
            {
                Map<String, Object> fieldSets = queryParameter.getFields();

                results = findAllColumns(entityClazz, (queryParameter.getColumns() != null ? queryParameter
                        .getColumns().toArray(new byte[][] {}) : null), fieldSets.values().toArray());
                return results;
            }
            else if (queryParameter.getFields() != null)
            {
                Set<String> columns = queryParameter.getFields().keySet();

                for (String column : columns)
                {
                    // ideally it will always be 1 value in map, else it will go
                    // it queryParameter.getClause() will not be null!
                    Double value = getDouble(PropertyAccessorHelper.getString(queryParameter.getFields().get(column)));
                    if (resource != null && resource.isActive())
                    {
                        Response response = ((Transaction) connection).zrangeByScore(
                                getHashKey(entityMetadata.getTableName(), column), value, value);
                        // ((Transaction) connection).exec();
                        ((RedisTransaction) resource).onExecute(((Transaction) connection));

                        rowKeys = (Set<String>) response.get();
                        // connection = reInitialize(connection, rowKeys);

                    }
                    else
                    {
                        rowKeys = ((Jedis) connection).zrangeByScore(getHashKey(entityMetadata.getTableName(), column),
                                value, value);
                    }
                }
            }
            else
            {
                if (resource != null && resource.isActive())
                {
                    Response response = ((Transaction) connection).zrange(
                            getHashKey(entityMetadata.getTableName(),
                                    ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), 0, -1);
                    // resource.onCommit()
                    // ((Transaction) connection).exec();
                    ((RedisTransaction) resource).onExecute(((Transaction) connection));

                    rowKeys = new HashSet<String>((Collection<? extends String>) response.get());
                }
                else
                {
                    rowKeys = new HashSet<String>(((Jedis) connection).zrange(
                            getHashKey(entityMetadata.getTableName(),
                                    ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()), 0, -1));
                }
            }

            for (String k : rowKeys)
            {
                connection = reInitialize(connection, rowKeys);
                Object record = fetch(entityClazz, k, connection, (queryParameter.getColumns() != null ? queryParameter
                        .getColumns().toArray(new byte[][] {}) : null));
                if (record != null)
                {
                    results.add(record);
                }
            }

        }
        catch (InstantiationException e)
        {
            logger.error("Error during persist, Caused by:", e);
            throw new PersistenceException(e);
        }
        catch (IllegalAccessException e)
        {
            logger.error("Error during persist, Caused by:", e);
            throw new PersistenceException(e);
        }
        catch (Exception e)
        {
            logger.error("Error during persist, Caused by:", e);
            throw new PersistenceException(e);
        }
        finally
        {
            onCleanup(connection);

        }

        return results;
    }
559971
public void commit(Xid xid, boolean onePhase) throws XAException
    {
        if (tc.isEntryEnabled()) Tr.entry(tc, "commit", new Object[] {xid, onePhase});

		final JCATranWrapper txWrapper;
		
		try
		{
			validateXid(xid);
			
			// Get the wrapper adding an association in the process
			txWrapper = getTxWrapper(xid, true);
		}
		catch (XAException e)
		{
			if (tc.isEntryEnabled()) Tr.exit(tc, "commit", "caught XAException: " + XAReturnCodeHelper.convertXACode(e.errorCode));
			throw e;
		}

		try
		{
			if (onePhase)
			{
				// Perform one-phase commit
				txWrapper.commitOnePhase();
			}
			else
			{
				// Perform ordinary commit (prepare has already been called)
				txWrapper.commit();
			}
		}
		catch (XAException e)
		{
			TxExecutionContextHandler.removeAssociation(txWrapper);
			
			if (tc.isEntryEnabled()) Tr.exit(tc, "commit", "rethrowing XAException: " + XAReturnCodeHelper.convertXACode(e.errorCode));
			throw e;
		}

		TxExecutionContextHandler.removeAssociation(txWrapper);

		if (tc.isEntryEnabled()) Tr.exit(tc, "commit");
    }
1333338
@Override
    protected int onExecuteUpdate()
    {
        Map<String, Object> persistDetails = new HashMap<String, Object>();
        DataFrame dataFrame;
        try
        {
            String query = getJPAQuery();// .toLowerCase();

            persistDetails = parseInsertIntoQuery(query);

            dataFrame = getDataFrameToPersist(query, (String) persistDetails.get("fetchQuery"));

            String clientName = (String) persistDetails.get("client");

            SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);
            dataClient.saveDataFrame(dataFrame, getEntityMetadata().getEntityClazz(), persistDetails);
        }
        catch (Exception e)
        {
            logger.error("Error during executing query, Caused by:", e);
            throw new QueryHandlerException(e);
        }

        return getDataFrameSize(dataFrame);
    }
337477
public T update(T entity) throws RowNotFoundException, OptimisticLockException {

        if (!hasPrimaryKey(entity)) {
            throw new RuntimeException(String.format("Tried to update entity of type %s without a primary key", entity
                    .getClass().getSimpleName()));
        }

        UpdateCreator update = new UpdateCreator(table);

        update.whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));

        if (versionColumn != null) {
            update.set(versionColumn.getColumnName() + " = " + versionColumn.getColumnName() + " + 1");
            update.whereEquals(versionColumn.getColumnName(), getVersion(entity));
        }

        for (Column column : columns) {
            if (!column.isReadOnly()) {
                update.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));
            }
        }

        int rows = new JdbcTemplate(ormConfig.getDataSource()).update(update);

        if (rows == 1) {

            if (versionColumn != null) {
                ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), getVersion(entity) + 1);
            }

            return entity;

        } else if (rows > 1) {

            throw new RuntimeException(
                    String.format("Updating table %s with id %s updated %d rows. There must be a mapping problem. Is column %s really the primary key?",
                            table, getPrimaryKey(entity), rows, idColumn));

        } else {

            //
            // Updated zero rows. This could be because our ID is wrong, or
            // because our object is out-of date. Let's try querying just by ID.
            //

            SelectCreator selectById = new SelectCreator()
            .column("count(*)")
            .from(table)
            .whereEquals(idColumn.getColumnName(), getPrimaryKey(entity));

            rows = new JdbcTemplate(ormConfig.getDataSource()).query(selectById, new ResultSetExtractor<Integer>() {
                @Override
                public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
                    rs.next();
                    return rs.getInt(1);
                }
            });

            if (rows == 0) {
                throw new RowNotFoundException(table, getPrimaryKey(entity));
            } else {
                throw new OptimisticLockException(table, getPrimaryKey(entity));
            }
        }
    }
643075
private void executeUpdates()
        throws EFapsException
    {
        ConnectionResource con = null;
        try {
            con = Context.getThreadContext().getConnectionResource();
            for (final Entry<SQLTable, AbstractSQLInsertUpdate<?>> entry : updatemap.entrySet()) {
                ((SQLUpdate) entry.getValue()).execute(con);
            }
        } catch (final SQLException e) {
            throw new EFapsException(SQLRunner.class, "executeOneCompleteStmt", e);
        }
    }
1190000
@Override
	public CompletableFuture<Acknowledge> updateTaskExecutionState(
			final TaskExecutionState taskExecutionState) {
		checkNotNull(taskExecutionState, "taskExecutionState");

		if (executionGraph.updateState(taskExecutionState)) {
			return CompletableFuture.completedFuture(Acknowledge.get());
		} else {
			return FutureUtils.completedExceptionally(
				new ExecutionGraphException("The execution attempt " +
					taskExecutionState.getID() + " was not found."));
		}
	}
65772
public void prepareUpdateStep1b() {

        if (!isInitialized()) {
            return;
        }

        if ((m_dbUpdateThread != null) && (m_dbUpdateThread.isFinished())) {
            // update is already finished, just wait for client to collect final data
            return;
        }

        if (m_dbUpdateThread == null) {
            m_dbUpdateThread = new CmsUpdateDBThread(this);
        }

        if (!m_dbUpdateThread.isAlive()) {
            m_dbUpdateThread.start();
        }
    }
1048076
public int executeUpdate(String sql) throws SQLException {
    if (executeInternal(sql, fetchSize, Statement.NO_GENERATED_KEYS)) {
      return 0;
    }
    return getUpdateCount();
  }
1083464
@SuppressWarnings("unchecked")
    public <T extends IEntity> T donotUpdateAccountOnTxns(T entity) throws FMSException {

        IntuitMessage intuitMessage = preparedonotUpdateAccountOnTxns(entity);

        //execute interceptors
        executeInterceptors(intuitMessage);

        return (T) retrieveEntity(intuitMessage);
    }