Saves the row to the database.

This performs an intelligent insert/update and reloads the properties with fresh data from the table on success.

@param   DatabaseContextInterface $context
@return DatabaseRowAbstract
171684
protected function _beforeInsert(DatabaseContextInterface $context)
    {
        if($this->hasProperty('ordering'))
        {
            if($this->ordering <= 0) {
                $this->ordering = $this->getMaxOrdering() + 1;
            } else {
                $this->reorder($this->ordering);
            }
        }
    }
562389
public function save() {
		$ownerTransaction = FALSE;
		try {
			if ($this->database->getConnection()->getPdo()->inTransaction() === FALSE) {
				$this->database->beginTransaction();
				$ownerTransaction = TRUE;
			}
			if (is_array($this->rows)) {
				foreach ($this->rows as $key => $row) {
					if ($row->toRow()) {
						$this->update($row);
					} else {
						$row->__referencePrepare();
						$returnEntity = $this->insert($row);
						unset($this->rows[$key]);
						$this->rows[$returnEntity->getPrimary()] = $returnEntity;
					}
					$this->protectLoop = $this->originalLoop;
				}
			}
			if ($this->database->getConnection()->getPdo()->inTransaction() === TRUE && $ownerTransaction === TRUE) {
				$this->database->commit();
			}
			return TRUE;
		} catch (\PDOException $e) {
			if ($this->database->getConnection()->getPdo()->inTransaction() === TRUE && $ownerTransaction === TRUE) {
				$this->database->rollBack();
			}
			//var_dump($e->getTrace());
			throw new \PDOException($e->getMessage());
		}
	}
659942
public function saveContext($context)
    {

        $time = time();
        $now = date("{$this->dateFormat} {$this->timeFormat}", $time);
        $settingsValue = serialize($context->getSettings());
        $id = $context->getRecordId();
        $consumer_pk = $context->getConsumer()->getRecordId();
        if (empty($id)) {
            $sql = sprintf("INSERT INTO {$this->dbTableNamePrefix}" . DataConnector::CONTEXT_TABLE_NAME . ' (consumer_pk, lti_context_id, ' .
                           'type, settings, created, updated) ' .
                           'VALUES (%d, %s, %s, %s, %s, %s)',
               $consumer_pk, DataConnector::quoted($context->ltiContextId),
               DataConnector::quoted($context->type),
               DataConnector::quoted($settingsValue),
               DataConnector::quoted($now), DataConnector::quoted($now));
        } else {
            $sql = sprintf("UPDATE {$this->dbTableNamePrefix}" . DataConnector::CONTEXT_TABLE_NAME . ' SET ' .
                           'lti_context_id = %s, type = %s, settings = %s, '.
                           'updated = %s' .
                           'WHERE (consumer_pk = %d) AND (context_pk = %d)',
               DataConnector::quoted($context->ltiContextId),
               DataConnector::quoted($context->type),
               DataConnector::quoted($settingsValue),
               DataConnector::quoted($now), $consumer_pk, $id);
        }
        $ok = mysql_query($sql);
        if ($ok) {
            if (empty($id)) {
                $context->setRecordId(mysql_insert_id());
                $context->created = $time;
            }
            $context->updated = $time;
        }

        return $ok;

    }
646329
public function commit()
    {
        // Throws a nice exception if no token
        $this->getToken();

        if (!$this->layout instanceof Layout) {
            throw new \LogicException("No contextual instance is set, cannot commit");
        }

        // This gets the temporary storage until now
        $this->getStorage()->delete($this->layout->getId());
        // Loaded instance is supposed to be the false one
        $this->storage->save($this->layout);

        $this->setToken(null);

        return $this;
    }
157491
public function checkContext(ContextInterface $context)
    {
        try {
            $checkedCode = $this->preprocessor->preprocess($context->getCheckedCode());
            $parsedStatements = $this->parser->parse($checkedCode);
            $this->traverser->traverse($parsedStatements, $context, $this->lexer->getTokens());
        } catch (\Exception $e) {
            $context->addError(new CheckError($e->getMessage()));
        } catch (\ParseException $e) {
            $context->addError(new CheckError($e->getMessage(), $e->getLine()));
        }
    }
