Execute batch.

@return the int
769938
public int executeBatch() {
        Cassandra.Client conn = null;
        Object pooledConnection = null;

        /**
         * Key -> Entity Class Value -> Map containing Row ID as Key and Mutation List as Value
         */
        Map<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>> batchMutationMap =
            new HashMap<Class<?>, Map<ByteBuffer, Map<String, List<Mutation>>>>();

        int recordsExecuted = 0;
        boolean setCounter = true;
        String batchQuery = CQLTranslator.BATCH_QUERY;
        batchQuery = StringUtils.replace(batchQuery, CQLTranslator.STATEMENT, "");
        StringBuilder batchQueryBuilder = new StringBuilder(batchQuery);
        try {
            boolean isCql3Enabled = false;
            for (Node node : nodes) {
                if (node.isDirty()) {
                    node.handlePreEvent();
                    Object entity = node.getData();
                    Object id = node.getEntityId();
                    EntityMetadata metadata =
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
                    if (metadata.isCounterColumnType() && setCounter) {
                        batchQueryBuilder = new StringBuilder(StringUtils.replace(batchQueryBuilder.toString(),
                            CQLTranslator.BEGIN_BATCH, CQLTranslator.BEGIN_COUNTER_BATCH));
                        setCounter = false;
                    }
                    persistenceUnit = metadata.getPersistenceUnit();
                    isUpdate = node.isUpdate();

                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                        .getMetamodel(metadata.getPersistenceUnit());

                    // delete can not be executed in batch

                    if (isCql3Enabled(metadata)) {
                        isCql3Enabled = true;
                        List<RelationHolder> relationHolders = getRelationHolders(node);
                        if (node.isInState(RemovedState.class)) {
                            String query;
                            query = onDeleteQuery(metadata, metadata.getTableName(), metaModel, id);
                            batchQueryBuilder.append(Constants.SPACE);
                            batchQueryBuilder.append(query);
                        } else {
                            List<String> insertQueries = getPersistQueries(metadata, entity, conn, relationHolders,
                                getTtlValues().get(metadata.getTableName()));
                            for (String query : insertQueries) {
                                batchQueryBuilder.append(Constants.SPACE);
                                batchQueryBuilder.append(query);
                            }
                        }
                    } else {
                        if (node.isInState(RemovedState.class)) {
                            delete(entity, id);
                        } else {
                            List<RelationHolder> relationHolders = getRelationHolders(node);
                            Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap =
                                new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
                            mutationMap = prepareMutation(metadata, entity, id, relationHolders, mutationMap);

                            recordsExecuted += mutationMap.size();
                            if (!batchMutationMap.containsKey(metadata.getEntityClazz())) {
                                batchMutationMap.put(metadata.getEntityClazz(), mutationMap);
                            } else {
                                batchMutationMap.get(metadata.getEntityClazz()).putAll(mutationMap);
                            }

                            indexNode(node, metadata);
                        }
                    }
                    node.handlePostEvent();
                }
            }

            // Write Mutation map to database

            if (!batchMutationMap.isEmpty()) {
                pooledConnection = getConnection();
                conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);

                for (Class<?> entityClass : batchMutationMap.keySet()) {
                    conn.batch_mutate(batchMutationMap.get(entityClass), consistencyLevel);
                }
            }

            if (!nodes.isEmpty() && isCql3Enabled) {
                batchQueryBuilder.append(CQLTranslator.APPLY_BATCH);
                executeCQLQuery(batchQueryBuilder.toString(), isCql3Enabled);
            }
        } catch (Exception e) {
            log.error("Error while persisting record. Caused by: .", e);
            throw new KunderaException(e);
        } finally {
            clear();
            if (pooledConnection != null) {
                releaseConnection(pooledConnection);
            }
        }

        return recordsExecuted;
    }
