public function updateRow($id, $updateArray) { $update = new Update($this->getTable()); $update->set($updateArray); $update->where->equalTo('id', $id); return $this->updateWith($update); }
public function save(\Api\Entity\Post $post) { $hydrator = $this->getHydrator(); $action = null; $postData = array('title' => $post->getTitle(), 'description' => $post->getDescription()); if ($post->getId()) { $action = new Update('posts'); $action->set($postData); $action->where(array('id = ?' => $post->getId())); } else { $postData['author_id'] = $post->getAuthorId(); $action = new Insert('posts'); $action->values($postData); } $sql = new Sql($this->getAdaptor()); $statement = $sql->prepareStatementForSqlObject($action); $result = $statement->execute(); if ($result instanceof ResultInterface) { if ($pk = $result->getGeneratedValue()) { $post->setId($pk); } return $this->getPost($post->getId()); } throw new \Exception('something went wrong.Please try again later'); }
public function setRequest($id) { if ($id == $this->user_id) { return true; } $user = $this->getUserById($id); if (is_array($user)) { if ($user["friendship"] == -1) { //insert $insert = new Insert('fg_friends'); $newData = array('user_one' => $this->user_id, 'user_two' => $id, 'state' => '0'); $insert->values($newData); $statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($insert); $resultSet = $statement->execute(); } else { if (!$user["i_am_adder"] && $user["friendship"] == 0) { //update $update = new Update('fg_friends'); $newData = array('state' => '1'); $update->set($newData); $update->where(array('user_one' => $id, 'user_two' => $this->user_id)); $statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($update); $resultSet = $statement->execute(); } } return true; } return false; }
/** * {@inheritDoc} */ public function save(PostInterface $postObject) { $postData = $this->hydrator->extract($postObject); unset($postData['id']); // Neither Insert nor Update needs the ID in the array if ($postObject->getId()) { // ID present, it's an Update $action = new Update('post'); $action->set($postData); $action->where(array('id = ?' => $postObject->getId())); } else { // ID NOT present, it's an Insert $action = new Insert('post'); $action->values($postData); } $sql = new Sql($this->dbAdapter); $stmt = $sql->prepareStatementForSqlObject($action); $result = $stmt->execute(); if ($result instanceof ResultInterface) { if ($newId = $result->getGeneratedValue()) { // When a value has been generated, set it on the object $postObject->setId($newId); } return $postObject; } throw new \Exception("Database error"); }
public function deleteOtherFeedPosts($feedId, array $postIds) { $Update = new Update(self::$_tableName); $Update->set([STATUS_COLUMN_NAME => 0]); $Update->where->addPredicate(new NotIn('foreign_id', $postIds))->equalTo('feed', $feedId); $affectedRows = $this->updateWith($Update); return $affectedRows; }
/** * @param Update $update */ public function preUpdate(Update $update) { $metaColumns = $this->tableGateway->getColumns(); if (count($metaColumns)) { $metaColumns = array_flip($metaColumns); $set = $update->getRawState('set'); $set = array_intersect_key($set, $metaColumns); $update->set($set); } }
/** * * @param string $userID * @return User */ public function updateUser(User $userObject) { $postData = $this->hydrator->extract($userObject); $action = new Update('user'); $action->set($postData); $action->where(array('userID = ?' => $userObject->getUserID())); $sql = new Sql($this->dbAdapter); $stmt = $sql->prepareStatementForSqlObject($action); $result = $stmt->execute(); if ($result instanceof ResultInterface) { // if ($newId = $result->getGeneratedValue()) { // // When a value has been generated, set it on the object // $postObject->setId($newId); // } return true; } }
public function update(\Api\Entity\User $user) { $hydrator = $this->getHydrator(); $postData = array('display_name' => $user->getDisplayName(), 'password' => $user->getPassword()); $update = new Update('user'); $update->set($postData); $update->where(array('user_id = ?' => $user->getUserId())); $sql = new Sql($this->getAdaptor()); $statement = $sql->prepareStatementForSqlObject($update); $result = $statement->execute(); if ($result instanceof ResultInterface) { if ($pk = $result->getGeneratedValue()) { $user->setUserId($pk); } return $this->getUser($user->getUserId()); } throw new \Exception('something went wrong.Please try again later'); }
/** * @coversNothing */ public function testSpecificationconstantsCouldBeOverridedByExtensionInGetSqlString() { $this->update = new UpdateIgnore(); $this->update->table('foo')->set(array('bar' => 'baz', 'boo' => new Expression('NOW()'), 'bam' => null))->where('x = y'); $this->assertEquals('UPDATE IGNORE "foo" SET "bar" = \'baz\', "boo" = NOW(), "bam" = NULL WHERE x = y', $this->update->getSqlString(new TrustingSql92Platform())); // with TableIdentifier $this->update = new UpdateIgnore(); $this->update->table(new TableIdentifier('foo', 'sch'))->set(array('bar' => 'baz', 'boo' => new Expression('NOW()'), 'bam' => null))->where('x = y'); $this->assertEquals('UPDATE IGNORE "sch"."foo" SET "bar" = \'baz\', "boo" = NOW(), "bam" = NULL WHERE x = y', $this->update->getSqlString(new TrustingSql92Platform())); }
/** * @throws Exception\RecordNotSavedException */ public function update(array $columnsValuesPairs) { $update = new ZfSql\Update($this->tableName); $update->set($columnsValuesPairs); $adapter = $this->sql->getAdapter(); if ($this->select->where) { $update->where($this->select->where); } $sqlString = $this->sql->getSqlStringForSqlObject($update); try { $result = $adapter->query($sqlString, $adapter::QUERY_MODE_EXECUTE); } catch (AdapterException\ExceptionInterface $e) { throw new Exception\RecordNotSavedException($e->getMessage(), 0, $e); } if (!$result->count()) { throw new Exception\RecordNotSavedException("No rows were affected"); } return true; }
/** * {@inheritdoc} */ public function save(PostInterface $postObject) { $postData = $this->hydrator->extract($postObject); unset($postData['id']); if ($postObject->getId()) { $action = new Update('posts'); $action->set($postData); $action->where(['id = ?' => $postObject->getId()]); } else { $action = new Insert('posts'); $action->values($postData); } $sql = new Sql($this->dbAdapter); $stmt = $sql->prepareStatementForSqlObject($action); $result = $stmt->execute(); if ($result instanceof ResultInterface) { if ($newId = $result->getGeneratedValue()) { $postObject->setId($newId); } return $postObject; } throw new \Exception("Database error."); }
/** * @param Route $model * * @return Route * @throws \Exception */ public function save(Route $model) : Route { $modelData = $this->hydrator->extract($model); if ($model->getId()) { $action = new Update($this->table); $action->set($modelData); $action->where(['id = ?' => $model->getId()]); } else { $action = new Insert($this->table); $action->values($modelData); } $sql = new Sql($this->dbAdapter); $statement = $sql->prepareStatementForSqlObject($action); $result = $statement->execute(); if (!$result instanceof ResultInterface) { throw new \Exception('Database Error'); } if ($newId = $result->getGeneratedValue()) { $model->setId($newId); } return $model; }
public function updateDefaultByName($user_id, $table, $data) { $update = new Update($this->table); unset($data['id']); unset($data['title']); unset($data['table_name']); unset($data['user']); if (!isset($data) || !is_array($data)) { $data = array(); } $update->set($data)->where->equalTo('table_name', $table)->equalTo('user', $user_id)->isNull('title'); $this->updateWith($update); }
/** * @covers Zend\Db\Sql\Update::__get */ public function testGetUpdateFails() { $getWhat = $this->update->__get('what'); $this->assertNull($getWhat); }
/** * @todo add $columns support * * @param Update $update * @return mixed * @throws Exception\RuntimeException */ protected function executeUpdate(Update $update) { $updateState = $update->getRawState(); if ($updateState['table'] != $this->table) { throw new Exception\RuntimeException('The table name of the provided Update object must match that of the table'); } // apply preUpdate features $this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_UPDATE, [$update]); $statement = $this->sql->prepareStatementForSqlObject($update); $result = $statement->execute(); // apply postUpdate features $this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_UPDATE, [$statement, $result]); return $result->getAffectedRows(); }
public function updateBookmark($payload) { $update = new Update($this->table); $update->set($payload); $this->updateWith($update); }
/** * @todo add $columns support * * @param Update $update * @return mixed * @throws Exception\RuntimeException */ protected function executeUpdate(Update $update) { $updateState = $update->getRawState(); if ($updateState['table'] != $this->table) { throw new Exception\RuntimeException('The table name of the provided Update object must match that of the table'); } // apply preUpdate features $this->featureSet->apply('preUpdate', array($update)); $statement = $this->sql->prepareStatementForSqlObject($update); $result = $statement->execute(); // apply postUpdate features $this->featureSet->apply('postUpdate', array($statement, $result)); return $result->getAffectedRows(); }
/** * Get a sql object to update an existing blog post * * @param int $id * @param PostEntity $post * @return Update */ protected function getPostUpdate($id, PostEntity $post) { $update = new Update(); $update->table(new TableIdentifier('blog_post'))->set(['title' => $post->getTitle(), 'author' => $post->getAuthor(), 'content' => $post->getContent(), 'is_visible' => $post->getIsVisible()])->where(['blog_post_id' => $id]); return $update; }
public function updateProduct($productData) { $id = $productData['id']; if (!empty($id)) { $action = new Update('products'); $action->set($productData); $action->where(array('id=?' => $id)); } $sql = new Sql($this->dbAdapter); $stmt = $sql->prepareStatementForSqlObject($action); $result = $stmt->execute(); if ($result instanceof ResultInterface) { if ($newId = $result->getGeneratedValue()) { return $newId; } return true; } throw new \Exception('Database Error'); }
public function updatePrivilege($attributes) { $attributes = $this->verifyPrivilege($attributes); $update = new Update($this->getTable()); $update->where->equalTo('id', $attributes['id']); $update->set(array('permissions' => $attributes['permissions'], 'read_field_blacklist' => $attributes['read_field_blacklist'], 'write_field_blacklist' => $attributes['write_field_blacklist'])); $this->updateWith($update); return $this->fetchById($attributes['id']); }
/** * @param string $expectedSql */ protected function assertTableGatewayLastSqlUpdate($expectedSql) { $actualSql = $this->update->getSqlString($this->mysqlPlatform); $this->assertSqlEquals($expectedSql, $actualSql); }
public function updatePrivilege($attributes) { $attributes = $this->verifyPrivilege($attributes); $data = $this->getFillableFields($attributes); $update = new Update($this->getTable()); $update->where->equalTo('id', $attributes['id']); $update->set($data); $this->updateWith($update); return $this->fetchById($attributes['id']); }
public function addOrUpdateRecordByArray(array $recordData, $tableName = null) { $tableName = is_null($tableName) ? $this->table : $tableName; foreach ($recordData as $columnName => $columnValue) { if (is_array($columnValue)) { // $table = is_null($tableName) ? $this->table : $tableName; throw new SuppliedArrayAsColumnValue('Attempting to write an array as the value for column `' . $tableName . '`.`' . $columnName . '.'); } } $columns = TableSchema::getAllNonAliasTableColumns($tableName); $recordData = SchemaManager::parseRecordValuesByType($recordData, $columns); $TableGateway = $this->makeTable($tableName); $rowExists = isset($recordData[$TableGateway->primaryKeyFieldName]); if ($rowExists) { $Update = new Update($tableName); $Update->set($recordData); $Update->where([$TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]]); $TableGateway->updateWith($Update); $this->runHook('postUpdate', [$TableGateway, $recordData, $this->adapter, null]); } else { $d = $this->applyHook('table.insert:before', [$tableName, $recordData]); $TableGateway->insert($d); $recordData[$TableGateway->primaryKeyFieldName] = $TableGateway->getLastInsertValue(); if ($tableName == 'directus_files') { $Files = new \Directus\Files\Files(); $ext = pathinfo($recordData['name'], PATHINFO_EXTENSION); $thumbnailPath = 'thumbs/THUMB_' . $recordData['name']; if ($Files->exists($thumbnailPath)) { $Files->rename($thumbnailPath, 'thumbs/' . $recordData[$this->primaryKeyFieldName] . '.' . $ext); } $updateArray = []; if ($Files->getSettings('file_naming') == 'file_id') { $Files->rename($recordData['name'], str_pad($recordData[$this->primaryKeyFieldName], 11, '0', STR_PAD_LEFT) . '.' . $ext); $updateArray['name'] = str_pad($recordData[$this->primaryKeyFieldName], 11, '0', STR_PAD_LEFT) . '.' . $ext; $recordData['name'] = $updateArray['name']; } if (!empty($updateArray)) { $Update = new Update($tableName); $Update->set($updateArray); $Update->where([$TableGateway->primaryKeyFieldName => $recordData[$TableGateway->primaryKeyFieldName]]); $TableGateway->updateWith($Update); } } $this->runHook('postInsert', [$TableGateway, $recordData, $this->adapter, null]); } $columns = TableSchema::getAllNonAliasTableColumnNames($tableName); $recordData = $TableGateway->fetchAll(function ($select) use($recordData, $columns, $TableGateway) { $select->columns($columns)->limit(1); $select->where->equalTo($TableGateway->primaryKeyFieldName, $recordData[$TableGateway->primaryKeyFieldName]); })->current(); return $recordData; }
/** * @todo add $columns support * * @param Update $update * @return int * @throws Exception\RuntimeException */ protected function executeUpdate(Update $update) { $updateState = $update->getRawState(); if ($updateState['table'] != $this->table) { throw new Exception\RuntimeException('The table name of the provided Update object must match that of the table'); } // apply preUpdate features $this->featureSet->apply(EventFeatureEventsInterface::EVENT_PRE_UPDATE, [$update]); $unaliasedTable = false; if (is_array($updateState['table'])) { $tableData = array_values($updateState['table']); $unaliasedTable = array_shift($tableData); $update->table($unaliasedTable); } $statement = $this->sql->prepareStatementForSqlObject($update); $result = $statement->execute(); // apply postUpdate features $this->featureSet->apply(EventFeatureEventsInterface::EVENT_POST_UPDATE, [$statement, $result]); // Reset original table information in Update instance, if necessary if ($unaliasedTable) { $update->table($updateState['table']); } return $result->getAffectedRows(); }
/** * @param Update $update * @return mixed * @throws Exception\RuntimeException * @throws \Directus\Acl\Exception\UnauthorizedFieldWriteException * @throws \Directus\Acl\Exception\UnauthorizedTableBigEditException * @throws \Directus\Acl\Exception\UnauthorizedTableEditException */ protected function executeUpdate(Update $update) { $currentUserId = null; if (Auth::loggedIn()) { $currentUser = Auth::getUserInfo(); $currentUserId = intval($currentUser['id']); } $updateState = $update->getRawState(); $updateTable = $this->getRawTableNameFromQueryStateTable($updateState['table']); $cmsOwnerColumn = $this->acl->getCmsOwnerColumnByTable($updateTable); $updateData = $updateState['set']; /** * ACL Enforcement */ // check if it's NOT soft delete $updateFields = $updateState['set']; $permissionName = 'edit'; $hasStatusColumn = array_key_exists(STATUS_COLUMN_NAME, $updateFields) ? true : false; if ($hasStatusColumn && $updateFields[STATUS_COLUMN_NAME] == STATUS_DELETED_NUM) { $permissionName = 'delete'; } if (!$this->acl->hasTablePrivilege($updateTable, 'big' . $permissionName)) { // Parsing for the column name is unnecessary. Zend enforces raw column names. /** * Enforce Privilege: "Big" Edit */ if (false === $cmsOwnerColumn) { // All edits are "big" edits if there is no magic owner column. $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); throw new UnauthorizedTableBigEditException($aclErrorPrefix . 'The table `' . $updateTable . '` is missing the `user_create_column` within `directus_tables` (BigEdit Permission Forbidden)'); } else { // Who are the owners of these rows? list($resultQty, $ownerIds) = $this->acl->getCmsOwnerIdsByTableGatewayAndPredicate($this, $updateState['where']); // Enforce if (is_null($currentUserId) || count(array_diff($ownerIds, [$currentUserId]))) { // $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); // throw new UnauthorizedTableBigEditException($aclErrorPrefix . "Table bigedit access forbidden on $resultQty `$updateTable` table record(s) and " . count($ownerIds) . " CMS owner(s) (with ids " . implode(", ", $ownerIds) . ")."); $groupsTableGateway = self::makeTableGatewayFromTableName($this->acl, 'directus_groups', $this->adapter); $group = $groupsTableGateway->find($this->acl->getGroupId()); throw new UnauthorizedTableBigEditException('[' . $group['name'] . '] permissions only allow you to [' . $permissionName . '] your own items.'); } } } if (!$this->acl->hasTablePrivilege($updateTable, $permissionName)) { /** * Enforce Privilege: "Little" Edit (I am the record CMS owner) */ if (false !== $cmsOwnerColumn) { if (!isset($predicateResultQty)) { // Who are the owners of these rows? list($predicateResultQty, $predicateOwnerIds) = $this->acl->getCmsOwnerIdsByTableGatewayAndPredicate($this, $updateState['where']); } if (in_array($currentUserId, $predicateOwnerIds)) { $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); throw new UnauthorizedTableEditException($aclErrorPrefix . 'Table edit access forbidden on ' . $predicateResultQty . '`' . $updateTable . '` table records owned by the authenticated CMS user (#' . $currentUserId . '.'); } } } // Enforce write field blacklist $attemptOffsets = array_keys($updateState['set']); $this->acl->enforceBlacklist($updateTable, $attemptOffsets, Acl::FIELD_WRITE_BLACKLIST); try { $this->emitter->run('table.update:before', [$updateTable, $updateData]); $this->emitter->run('table.update.' . $updateTable . ':before', [$updateData]); $result = parent::executeUpdate($update); $this->emitter->run('table.update', [$updateTable, $updateData]); $this->emitter->run('table.update:after', [$updateTable, $updateData]); $this->emitter->run('table.update.' . $updateTable, [$updateData]); $this->emitter->run('table.update.' . $updateTable . ':after', [$updateData]); return $result; } catch (\Zend\Db\Adapter\Exception\InvalidQueryException $e) { // @TODO: these lines are the same as the executeInsert, // let's put it together if (strpos(strtolower($e->getMessage()), 'duplicate entry') !== FALSE) { throw new DuplicateEntryException($e->getMessage()); } if ('production' !== DIRECTUS_ENV) { throw new \RuntimeException('This query failed: ' . $this->dumpSql($update), 0, $e); } // @todo send developer warning throw $e; } }
/** * @covers Zend\Db\Sql\Update::getSqlString */ public function testGetSqlString() { $this->update->table('foo')->set(array('bar' => 'baz', 'boo' => new Expression('NOW()'), 'bam' => null))->where('x = y'); $this->assertEquals('UPDATE "foo" SET "bar" = \'baz\', "boo" = NOW(), "bam" = NULL WHERE x = y', $this->update->getSqlString()); }
public function markAsRead($messageIds, $uid) { $update = new Update($this->getTable()); $update->set(['read' => 1])->where->in('message_id', $messageIds)->and->where->equalTo('recipient', $uid); return $this->updateWith($update); }
/** * @param ExpressionInterface $expression * @param PlatformInterface $platform * @param DriverInterface $driver * @param string $namedParameterPrefix * @return \Zend\Db\Adapter\StatementContainer */ protected function processExpression(ExpressionInterface $expression, PlatformInterface $platform, DriverInterface $driver = null, $namedParameterPrefix = null) { if ($expression instanceof ExpressionDecorator) { $expressionDecorator = $expression; } else { $expressionDecorator = new ExpressionDecorator($expression, $platform); } return parent::processExpression($expressionDecorator, $platform, $driver, $namedParameterPrefix); }
/** * @param Update $update * @return mixed * @throws Exception\RuntimeException * @throws \Directus\Acl\Exception\UnauthorizedFieldWriteException * @throws \Directus\Acl\Exception\UnauthorizedTableBigEditException * @throws \Directus\Acl\Exception\UnauthorizedTableEditException */ protected function executeUpdate(Update $update) { $currentUserId = null; if (Auth::loggedIn()) { $currentUser = Auth::getUserInfo(); $currentUserId = intval($currentUser['id']); } $updateState = $update->getRawState(); $updateTable = $this->getRawTableNameFromQueryStateTable($updateState['table']); $cmsOwnerColumn = $this->acl->getCmsOwnerColumnByTable($updateTable); /** * ACL Enforcement */ // check if it's NOT soft delete $updateFields = $updateState['set']; if (!(count($updateFields) == 2 && array_key_exists(STATUS_COLUMN_NAME, $updateFields) && $updateFields[STATUS_COLUMN_NAME] == STATUS_DELETED_NUM)) { if (!$this->acl->hasTablePrivilege($updateTable, 'bigedit')) { // Parsing for the column name is unnecessary. Zend enforces raw column names. /** * Enforce Privilege: "Big" Edit */ if (false === $cmsOwnerColumn) { // All edits are "big" edits if there is no magic owner column. $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); throw new UnauthorizedTableBigEditException($aclErrorPrefix . "The table `{$updateTable}` is missing the `user_create_column` within `directus_tables` (BigEdit Permission Forbidden)"); } else { // Who are the owners of these rows? list($resultQty, $ownerIds) = $this->acl->getCmsOwnerIdsByTableGatewayAndPredicate($this, $updateState['where']); // Enforce if (is_null($currentUserId) || count(array_diff($ownerIds, array($currentUserId)))) { $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); throw new UnauthorizedTableBigEditException($aclErrorPrefix . "Table bigedit access forbidden on {$resultQty} `{$updateTable}` table record(s) and " . count($ownerIds) . " CMS owner(s) (with ids " . implode(", ", $ownerIds) . ")."); } } /** * Enforce write field blacklist (if user lacks bigedit privileges on this table) */ $attemptOffsets = array_keys($updateState['set']); $this->acl->enforceBlacklist($updateTable, $attemptOffsets, Acl::FIELD_WRITE_BLACKLIST); } if (!$this->acl->hasTablePrivilege($updateTable, 'edit')) { /** * Enforce Privilege: "Little" Edit (I am the record CMS owner) */ if (false !== $cmsOwnerColumn) { if (!isset($predicateResultQty)) { // Who are the owners of these rows? list($predicateResultQty, $predicateOwnerIds) = $this->acl->getCmsOwnerIdsByTableGatewayAndPredicate($this, $updateState['where']); } if (in_array($currentUserId, $predicateOwnerIds)) { $aclErrorPrefix = $this->acl->getErrorMessagePrefix(); throw new UnauthorizedTableEditException($aclErrorPrefix . "Table edit access forbidden on {$predicateResultQty} `{$updateTable}` table records owned by the authenticated CMS user (#{$currentUserId})."); } } } } try { return parent::executeUpdate($update); } catch (\Zend\Db\Adapter\Exception\InvalidQueryException $e) { if ('production' !== DIRECTUS_ENV) { // @TODO: these lines are the same as the executeInsert, // let's put it together if (strpos(strtolower($e->getMessage()), 'duplicate entry') !== FALSE) { throw new DuplicateEntryException($e->getMessage()); } throw new \RuntimeException("This query failed: " . $this->dumpSql($update), 0, $e); } // @todo send developer warning throw $e; } }
/** * {@inheritDoc} */ public function setRefreshToken($refreshToken, $clientId, $userId, $expires, $scope = null) { $expires = date('Y-m-d H:i:s', $expires); if ($this->getRefreshToken($refreshToken)) { $update = new Update($this->config['refresh_token_table']); $update->set(array('client_id' => $clientId, 'user_id' => $userId, 'expires' => $expires, 'scope' => $scope))->where(array('refresh_token' => $refreshToken)); return $this->execute($update); } else { $insert = new Insert($this->config['refresh_token_table']); $insert->values(array('refresh_token' => $refreshToken, 'client_id' => $clientId, 'user_id' => $userId, 'expires' => $expires, 'scope' => $scope)); return $this->execute($insert); } }