Inserts or updates entity based on identifier
@return boolean
177022
public function save() {

		if(null === $this -> getAdapter()) {
			return trigger_error('Adapter is not set. Set the adapter with the setAdapter() method', E_USER_ERROR);
		}

		//Execute user defined before save function
		$this -> beforeSave();

		$class   = new \ReflectionClass(get_class($this));
		$values  = $this -> toArray();
		$columns = [];

		array_walk($values, function($a, $b) use (&$columns, &$values) { 

			if(true === in_array($b, $this -> exclude)) {
				
				unset($values[$b]);
				return;
			}

			if($a instanceof DateTime) {
				$values[$b] = $a -> loadFormat();
			}

			if(true === is_array($a)) {
				$values[$b] = json_encode($a);
			}

			$columns[] = sprintf('`%s` = VALUES(`%s`)', $this -> getAdapter() -> escape($b), $this -> getAdapter() -> escape($b));
		});

		//Convert column names to column names with backtics
		foreach($values as $column => $value) {
			
			$values['`' . $column . '`'] = $value;
			unset($values[$column]);
		}

		$query = sprintf('INSERT INTO %s (%s) VALUES(%s) ON DUPLICATE KEY UPDATE %s', $this -> getAdapter() -> escape($this -> getTable()), implode(array_keys($values), ', '), implode(array_fill(0, count($values), '?'), ','), implode($columns, ', '));

		$this -> getAdapter() -> query($query, array_values($values));

		$success = $this -> getAdapter() -> execute();
		
		//Set new id if last id is not null
		$id  		= $this -> getAdapter() -> getLastId();
		$ids 		= $this -> getIdentifier();
		$affected 	= $this -> getAdapter() -> getAffected();

		if(count($ids) > 0 && $affected > 0) {

			$method = sprintf('set%s', NameConvert :: toCamelcase($ids[0], true));

			if(true === method_exists($this, $method)) {
				call_user_func_array([$this, $method], [$id]);
			}
		}

		//Execute user defined after save function
		$this -> afterSave();

		return $success;
	}
1155214
protected function insert()
    {
        $aggregate = $this->aggregate;

        $attributes = $aggregate->getRawAttributes();

        $keyName = $aggregate->getEntityMap()->getKeyName();

        // Check if the primary key is defined in the attributes
        if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
            $this->query->insert($attributes);
        } else {
            // Prevent inserting with a null ID
            if (array_key_exists($keyName, $attributes)) {
                unset($attributes[$keyName]);
            }

            if (isset($attributes['attributes'])) {
                unset($attributes['attributes']);
            }

            $id = $this->query->insertGetId($attributes, $keyName);

            $aggregate->setEntityAttribute($keyName, $id);
        }
    }
817728
public function idExists($identifer = null)
    {
        if (is_null($identifer)) {
            $identifer = $this->getMyKey();
        }
        $ignorestate = $this->ignore404();
        $this->ignore404(true);
        $cands       = $this->getFlexiData(null,
            [
                'detail' => 'custom:'.$this->getKeyColumn(),
                $this->getKeyColumn() => $identifer
        ]);
        $this->ignore404($ignorestate);
        return ($this->lastResponseCode == 200) && !empty($cands);
    }
973601
function insert_identity($data)
    {
        if (!$this->ID)
            return false;

        unset($data['user_id']);

        $insert_cols   = array();
        $insert_values = array();

        foreach ((array)$data as $col => $value) {
            $insert_cols[]   = $this->db->quote_identifier($col);
            $insert_values[] = $value;
        }

        $insert_cols[]   = $this->db->quote_identifier('user_id');
        $insert_values[] = $this->ID;

        $sql = "INSERT INTO ".$this->db->table_name('identities', true).
            " (`changed`, ".join(', ', $insert_cols).")".
            " VALUES (".$this->db->now().", ".join(', ', array_pad(array(), count($insert_values), '?')).")";

        $insert = $this->db->query($sql, $insert_values);

        // clear the cache
        $this->identities = array();
        $this->emails     = null;

        return $this->db->insert_id('identities');
    }