411487
public function getDBQueryBuilder(Context $context = null)
    {
        if ($this->dbQueryBuilder == null) {
            $this->dbQueryBuilder = new Miner();
            $this->dbQueryBuilder->setEscapes($this->config['mysql'][$this->active]['escapes'] ?? true);
            $this->dbQueryBuilder->mysqlPool = $this;
        }
        $this->dbQueryBuilder->context = $context;
        
        return $this->dbQueryBuilder;
    }
976062
public function execute(ServerContextInterface $context = null)
    {
        if (null === $context) {
            $context = new ServerContext();
        }

        $this->logServerStart($context);

        $this->server->start(
            $context,
            $this->decorateRequestHandler($this->requestHandler)
        );
    }
312801
public function insert(KDatabaseRowInterface $row)
    {
        // Create query object.
        $query = $this->getObject('lib:database.query.insert')
            ->table($this->getBase());

        //Create commandchain context
        $context = $this->getContext();
        $context->table     = $this->getBase();
        $context->data      = $row;
        $context->query     = $query;
        $context->affected = false;

        if ($this->invokeCommand('before.insert', $context) !== false)
        {
            // Filter the data and remove unwanted columns.
            $data = $this->filter($context->data->getProperties());
            $context->query->values($this->mapColumns($data));

            // Execute the insert query.
            $context->affected = $this->getAdapter()->insert($context->query);

            // Set the status and data before calling the command chain
            if ($context->affected !== false)
            {
                if ($context->affected)
                {
                    if(($column = $this->getIdentityColumn()) && $this->getColumn($this->mapColumns($column, true), true)->autoinc) {
                        $data[$this->getIdentityColumn()] = $this->getAdapter()->getInsertId();
                    }

                    $context->data->setProperties($this->mapColumns($data, true))->setStatus(KDatabase::STATUS_CREATED);
                }
                else $context->data->setStatus(KDatabase::STATUS_FAILED);
            }

            $this->invokeCommand('after.insert', $context);
        }

        return $context->affected;
    }
1267926
public function delete(DatabaseRowInterface $row)
    {
        // Create query object.
        $query = $this->getObject('lib:database.query.delete')
            ->table($this->getBase());

        //Create commandchain context
        $context = $this->getContext();
        $context->table     = $this->getBase();
        $context->data      = $row;
        $context->query     = $query;
        $context->affected  = false;

        if ($this->invokeCommand('before.delete', $context) !== false)
        {
            foreach ($this->getPrimaryKey() as $key => $column)
            {
                $context->query->where($column->name . ' = :' . $column->name)
                    ->bind(array($column->name => $context->data->$key));
            }

            // Execute the delete query.
            $context->affected = $this->getDriver()->delete($context->query);

            // Set the query in the context.
            if ($context->affected !== false) {
                $context->data->setStatus($context->affected ? Database::STATUS_DELETED : Database::STATUS_FAILED);
            }

            $this->invokeCommand('after.delete', $context);
        }

        return $context->affected;
    }
197977
public function getSync(Context $context = null)
    {
        $activeConfig = $this->config['mysql'][$this->active];
        $client = $this->getDBQueryBuilder($context);
        if ($client->getPdoConnection() === null) {
            return $client->pdoConnect($activeConfig);
        } else {
            return $client;
        }
    }
1349055
protected function _beforeInsert(KDatabaseContext $context)
    {
        $method = 'get'.ucfirst($this->_column);
        if($context->data->$method() instanceof KObjectConfigInterface) {
            $context->data->setProperty($this->_column, $context->data->$method()->toString());
        }
    }
