Insert a new row
@param Garp_Model $model
@param Array $data Collection of data
@param Array $mapping Collection of column names
@return Mixed primary key
494407
protected function _insert(Garp_Model $model, array $data, array $mapping) {
        $newData = array();
        // Remove unused mappings
        $mapping = array_filter($mapping);
        foreach ($mapping as $key => $val) {
            $newData[$val] = $data[$key];
        }
        return $model->insert($newData);
    }
498235
public function bindWithI18nModel(Garp_Model_Db $model) {
        $i18nModel = $this->getI18nModel($model);
        $model->bindModel(
            self::I18N_MODEL_BINDING_ALIAS, array(
            'modelClass' => $i18nModel,
            'conditions' => $i18nModel->select()->from(
                $i18nModel->getName(),
                array_merge($this->_translatableFields, array(self::LANG_COLUMN))
            )
            )
        );
    }
710680
private function recurseRecord($method, $name, array $data, $index = null)
    {
        // Get model and determine primary key column
        $class = Str::camel($name);
        $model = $this->{$class}()->getModel();
        $primaryKey = (isset($model->primaryKey)) ? $model->primaryKey : 'id';

        $key = array_get($data, $primaryKey);

        // Find record and perform action on it
        $record = $model->findOrCreateRecord($key);
        $result = $record->recurse($method, $data, $this->getParameters('ruleset', $name), $this->getParameters('messageset', $name));

        // Capture errors
        $this->errors = $this->mergeErrors($this->errors, $record->getErrorBag(), $index);

        // Attach relationhip to record
        if ($result) $this->setRelationship($record, $name, $class, $index);

        // Record failure
        return $result;
    }
1126517
public function populateJoinedRelations($model, array $row)
    {
        foreach ($row as $key => $value) {
            if (empty($this->join) || !is_array($value) || $model->hasAttribute($key)) {
                continue;
            }
            foreach ($this->join as $join) {
                $keys = array_keys($join);
                $name = array_shift($keys);
                $closure = array_shift($join);

                if (is_int($name)) {
                    $name = $closure;
                    $closure = null;
                }
                if ($name !== $key) {
                    continue;
                }
                if ($model->isRelationPopulated($name)) {
                    continue 2;
                }
                $records = [];
                $relation = $model->getRelation($name);
                $relationClass = $relation->modelClass;
                if ($closure !== null) {
                    call_user_func($closure, $relation);
                }
                $relation->prepare();

                if ($relation->multiple) {
                    foreach ($value as $item) {
                        $relatedModel = $relationClass::instantiate($item);
                        $relatedModelClass = get_class($relatedModel);
                        $relatedModelClass::populateRecord($relatedModel, $item);
                        $relation->populateJoinedRelations($relatedModel, $item);
                        $relation->addInverseRelation($relatedModel, $model);
                        $relatedModel->trigger(BaseActiveRecord::EVENT_AFTER_FIND);
                        if ($relation->indexBy !== null) {
                            $index = is_string($relation->indexBy)
                                ? $relatedModel[$relation->indexBy]
                                : call_user_func($relation->indexBy, $relatedModel);
                            $records[$index] = $relatedModel;
                        } else {
                            $records[] = $relatedModel;
                        }
                    }
                } else {
                    $relatedModel = $relationClass::instantiate($value);
                    $relatedModelClass = get_class($relatedModel);
                    $relatedModelClass::populateRecord($relatedModel, $value);
                    $relation->populateJoinedRelations($relatedModel, $value);
                    $relation->addInverseRelation($relatedModel, $model);
                    $relatedModel->trigger(BaseActiveRecord::EVENT_AFTER_FIND);
                    $records = $relatedModel;
                }

                $model->populateRelation($name, $records);
            }
        }
    }
309596
public function insert($table, $data)
    {
        $query = $this->provider->buildInsertQuery($table, $data);

        return $this->provider->query($query, null);
    }
