Executes all queued document insertions.

Queued documents without an ID will inserted in a batch and queued
documents with an ID will be upserted individually.

If no inserts are queued, invoking this method is a NOOP.

@throws DriverException
505563
public function executeInserts(array $options = []) : void
    {
        if (! $this->queuedInserts) {
            return;
        }

        $inserts = [];
        $options = $this->getWriteOptions($options);
        foreach ($this->queuedInserts as $oid => $document) {
            $data = $this->pb->prepareInsertData($document);

            // Set the initial version for each insert
            if ($this->class->isVersioned) {
                $versionMapping = $this->class->fieldMappings[$this->class->versionField];
                $nextVersion    = null;
                if ($versionMapping['type'] === 'int') {
                    $nextVersion = max(1, (int) $this->class->reflFields[$this->class->versionField]->getValue($document));
                    $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersion);
                } elseif ($versionMapping['type'] === 'date') {
                    $nextVersionDateTime = new DateTime();
                    $nextVersion         = Type::convertPHPToDatabaseValue($nextVersionDateTime);
                    $this->class->reflFields[$this->class->versionField]->setValue($document, $nextVersionDateTime);
                }
                $data[$versionMapping['name']] = $nextVersion;
            }

            $inserts[] = $data;
        }

        if ($inserts) {
            try {
                assert($this->collection instanceof Collection);
                $this->collection->insertMany($inserts, $options);
            } catch (DriverException $e) {
                $this->queuedInserts = [];
                throw $e;
            }
        }

        /* All collections except for ones using addToSet have already been
         * saved. We have left these to be handled separately to avoid checking
         * collection for uniqueness on PHP side.
         */
        foreach ($this->queuedInserts as $document) {
            $this->handleCollections($document, $options);
        }

        $this->queuedInserts = [];
    }
197943
@Override
    public int executeBatch()
    {
        Map<String, List<Row>> batchData = new HashMap<String, List<Row>>();
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    Row action = null;
                    node.handlePreEvent();
                    Object rowKey = node.getEntityId();
                    Object entity = node.getData();
                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
                    String tableName = HBaseUtils.getHTableName(m.getSchema(), m.getTableName());
                    if (node.isInState(RemovedState.class))
                    {
                        action = handler.prepareDelete(rowKey);
                    }
                    else
                    {
                        HBaseRow hbaseRow = ((HBaseDataHandler) handler).createHbaseRow(m, entity, rowKey, null);
                        action = handler.preparePut(hbaseRow);
                    }
                    node.handlePostEvent();
                    if (!batchData.containsKey(tableName))
                    {
                        batchData.put(tableName, new ArrayList<Row>());
                    }
                    batchData.get(tableName).add(action);
                }
            }

            if (!batchData.isEmpty())
            {
                ((HBaseDataHandler) handler).batchProcess(batchData);
            }
            return batchData.size();
        }
        catch (IOException ioex)
        {
            log.error("Error while executing batch insert/update, Caused by: .", ioex);
            throw new KunderaException(ioex);
        }

    }
664060
public void serializeInsert(QueryMetadata metadata, RelationalPath<?> entity,
                                List<SQLInsertBatch> batches, SQLSerializer context) {
        context.serializeForInsert(metadata, entity, batches);

        if (!metadata.getFlags().isEmpty()) {
            context.serialize(Position.END, metadata.getFlags());
        }
    }
119094
private void executeBatchRewrite(Results results,
      final ClientPrepareResult prepareResult, List<ParameterHolder[]> parameterList,
      boolean rewriteValues) throws SQLException {

    cmdPrologue();

    ParameterHolder[] parameters;
    int currentIndex = 0;
    int totalParameterList = parameterList.size();

    try {

      do {

        currentIndex = ComQuery.sendRewriteCmd(writer, prepareResult.getQueryParts(), currentIndex,
            prepareResult.getParamCount(), parameterList, rewriteValues);
        getResult(results);

        if (Thread.currentThread().isInterrupted()) {
          throw new SQLException("Interrupted during batch", INTERRUPTED_EXCEPTION.getSqlState(),
              -1);
        }

      } while (currentIndex < totalParameterList);

    } catch (SQLException sqlEx) {
      throw logQuery.exceptionWithQuery(sqlEx, prepareResult);
    } catch (IOException e) {
      throw handleIoException(e);
    } finally {
      results.setRewritten(rewriteValues);
    }
  }
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);
        }
    }
738505
private function doInsertByQueries(): void
    {
        $data = $this->generateFakeData();

        $queryBuilder = $this->dbUtils->getConn()->createQueryBuilder();
        $queryBuilder = $queryBuilder->insert($this->entity);
        foreach ($data as $field => $value) {
            $queryBuilder = $queryBuilder->setValue($field, ":$field");
            $queryBuilder = $queryBuilder->setParameter(":$field", $value);
        }

        $this->returnRes === true ?
            array_push($this->queries, $this->dbUtils->getRawSQL($queryBuilder)) :
            null;

        if ($this->pretend === false) {
            $queryBuilder->execute();
        }
    }
