Schedules a document for upsert into the database and adds it to the
identity map

@internal

@throws InvalidArgumentException
495989
public function scheduleForUpsert(ClassMetadata $class, object $document) : void
    {
        $oid = spl_object_hash($document);

        if ($class->isEmbeddedDocument) {
            throw new InvalidArgumentException('Embedded document can not be scheduled for upsert.');
        }
        if (isset($this->documentUpdates[$oid])) {
            throw new InvalidArgumentException('Dirty document can not be scheduled for upsert.');
        }
        if (isset($this->documentDeletions[$oid])) {
            throw new InvalidArgumentException('Removed document can not be scheduled for upsert.');
        }
        if (isset($this->documentUpserts[$oid])) {
            throw new InvalidArgumentException('Document can not be scheduled for upsert twice.');
        }

        $this->documentUpserts[$oid]     = $document;
        $this->documentIdentifiers[$oid] = $class->getIdentifierValue($document);
        $this->addToIdentityMap($document);
    }
777144
public function scheduleForUpdate($entity) : void
    {
        $oid = spl_object_id($entity);

        if (! isset($this->entityIdentifiers[$oid])) {
            throw ORMInvalidArgumentException::entityHasNoIdentity($entity, 'scheduling for update');
        }

        if (isset($this->entityDeletions[$oid])) {
            throw ORMInvalidArgumentException::entityIsRemoved($entity, 'schedule for update');
        }

        if (! isset($this->entityUpdates[$oid]) && ! isset($this->entityInsertions[$oid])) {
            $this->entityUpdates[$oid] = $entity;
        }
    }
230226
private function commitPersisted()
    {
        $sortedDocuments = $this->sortObjects($this->scheduledForPersist);
        $client = $this->sm->getClient();

        foreach ($sortedDocuments as $entityName => $documents) {
            $classMetadata = $this->sm->getClassMetadata($entityName);
            $this->updatedIndexes[] = $classMetadata->index;
            $client->addDocuments($classMetadata, $documents);
        }
    }
1091931
function insert() {
		if (isset($this->document['_id']))
			return $this->update();
		if (isset($this->trigger['beforeinsert']) &&
			\Base::instance()->call($this->trigger['beforeinsert'],
				[$this,['_id'=>$this->document['_id']]])===FALSE)
			return $this->document;
		if ($this->legacy) {
			$this->collection->insert($this->document);
			$pkey=['_id'=>$this->document['_id']];
		}
		else {
			$result=$this->collection->insertone($this->document);
			$pkey=['_id'=>$result->getinsertedid()];
		}
		if (isset($this->trigger['afterinsert']))
			\Base::instance()->call($this->trigger['afterinsert'],
				[$this,$pkey]);
		$this->load($pkey);
		return $this->document;
	}
217009
def bulk_upsert(self, docs, namespace, timestamp):
        
        if self.auto_commit_interval is not None:
            add_kwargs = {
                "commit": (self.auto_commit_interval == 0),
                "commitWithin": str(self.auto_commit_interval)
            }
        else:
            add_kwargs = {"commit": False}

        cleaned = (self._clean_doc(d, namespace, timestamp) for d in docs)
        if self.chunk_size > 0:
            batch = list(next(cleaned) for i in range(self.chunk_size))
            while batch:
                self.solr.add(batch, **add_kwargs)
                batch = list(next(cleaned)
                             for i in range(self.chunk_size))
        else:
            self.solr.add(cleaned, **add_kwargs)
448677
private function computeScheduleInsertsChangeSets() : void
    {
        foreach ($this->documentInsertions as $document) {
            $class = $this->dm->getClassMetadata(get_class($document));
            if ($class->isEmbeddedDocument) {
                continue;
            }

            $this->computeChangeSet($class, $document);
        }
    }
1206408
public function upsert($document, $parentPath = null)
    {
        $class     = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);

        if (!$class->isEmbeddedDocument) {
            $qb         = $this->dm->createQueryBuilder($class->name);
            $identifier = $class->createIdentifier($document);

            $qb->update();
            $qb->setIdentifier($identifier);
        } elseif ($parentPath === null) {
            throw new \InvalidArgumentException;
        }

        foreach ($changeset as $attributeName => $change) {
            if ($class->isIdentifier($attributeName)) {
                continue;
            }

            list($old, $new) = $change;

            $mapping            = $class->getPropertyMetadata($attributeName);
            $discriminatorValue = null;

            if ($mapping->embedded && $mapping->isOne()) {
                $embeddedClassName  = get_class($new);
                $embeddedClass      = $this->dm->getClassMetadata($embeddedClassName);
                $discriminatorValue = $embeddedClass->getEmbeddedDiscriminatorValue($mapping, $new);
                //@Many will set discriminator in updatePath
            }

            if ($class->isEmbeddedDocument) {
                $path = $parentPath->map($attributeName, $discriminatorValue);
            } else {
                $path = $qb->attr($attributeName, $discriminatorValue);
            }

            $this->updatePath($path, $old, $new, true);
        }

        // add discriminator if the class has one
        if ($class->discriminatorAttribute !== null) {
            if ($class->isEmbeddedDocument) {
                $path = $parentPath->map($class->discriminatorAttribute);
            } else {
                $path = $qb->attr($class->discriminatorAttribute);
            }

            $path->set(
                $class->discriminatorValue !== null
                    ? $class->discriminatorValue
                    : $class->name
            );
        }

        if ($this->class->isVersioned) {
            // Set the initial version. Only supported on top-level documents.

            $versionMapping = $this->class->getPropertyMetadata($this->class->versionAttribute);
            $nextVersion    = null;

            if ($versionMapping->type === Type::INT) {
                $nextVersion = max(1, (int)$versionMapping->getValue($document));
            } elseif ($versionMapping->isDateType()) {
                $nextVersion = new \DateTime();
            }

            $nextVersion = $versionMapping->getType()->convertToDatabaseValue($nextVersion);
            $versionMapping->setValue($document, $nextVersion);

            $qb->attr($versionMapping->name)->set($nextVersion);
        }

        //DynamoDB will upsert even if we only pass the id conditional with no UpdateExpression

        if (!$class->isEmbeddedDocument) {
            $qb->getQuery()->execute();
        }
    }