386131
public function insert(Model $m, $data)
    {
        $insert = $m->action('insert');

        // don't set id field at all if it's NULL
        if ($m->id_field && array_key_exists($m->id_field, $data) && $data[$m->id_field] === null) {
            unset($data[$m->id_field]);
        }

        $insert->set($this->typecastSaveRow($m, $data));

        $st = null;

        try {
            $m->hook('beforeInsertQuery', [$insert]);
            $st = $insert->execute();
        } catch (\PDOException $e) {
            throw new Exception([
                'Unable to execute insert query',
                'query'      => $insert->getDebugQuery(false),
                'model'      => $m,
                'conditions' => $m->conditions,
            ], null, $e);
        }

        $m->hook('afterInsertQuery', [$insert, $st]);

        return $m->lastInsertID();
    }
1242773
public function beforeInsert($model, &$data)
    {
        if ($this->weak) {
            return;
        }

        if ($model->hasField($this->master_field)
            && $model[$this->master_field]
        ) {
            // The value for the master_field is set,
            // we are going to use existing record.
            return;
        }

        // Figure out where are we going to save data
        $persistence = $this->persistence ?:
            $this->owner->persistence;

        $this->id = $persistence->insert(
            $model,
            $this->save_buffer,
            $this->foreign_table
        );

        $data[$this->master_field] = $this->id;

        //$this->owner->set($this->master_field, $this->id);
    }
817923
private function createInsertObj(Model $model)
    {
        $metadata = $model->getMetadata();
        $insert = [
            $this->getIdentifierKey()   => $this->convertId($model->getId()),
        ];
        if (true === $metadata->isChildEntity()) {
            $insert[$this->getPolymorphicKey()] = $metadata->type;
        }
        return $this->appendChangeSet($model, $insert, $this->getCreateChangeSetHandler());
    }
851180
public function insert(&$model)
    {
        $is_model = is_a($model, $this->model_class);
        if (!is_array($model) && !$is_model)
            throw new InvalidTypeException("An array or a instance of {$this->model_class} should be provided");

        $record = $is_model ? $model->getRecord() : $model;
        $db_record = array();
        $table = $this->table;
        $columns = $table->getColumns();

        foreach ($columns as $field => $def)
        {
            if (!isset($record[$field]) && !$def->isNullable() && $def->getDefault() === null && !$def->getSerial())
                throw new InvalidValueException("Column must not be null: {$field}");
        }

        foreach ($record as $field => $value)
        {
            if (!isset($columns[$field]))
                throw new DAOException("Invalid field: " . $field);

            $coldef = $columns[$field];
            $db_record[$field] = $coldef->beforeInsertFilter($value);
        }


        $pkey = $table->getPrimaryColumns();
        if ($pkey === null)
            $pkey = [];
        $insert = new Query\Insert($this->tablename, $db_record, $pkey);

        $drv = $this->db->getDriver();
        $drv->insert($insert, $pkey);
            
        // Store the potentially generated serial in the inserted record
        $pkey_values = $insert->getInsertId();
        foreach ($pkey as $pkey_column)
        {
            if (!$pkey_column->getSerial())
                continue;

            $colname = $pkey_column->getName();
            if (!isset($pkey_values[$colname]))
                throw new DAOException("No value generated for serial column {$colname}");

            if ($is_model)
                $model->setField($colname, (int)$pkey_values[$colname]);
            else
                $model[$colname] = (int)$pkey_values[$colname];
        }

        if ($is_model)
        {
            $model->markClean();
            $model->setSourceDB($this->db);
        }

        return $pkey_values;
    }