569774
private void executeInserts() throws EFapsException
    {
        ConnectionResource con = null;
        try {
            final Insert insert = (Insert) runnable;
            con = Context.getThreadContext().getConnectionResource();
            long id = 0;
            for (final Entry<SQLTable, AbstractSQLInsertUpdate<?>> entry : updatemap.entrySet()) {
                if (id != 0) {
                    entry.getValue().column(entry.getKey().getSqlColId(), id);
                }
                if (entry.getKey().getSqlColType() != null) {
                    entry.getValue().column(entry.getKey().getSqlColType(), insert.getType().getId());
                }
                final Long created = ((SQLInsert) entry.getValue()).execute(con);
                if (created != null) {
                    id = created;
                    insert.evaluateInstance(created);
                }
            }
        } catch (final SQLException e) {
            throw new EFapsException(SQLRunner.class, "executeOneCompleteStmt", e);
        }
    }
147221
public void insert(QueryParameters params) throws SQLException {
        getCurrentResultSet().moveToInsertRow();

        updateResultSetCurrentLine(getCurrentResultSet(), params);
        getCurrentResultSet().insertRow();

        getCurrentResultSet().moveToCurrentRow();
    }
238734
private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap)
    {
        if (!bulkWriteOperationMap.isEmpty())
        {
            for (BulkWriteOperation builder : bulkWriteOperationMap.values())
            {
                try
                {
                    builder.execute(getWriteConcern());
                }
                catch (BulkWriteException bwex)
                {
                    log.error("Batch insertion is not performed due to error in write command. Caused By: ", bwex);
                    throw new KunderaException(
                            "Batch insertion is not performed due to error in write command. Caused By: ", bwex);
                }
                catch (MongoException mex)
                {
                    log.error("Batch insertion is not performed. Caused By: ", mex);
                    throw new KunderaException("Batch insertion is not performed. Caused By: ", mex);
                }
            }
        }
    }
328316
public ResultSet executeWithKeys() {
        context = startContext(connection(), metadata, entity);
        try {
            PreparedStatement stmt = null;
            if (batches.isEmpty()) {
                stmt = createStatement(true);
                listeners.notifyInsert(entity, metadata, columns, values, subQuery);

                listeners.preExecute(context);
                stmt.executeUpdate();
                listeners.executed(context);
            } else if (batchToBulk) {
                stmt = createStatement(true);
                listeners.notifyInserts(entity, metadata, batches);

                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.notifyInserts(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);
                    }
                }
            };
        } catch (SQLException e) {
            onException(context, e);
            reset();
            endContext(context);
            throw configuration.translate(queryString, constants, e);
        }
    }
1268249
public function flush()
    {
        $insert = array();
        $update = array();
        $delete = array();

        // fill batch objects
        foreach ($this->pool as $document) {
            /* @var $document \Sokil\Mongo\Document */

            // collection
            $collection = $document->getCollection();
            $collectionName = $collection->getName();

            // persisting
            switch ($this->pool->offsetGet($document)) {
                case self::STATE_SAVE:
                    if ($document->isStored()) {
                        if (!isset($update[$collectionName])) {
                            $update[$collectionName] = new \MongoUpdateBatch($collection->getMongoCollection());
                        }
                        $update[$collectionName]->add(array(
                            'q' => array(
                                '_id' => $document->getId(),
                            ),
                            'u' => $document->getOperator()->toArray(),
                        ));
                    } else {
                        if (!isset($insert[$collectionName])) {
                            $insert[$collectionName] = new \MongoInsertBatch($collection->getMongoCollection());
                        }
                        $insert[$collectionName]->add($document->toArray());
                    }
                    break;

                case self::STATE_REMOVE:
                    // delete document form db
                    if ($document->isStored()) {
                        if (!isset($delete[$collectionName])) {
                            $delete[$collectionName] = new \MongoDeleteBatch($collection->getMongoCollection());
                        }
                        $delete[$collectionName]->add(array(
                            'q' => array(
                                '_id' => $document->getId(),
                            ),
                            'limit' => 1,
                        ));
                    }
                    // remove link form pool
                    $this->detach($document);
                    break;
            }
        }

        // write operations
        $writeOptions = array('w' => 1);
        
        // execute batch insert operations
        if ($insert) {
            foreach ($insert as $collectionName => $collectionInsert) {
                $collectionInsert->execute($writeOptions);
            }
        }

        // execute batch update operations
        if ($update) {
            foreach ($update as $collectionName => $collectionUpdate) {
                $collectionUpdate->execute($writeOptions);
            }
        }

        // execute batch delete operations
        if ($delete) {
            foreach ($delete as $collectionName => $collectionDelete) {
                $collectionDelete->execute($writeOptions);
            }
        }

        return $this;
    }
