/** Create UPDATE query * * @param string $table * @param array|string $set * @param string $primaryKey * * @return UpdateQuery */ public function update($table, $set = array(), $primaryKey = null) { $query = new UpdateQuery($this, $table); $query->set($set); if ($primaryKey) { $primaryKeyName = $this->getStructure()->getPrimaryKey($table); $query = $query->where($primaryKeyName, $primaryKey); } return $query; }
/** Create UPDATE query * * @param string $table * @param array|string $set * @param string $where * @param string $whereParams one or more params for where * * @return \UpdateQuery */ public function update($table, $set = array(), $where = '', $whereParams = '') { $query = new UpdateQuery($this, $table, $set, $where); $query->set($set); $args = func_get_args(); if (count($args) > 2) { array_shift($args); array_shift($args); if (is_null($args)) { $args = array(); } $query = call_user_func_array(array($query, 'where'), $args); } return $query; }
public function execute_logged($message, $tag, $module, $variables = array()) { if (($retval = parent::execute()) !== 0) { cvwobase_add_audit($message, $tag, $module, $variables); } return $retval; }
public static function permit($role, $action, $subject, $subject_id, $control) { $result = false; $params = array(':role' => $role, ':control' => $control, ':action' => $action, ':subject' => $subject, ':subject_id' => $subject_id); $query = new SelectQuery('Permission'); $query->filter('`role` = :role')->filter('`control` = :control')->filter('`action` = :action')->filter('`subject` = :subject')->filter('`subject_id` = :subject_id')->filter('system = 0'); $id = $query->fetchColumn($params); if ($id) { $query = new UpdateQuery('Permission'); $query->data(array('control' => ':control'))->filter('`id` = :id'); return $query->execute(array(':id' => $id, ':control' => $control)); } else { $data = array('role', 'control', 'action', 'subject', 'subject_id'); $data = array_combine($data, array_values($params)); $query = new InsertQuery('Permission'); $query->data($data); return $query->execute(); } }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { ArgumentValidator::validate($value, StringValidatorRule::getRule()); // Store the size in the object in case its asked for again. try { $size = ByteSize::fromString($value); } catch (InvalidArgumentException $e) { $size = ByteSize::withValue(0); } $this->_size = $size->value(); // then write it to the database. $dbHandler = Services::getService("DatabaseManager"); // Check to see if the name is in the database $query = new SelectQuery(); $query->addTable("dr_file"); $query->addColumn("COUNT(*) as count"); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it already exists, use an update query. if ($result->field("count") > 0) { $query = new UpdateQuery(); $query->setTable("dr_file"); $query->setColumns(array("size")); $query->setValues(array("'" . addslashes($this->_size) . "'")); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); } else { $query = new InsertQuery(); $query->setTable("dr_file"); $query->setColumns(array("id", "size")); $query->setValues(array("'" . $this->_recordId->getIdString() . "'", "'" . addslashes($this->_size) . "'")); } $result->free(); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Uses the ID passed and updates the database row with * new data. * @param integer $dbID The {@link DBHandler} database ID to query. * @param integer $dataID The ID in the database of the data to be updated. * @access public * @return void */ function update($dbID, $dataID) { if (!$dataID) { return false; } $query = new UpdateQuery(); $query->setTable($this->_table); $query->setColumns(array("data")); $query->setWhere("id='" . addslashes($dataID) . "'"); $query->setValues(array("'" . addslashes($this->asString()) . "'")); $dbHandler = Services::getService("DatabaseManager"); $result = $dbHandler->query($query, $dbID); if (!$result) { throwError(new UnknownDBError("StorableString")); return false; } return true; }
/** * Uses the ID passed and updates the database row with * new data. * @param integer $dbID The {@link DBHandler} database ID to query. * @param integer $dataID The ID in the database of the data to be updated. * @access public * @return void */ function update($dbID, $dataID) { if (!$dataID) { return false; } $query = new UpdateQuery(); $query->setTable("dm_okitype"); $query->setColumns(array("domain", "authority", "keyword")); $query->setWhere("id='" . addslashes($dataID) . "'"); $query->setValues(array("'" . addslashes($this->getDomain()) . "'", "'" . addslashes($this->getAuthority()) . "'", "'" . addslashes($this->getKeyword()) . "'")); $dbHandler = Services::getService("DatabaseManager"); $result = $dbHandler->query($query, $dbID); if (!$result) { throwError(new UnknownDBError("StorableOKIType")); return false; } return true; }
/** * Forcibly set the creation date of this Asset. This is meant to be used when importing * from backups. * * WARNING: NOT IN OSID * * @param object DateAndTime $date * @return void * @access public * @since 1/25/08 */ public function forceSetModificationDate(DateAndTime $date) { $dbHandler = Services::getService("DatabaseManager"); $query = new UpdateQuery(); $query->setTable("dr_asset_info"); $query->addValue("modify_timestamp", $date->asString()); $query->addWhere("asset_id='" . $this->getId()->getIdString() . "'"); $dbHandler->query($query, $this->_dbIndex); $this->_modifyDate = $date; }
/** * Update the description for this Hierarchy. * * @param string $description * * @throws object HierarchyException An exception with one of * the following messages defined in * org.osid.hierarchy.HierarchyException may be thrown: {@link * org.osid.hierarchy.HierarchyException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.hierarchy.HierarchyException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.hierarchy.HierarchyException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.hierarchy.HierarchyException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.hierarchy.HierarchyException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateDescription($description) { // ** parameter validation ArgumentValidator::validate($description, StringValidatorRule::getRule(), true); // ** end of parameter validation if ($this->_description == $description) { return; } // nothing to update // update the object $this->_description = $description; // update the database $dbHandler = Services::getService("DatabaseManager"); $query = new UpdateQuery(); $query->setTable("az2_hierarchy"); $query->addWhereEqual('id', $this->getId()->getIdString()); $query->addValue('description', $description); $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex); if ($queryResult->getNumberOfRows() == 0) { throw new OperationFailedException("No rows updated."); } if ($queryResult->getNumberOfRows() > 1) { throw new OperationFailedException("Too many rows updated, expecting 1."); } }
/** * Tests the generateSQLQuery() without WHERE clause. */ function test() { // insert one row $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->addRowOfValues(array("'Spaceboy'")); $query->setAutoIncrementColumn("id", "test1_id_seq"); $result = $this->db->query($query); $lastId = $result->getLastAutoIncrementValue(); // insert it again, the id must have increased by one $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $this->assertIdentical($result->getLastAutoIncrementValue(), $lastId + 1); // add several rows at the same time $query->addRowOfValues(array("'Astrogirl'")); $result = $this->db->query($query); $this->assertIdentical($result->getLastAutoIncrementValue(), $lastId + 3); // now insert in the other test table $query = new InsertQuery(); $query->setTable("test"); $query->setColumns(array("FK", "value")); $query->addRowOfValues(array($lastId, "'Ziggy'")); $query->addRowOfValues(array($lastId + 1, "'Lost in the Stars'")); $query->addRowOfValues(array($lastId + 2, "'Headstar'")); $query->addRowOfValues(array($lastId + 3, "'Stardust'")); $query->setAutoIncrementColumn("id", "test1_id_seq"); $result = $this->db->query($query); // join the inserted rows $query = new SelectQuery(); $query->addTable("test1"); $query->addTable("test", INNER_JOIN, "test.FK = test1.id"); $query->addColumn("id", "dm86_id", "test"); $query->addColumn("FK", "dm86_fk", "test"); $query->addColumn("value", "dm86_value", "test"); $query->addColumn("id", "dm98_id", "test1"); $query->addColumn("value", "dm98_value", "test1"); $query->addWhere("test1.id >= " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 4); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId); $this->assertIdentical($result->field("dm86_value"), "Ziggy"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 1); $this->assertIdentical($result->field("dm86_value"), "Lost in the Stars"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 1); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 2); $this->assertIdentical($result->field("dm86_value"), "Headstar"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 2); $this->assertIdentical($result->field("dm98_value"), "Spaceboy"); $result->advanceRow(); $this->assertIdentical((int) $result->field("dm86_fk"), $lastId + 3); $this->assertIdentical($result->field("dm86_value"), "Stardust"); $this->assertIdentical((int) $result->field("dm98_id"), $lastId + 3); $this->assertIdentical($result->field("dm98_value"), "Astrogirl"); $result->free(); $query = new UpdateQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->setValues(array("'I changed you MF!'")); $query->addWhere("id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $query = new SelectQuery(); $query->addTable("test1"); $query->addColumn("value"); $query->addWhere("test1.id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $this->assertIdentical($result->field("value"), "I changed you MF!"); $result->free(); $query = new DeleteQuery(); $query->setTable("test1"); $query->addWhere("id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 1); $query = new SelectQuery(); $query->addTable("test1"); $query->addColumn("value"); $query->addWhere("test1.id = " . $lastId); $result = $this->db->query($query); $this->assertIdentical($result->getNumberOfRows(), 0); $result->free(); }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { if (!is_null($value)) { ArgumentValidator::validate($value, NonzeroLengthStringValidatorRule::getRule()); } // Store the name in the object in case its asked for again. $this->_type = $value; // then write it to the database. $dbHandler = Services::getService("DatabaseManager"); // If we have a key, make sure it exists. if ($this->_type && $this->_type != "NULL") { // Check to see if the type is in the database $query = new SelectQuery(); $query->addTable("dr_mime_type"); $query->addColumn("id"); $query->addWhere("type = '" . $this->_type . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it doesn't exist, insert it. if (!$result->getNumberOfRows()) { $query = new InsertQuery(); $query->setTable("dr_mime_type"); $query->setAutoIncrementColumn("id", "dr_mime_type_id_seq"); $query->setColumns(array("type")); $query->setValues(array("'" . addslashes($this->_type) . "'")); $result2 = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $mimeId = "'" . $result2->getLastAutoIncrementValue() . "'"; } else { $mimeId = "'" . $result->field("id") . "'"; } $result->free(); } else { $mimeId = "NULL"; } // add its id to the file. $query = new UpdateQuery(); $query->setTable("dr_file"); $query->setColumns(array("fk_mime_type")); $query->setValues(array($mimeId)); $query->addWhere("id = '" . $this->_recordId->getIdString() . "'"); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Update a record table for a set of harvesters and repositories * * @param string $table * @param array $allowedRepositoryIdStrings * @param array $authGroupIdStrings The ids of the groups to check view authorization for, * May be one of the following or another group Id string: * edu.middlebury.agents.everyone * edu.middlebury.agents.all_agents * If empty, all assets in the specified repositories will be added regardless of * their visibility. * * @return void * @access public * @since 3/9/07 */ function updateTable($table, $allowedRepositoryIdStrings, $authGroupIdStrings) { ArgumentValidator::validate($table, StringValidatorRule::getRule()); ArgumentValidator::validate($allowedRepositoryIdStrings, ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); ArgumentValidator::validate($authGroupIdStrings, ArrayValidatorRuleWithRule::getRule(StringValidatorRule::getRule())); $harmoni = Harmoni::instance(); $config = $harmoni->getAttachedData('OAI_CONFIG'); $repositoryManager = Services::getService('Repository'); $authorizationManager = Services::getService('AuthZ'); $idManager = Services::getService("IdManager"); $dbc = Services::getService("DatabaseManager"); $authGroupIds = array(); foreach ($authGroupIdStrings as $id) { $authGroupIds[] = $idManager->getId($id); } $baseCheckQuery = new SelectQuery(); $baseCheckQuery->addTable('oai_' . $table); $baseCheckQuery->addColumn('datestamp'); $baseCheckQuery->addColumn('deleted'); $baseUpdateQuery = new UpdateQuery(); $baseUpdateQuery->setTable('oai_' . $table); $baseUpdateColumns = array('datestamp', 'deleted', 'oai_set', 'dc_title', 'dc_description'); $dcUpdateColumns = array('datestamp', 'deleted', 'oai_set', 'dc_title', 'dc_description', 'dc_creator', 'dc_subject', 'dc_contributor', 'dc_publisher', 'dc_date', 'dc_type', 'dc_format', 'dc_identifier', 'dc_source', 'dc_language', 'dc_relation', 'dc_coverage', 'dc_rights'); $baseInsertQuery = new InsertQuery(); $baseInsertQuery->setTable('oai_' . $table); $baseInsertColumns = array('datestamp', 'oai_identifier', 'deleted', 'oai_set', 'dc_title', 'dc_description'); $dcInsertColumns = array('datestamp', 'oai_identifier', 'deleted', 'oai_set', 'dc_title', 'dc_description', 'dc_creator', 'dc_subject', 'dc_contributor', 'dc_publisher', 'dc_date', 'dc_type', 'dc_format', 'dc_identifier', 'dc_source', 'dc_language', 'dc_relation', 'dc_coverage', 'dc_rights'); $baseDeleteQuery = new UpdateQuery(); $baseDeleteQuery->setTable('oai_' . $table); $baseDeleteQuery->addValue('deleted', 'true'); $baseDeleteQuery->addRawValue('datestamp', 'NOW()'); $baseUndeleteQuery = new UpdateQuery(); $baseUndeleteQuery->setTable('oai_' . $table); $baseUndeleteQuery->addValue('deleted', 'false'); $baseUndeleteQuery->addRawValue('datestamp', 'NOW()'); $forceUpdate = false; $repositories = $repositoryManager->getRepositories(); $r = 0; if (count($allowedRepositoryIdStrings)) { $numR = count($allowedRepositoryIdStrings); } else { $numR = $repositories->count(); } $numUpdates = 0; $numDeleted = 0; $message = _('Updating OAI records for repository (%1 of %2) : '); $message = str_replace('%2', $numR, $message); $instituteId = $idManager->getId('edu.middlebury.agents.users'); $viewId = $idManager->getId('edu.middlebury.authorization.view'); require_once HARMONI . "/utilities/Timer.class.php"; $timer = new Timer(); $timer->start(); $existingRepositoryIds = array(); while ($repositories->hasNext()) { $updatesInRepository = 0; $repository = $repositories->next(); $repositoryId = $repository->getId(); // Only work with allowed repositories if (count($allowedRepositoryIdStrings) && !in_array($repositoryId->getIdString(), $allowedRepositoryIdStrings)) { continue; } $r++; $existingRepositoryIds[] = $repositoryId->getIdString(); $assets = $repository->getAssets(); $status = new CLIStatusStars(str_replace('%1', $r, $message) . $repository->getDisplayName()); $status->initializeStatistics($assets->count()); $existingAssetIds = array(); while ($assets->hasNext()) { $asset = $assets->next(); $assetId = $asset->getId(); $existingAssetIds[] = $assetId->getIdString(); try { $modificationDate = $asset->getModificationDate(); } catch (UnimplementedException $e) { $modificationDate = DateAndTime::now(); } $query = $baseCheckQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if (!$result->getNumberOfRows()) { // printpre("Doesn't exist:\t".$asset->getDisplayName().""); $query = $baseInsertQuery->copy(); $query->addValue('oai_set', $repositoryId->getIdString()); $query->addValue('oai_identifier', $assetId->getIdString()); } else { // printpre("Exists:\t".$asset->getDisplayName().""); if ($modificationDate->isGreaterThan(DateAndTime::fromString($result->field('datestamp'))) || $forceUpdate) { // printpre("\tUpdating:\t".$asset->getDisplayName()); $query = $baseUpdateQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); } else { $query = null; } } if ($query) { $query->addRawValue('datestamp', 'NOW()'); } $isCurrentlyDeleted = $result->getNumberOfRows() && $result->field('deleted') == 'true' ? true : false; $result->free(); if (!count($authGroupIds)) { $isVisible = true; } else { $isVisible = false; try { foreach ($authGroupIds as $id) { if ($authorizationManager->isAuthorized($id, $viewId, $assetId)) { $isVisible = true; break; } } } catch (UnknownIdException $e) { $isVisible = true; } } if ($query) { //Add the data fields // Deleted if ($isVisible) { $query->addValue('deleted', 'false'); } else { $query->addValue('deleted', 'true'); } $query->addValue('dc_title', $asset->getDisplayName()); $query->addValue('dc_description', $asset->getDescription()); $this->addDublinCoreValues($asset, $query); $dbc->query($query, $config->getProperty('OAI_DBID')); $updatesInRepository++; $numUpdates++; } else { if ($isCurrentlyDeleted && $isVisible) { $query = $baseUndeleteQuery->copy(); } else { if (!$isCurrentlyDeleted && !$isVisible) { $query = $baseDeleteQuery->copy(); } else { $query = null; } } if ($query) { $query->addWhereEqual("oai_set", $repositoryId->getIdString()); $query->addWhereEqual("oai_identifier", $assetId->getIdString()); $dbc->query($query, $config->getProperty('OAI_DBID')); $updatesInRepository++; $numUpdates++; } } $status->updateStatistics(); } // Update any missing assets as deleted $query = $baseDeleteQuery->copy(); $query->addWhereEqual("oai_set", $repositoryId->getIdString()); if (count($existingAssetIds)) { $query->addWhereEqual("deleted", "false"); $query->addWhereNotIn("oai_identifier", $existingAssetIds); } $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if ($result->getNumberOfRows()) { $updatesInRepository = $updatesInRepository + $result->getNumberOfRows(); $numUpdates = $numUpdates + $result->getNumberOfRows(); } print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Elapsed Time:\t"; $timer->end(); printf("%1.2f", $timer->printTime()); print " seconds"; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : ""; print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Updates: " . $updatesInRepository; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : "\n"; } // Update any missing repositories as deleted $query = $baseDeleteQuery->copy(); $query->addWhereEqual("deleted", "false"); if (count($existingRepositoryIds)) { $query->addWhereNotIn("oai_set", $existingRepositoryIds); } $result = $dbc->query($query, $config->getProperty('OAI_DBID')); if ($result->getNumberOfRows()) { $updatesInRepository = $updatesInRepository + $result->getNumberOfRows(); $numUpdates = $numUpdates + $result->getNumberOfRows(); } print OAI_UPDATE_OUTPUT_HTML ? "<pre>" : "\n"; print "Total Updates:\t" . $numUpdates; print OAI_UPDATE_OUTPUT_HTML ? "</pre>" : "\n"; }
public function execute() { if (!empty($this->queryOptions['sqlite_return_matched_rows'])) { return parent::execute(); } // Get the fields used in the update query, and remove those that are already // in the condition. $fields = $this->expressionFields + $this->fields; $this->removeFieldsInCondition($fields, $this->condition); // Add the inverse of the fields to the condition. $condition = new DatabaseCondition('OR'); foreach ($fields as $field => $data) { if (is_array($data)) { // The field is an expression. $condition->where($field . ' <> ' . $data['expression']); $condition->isNull($field); } elseif (!isset($data)) { // The field will be set to NULL. $condition->isNull($field); } else { $condition->condition($field, $data, '<>'); $condition->isNull($field); } } if (count($condition)) { $condition->compile($this->connection, $this); $this->condition->where((string) $condition, $condition->arguments()); } return parent::execute(); }
/** * Enable a plugin * * @param object Type $type * @return void * @access public * @since 8/22/07 */ public function enablePlugin(Type $type) { $db = Services::getService("DBHandler"); // write the type to the database $query = new UpdateQuery(); $query->setTable('plugin_type'); $query->addValue("type_enabled", '1'); $query->addWhereEqual("type_domain", $type->getDomain()); $query->addWhereEqual("type_Authority", $type->getAuthority()); $query->addWhereEqual("type_keyword", $type->getKeyword()); $db->query($query, IMPORTER_CONNECTION); $this->addPluginToArray($type, 'enabled'); }
/** * Given the object in table $table with id $id, change the field with name $key to $value * * @param object Id $id The Id of the object in question * @param string $table The table that our object resides in * @param string $key The name of the field * @param mixed $value The value to pass in * * * @access private */ function _setField($id, $table, $key, $value) { //just an update query $dbHandler = Services::getService("DBHandler"); $query = new UpdateQuery(); $query->setTable($table); $query->addWhere("id='" . addslashes($id->getIdString()) . "'"); $query->setColumns(array(addslashes($key))); $query->setValues(array("'" . addslashes($value) . "'")); $dbHandler->query($query); }
/** * Commits any changes that have been made to the database. If neither update() nor prune() have been * called, even if changes have been made, they will not be reflected in the database. * @return bool * @access public */ function commit() { $dbHandler = Services::getService("DatabaseManager"); if ($this->_update) { // let's re-cast our primitive to a storablePrimitive $this->recastAsStorable(); // first we need to commit the actual Primitive value // so that we can get its ID if (!$this->_dataID) { $this->_dataID = $this->_primitive->insert(DATAMANAGER_DBID); } else { $this->_primitive->update(DATAMANAGER_DBID, $this->_dataID); } $this->_date = DateAndTime::now(); if ($this->_myID) { // we're already in the DB. just update the entry $query = new UpdateQuery(); $query->setWhere("id='" . addslashes($this->_myID) . "'"); $query->setColumns(array("value_index", "active", "modified")); $query->setValues(array($this->_parent->getIndex(), $this->_active ? 1 : 0, $dbHandler->toDBDate($this->_date, DATAMANAGER_DBID))); } else { // we have to insert a new one $query = new InsertQuery(); $idManager = Services::getService("Id"); $newID = $idManager->createId(); $this->_myID = $newID->getIdString(); $query->setColumns(array("id", "fk_record", "fk_schema_field", "value_index", "fk_data", "active", "modified")); $schema = $this->_parent->_parent->_parent->getSchema(); $schemaField = $this->_parent->_parent->getSchemaField(); $query->addRowOfValues(array("'" . addslashes($this->_myID) . "'", "'" . addslashes($this->_parent->_parent->_parent->getID()) . "'", "'" . addslashes($schemaField->getID()) . "'", $this->_parent->getIndex(), "'" . addslashes($this->_dataID) . "'", $this->_active ? 1 : 0, $dbHandler->toDBDate($this->_date, DATAMANAGER_DBID))); } $query->setTable("dm_record_field"); $result = $dbHandler->query($query, DATAMANAGER_DBID); if (!$result) { throwError(new UnknownDBError("DMRecord")); return false; } } if ($this->_prune && $this->_dataID) { if ($id = $this->getID()) { // ok, let's get rid of ourselves... completely! $query = new DeleteQuery(); $query->setTable("dm_record_field"); $query->setWhere("id='" . addslashes($id) . "'"); $res = $dbHandler->query($query, DATAMANAGER_DBID); if (!$res) { throwError(new UnknownDBError("DMRecord")); } // now tell the data object to prune itself $this->recastAsStorable(); $this->_primitive->prune(DATAMANAGER_DBID, $this->_dataID); // and we have to get rid of any tag mappings where we are included. $query = new DeleteQuery(); $query->setTable("dm_tag_map"); $query->setWhere("fk_record_field='" . addslashes($id) . "'"); $res = $dbHandler->query($query, DATAMANAGER_DBID); if (!$res) { throwError(new UnknownDBError("DMRecord")); } } } // reset the prune flag $this->_prune = false; // reset the update flag $this->_update = false; return true; }
/** * Change the Enrollment Status Type for the student on the roster. * * @param object Id $agentId * @param object Type $enrollmentStatusType * * @throws object CourseManagementException An exception * with one of the following messages defined in * org.osid.coursemanagement.CourseManagementException may be * thrown: {@link * org.osid.coursemanagement.CourseManagementException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.coursemanagement.CourseManagementException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.coursemanagement.CourseManagementException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.coursemanagement.CourseManagementException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.coursemanagement.CourseManagementException#NULL_ARGUMENT * NULL_ARGUMENT}, {@link * org.osid.coursemanagement.CourseManagementException#UNKNOWN_TYPE * UNKNOWN_TYPE} * * @access public */ function changeStudent(Id $agentId, Type $enrollmentStatusType) { $dbManager = Services::getService("DatabaseManager"); $query = new SelectQuery(); $query->addTable('cm_enroll'); $query->addWhere("fk_cm_section='" . addslashes($this->_id->getIdString()) . "'"); $query->addWhere("fk_student_id='" . addslashes($agentId->getIdString()) . "'"); //I don't need Id, but I need to select something for the query to work $query->addColumn('id'); $res = $dbManager->query($query); if ($res->getNumberOfRows() == 0) { throwError(new Error("Cannot change status of student [" . $agentId->getIDString() . "] because that student in not enrolled in the course[" . $this->_id->getIdString() . "]", "CourseManagement", true)); } else { if ($res->getNumberOfRows() > 1) { print "<b>Warning!</b> Student with id " . $agentId->getIdString() . " is already enrolled in section " . $this->getDisplayName() . " twice."; } } $typeIndex = $this->_typeToIndex('enroll_stat', $enrollmentStatusType); $query = new UpdateQuery(); $query->setTable('cm_enroll'); $query->addWhere("fk_cm_section='" . addslashes($this->_id->getIdString()) . "'"); $query->addWhere("fk_student_id='" . addslashes($agentId->getIdString()) . "'"); $query->setColumns(array('fk_cm_enroll_stat_type')); $query->setValues(array("'" . addslashes($typeIndex) . "'")); $dbManager->query($query); }
/** * Given an associative array of old Id strings and new Id strings. * Update any of the old Ids that this plugin instance recognizes to their * new value. * * @param array $idMap An associative array of old id-strings to new id-strings. * @return void * @access public * @since 1/24/08 */ public function replaceIds(array $idMap) { $doc = $this->getVersionXml(); $this->pluginInstance->replaceIdsInVersion($idMap, $doc); $query = new UpdateQuery(); $query->setTable('segue_plugin_version'); $query->addWhereEqual('version_id', $this->getVersionId()); $query->addValue('version_xml', $doc->saveXML()); $dbc = Services::getService('DBHandler'); $dbc->query($query, IMPORTER_CONNECTION); }
/** * the date when this Authorization stops being effective. * * @param object DateAndTime $effectiveDate * * @throws object AuthorizationException An exception with * one of the following messages defined in * org.osid.authorization.AuthorizationException may be thrown: * {@link * org.osid.authorization.AuthorizationException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.authorization.AuthorizationException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.authorization.AuthorizationException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.authorization.AuthorizationException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.authorization.AuthorizationException#NULL_ARGUMENT * NULL_ARGUMENT}, {@link * org.osid.authorization.AuthorizationException#EFFECTIVE_PRECEDE_EXPIRATION} * * @access public */ function updateEffectiveDate($effectiveDate) { if (!$this->isExplicit()) { // "Cannot modify an implicit Authorization." throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true)); } // ** parameter validation ArgumentValidator::validate($effectiveDate, HasMethodsValidatorRule::getRule("asDateAndTime"), true); // ** end of parameter validation // make sure effective date is before expiration date if ($effectiveDate->isGreaterThan($this->_expirationDate)) { throwError(new Error(AuthorizationException::EFFECTIVE_PRECEDE_EXPIRATION(), "Authorization", true)); } if ($this->_effectiveDate->isEqualTo($effectiveDate)) { return; } // nothing to update // update the object $this->_effectiveDate = $effectiveDate; // update the database $dbHandler = Services::getService("DatabaseManager"); $query = new UpdateQuery(); $query->setTable("az2_explicit_az"); $query->addWhereEqual("id", $this->_id); $timestamp = $dbHandler->toDBDate($effectiveDate, $this->_cache->_dbIndex); $query->addValue("effective_date", $timestamp); $queryResult = $dbHandler->query($query, $this->_cache->_dbIndex); if ($queryResult->getNumberOfRows() == 0) { throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true)); } if ($queryResult->getNumberOfRows() > 1) { throwError(new Error(AuthorizationException::OPERATION_FAILED(), "Authorization", true)); } }
/** * Rename the tag for the given agent * * @param object Id $agentId * @param string $newValue * @return void * @access public * @since 11/27/06 */ function renameForAgent($agentId, $newValue) { $newTag = new Tag($newValue); $query = new UpdateQuery(); $query->setTable('tag'); $query->setColumns(array('value')); $query->setValues(array("'" . addslashes($newTag->getValue()) . "'")); $query->addWhere("tag.value='" . addslashes($this->getValue()) . "'"); $query->addWhere("tag.user_id='" . addslashes($agentId->getIdString()) . "'"); $dbc = Services::getService("DatabaseManager"); $dbc->query($query, $this->getDatabaseIndex()); }
/** * Called by the {@link save()} method to update the object * @param vars - (optional) An array of key,value pairs to be assigned * for this object * @access protected * @see insert,save */ protected function update($vars = '') { if (!$this->table->tainted()) { if ($vars) { $this->parse($vars); } $query = new UpdateQuery($this->tableName()); $fields = $this->table()->fields(); foreach ($fields as $cur_field) { if ($cur_field->requiresUpdate() && !$cur_field->key()) { if (!$cur_field->isSetted()) { $value = Query::clean($cur_field->value()); } else { $value = $cur_field->value(); } $query->updateField($cur_field->name(), $value, $cur_field->getQuotes()); $cur_field->updated(); } } $query->setClause($this->uniqueClause()); $query->doQuery(); $this->clearQueryCache(); //$this->table->refresh(); $ret = true; } else { $this->taintException(); } return $ret; }
/** * Update the value for this Part. * * @param object mixed $value (original type: java.io.Serializable) * * @throws object RepositoryException An exception with one of * the following messages defined in * org.osid.repository.RepositoryException may be thrown: {@link * org.osid.repository.RepositoryException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.repository.RepositoryException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.repository.RepositoryException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.repository.RepositoryException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.repository.RepositoryException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateValue($value) { // ArgumentValidator::validate($value, StringValidatorRule::getRule()); $dbHandler = Services::getService("DatabaseManager"); // Delete the row if we are setting the value to null if (is_null($value)) { $query = new DeleteQuery(); $query->setTable("dr_file_data"); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); return; } // Store the data in the object in case its asked for again. // $this->_data = $value; // Make sure that the dr_file row is inserted. $query = new InsertQuery(); $query->setTable("dr_file"); $query->addValue("id", $this->_recordId->getIdString()); try { $dbHandler->query($query, $this->_configuration->getProperty("database_index")); } catch (QueryDatabaseException $e) { // If an error is thrown inserting (because the file already exists) // ignore it. } $dbHandler->beginTransaction($this->_configuration->getProperty("database_index")); // Base64 encode the data to preserve it, // then write it to the database. // Check to see if the data is in the database $query = new SelectQuery(); $query->addTable("dr_file_data"); $query->addColumn("COUNT(*) as count"); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); $result = $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // If it already exists, use an update query. if ($result->field("count") > 0) { $query = new UpdateQuery(); $query->setTable("dr_file_data"); $query->setColumns(array("data")); $query->setValues(array("'" . base64_encode($value) . "'")); $query->addWhere("fk_file = '" . $this->_recordId->getIdString() . "'"); } else { $query = new InsertQuery(); $query->setTable("dr_file_data"); $query->setColumns(array("fk_file", "data")); $query->setValues(array("'" . $this->_recordId->getIdString() . "'", "'" . base64_encode($value) . "'")); } $result->free(); // printpre($query); // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); // run the query $dbHandler->query($query, $this->_configuration->getProperty("database_index")); // Update the size row. $query = new UpdateQuery(); $query->setTable("dr_file"); $query->addValue("size", strval(strlen($value))); $query->addWhereEqual("id", $this->_recordId->getIdString()); $dbHandler->query($query, $this->_configuration->getProperty("database_index")); $dbHandler->commitTransaction($this->_configuration->getProperty("database_index")); $this->_asset->updateModificationDate(); }
/** * Update the reference name for this Function. * * WARNING: NOT IN OSID * * @param string $referenceName * * @throws object AuthorizationException An exception with * one of the following messages defined in * org.osid.authorization.AuthorizationException may be thrown: * {@link * org.osid.authorization.AuthorizationException#OPERATION_FAILED * OPERATION_FAILED}, {@link * org.osid.authorization.AuthorizationException#PERMISSION_DENIED * PERMISSION_DENIED}, {@link * org.osid.authorization.AuthorizationException#CONFIGURATION_ERROR * CONFIGURATION_ERROR}, {@link * org.osid.authorization.AuthorizationException#UNIMPLEMENTED * UNIMPLEMENTED}, {@link * org.osid.authorization.AuthorizationException#NULL_ARGUMENT * NULL_ARGUMENT} * * @access public */ function updateReferenceName($referenceName) { // ** parameter validation $stringRule = StringValidatorRule::getRule(); ArgumentValidator::validate($referenceName, $stringRule, true); // ** end of parameter validation if ($this->_referenceName == $referenceName) { return; } // nothing to update // update the object $this->_referenceName = $referenceName; // update the database $dbHandler = Services::getService("DatabaseManager"); $query = new UpdateQuery(); $query->setTable("az_function"); $query->addWhereEqual("function_id", $this->getId()->getIdString()); $query->addValue("function_reference_name", $referenceName); $queryResult = $dbHandler->query($query, $this->_dbIndex); if ($queryResult->getNumberOfRows() == 0) { throwError(new Error(AuthorizationExeption::OPERATION_FAILED(), "AuthorizationFunction", true)); } if ($queryResult->getNumberOfRows() > 1) { throwError(new Error(AuthorizationExeption::OPERATION_FAILED(), "AuthorizationFunction", true)); } }
/** * Update the last-changed timestamp for the node to be now so that the authorization * system can sychronize with the new value. * * @param object Id $nodeId * @return void * @access public * @since 12/20/05 */ function dirtyNode(Id $nodeId) { // Need to test more to determin if the Harmoni_Db version is fast enough to use. // if (isset($this->authorizationManager->harmoni_db)) // return $this->dirtyNode_Harmoni_Db($nodeId); $hierarchyManager = $this->authorizationManager->getHierarchyManager(); $node = $hierarchyManager->getNode($nodeId); $hierarchy = $hierarchyManager->getHierarchyForNode($node); $dbHandler = Services::getService("DBHandler"); if (isset($this->_configuration)) { $dbIndex = $this->_configuration->getProperty('database_index'); } else { $dbIndex = $hierarchyManager->_configuration->getProperty('database_index'); } $traversalInfo = $hierarchy->traverse($nodeId, Hierarchy::TRAVERSE_MODE_DEPTH_FIRST, Hierarchy::TRAVERSE_DIRECTION_DOWN, Hierarchy::TRAVERSE_LEVELS_ALL); $nodesToDirty = array(); while ($traversalInfo->hasNext()) { $info = $traversalInfo->next(); $nodeId = $info->getNodeId(); $idString = $nodeId->getIdString(); if (isset($_SESSION['__isAuthorizedCache'])) { foreach (array_keys($_SESSION['__isAuthorizedCache']) as $agentIdString) { if (isset($_SESSION['__isAuthorizedCache'][$agentIdString][$idString])) { unset($_SESSION['__isAuthorizedCache'][$agentIdString][$idString]); } } } $nodesToDirty[] = "'" . addslashes($idString) . "'"; } // Update the node's az_changed time // so that it can be removed from the caches of other users during // their synchronization. $query = new UpdateQuery(); $query->setTable("az2_node"); $query->setColumns(array("last_changed")); $query->setValues(array("NOW()")); $query->addWhere("id IN (" . implode(", ", $nodesToDirty) . ")"); // printpre(MySQL_SQLGenerator::generateSQLQuery($query)); $queryResult = $dbHandler->query($query, $dbIndex); }
/** * Set the contents of the file * * @param string $contents * @return null * @access public * @since 5/15/08 */ public function setContents($contents) { try { $this->getContents(); $query = new UpdateQuery(); $query->addWhereEqual('fk_theme', $this->themeId); $query->addWhereEqual('path', $this->path); } catch (UnknownIdException $e) { $query = new InsertQuery(); $query->addValue('fk_theme', $this->themeId); $query->addValue('path', $this->path); $mime = Services::getService("MIME"); $query->addValue('mime_type', $mime->getMIMETypeForFileName($this->getBaseName())); } $query->setTable('segue_site_theme_image'); $query->addValue('data', base64_encode($contents)); $query->addValue('size', strlen($contents)); $dbMgr = Services::getService("DatabaseManager"); $result = $dbMgr->query($query, $this->databaseIndex); if (!$result->hasNext()) { throw new UnknownIdException("Theme image '" . $this->path . "' for theme '" . $this->themeId . "' does not exist."); } return $result->field('data'); }
/** * Confirm an email address * * @param object AuthNTokens $email * @param string $confirmationCode * @return boolean True on success * @access public * @since 6/4/08 */ public function confirmEmail(AuthNTokens $authNTokens, $confirmationCode) { $dbc = Services::getService("DatabaseManager"); $dbId = $this->_configuration->getProperty('database_id'); $authenticationTable = $this->_configuration->getProperty('authentication_table'); $usernameField = $this->_configuration->getProperty('username_field'); $passwordField = $this->_configuration->getProperty('password_field'); $query = new UpdateQuery(); $query->setTable($authenticationTable); $query->addValue("email_confirmed", "1"); $query->addWhereEqual($usernameField, $authNTokens->getUsername()); $query->addWhereEqual('confirmation_code', $confirmationCode); $result = $dbc->query($query, $dbId); if ($result->getNumberOfRows()) { $confirmed = TRUE; } else { $confirmed = FALSE; } // Log the success or failure if (Services::serviceRunning("Logging")) { $loggingManager = Services::getService("Logging"); $log = $loggingManager->getLogForWriting("Authentication"); $formatType = new Type("logging", "edu.middlebury", "AgentsAndNodes", "A format in which the acting Agent[s] and the target nodes affected are specified."); $priorityType = new Type("logging", "edu.middlebury", "Event_Notice", "Normal events."); $properties = $this->getPropertiesForTokens($authNTokens); if ($confirmed) { $item = new AgentNodeEntryItem("Visitor Registration Confirmed", "Visitor Registration Confirmed: <br/> Name: " . htmlspecialchars($properties->getProperty('name')) . " <br/> Email: " . htmlspecialchars($authNTokens->getIdentifier())); } else { $priorityType = new Type("logging", "edu.middlebury", "User_Error", "Events that indicate errors in user supplied data."); $item = new AgentNodeEntryItem("Visitor Registration Failed", "Visitor Registration email confirmation failed. Confirmation code/email mis-match: <br/> Name: " . htmlspecialchars($properties->getProperty('name')) . " <br/> Email: " . htmlspecialchars($authNTokens->getIdentifier())); } $log->appendLogWithTypes($item, $formatType, $priorityType); } return $confirmed; }
/** * Run the update * * @return boolean * @access public * @since 3/8/07 */ function runUpdate() { $dbc = Services::getService('DatabaseManager'); $dbc->beginTransaction(); $toUpdate = array(array('table' => "j_node_node", 'column' => "fk_parent"), array('table' => "j_node_node", 'column' => "fk_child"), array('table' => "node", 'column' => "node_id"), array('table' => "node_ancestry", 'column' => "fk_node"), array('table' => "node_ancestry", 'column' => "fk_ancestor"), array('table' => "node_ancestry", 'column' => "fk_ancestors_child")); foreach ($toUpdate as $unit) { $query = new UpdateQuery(); $query->setTable($unit['table']); $query->setColumns(array($unit['column'])); $query->setValues(array("'edu.middlebury.repositories_root'")); $query->addWhere($unit['column'] . "='edu.middlebury.concerto.collections_root'"); $results = $dbc->query($query, 0); print "\n<br/>" . $results->getNumberOfRows() . " rows in " . $unit['table'] . " (column " . $unit['column'] . ") updated"; } $dbc->commitTransaction(); print "<div style='font-weight: bold'>" . _("Please update your repository config to use the new repository root id, 'edu.middlebury.repositories_root'.") . "</div>"; return true; }
public function testAlternateSetSyntax() { $q = new UpdateQuery('test'); $q->setValues(array(array('foo', 'bar'), array('baz', 'bar'))); $sql = $q->sql(); $this->assertEquals('UPDATE `test` AS `t0` SET `t0`.`foo` = :p1, `t0`.`baz` = :p2', $sql); }
/** * Update the description * * @param string $description * @return null * @access public * @since 5/15/08 */ public function updateDescription($description) { if (!$this->canModify()) { throw new PermissionDeniedException(); } $this->description = $description; $query = new UpdateQuery(); $query->setTable('segue_site_theme'); $query->addValue('description', $description); $query->addWhereEqual('id', $this->id); $dbc = Services::getService('DatabaseManager'); $dbc->query($query, $this->databaseIndex); }
function test_All_Queries() { $value = "'Depeche Mode rocks!'"; $this->dbhandler->connect(); // create a new queue of queries to execuete $queryQueue = new Queue(); $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->addRowOfValues(array($value)); $queryQueue->add($query); $query = new InsertQuery(); $query->setTable("test1"); $query->setColumns(array(id, value)); $query->addRowOfValues(array("3000000", $value)); $queryQueue->add($query); $query = new DeleteQuery(); $query->setTable("test1"); $query->setWhere("id = 3000000"); $queryQueue->add($query); $query = new UpdateQuery(); $query->setTable("test1"); $query->setColumns(array("value")); $query->setValues(array($value)); $query->setWhere("id > 1000 AND id < 1006"); $queryQueue->add($query); $resultQueue = $this->dbhandler->queryQueue($queryQueue); $this->assertEqual($this->dbhandler->getTotalNumberOfQueries(), 4); $this->assertEqual($this->dbhandler->getTotalNumberOfSuccessfulQueries(), 4); $this->assertEqual($this->dbhandler->getTotalNumberOfFailedQueries(), 0); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $this->assertNotNull($result->getLastAutoIncrementValue()); $id = $result->getLastAutoIncrementValue(); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $this->assertNotNull($result->getLastAutoIncrementValue()); $result = $resultQueue->next(); $this->assertEqual($result->getNumberOfRows(), 1); $result = $resultQueue->next(); $query = new SelectQuery(); $query->setColumns(array("value")); $query->addTable("test1"); $query->setWhere("id = {$id}"); $result = $this->dbhandler->query($query); $this->assertEqual($this->dbhandler->getTotalNumberOfQueries(), 5); $this->assertEqual($this->dbhandler->getTotalNumberOfSuccessfulQueries(), 5); $this->assertEqual($this->dbhandler->getTotalNumberOfFailedQueries(), 0); $this->assertEqual("'" . $result->field("value") . "'", $value); $result->free(); }