703642
public int[] execute(Iterable<String> sqls, int batchSize) throws SQLException {
		if (sqls == null) {
			return null;
		}
		
		List<int[]> tmpResultList = new ArrayList<int[]>();
		
		Statement stmt = null;
		try {
			int counter = 0;
			stmt = conn.createStatement();
			for (String sql : sqls) {
				stmt.addBatch(sql);
				counter ++;
				if (batchSize > 0 && counter % batchSize == 0) {
					tmpResultList.add(stmt.executeBatch());
				}
			}
			tmpResultList.add(stmt.executeBatch());

		} catch (SQLException e) {
			throw e;
		} finally {
			try {
				if (stmt != null && stmt.isClosed() == false) {
					stmt.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage());
			}
		}
		
		int[] result = new int[0];
		for (int[] tmpResult : tmpResultList) {
			int[] tmpArray = new int[result.length + tmpResult.length];
			
			System.arraycopy(result, 0, tmpArray, 0, result.length);
			System.arraycopy(tmpResult, 0, tmpArray, result.length, tmpResult.length);
			
			result = tmpArray;
		}

		return result;
	}
146645
public void compileBatch(String []files)
    throws IOException, ClassNotFoundException
  {
    if (_compileParent) {
      try {
        if (_loader instanceof Make)
          ((Make) _loader).make();
      } catch (Exception e) {
        throw new IOException(e);
      }
    }

    if (files.length == 0)
      return;

    // only batch a number of files at a time

    int batchCount = _maxBatch;
    if (batchCount < 0)
      batchCount = Integer.MAX_VALUE / 2;
    else if (batchCount == 0)
      batchCount = 1;

    IOException exn = null;

    ArrayList<String> uniqueFiles = new ArrayList<String>();
    for (int i = 0; i < files.length; i++) {
      if (! uniqueFiles.contains(files[i]))
        uniqueFiles.add(files[i]);
    }
    files = new String[uniqueFiles.size()];
    uniqueFiles.toArray(files);

    LineMap lineMap = null;
    
    _compilerService.compile(this, files, lineMap);

    /*
    synchronized (LOCK) {
      for (int i = 0; i < files.length; i += batchCount) {
        int len = files.length - i;

        len = Math.min(len, batchCount);

        String []batchFiles = new String[len];

        System.arraycopy(files, i, batchFiles, 0, len);

        Arrays.sort(batchFiles);

        try {
          compileInt(batchFiles, null);
        } catch (IOException e) {
          if (exn == null)
            exn = e;
          else
            log.log(Level.WARNING, e.toString(), e);
        }
      }
    }

    if (exn != null)
      throw exn;
      */
  }
610963
public Result execute() {
        long start = clock().getTick();
        Result result;
        try {
            result = check();
        } catch (Exception e) {
            result = Result.unhealthy(e);
        }
        result.setDuration(TimeUnit.MILLISECONDS.convert(clock().getTick() - start, TimeUnit.NANOSECONDS));
        return result;
    }
145151
public static int getBatchUpdateCount(int[] batchExecuteResult){
		int result = 0;
		for (int c: batchExecuteResult){
			if (c >= 0){
				// real count
				result += c;
			}else if (c == -2){
				// unknown
				return -2;
			}else{
				// error or others
				// do nothing
			}
		}
		return result;
	}
84584
private void executeBatch(BatchStatement batchState) {
        if (batchState.size() > 0) {
            m_logger.debug("Executing synchronous batch with {} statements", batchState.size());
            m_dbservice.getSession().execute(batchState);
        }
    }
858187
void doBatchEnd(String batch, Object args) {
    checkOpen();
    JsonObject message = createMessage(args)
        .putString("action", "endBatch")
        .putString("batch", batch);
    if (open && !paused) {
      if (log.isDebugEnabled()) {
        log.debug(String.format("%s - Batch end: Batch[batch=%s, args=%s]", this, batch, args));
      }
      eventBus.send(inAddress, message);
    }
    if (currentBatch != null && currentBatch.id().equals(batch)) {
      currentBatch = null;
    }
  }