54823
private function internalInsert()
    {
        if ($this->triggerEvent(self::EVENT_NAME_BEFORE_INSERT)->isCancelled()) {
            return;
        }

        $document = $this->toArray();

        // try write document
        try {
            $this
                ->collection
                ->getMongoCollection()
                ->insert($document);
        } catch (\Exception $e) {
            throw new WriteException(
                $e->getMessage(),
                $e->getCode(),
                $e
            );
        }

        // set id
        $this->defineId($document['_id']);

        // after insert event
        $this->triggerEvent(self::EVENT_NAME_AFTER_INSERT);
    }
495382
@Override
    public int executeBatch()
    {
        List<JsonObject> objectsToPersist = new ArrayList<JsonObject>();
        HttpResponse response = null;
        String databaseName = null;
        boolean isbulk = false;
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    // delete can not be executed in batch
                    if (node.isInState(RemovedState.class))
                    {
                        delete(node.getData(), node.getEntityId());
                    }
                    else
                    {
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                node.getDataClass());
                        databaseName = metadata.getSchema();
                        JsonObject asJsonObject = CouchDBObjectMapper.getJsonOfEntity(metadata, node.getData(),
                                node.getEntityId(), getRelationHolders(node), kunderaMetadata);
                        objectsToPersist.add(asJsonObject);
                        isbulk = true;
                    }
                    node.handlePostEvent();
                }
            }

            if (isbulk)
            {
                try
                {
                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                            CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()
                                    + CouchDBConstants.URL_SEPARATOR + "_bulk_docs", null, null);

                    HttpPost post = new HttpPost(uri);
                    String object = String.format("{%s%s}", "\"all_or_nothing\": true,",
                            "\"docs\": " + gson.toJson(objectsToPersist));
                    StringEntity entity = new StringEntity(object, "UTF-8");
                    entity.setContentType("application/json");
                    post.setEntity(entity);
                    response = httpClient.execute(httpHost, post, CouchDBUtils.getContext(httpHost));
                }
                catch (Exception e)
                {
                    log.error("Error while executing batch, caused by {}. ", e);
                    throw new KunderaException("Error while executing batch. caused by :" + e);
                }
            }
        }
        catch (OperationNotSupportedException e)
        {
            throw new KunderaException(e.getMessage());
        }
        finally
        {
            CouchDBUtils.closeContent(response);
        }

        return nodes.size();
    }
251417
private function executeInserts(ClassMetadata $class, array $documents, array $options = []) : void
    {
        $persister = $this->getDocumentPersister($class->name);

        foreach ($documents as $oid => $document) {
            $persister->addInsert($document);
            unset($this->documentInsertions[$oid]);
        }

        $persister->executeInserts($options);

        foreach ($documents as $document) {
            $this->lifecycleEventManager->postPersist($class, $document);
        }
    }
883902
private void execute(Map<Key, List<TableOperation>> batches)
    {
        if (batches != null && !batches.isEmpty())
        {
            try
            {
                for (List<TableOperation> batch : batches.values())
                {
                    tableAPI.execute(batch, null);
                }
            }
            catch (DurabilityException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            catch (TableOpExecutionException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            catch (FaultException e)
            {
                log.error("Error while executing operations in OracleNOSQL, Caused by:" + e + ".");
                throw new PersistenceException("Error while Persisting data using batch", e);
            }
            finally
            {
                batches.clear();
            }
        }
    }
628524
public void insert(Platform platform, Database model, int batchSize) throws SQLException
    {
        if (batchSize <= 1)
        {
            for (Iterator it = _beans.iterator(); it.hasNext();)
            {
                platform.insert(model, (DynaBean)it.next());
            }
        }
        else
        {
            for (int startIdx = 0; startIdx < _beans.size(); startIdx += batchSize)
            {
                platform.insert(model, _beans.subList(startIdx, startIdx + batchSize));
            }
        }
    }
848231
public function run_insert($sql, array $params=null, $seqName=null, array $driverOptions=array()) {
		
		#$this->sth = $this->dbh->prepare($sql, $driverOptions);
		#$this->sth->execute($params);
		$numRows = $this->run_query($sql, $params, $driverOptions);
		
		if($numRows > 0 && is_object($this->dbh)) {
			$retval = $this->dbh->lastInsertId($seqName);
		}
		else {
			throw new \Exception(__METHOD__ .": insert failed");
		}
		
		#$retval = $this->dbh->lastInsertId($seqName);
		return($retval);
	}