1318631
public function load(LoadingContext $context) : array
    {
        $rows      = $context->query($this->select)->getRows();
        $data      = [];

        foreach ($this->columnIndexMap as $columnName => $index) {
            foreach ($rows as $key => $row) {
                $data[$key][$index] = $row->getColumn($columnName);
            }
        }

        foreach ($this->relationsToLoad as $index => list($relation, $parentTable, $parentColumnMap)) {
            /** @var Table $parentTable */
            if ($relation instanceof IToOneRelation) {
                $map       = new ParentChildMap($parentTable->getPrimaryKeyColumnName());
                $rowKeyMap = new \SplObjectStorage();

                foreach ($rows as  $key => $row) {
                    $mappedColumnData = [];
                    $originalColumnData = $row->getColumnData();

                    foreach($parentColumnMap as $original => $mapped) {
                        $mappedColumnData[$mapped] = $originalColumnData[$original];
                    }

                    $mappedRow = new Row($parentTable, $mappedColumnData);

                    $map->add($mappedRow, null);
                    $rowKeyMap[$mappedRow] = $key;
                }

                $relation->load($context, $map);

                foreach ($map->getItems() as $item) {
                    $data[$rowKeyMap[$item->getParent()]][$index] = $item->getChild();
                }
            } elseif ($relation instanceof IToManyRelation) {
                $map = new ParentChildrenMap($parentTable->getPrimaryKeyColumnName());
                $rowKeyMap = new \SplObjectStorage();

                foreach ($rows as $key => $row) {
                    $mappedColumnData = [];
                    $originalColumnData = $row->getColumnData();

                    foreach($parentColumnMap as $original => $mapped) {
                        $mappedColumnData[$mapped] = $originalColumnData[$original];
                    }

                    $mappedRow = new Row($parentTable, $mappedColumnData);

                    $map->add($mappedRow, []);
                    $rowKeyMap[$mappedRow] = $key;
                }

                $relation->load($context, $map);

                foreach ($map->getItems() as $item) {
                    $data[$rowKeyMap[$item->getParent()]][$index] = $relation->buildCollection($item->getChildren());
                }
            }
        }

        return $data;
    }
274658
protected function _actionCreate(ModelContext $context)
    {
        //Get the data
        $data = ModelContext::unbox($context->properties);

        if(!is_numeric(key($data))) {
            $data = array($data);
        }

        //Entity options
        $options = array(
            'data'            => $data,
            'identity_column' => $context->getIdentityKey()
        );

        return $this->getTable()->createRowset($options);
    }
235966
public function loadContext($context) {
        global $DB;

        if (!empty($context->getRecordId())) {
            $params = ['id' => $context->getRecordId()];
        } else {
            $params = [
                'consumerid' => $context->getConsumer()->getRecordId(),
                'lticontextkey' => $context->ltiContextId
            ];
        }
        if ($row = $DB->get_record($this->contexttable, $params)) {
            $context->setRecordId($row->id);
            $context->setConsumerId($row->consumerid);
            $context->ltiContextId = $row->lticontextkey;
            $context->type = $row->type;
            $settings = unserialize($row->settings);
            if (!is_array($settings)) {
                $settings = array();
            }
            $context->setSettings($settings);
            $context->created = $row->created;
            $context->updated = $row->updated;
            return true;
        }

        return false;
    }
870856
public function insertUpdateRow ($row, $filterColumns = true)
		{
			if ($filterColumns) {
				$row = $this->filterColumns($row, false);
			}

			$this->database->createQuery()
				->insertUpdate()
				->into($this->table)
				->set($row)
				->execute();

			return $this->database->insertId();
		}
341722
protected function initializeSorting(ContextInterface $context)
    {
        if (null !== $activeSort = $context->getActiveSort()) {
            $columnName = $activeSort->getColumnName();
            if ($this->table->hasColumn($columnName)) {
                $this->table->getColumn($columnName)->applySort($this, $activeSort);
            }
        }
    }
704970
public function bind(Context $context)
    {
        if (! isset($context->__UBID)) {
            $context->__UBID = 0;
        }
        $context->__UBID ++;
        
        return spl_object_hash($context) . $context->__UBID;
    }