917795
public function update()
    {
        $conditions = $this->infosMergeds['fields_and_values'];

        $this->sql = new PhiberQueryWriter("update", [
            "table"  => $this->table,
            "fields" => $this->fields,
            "values" => $this->fieldsValues,
            "where"  => isset($this->infosMergeds['where']) ?
                $this->infosMergeds['where'] :
                null,
            "limit"  => isset($this->infosMergeds['limit']) ?
                $this->infosMergeds['limit'] :
                null,
            "offset"  => isset($this->infosMergeds['offset']) ?
                $this->infosMergeds['offset'] :
                null
        ]);

        if ($this->phiberConfig->verifyExecuteQueries()) {

            $this->PDO = $this->PDO->prepare($this->sql);
            for ($i = 0; $i < count($this->fields); $i++) {
                if (!empty($this->fieldsValues[$i])) {
                    $this->PDO->bindValue($this->fields[$i], $this->fieldsValues[$i]);
                }
            }

            while (current($conditions)) {
                $this->PDO->bindValue(
                    "condition_" . key($conditions), 
                    $conditions[key($conditions)]
                );
                
                next($conditions);
            }

            if ($this->PDO->execute()) {
                return true;
            }
        }

        return false;
    }
1333218
private function getPreparedInsertUpdate()
    {
        if (is_null($this->preparedInsertUpdate)) {
            $this->preparedInsertUpdate = $this->getServer()
                ->insert($this->tableName)
                ->set($this->keyColumnName, ':id')
                ->set($this->valueColumnName, ':value')
                ->set($this->expireColumnName, ':expire')
                ->onDuplicateKey($this->keyColumnName)
                ->set($this->valueColumnName, ':newValue')
                ->set($this->expireColumnName, ':newExpire');
        }

        return $this->preparedInsertUpdate;
    }
964827
protected function storeEntity()
    {
        $request = $this->getRequest();
        $id = $request->getParameter('id');
        // Try to find an existing instance of the entity.
        $entity = NULL;
        try {
            $entity = $this->getFactory()->findEntity($id);
        } catch (NotFoundException $exception) {
            // Not found? Create it.
            $className = $this->getFactory()->getEntitiesClassName();
            $entity = new $className(array(
                'id' => $id,
            ));
        }


        // Get the data from the request.
        $dataFromRequest = $this->getEntityDataFromRequest();
        if ($this->nullsIgnoredOnStore) {
            // Remove unspecified values, so that they are not modified.
            $dataFromRequest = array_filter(
                $dataFromRequest,
                function ($value) {
                    return !is_null($value);
                }
            );
        }
        // Update the product from the request data.
        $entity->update($dataFromRequest);
        // Store the entity.
        $entity->store();

        return $entity;
    }
465565
public function update($entity)
    {
        $identifier = $this->getIdentifier($entity);
        $data       = $this->builder->reduce($entity);

        $this->connection->update($this->tableName, $data, $identifier);

        $this->builder->resolve($entity);
    }