1303580
def upsert(self, doc, namespace, timestamp):
        
        database, coll = self._db_and_collection(namespace)

        meta_collection_name = self._get_meta_collection(namespace)

        self.meta_database[meta_collection_name].replace_one(
            {self.id_field: doc["_id"], "ns": namespace},
            {self.id_field: doc["_id"], "_ts": timestamp, "ns": namespace},
            upsert=True,
        )

        self.mongo[database][coll].replace_one({"_id": doc["_id"]}, doc, upsert=True)
576441
def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
    ''''''
    # Mongo does not allow mixing atomic modifiers and non-$set sets in the
    # same update, so the choice is to either run the first upsert on
    # {'_id':id} to ensure the record is in place followed by an atomic update
    # based on the series type, or use $set for all of the keys to be used in
    # creating the record, which then disallows setting our own _id because
    # that "can't be updated". So the tradeoffs are:
    #   * 2 updates for every insert, maybe a local cache of known _ids and the
    #     associated memory overhead
    #   * Query by the 2 or 3 key tuple for this interval and the associated
    #     overhead of that index match vs. the presumably-faster match on _id
    #   * Yet another index for the would-be _id of i_key or r_key, where each
    #     index has a notable impact on write performance.
    # For now, choosing to go with matching on the tuple until performance
    # testing can be done. Even then, there may be a variety of factors which
    # make the results situation-dependent.
    insert = {'name':name, 'interval':config['i_calc'].to_bucket(timestamp)}
    if not config['coarse']:
      insert['resolution'] = config['r_calc'].to_bucket(timestamp)
    # copy the query before expire_from as that is not indexed
    query = insert.copy()

    if config['expire']:
      insert['expire_from'] = datetime.utcfromtimestamp( timestamp )

    # switch to atomic updates
    insert = {'$set':insert.copy()}

    # need to hide the period of any values. best option seems to be to pick
    # a character that "no one" uses.
    if isinstance(value, (str,unicode)):
      value = value.replace('.', self._escape_character)
    elif isinstance(value, float):
      value = str(value).replace('.', self._escape_character)

    self._insert_type( insert, value )

    # TODO: use write preference settings if we have them
    if not kwargs.get('dry_run',False):
      self._client[interval].update( query, insert, upsert=True, check_keys=False )
    return query, insert
40805
public function preUpdate(ClassMetadata $class, $document)
    {
        if (!empty($class->lifecycleCallbacks[Event::preUpdate])) {
            $class->invokeLifecycleCallbacks(Event::preUpdate, $document, [
                new PreUpdateEventArgs($document, $this->dm, $this->uow->getDocumentChangeSet($document))
            ]);
            $this->uow->recomputeSingleDocumentChangeSet($class, $document);
        }
        $this->evm->dispatchEvent(Event::preUpdate, new PreUpdateEventArgs($document, $this->dm, $this->uow->getDocumentChangeSet($document)));
        $this->cascadePreUpdate($class, $document);
    }
1097401
private function insert() {
        if ($this->isPersistent()) throw new RuntimeException('Cannot insert already persistent '.$this);

        // pre-processing hook
        if ($this->beforeInsert() !== true)
            return $this;

        $mapping = $this->dao()->getMapping();

        // collect column values
        $values = [];
        foreach ($mapping['columns'] as $column => $property) {
            $values[$column] = $this->getPhysicalValue($column);
        };

        // perform insertion
        $id = $this->doInsert($values);
        $this->_modified = false;

        // assign the returned identity value
        $idName = $mapping['identity']['name'];
        if ($this->$idName === null)
            $this->$idName = $id;

        // post-processing hook
        $this->afterInsert();
        return $this;
    }