1157240
@Override
	public int count() {
		if (batch) {
			throw new IllegalStateException(
					"Since the parameter has already been set with addBatch() method, please call batch() method.");
		}
		try {
			return agent().update(context());
		} catch (SQLException e) {
			throw new UroborosqlSQLException(e);
		}
	}
928819
public ResultSet executeWithKeys() {
        context = startContext(connection(), metadata, entity);
        try {
            if (configuration.getTemplates().isNativeMerge()) {
                PreparedStatement stmt = null;
                if (batches.isEmpty()) {
                    stmt = createStatement(true);
                    listeners.notifyMerge(entity, metadata, keys, columns, values, subQuery);

                    listeners.preExecute(context);
                    stmt.executeUpdate();
                    listeners.executed(context);
                } else {
                    Collection<PreparedStatement> stmts = createStatements(true);
                    if (stmts != null && stmts.size() > 1) {
                        throw new IllegalStateException("executeWithKeys called with batch statement and multiple SQL strings");
                    }
                    stmt = stmts.iterator().next();
                    listeners.notifyMerges(entity, metadata, batches);

                    listeners.preExecute(context);
                    stmt.executeBatch();
                    listeners.executed(context);
                }

                final Statement stmt2 = stmt;
                ResultSet rs = stmt.getGeneratedKeys();
                return new ResultSetAdapter(rs) {
                    @Override
                    public void close() throws SQLException {
                        try {
                            super.close();
                        } finally {
                            stmt2.close();
                            reset();
                            endContext(context);
                        }
                    }
                };
            } else {
                if (hasRow()) {
                    // update
                    SQLUpdateClause update = new SQLUpdateClause(connection(), configuration, entity);
                    update.addListener(listeners);
                    populate(update);
                    addKeyConditions(update);
                    reset();
                    endContext(context);
                    return EmptyResultSet.DEFAULT;
                } else {
                    // insert
                    SQLInsertClause insert = new SQLInsertClause(connection(), configuration, entity);
                    insert.addListener(listeners);
                    populate(insert);
                    return insert.executeWithKeys();
                }
            }
        } catch (SQLException e) {
            onException(context,e);
            reset();
            endContext(context);
            throw configuration.translate(queryString, constants, e);
        }
    }
17119
public function batchExecute()
    {
        $results = $this->execute(new InvokeSpec($this->units, false))->getResults();

        // Make right order in sequence of results. It's required operation, because JSON-RPC2
        // specification define: "The Response objects being returned from a batch call MAY be returned
        // in any order within the Array. The Client SHOULD match contexts between the set of Request objects and the
        // resulting set of Response objects based on the id member within each Object."

        $callMap = [];
        foreach ($this->units as $index => $unit) {
            /** @var Invoke $unit */
            $callMap[$unit->getRawId()] = $index;
        }

        if (count($results) !== count($this->units)) {
            throw new InvalidResponseException();
        }

        $resultSequence = [];
        foreach ($results as $result) {
            if ($result instanceof Result) {
                /** @var Result $result */
                $resultSequence[ $callMap[$result->getId()] ] = $result->getResult();
            } elseif ($result instanceof Error) {
                /** @var Error $result */
                $resultSequence[ $callMap[$result->getId()] ] = $this->serverErrorMode === self::ERRMODE_EXCEPTION ? $result->getBaseException() : null;
            }
        }
        ksort($resultSequence);
        $this->units = [];

        return $resultSequence;
    }
849876
public function execute()
    {
        $stmt = $this->connection->prepare($this->getSQL());
        $stmt->execute($this->getParams());

        return $this->counting ? (int) $stmt->fetchColumn() : $stmt->fetchAll();
    }