991974
public function update()
	{
		$db = \App::get('db');

		if (empty($db))
		{
			return false;
		}

		if (!is_numeric($this->gidNumber))
		{
			return false;
		}

		if (empty($this->_updatedkeys))
		{
			return true;
		}

		$query = "UPDATE `#__xgroups` SET ";

		$classvars = get_class_vars(__CLASS__);

		$first = true;
		$affected = 0;

		foreach ($classvars as $property => $value)
		{
			if (($property{0} == '_') || in_array($property, self::$_list_keys))
			{
				continue;
			}

			if (!in_array($property, $this->_updatedkeys))
			{
				continue;
			}

			if (!$first)
			{
				$query .= ',';
			}
			else
			{
				$first = false;
			}

			$value = $this->$property;

			if ($value === null)
			{
				$query .= "`$property`=NULL";
			}
			else
			{
				$query .= "`$property`=" . $db->quote($value);
			}
		}

		$query .= " WHERE `gidNumber`=" . $db->quote($this->gidNumber) . ";";

		if (($first != true) && !empty($query))
		{
			$db->setQuery($query);

			$result = $db->query();

			if ($result === false)
			{
				return false;
			}

			$affected = $db->getAffectedRows();
		}

		$aNewUserGroupEnrollments = array();

		foreach (self::$_list_keys as $property)
		{
			if (!in_array($property, $this->_updatedkeys))
			{
				continue;
			}

			$aux_table = "#__xgroups_" . $property;

			$list = $this->$property;

			if (!is_null($list) && !is_array($list))
			{
				$list = array($list);
			}

			$ulist = null;
			$tlist = null;

			foreach ($list as $value)
			{
				if (!is_null($ulist))
				{
					$ulist .= ',';
					$tlist .= ',';
				}

				$ulist .= $db->quote($value);
				$tlist .= '(' . $db->quote($this->gidNumber) . ',' . $db->quote($value) . ')';
			}

			// @FIXME: I don't have a better solution yet. But the next refactoring of this class
			// should eliminate the ability to read the entire member table due to problems with
			// scale on a large (thousands of members) groups. The add function should track the members
			// being added to a group, but would need to be verified to handle adding members
			// already in group. *njk*

			// @FIXME: Not neat, but because all group membership is resaved every time even for single additions
			// there is no nice way to detect only *new* additions without this check. I don't want to
			// fire off an 'onUserGroupEnrollment' event for users unless they are really being enrolled. *drb*

			if (in_array($property, array('members', 'managers')))
			{
				$query = "SELECT uidNumber FROM `#__xgroups_members` WHERE gidNumber=" . $this->gidNumber;
				$db->setQuery($query);

				// compile current list of members in this group
				$aExistingUserMembership = array();

				if (($results = $db->loadAssoc()))
				{
					foreach ($results as $uid)
					{
						$aExistingUserMembership[] = $uid;
					}
				}

				// see who is new, merge with previous additions so we have a complete list after we are done
				$aNewUserGroupEnrollments = array_merge($aNewUserGroupEnrollments, array_diff($list, $aExistingUserMembership));

			}

			if (is_array($list) && count($list) > 0)
			{
				if (in_array($property, array('members', 'managers', 'applicants', 'invitees')))
				{
					$query = "REPLACE INTO $aux_table (gidNumber,uidNumber) VALUES $tlist;";
				}

				$db->setQuery($query);

				if ($db->query())
				{
					$affected += $db->getAffectedRows();
				}
			}

			if (!is_array($list) || count($list) == 0)
			{
				if (in_array($property, array('members', 'managers', 'applicants', 'invitees')))
				{
					$query = "DELETE FROM $aux_table WHERE gidNumber=" . $db->quote($this->gidNumber) . ";";
				}
			}
			else
			{
				if (in_array($property, array('members', 'managers', 'applicants', 'invitees')))
				{
					$query = "DELETE m FROM `#__xgroups_$property` AS m WHERE " . " m.gidNumber=" .
						$db->quote($this->gidNumber) . " AND m.uidNumber NOT IN (" . $ulist . ");";
				}
			}

			$db->setQuery($query);

			if ($db->query())
			{
				$affected += $db->getAffectedRows();
			}
		}

		// After SQL is done and has no errors, fire off onGroupUserEnrolledEvents
		// for every user added to this group
		foreach ($aNewUserGroupEnrollments as $userid)
		{
			\Event::trigger('groups.onGroupUserEnrollment', array($this->gidNumber, $userid));
		}

		if ($affected > 0)
		{
			\Event::trigger('user.onAfterStoreGroup', array($this));
		}

		return true;
	}
1261261
protected function _insert()
    {
        $result = parent::_insert();

        if ($result) {
            //also insert to multilang tables if it is separate
            foreach ($this->_getLanguageSetTables() as $table) {
                $sql = "insert into $table set " . $this->_getUpdateFieldsForTable($table, $this->getUseSkipSaveFields());

                $result = $result && (bool) $this->executeDatabaseQuery($sql);
            }
        }

        return $result;
    }