1019187
protected function _modifyReferenceDataForMultilingualModels(array &$referenceData, Garp_Model_Db $model) {
        // Try to fetch the baseFields from the localised model
        $i18nModelFactory = new Garp_I18n_ModelFactory($referenceData[Garp_Model_Behavior_Translatable::LANG_COLUMN]);
        $unilingualModel = $model->getUnilingualModel();
        $localizedModel = $i18nModelFactory->getModel($unilingualModel);
        $localizedModel->unregisterObserver('Translatable');
        $localizedModel->unregisterObserver('Draftable');
        $referenceMap = $model->getReference(get_class($unilingualModel));

        // Construct a query that fetches the base fields from the parent model
        $baseFields = $this->_config['baseField'];
        $baseFields = $this->_baseFieldConfigToColumns($baseFields);
        $select = $localizedModel->select()
            ->from($localizedModel->getName(), $baseFields)
        ;
        foreach ($referenceMap['columns'] as $i => $col) {
            if (!isset($referenceMap['refColumns'][$i])) {
                throw new Exception('ReferenceMap is invalid: columns does not match up with refColumns.');
            }
            $refCol = $referenceMap['refColumns'][$i];
            // If the required foreign key is not in $referenceData, we won't be able to solve the problem
            if (!isset($referenceData[$col])) {
                return null;
            }
            $select->where("$refCol = ?", $referenceData[$col]);
        }
        $localizedRecord = $localizedModel->fetchRow($select)->toArray();
        $referenceData = array_merge($localizedRecord, $referenceData);
    }
1315110
public function insert($table, array $data = [])
    {
        /**
         * Flatten data for possible multivalued values like geometric POINT or so.
         */
        $cache = $this->repository->getCache();
        foreach ($data as $key => &$val) {
            if (is_array($val)) {
                if ($cache->tableHasField($table, $key) && $cache->getField($key, $table)['type'] == 'point') {
                    $x = ($val['x'] ?? $val[0]) ?? 0;
                    $y = ($val['y'] ?? $val[1]) ?? 0;
                    $val = new Raw('GeomFromText(\'POINT(' . $x . ' ' . $y . ')\')');
                }
            }
        }

        /**
         * We will insert $data into $table ...
         */
        $query = (new Insert())->table($table)->setInsert($data);

        /**
         * ... prepare query ...
         */
        $prepare = $this->repository->prepareQuery($query);

        /**
         * ... execute it ...
         */
        $this->repository->executePrepared($prepare);

        /**
         * ... and return inserted ID.
         */
        return $this->repository->getConnection()->lastInsertId();
    }
688298
public function insert($storageName, $key, array $data)
    {
        try {
            $this->conn->insert($this->table, [
                $this->keyColumn  => $key,
                $this->dataColumn => serialize($data),
            ]);
        } catch (\Exception $e) {
        }
    }
1203386
public function update(array $data) {
        // check if primary key is available
        $prim = $this->_model->info(Zend_Db_Table::PRIMARY);
        if (!is_array($prim)) {
            $prim = array($prim);
        }

        $where = array();
        foreach ($prim as $key) {
            if (!array_key_exists($key, $data)) {
                throw new Garp_Content_Exception('Primary key ' . $key . ' not available in data');
            }
            $where[] = $this->_model->getAdapter()->quoteInto($key . ' = ?', $data[$key]);
            unset($data[$key]);
        }
        $where = implode(' AND ', $where);

        try {
            /**
             * First, see if the user is allowed to update everything
             */
            $this->_checkAcl('update');
        } catch (Garp_Auth_Exception $e) {
            /**
             * If that fails, check if the user is allowed to update her own material
             * AND if the current item is hers.
             */
            $this->_checkAcl('update_own');

            /**
             * Good, the user is allowed to 'update_own'. In that case we have to check if
             * the current item is actually the user's.
             */
            if (!$this->_itemBelongsToUser($data, $where)) {
                throw new Garp_Auth_Exception('You are only allowed to edit your own material.');
            }
        }
        return $this->_model->update($data, $where);
    }