1273658
@Override
    public int executeBatch()
    {
        Object connection = getConnection();
        // Create a hashset and populate data into it
        Pipeline pipeLine = null;
        if (isBoundTransaction())
        {
            pipeLine = ((Jedis) connection).pipelined();
        }
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    // delete can not be executed in batch
                    if (node.isInState(RemovedState.class))
                    {
                        onDelete(node.getData(), node.getEntityId(), pipeLine != null ? pipeLine : connection);
                    }
                    else
                    {

                        List<RelationHolder> relationHolders = getRelationHolders(node);
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                node.getDataClass());

                        onPersist(metadata, node.getData(), node.getEntityId(), relationHolders,
                                pipeLine != null ? pipeLine : connection);
                    }
                    node.handlePostEvent();
                }
            }
        }
        finally
        {
            //
            if (pipeLine != null)
            {
                pipeLine.sync(); // send I/O.. as persist call. so no need to
                                 // read
                // response?
            }
            onCleanup(connection);
        }

        return nodes.size();
    }
1062353
public int execute()
    {
        int executed = 0;
        final long now = now();
        for (Entry<Timer, Long> entry : entries()) {
            final Timer timer = entry.getKey();
            final Long expiration = entry.getValue();

            //  Dead timer, lets remove it and continue
            if (!timer.alive) {
                //  Remove it from the list of active timers.
                timers.remove(expiration, timer);
                continue;
            }
            //  Map is ordered, if we have to wait for current timer we can stop.
            if (expiration - now > 0) {
                break;
            }

            insert(timer);

            timer.handler.time(timer.args);
            ++executed;
        }
        return executed;
    }
455052
function executeBatches(bulkOperation, options, callback) {
  let numberOfCommandsToExecute = bulkOperation.s.batches.length;
  // Execute over all the batches
  for (let i = 0; i < bulkOperation.s.batches.length; i++) {
    executeBatch(bulkOperation, bulkOperation.s.batches[i], options, function(err) {
      // Count down the number of commands left to execute
      numberOfCommandsToExecute = numberOfCommandsToExecute - 1;

      // Execute
      if (numberOfCommandsToExecute === 0) {
        // Driver level error
        if (err) return handleCallback(callback, err);

        const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult);
        if (bulkOperation.handleWriteError(callback, writeResult)) return;

        return handleCallback(callback, null, writeResult);
      }
    });
  }
}
598029
def execute_batch
    check_closed

    cnt = 0

    if @bstmt
      cnt += @bstmt.execute_batch.inject(:+) || 0
      @spool.give @bstmt
      @bstmt = nil
    end

    @pstmts.each do |pstmt|
      cnt += pstmt.execute_batch
    end

    cnt
  end