147339
function insert() {
		if ($this->id)
			return $this->update();
		$db=$this->db;
		$now=microtime(TRUE);
		while (($id=uniqid(NULL,TRUE)) &&
			($data=&$db->read($this->file)) && isset($data[$id]) &&
			!connection_aborted())
			usleep(mt_rand(0,100));
		$this->id=$id;
		$pkey=['_id'=>$this->id];
		if (isset($this->trigger['beforeinsert']) &&
			\Base::instance()->call($this->trigger['beforeinsert'],
				[$this,$pkey])===FALSE)
			return $this->document;
		$data[$id]=$this->document;
		$db->write($this->file,$data);
		$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
			$this->file.' [insert] '.json_encode($this->document));
		if (isset($this->trigger['afterinsert']))
			\Base::instance()->call($this->trigger['afterinsert'],
				[$this,$pkey]);
		$this->load(['@_id=?',$this->id]);
		return $this->document;
	}
588454
public function insert($entity)
    {
        $entity->set($this->_property, $this->getRoot());

        //only add the entity into the entityset if it has
        //already been loaded
        //otherwise don't
        if ($this->getObject()->isLoaded()) {
            $this->getObject()->insert($entity);
        }

        return $entity;
    }
34519
def _insert_or_replace_entity(entity, require_encryption=False,
                              key_encryption_key=None, encryption_resolver=None):
    '''
    
    '''
    _validate_entity(entity, key_encryption_key is not None)
    _validate_encryption_required(require_encryption, key_encryption_key)

    request = HTTPRequest()
    request.method = 'PUT'
    request.headers = {
        _DEFAULT_CONTENT_TYPE_HEADER[0]: _DEFAULT_CONTENT_TYPE_HEADER[1],
        _DEFAULT_ACCEPT_HEADER[0]: _DEFAULT_ACCEPT_HEADER[1],
    }

    if(key_encryption_key):
        entity = _encrypt_entity(entity, key_encryption_key, encryption_resolver)
    request.body = _get_request_body(_convert_entity_to_json(entity))

    return request
1314678
public function update()
	{
		if (!is_numeric($this->get('uidNumber')))
		{
			return false;
		}

		$db =  \App::get('db');

		$modifiedDate = gmdate('Y-m-d H:i:s');

		$this->set('modifiedDate', $modifiedDate);

		$query = "UPDATE `#__xprofiles` SET ";

		$classvars = get_class_vars(__CLASS__);

		$first = true;
		$affected = 0;

		foreach ($classvars as $property => $value)
		{
			if ('_' == substr($property, 0, 1))
			{
				continue;
			}

			if (!$first)
			{
				$query .= ',';
			}
			else
			{
				$first = false;
			}

			if ($property == 'params')
			{
				if (is_object($this->_params))
				{
					$query .= "params='".str_replace("", "", $this->_params->toString())."'";
				}
				else
				{
					$query .= "params=''";
				}
				continue;
			}

			if ($this->get($property) === null)
			{
				$query .= "$property=NULL";
			}
			else
			{
				$query .= "$property=" . $db->quote($this->get($property));
			}
		}

		$query .= " WHERE uidNumber=" . $db->quote($this->get('uidNumber')) . ";";

		$db->setQuery($query);

		if (!$db->query())
		{
			$this->setError('Error updating data in xprofiles table: ' . $db->getErrorMsg());
		}

		$affected = $db->getAffectedRows();

		foreach ($classvars as $property => $value)
		{
			if (('_auxv_' != substr($property, 0, 6)) && ('_auxs_' != substr($property, 0, 6)))
			{
				continue;
			}

			$property = substr($property, 6);

			$first = true;

			$query = "REPLACE INTO #__xprofiles_" . $property . " (uidNumber, " . $property . ") VALUES ";
			$query_values = "";

			$list = $this->get($property);

			if (!is_array($list))
			{
				$list = array($list);
			}

			foreach ($list as $value)
			{
				if (!$first)
				{
					$query_values .= ',';
				}

				$first = false;

				$query_values .= '(' . $db->quote($this->get('uidNumber')) . ',' . $db->quote($value) . ')';
			}

			if ($query_values != '')
			{
				$db->setQuery($query . $query_values);

				if (!$db->query())
				{
					$this->setError("Error updating data in xprofiles $property table: " . $db->getErrorMsg());
				}
				else
				{
					$affected += $db->getAffectedRows();
				}
			}

			if (property_exists(__CLASS__, '_auxv_' . $property))
			{
				foreach ($list as $key => $value)
				{
					$list[$key] = $db->quote($value);
				}

				$valuelist = implode($list, ",");

				if (empty($valuelist))
				{
					$valuelist = "''";
				}

				$query = "DELETE FROM #__xprofiles_" . $property . " WHERE uidNumber=" . $this->get('uidNumber') . " AND $property NOT IN ($valuelist);";

				$db->setQuery($query);

				if (!$db->query())
				{
					$this->setError("Error deleting data in xprofiles $property table: " . $db->getErrorMsg());
				}
				else
				{
					$affected += $db->getAffectedRows();
				}
			}
		}

		if ($affected > 0)
		{
			Event::trigger('user.onAfterStoreProfile', array($this));
		}

		return true;
	}