166114
private function executeUpserts(ClassMetadata $class, array $options = array())
    {
        $className = $class->name;
        $persister = $this->getDocumentPersister($className);
        $collection = $this->dm->getDocumentCollection($className);

        $upsertedDocuments = array();

        foreach ($this->documentUpserts as $oid => $document) {
            if (get_class($document) === $className) {
                $persister->addUpsert($document);
                $upsertedDocuments[] = $document;
                unset($this->documentUpserts[$oid]);
            }
        }

        $persister->executeUpserts($options);

        $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postPersist]);
        $hasListeners = $this->evm->hasListeners(Events::postPersist);

        foreach ($upsertedDocuments as $document) {
            if ($hasLifecycleCallbacks) {
                $class->invokeLifecycleCallbacks(Events::postPersist, $document);
            }
            if ($hasListeners) {
                $this->evm->dispatchEvent(Events::postPersist, new LifecycleEventArgs($document, $this->dm));
            }
            $this->cascadePostPersist($class, $document);
        }
    }
810656
private void setUpdateProperties(final String id, final JSONObject needUpdateJsonObject,
                                     final List<Object> paramList, final StringBuilder sql) throws JSONException {
        final Iterator<String> keys = needUpdateJsonObject.keys();
        String key;

        boolean isFirst = true;
        final StringBuilder wildcardString = new StringBuilder();

        while (keys.hasNext()) {
            key = keys.next();

            if (isFirst) {
                wildcardString.append(" SET ").append(key).append(" = ?");
                isFirst = false;
            } else {
                wildcardString.append(", ").append(key).append(" = ?");
            }

            paramList.add(needUpdateJsonObject.get(key));
        }

        sql.append("UPDATE ").append(getName()).append(wildcardString).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
        paramList.add(id);
    }
564637
function upsertWithLogging(tableName, instance, action, shouldOverwrite) {
        Validate.isString(tableName, 'tableName');
        Validate.notNullOrEmpty(tableName, 'tableName');

        Validate.notNull(instance, 'instance');
        Validate.isValidId(instance.id, 'instance.id');
        
        if (!store) {
            throw new Error('MobileServiceSyncContext not initialized');
        }
        
        return store.lookup(tableName, instance.id, true /* suppressRecordNotFoundError */).then(function(existingRecord) {
            if (existingRecord && !shouldOverwrite) {
                throw new Error('Record with id ' + existingRecord.id + ' already exists in the table ' + tableName);
            }
        }).then(function() {
            return operationTableManager.getLoggingOperation(tableName, action, instance);
        }).then(function(loggingOperation) {
            return store.executeBatch([
                {
                    action: 'upsert',
                    tableName: tableName,
                    data: instance
                },
                loggingOperation
            ]);
        }).then(function() {
            return instance;
        });
    }
1044332
public function computeSingleDocumentChangeSet($document)
    {
        $state = $this->getDocumentState($document);

        if ($state !== self::STATE_MANAGED && $state !== self::STATE_REMOVED) {
            throw new InvalidArgumentException('Document has to be managed for single computation '.self::objToStr($document, $this->dm));
        }

        foreach ($this->scheduledInserts as $insertedDocument) {
            $class = $this->dm->getClassMetadata(get_class($insertedDocument));
            $this->computeChangeSet($class, $insertedDocument);
        }

        // Ignore uninitialized proxy objects
        if ($document instanceof Proxy && !$document->__isInitialized()) {
            return;
        }

        $oid = spl_object_hash($document);
        if (!isset($this->scheduledInserts[$oid])) {
            $class = $this->dm->getClassMetadata(get_class($document));
            $this->computeChangeSet($class, $document);
        }
    }
288746
public function invokeLifecycleCallbacks(string $event, object $document, ?array $arguments = null) : void
    {
        if (! $document instanceof $this->name) {
            throw new InvalidArgumentException(sprintf('Expected document class "%s"; found: "%s"', $this->name, get_class($document)));
        }

        if (empty($this->lifecycleCallbacks[$event])) {
            return;
        }

        foreach ($this->lifecycleCallbacks[$event] as $callback) {
            if ($arguments !== null) {
                $document->$callback(...$arguments);
            } else {
                $document->$callback();
            }
        }
    }
211638
public function ensureDocumentIndexes(string $documentName, ?int $maxTimeMs = null, ?WriteConcern $writeConcern = null, bool $background = false) : void
    {
        $class = $this->dm->getClassMetadata($documentName);
        if ($class->isMappedSuperclass || $class->isEmbeddedDocument || $class->isQueryResultDocument) {
            throw new InvalidArgumentException('Cannot create document indexes for mapped super classes, embedded documents or query result documents.');
        }

        if ($class->isFile) {
            $this->ensureGridFSIndexes($class, $maxTimeMs, $writeConcern, $background);
        }

        $indexes = $this->getDocumentIndexes($documentName);
        if (! $indexes) {
            return;
        }

        $collection = $this->dm->getDocumentCollection($class->name);
        foreach ($indexes as $index) {
            $collection->createIndex($index['keys'], $this->getWriteOptions($maxTimeMs, $writeConcern, $index['options'] + ['background' => $background]));
        }
    }