137466
private PrepareResult executeBatchStandard(int estimatedParameterCount) throws SQLException {
    int totalExecutionNumber = getTotalExecutionNumber();
    SQLException exception = null;
    BulkStatus status = new BulkStatus();

    ComStmtPrepare comStmtPrepare = null;
    FutureTask<AsyncMultiReadResult> futureReadTask = null;

    int requestNumberByBulk;
    int paramCount = estimatedParameterCount;
    try {
      do {
        status.sendEnded = false;
        status.sendSubCmdCounter = 0;
        requestNumberByBulk = Math.min(totalExecutionNumber - status.sendCmdCounter,
            protocol.getOptions().useBatchMultiSendNumber);
        protocol.changeSocketTcpNoDelay(false); //enable NAGLE algorithm temporary.

        //add prepare sub-command
        if (readPrepareStmtResult && prepareResult == null) {

          comStmtPrepare = new ComStmtPrepare(protocol, sql);
          comStmtPrepare.send(writer);

          //read prepare result
          prepareResult = comStmtPrepare.read(protocol.getReader(), protocol.isEofDeprecated());
          statementId = ((ServerPrepareResult) prepareResult).getStatementId();
          paramCount = getParamCount();
        }

        boolean useCurrentThread = false;

        for (; status.sendSubCmdCounter < requestNumberByBulk; ) {
          sendCmd(writer, results, parametersList, queries, paramCount, status, prepareResult);
          status.sendSubCmdCounter++;
          status.sendCmdCounter++;
          if (useCurrentThread) {
            try {
              protocol.getResult(results);
            } catch (SQLException qex) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw qex;
              } else {
                exception = qex;
              }
            }
          } else if (futureReadTask == null) {
            try {
              futureReadTask = new FutureTask<>(new AsyncMultiRead(comStmtPrepare, status,
                  protocol, false, this, paramCount,
                  results, parametersList, queries, prepareResult));
              AbstractQueryProtocol.readScheduler.execute(futureReadTask);
            } catch (RejectedExecutionException r) {
              useCurrentThread = true;
              try {
                protocol.getResult(results);
              } catch (SQLException qex) {
                if (((readPrepareStmtResult && prepareResult == null) || !protocol
                    .getOptions().continueBatchOnError)) {
                  throw qex;
                } else {
                  exception = qex;
                }
              }
            }
          }
        }

        status.sendEnded = true;
        if (!useCurrentThread) {
          protocol.changeSocketTcpNoDelay(protocol.getOptions().tcpNoDelay);
          try {
            AsyncMultiReadResult asyncMultiReadResult = futureReadTask.get();

            if (binaryProtocol && prepareResult == null
                && asyncMultiReadResult.getPrepareResult() != null) {
              prepareResult = asyncMultiReadResult.getPrepareResult();
              statementId = ((ServerPrepareResult) prepareResult).getStatementId();
              paramCount = prepareResult.getParamCount();
            }

            if (asyncMultiReadResult.getException() != null) {
              if (((readPrepareStmtResult && prepareResult == null) || !protocol
                  .getOptions().continueBatchOnError)) {
                throw asyncMultiReadResult.getException();
              } else {
                exception = asyncMultiReadResult.getException();
              }
            }
          } catch (ExecutionException executionException) {
            if (executionException.getCause() == null) {
              throw new SQLException("Error reading results " + executionException.getMessage());
            }
            throw new SQLException(
                "Error reading results " + executionException.getCause().getMessage());
          } catch (InterruptedException interruptedException) {
            protocol.setActiveFutureTask(futureReadTask);
            Thread.currentThread().interrupt();
            throw new SQLException("Interrupted awaiting response ",
                INTERRUPTED_EXCEPTION.getSqlState(), interruptedException);
          } finally {
            //bulk can prepare, and so if prepare cache is enable, can replace an already cached prepareStatement
            //this permit to release those old prepared statement without conflict.
            protocol.forceReleaseWaitingPrepareStatement();
          }
        }

        if (protocol.isInterrupted()) {
          //interrupted during read, must throw an exception manually
          futureReadTask.cancel(true);
          throw new SQLTimeoutException("Timeout during batch execution");
        }
        futureReadTask = null;

      } while (status.sendCmdCounter < totalExecutionNumber);

      if (exception != null) {
        throw exception;
      }

      return prepareResult;

    } catch (IOException e) {
      status.sendEnded = true;
      status.sendCmdCounter = 0; //to ensure read doesn't hang
      throw protocol.handleIoException(e);
    }

  }
951458
@Override
	public int count() {
		try (Stream<?> paramStream = stream) {
			int count = paramStream.map(r -> {
				Map<String, Object> m = toMap(r);
				paramMap(m);
				context().addBatch();
				return condition.test(context(), m) ? executeBatch() : 0;
			}).reduce(0, (joined, element) -> joined + element);
			return count + (context().batchCount() != 0 ? executeBatch() : 0);
		} finally {
			stream = null;
			condition = DEFAULT_BATCH_WHEN_CONDITION;
			batchAction = DEFAULT_BATCH_ACTION;
			errorAction = DEFAULT_ERROR_ACTION;
		}
	}