1265567
protected function insertModelAsFirstRoot(Model &$model)
    {
        /** @var \T4\Orm\Model $class */
        $class = get_class($model);
        $tableName = $class::getTableName();
        /** @var \T4\Dbal\Connection $connection */
        $connection = $class::getDbConnection();

        $query = (new Query())
            ->select('MIN(__lft)')->from($tableName);
        $minLft = (int)$connection->query($query)->fetchScalar();

        $width = $model->getTreeWidth();
        $this->expandTreeBeforeLft($connection, $tableName, $minLft, $width);

        if (!$model->isNew()) {
            $model->refreshTreeColumns();
            $query = (new Query("
                UPDATE `" . $tableName . "`
                SET
                    `__lft` = `__lft` - :lft + :min,
                    `__rgt` = `__rgt` - :lft + :min,
                    `__lvl` = `__lvl` - :lvl
                WHERE `__lft` >= :lft AND `__rgt` <= :rgt
                "))
                ->params([':min' => $minLft, ':width'=> $width, ':lft' => $model->__lft, ':rgt' => $model->__rgt, ':lvl' => $model->__lvl]);
            $connection->execute($query);
            $this->removeFromTreeByElement($model);
        }

        $model->__lft = $minLft;
        $model->__rgt = $model->__lft + $width;
        $model->__lvl = 0;
        $model->__prt = 0;
    }
797403
public function afterSave(Garp_Model_Db $model, $primaryKey) {
        if (is_array($primaryKey)) {
            throw new Exception(self::ERROR_PRIMARY_KEY_CANNOT_BE_ARRAY);
        }

        $boundModel = new Garp_Service_Elasticsearch_Db_BoundModel($model);
        $row = $boundModel->fetchRow($primaryKey);

        if (!$row) {
            /* This is not supposed to happen,
            but due to concurrency it theoretically might. */
            return;
        }

        if (!$this->getRootable()) {
            /* This record should not appear directly in the index,
            *  but only as related records.
            */
            return;
        }

        $rowFilter          = new Garp_Service_Elasticsearch_Db_RowFilter($model);
        $columns            = $this->getColumns();
        $filteredRow        = $rowFilter->filter($row, $columns);

        $elasticModel       = $this->_getElasticModel($model);
        $pkMash             = $this->_mashPrimaryKey($primaryKey);
        $filteredRow['id']  = $pkMash;

        $elasticModel->save($filteredRow);
    }
37193
private function populateRecord($query,$row)
	{
		// determine the primary key value
		if(is_string($this->_pkAlias))  // single key
		{
			if(isset($row[$this->_pkAlias]))
				$pk=$row[$this->_pkAlias];
			else	// no matching related objects
				return null;
		}
		else // is_array, composite key
		{
			$pk=array();
			foreach($this->_pkAlias as $name=>$alias)
			{
				if(isset($row[$alias]))
					$pk[$name]=$row[$alias];
				else	// no matching related objects
					return null;
			}
			$pk=serialize($pk);
		}

		// retrieve or populate the record according to the primary key value
		if(isset($this->records[$pk]))
			$record=$this->records[$pk];
		else
		{
			$attributes=array();
			$aliases=array_flip($this->_columnAliases);
			foreach($row as $alias=>$value)
			{
				if(isset($aliases[$alias]))
					$attributes[$aliases[$alias]]=$value;
			}
			$record=$this->model->populateRecord($attributes,false);
			foreach($this->children as $child)
			{
				if(!empty($child->relation->select))
					$record->addRelatedRecord($child->relation->name,null,$child->relation instanceof CHasManyRelation);
			}
			$this->records[$pk]=$record;
		}

		// populate child records recursively
		foreach($this->children as $child)
		{
			if(!isset($query->elements[$child->id]) || empty($child->relation->select))
				continue;
			$childRecord=$child->populateRecord($query,$row);
			if($child->relation instanceof CHasOneRelation || $child->relation instanceof CBelongsToRelation)
				$record->addRelatedRecord($child->relation->name,$childRecord,false);
			else // has_many and many_many
			{
				// need to double check to avoid adding duplicated related objects
				if($childRecord instanceof CActiveRecord)
					$fpk=serialize($childRecord->getPrimaryKey());
				else
					$fpk=0;
				if(!isset($this->_related[$pk][$child->relation->name][$fpk]))
				{
					if($childRecord instanceof CActiveRecord && $child->relation->index!==null)
						$index=$childRecord->{$child->relation->index};
					else
						$index=true;
					$record->addRelatedRecord($child->relation->name,$childRecord,$index);
					$this->_related[$pk][$child->relation->name][$fpk]=true;
				}
			}
		}

		return $record;
	}
795051
public function update($model, array $data = [])
    {
        $this->setModelData($model, $data);

        return $this->saveForUpdate($model);
    }