/*
(non-Javadoc)

@see
com.impetus.client.hbase.admin.DataHandler#batchProcess(java.util.Map)
492434
@Override
    public void batchProcess(Map<String, List<Row>> batchData)
    {
        for (String tableName : batchData.keySet())
        {
            List<Row> actions = batchData.get(tableName);
            try
            {
                Table hTable = gethTable(tableName);
                hTable.batch(actions, new Object[actions.size()]);
            }
            catch (IOException | InterruptedException e)
            {
                logger.error("Error while batch processing on HTable: " + tableName);
                throw new PersistenceException(e);
            }

        }

    }
1332232
private void doBatchStart(final JsonObject message) {
    if (currentBatch != null) {
      currentBatch.handleEnd(null);
    }
    String batchID = message.getString("batch");
    Object args = deserializer.deserialize(message);
    if (log.isDebugEnabled()) {
      log.debug(String.format("%s - Batch started: Batch[batch=%s, args=%s]", this, batchID, args));
    }
    currentBatch = new DefaultConnectionInputBatch(batchID, this);
    if (batchHandler != null) {
      batchHandler.handle(currentBatch);
    }
    currentBatch.handleStart(args);
  }
420120
@Override
	public final void addBatch(String s) throws SQLException {
		batchSql.add(s);

		stmt.addBatch(s);
	}
601898
public int[] updateBatch(@SQL @NotNull String sql, @NotNull List<? extends  List<?>> argumentLists) {
        SqlQuery query = SqlQuery.query(sql, "<batch-update>");

        return withCurrentTransaction(query, tx -> {
            logQuery(query);

            try (PreparedStatement ps = tx.getConnection().prepareStatement(sql)) {
                bindQueryParameters(ps, query);
                for (List<?> arguments : argumentLists) {
                    bindArguments(ps, arguments);
                    ps.addBatch();
                }
                long startTime = currentTimeMillis();
                int[] counts = ps.executeBatch();
                logQueryExecution(query, currentTimeMillis() - startTime);
                return counts;
            }
        });
    }
566667
@Override
    public void run(final Iterable<Object[]> buffer) throws Exception {

        final UpdateableDatastoreConnection con = datastore.openConnection();
        try {
            final Column[] columns = con.getSchemaNavigator().convertToColumns(schemaName, tableName, columnNames);

            if (logger.isDebugEnabled()) {
                logger.debug("Inserting into columns: {}", Arrays.toString(columns));
            }

            final UpdateableDataContext dc = con.getUpdateableDataContext();
            dc.executeUpdate(new BatchUpdateScript() {
                @Override
                public void run(UpdateCallback callback) {
                    int insertCount = 0;
                    for (Object[] rowData : buffer) {
                        RowInsertionBuilder insertBuilder = callback.insertInto(columns[0].getTable());
                        for (int i = 0; i < columns.length; i++) {
                            insertBuilder = insertBuilder.value(columns[i], rowData[i]);
                        }

                        if (logger.isDebugEnabled()) {
                            logger.debug("Inserting: {}", Arrays.toString(rowData));
                        }

                        try {
                            insertBuilder.execute();
                            insertCount++;
                            _writtenRowCount.incrementAndGet();
                        } catch (final RuntimeException e) {
                            errorOccurred(rowData, e);
                        }
                    }

                    if (insertCount > 0) {
                        _componentContext.publishMessage(new ExecutionLogMessage(insertCount
                                + " inserts executed"));
                    }
                }
            });

        } finally {

            con.close();
        }
    }
1149483
@Override
    public List<DataSet> batchBy(int num) {
        List<DataSet> batched = Lists.newArrayList();
        for (List<DataSet> splitBatch : Lists.partition(asList(), num)) {
            batched.add(DataSet.merge(splitBatch));
        }
        return batched;
    }
161573
private function doSourceReprocess($batchLimit, $batchCount, $params, $output)
    {
        $timeStart = microtime(true);

        do {
            // 1) Get MAX(date_added) records where reprocess_flag = 1
            $batchStart = microtime(true);
            $params     = $this->getDateParams($params, 'MauticContactLedgerBundle:CampaignSourceStats');

            if ('invalid' == $params['dateFrom']) {
                $output->writeln(
                    '<comment>Exiting without Running. Reprocess Cron has re-written all history for Source (no more reprocessFlag = true). </comment>'
                );
                $batchCount = $batchLimit;
            } else {
                $output->writeln(
                    '<comment>Batch Index: '.(int) $batchCount."  --> Using Parameters:\n \tDate => ".$params['dateFrom'].' and '.$params['dateTo']." UTC,\n \tQuery Cache Directory => ".$params['cacheDir'].'</comment>'
                );

                // 2) Get entities that match date_added
                $entitiesToReprocess = $this->getEntitiesToReprocess($params, 'MauticContactLedgerBundle:CampaignSourceStats');

                // 3) reprocess data using this new date criteria
                $statData = $this->getCampaignSourceStatsData($params);

                foreach ($statData as $stat) {
                    $entity = $this->mapSourceArrayToEntity($stat, $params['dateTo']);
                    $entity->setReprocessFlag(false);
                    $this->em->persist($entity);
                }

                // 4) purge records from step 2
                foreach ($entitiesToReprocess as $entityToDelete) {
                    $this->em->remove($entityToDelete);
                }

                // 5) flush and repeat
                $this->em->flush();
                $timeContext = microtime(true);
                $contextTime = $timeContext - $timeStart;
                $batchRun    = $timeContext - $batchStart;
                $output->writeln(
                    "<comment>\t⌛ Batch Run Time: ".$batchRun.'  --> Total Elapsed time so far: '.$contextTime.'.</comment>'
                );
            }
            ++$batchCount;
        } while ($batchCount < $batchLimit);

        $this->completeRun();

        $output->writeln('<info>Complete With No Errors.</info>');
        $timeEnd     = microtime(true);
        $elapsedTime = $timeEnd - $timeStart;
        $output->writeln("<info>Total Execution Time: $elapsedTime.</info>");
    }
463568
public void batch(List<? extends Row> actions, @Nullable Object[] results)
      throws IOException, InterruptedException {
    if (results == null) {
      results = new Object[actions.size()];
    }
    batchCallback(actions, results, null);
  }
237927
protected void batchHandle(Iterable<?> entities, BatchType batchType,
			int batchSize) {
		Session session = getCurrentSession();
		Iterator<?> it = entities.iterator();
		int count = 0;
		while (it.hasNext()) {
			count++;
			Object entity = it.next();
			switch (batchType) {
			case SAVE:
				session.save(entity);
				break;
			case UPDATE:
				session.update(entity);
				break;
			case SAVE_OR_UPDATE:
				session.saveOrUpdate(entity);
				break;
			case DELETE:
				session.delete(entity);
				break;
			}
			if (count % batchSize == 0) {
				session.flush();
				session.clear();
			}
		}
	}
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();
    }
786188
public void processEvent(QueryBatch batch) {
    if ( ! (batch.getClient() instanceof DatabaseClientImpl) ) {
      throw new IllegalStateException("DatabaseClient must be instanceof DatabaseClientImpl");
    }
    StringHandle uris = new StringHandle(String.join("\n", batch.getItems()))
      .withMimetype("text/uri-list");
    RESTServices services = ((DatabaseClientImpl) batch.getClient()).getServices();
    try {
      RequestParameters params = new RequestParameters();
      if ( transform != null ) transform.merge(params);
      params.add("result", applyResult.toString().toLowerCase());
      List<String> responseUris = new BufferedReader(
        services.postResource(null, "internal/apply-transform", null, params, uris, new ReaderHandle()).get()
      ).lines().collect(Collectors.toList());
      QueryBatchImpl processedBatch = new QueryBatchImpl()
        .withClient( batch.getClient() )
        .withItems( responseUris.toArray(new String[responseUris.size()]) )
        .withTimestamp( batch.getTimestamp() )
        .withJobBatchNumber( batch.getJobBatchNumber() )
        .withJobResultsSoFar( batch.getJobResultsSoFar() )
        .withForestBatchNumber( batch.getForestBatchNumber() )
        .withForestResultsSoFar( batch.getForestResultsSoFar() )
        .withForest( batch.getForest() )
        .withServerTimestamp( batch.getServerTimestamp() )
        .withJobTicket( batch.getJobTicket() );
      for ( QueryBatchListener listener : successListeners ) {
        try {
          listener.processEvent(processedBatch);
        } catch (Throwable t) {
          logger.error("Exception thrown by an onSuccess listener", t);
        }
      }

      List<String> skippedRequestUris = new ArrayList<>(Arrays.asList(batch.getItems()));
      skippedRequestUris.removeAll( responseUris );
      if ( skippedRequestUris.size() > 0 ) {
        QueryBatchImpl skippedBatch = processedBatch
          .withItems( skippedRequestUris.toArray(new String[0]) );
        for ( QueryBatchListener listener : skippedListeners ) {
          try {
            listener.processEvent(skippedBatch);
          } catch (Throwable t) {
            logger.error("Exception thrown by an onSkipped listener", t);
          }
        }
      }
    } catch (Throwable t) {
      for ( BatchFailureListener<Batch<String>> listener : failureListeners ) {
        try {
          listener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onBatchFailure listener", t2);
        }
      }
      for ( BatchFailureListener<QueryBatch> queryBatchFailureListener : queryBatchFailureListeners ) {
        try {
          queryBatchFailureListener.processFailure(batch, t);
        } catch (Throwable t2) {
          logger.error("Exception thrown by an onFailure listener", t2);
        }
      }
      logger.warn("Error: {} in batch with urs ({})", t.toString(),
        Arrays.asList(batch.getItems()));
    }
  }
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);
		}
	}
1370595
public JSONObject batch(List<JSONObject> actions, RequestOptions requestOptions) throws AlgoliaException {
    return postBatch(actions, requestOptions);
  }
877816
public void executeBatchIfNecessary() throws OJBBatchUpdateException
    {
        if (batchCon != null)
        {
            try
            {
                batchCon.executeBatchIfNecessary();
            }
            catch (Throwable th)
            {
                throw new OJBBatchUpdateException(th);
            }
        }
    }
685477
function executeBatch(bulkOperation, batch, options, callback) {
  function resultHandler(err, result) {
    // Error is a driver related error not a bulk op error, terminate
    if (((err && err.driver) || (err && err.message)) && !(err instanceof MongoWriteConcernError)) {
      return handleCallback(callback, err);
    }

    // If we have and error
    if (err) err.ok = 0;
    if (err instanceof MongoWriteConcernError) {
      return handleMongoWriteConcernError(batch, bulkOperation.s.bulkResult, false, err, callback);
    }
    handleCallback(
      callback,
      null,
      mergeBatchResults(false, batch, bulkOperation.s.bulkResult, err, result)
    );
  }

  bulkOperation.finalOptionsHandler({ options, batch, resultHandler }, callback);
}
1193075
@WithBridgeMethods(value = SQLDeleteClause.class, castRequired =  true)
    public C addBatch() {
        batches.add(metadata);
        metadata = new DefaultQueryMetadata();
        metadata.addJoin(JoinType.DEFAULT, entity);
        metadata.setValidatingVisitor(validatingVisitor);
        return (C) this;
    }
80523
function BatchResult(tableService, table, operations) {
  this.tableService = tableService;
  this.table = table;
  this.operations = operations;
  this.batchBoundary = 'batch_' + BatchResult._getBoundary();
  this.changesetBoundary = 'changeset_' + BatchResult._getBoundary();
}