457938
public function updateId()
    {
        if (empty($this->parentNode->key)) {
            $this->id = "{$this->keyDelimiter}$this->key{$this->keyDelimiter}";
        } else {
            $this->id = "{$this->parentNode->id}$this->keyDelimiter{$this->key}$this->keyDelimiter";
        }
        $this->id = preg_replace('/[#]{2,}/', self::DEFAULT_KEY_DELIMITER, $this->id);
    }
458726
protected function _insert()
    {
        if ($this->oxcategories__oxparentid->value != "oxrootid") {
            // load parent
            $oParent = oxNew(\OxidEsales\Eshop\Application\Model\Category::class);
            //#M317 check if parent is loaded
            if (!$oParent->load($this->oxcategories__oxparentid->value)) {
                return false;
            }

            $sAdd = " and oxshopid = '" . $this->getShopId() . "' ";

            // update existing nodes
            $oDb = \OxidEsales\Eshop\Core\DatabaseProvider::getDb();
            $oDb->execute(
                "UPDATE oxcategories SET OXLEFT = OXLEFT + 2
                                           WHERE  OXROOTID = " . $oDb->quote($oParent->oxcategories__oxrootid->value) . "
                            AND OXLEFT >   " . ((int) $oParent->oxcategories__oxright->value) . "
                            AND OXRIGHT >= " . ((int) $oParent->oxcategories__oxright->value) . $sAdd
            );


            $oDb->execute(
                "UPDATE oxcategories SET OXRIGHT = OXRIGHT + 2
                                           WHERE  OXROOTID = " . $oDb->quote($oParent->oxcategories__oxrootid->value) . "
                            AND OXRIGHT >= " . ((int) $oParent->oxcategories__oxright->value) . $sAdd
            );

            if (!$this->getId()) {
                $this->setId();
            }

            $this->oxcategories__oxrootid = new \OxidEsales\Eshop\Core\Field($oParent->oxcategories__oxrootid->value, \OxidEsales\Eshop\Core\Field::T_RAW);
            $this->oxcategories__oxleft = new \OxidEsales\Eshop\Core\Field($oParent->oxcategories__oxright->value, \OxidEsales\Eshop\Core\Field::T_RAW);
            $this->oxcategories__oxright = new \OxidEsales\Eshop\Core\Field($oParent->oxcategories__oxright->value + 1, \OxidEsales\Eshop\Core\Field::T_RAW);

            return parent::_insert();
        } else {
            // root entry
            if (!$this->getId()) {
                $this->setId();
            }

            $this->oxcategories__oxrootid = new \OxidEsales\Eshop\Core\Field($this->getId(), \OxidEsales\Eshop\Core\Field::T_RAW);
            $this->oxcategories__oxleft = new \OxidEsales\Eshop\Core\Field(1, \OxidEsales\Eshop\Core\Field::T_RAW);
            $this->oxcategories__oxright = new \OxidEsales\Eshop\Core\Field(2, \OxidEsales\Eshop\Core\Field::T_RAW);

            return parent::_insert();
        }
    }
43256
public function setDone() {
        $migration = $this->getMigration();
        if ($migration['state']) {
            return true; //alredy done
        }
        $this->db()->update($this->table, array('state' => true), array('id' => $migration['id']));
    }