function _qwp_process_ops(&$msg, &$data, &$msg_type, &$ret) { global $FN_PROCESS_NEED_TRANSACTION; $ctx = false; if ($FN_PROCESS_NEED_TRANSACTION) { $ctx = db_transaction(); } try { global $FN_PROCESS_OPS; if (isset($FN_PROCESS_OPS)) { if ($FN_PROCESS_OPS($msg, $data) !== false) { $msg_type = "info"; $ret = true; } } else { $msg = L("No ops processor!"); } } catch (PDOException $e) { if ($e->errorInfo[1] == 1062) { $msg = L("Duplicated record when doing ops, please check the parameters!"); } else { $msg = L("Failed to execute query: ") . (IN_DEBUG ? $e->query_string : $e->getMessage()); } } catch (Exception $e) { $msg = L("Exception happens: ") . $e->getMessage(); } if ($ret !== true && $ctx) { $ctx->rollback(); } }
function addComment($props) { if (!$props) { drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error'); return false; } //global $user; $txn = db_transaction(); try { //$uid = $user->uid; //$props['author'] = $uid; $now = new DateTime(); $props['date_posted'] = $now->format('Y-m-d H:i:s'); // check for top level posts with an empty parent & set it to mysql null. if (!isset($props['parent_id']) || empty($props['parent_id'])) { $props['parent_id'] = null; } $result = FALSE; $query = db_insert(tableName('comment'))->fields($props); $id = $query->execute(); if ($id) { $result = $id; } else { drupal_set_message(t('We could not add your comment'), 'error'); } } catch (Exception $ex) { $txn->rollback(); drupal_set_message(t('We could not add your comment. ') . (_DEBUG ? $ex->__toString() : ''), 'error'); } return $result; }
/** * @param DataControllerCallContext $callcontext * @param DatasetMetaData $dataset * @param DatasetStorageObserver[] $observers * @throws Exception */ protected function dropDatasetStorage(DataControllerCallContext $callcontext, DatasetMetaData $dataset, array $observers = NULL) { MetaModelFactory::getInstance()->startGlobalModification(); try { $transaction = db_transaction(); try { if (isset($observers)) { foreach ($observers as $observer) { $observer->unregisterDataset($callcontext, $dataset, DatasetStorageObserver::STAGE__BEFORE); } } // dropping physical storage of the dataset $request = new DatasetStorageRequest($dataset->name); LogHelper::log_debug($request); $this->datasourceStructureHandler->dropDatasetStorage($callcontext, $request); $dataset->used = FALSE; if (isset($observers)) { foreach ($observers as $observer) { $observer->unregisterDataset($callcontext, $dataset, DatasetStorageObserver::STAGE__AFTER); } } } catch (Exception $e) { $transaction->rollback(); throw $e; } } catch (Exception $e) { MetaModelFactory::getInstance()->finishGlobalModification(FALSE); throw $e; } MetaModelFactory::getInstance()->finishGlobalModification(TRUE); }
public function delete($ids, \DatabaseTransaction $transaction = NULL) { $transaction = isset($transaction) ? $transaction : db_transaction(); try { parent::delete($ids, $transaction); db_delete('observers')->condition('observable_id', $ids, 'IN')->execute(); } catch (\Exception $e) { watchdog_exception($this->entityType, $e); $transaction->rollback(); throw $e; } }
/** * @param \Roomify\Bat\Event\Event $event * @param $granularity * * @return bool */ public function storeEvent(Event $event, $granularity = Event::BAT_HOURLY) { $stored = TRUE; $transaction = db_transaction(); try { // Itemize an event so we can save it $itemized = $event->itemize(new EventItemizer($event, $granularity)); //Write days foreach ($itemized[Event::BAT_DAY] as $year => $months) { foreach ($months as $month => $days) { db_merge($this->day_table_no_prefix)->key(array('unit_id' => $event->getUnitId(), 'year' => $year, 'month' => $month))->fields($days)->execute(); } } if ($granularity == Event::BAT_HOURLY && isset($itemized[Event::BAT_HOUR])) { // Write Hours foreach ($itemized[Event::BAT_HOUR] as $year => $months) { foreach ($months as $month => $days) { foreach ($days as $day => $hours) { // Count required as we may receive empty hours for granular events that start and end on midnight if (count($hours) > 0) { db_merge($this->hour_table_no_prefix)->key(array('unit_id' => $event->getUnitId(), 'year' => $year, 'month' => $month, 'day' => substr($day, 1)))->fields($hours)->execute(); } } } } //If we have minutes write minutes foreach ($itemized[Event::BAT_MINUTE] as $year => $months) { foreach ($months as $month => $days) { foreach ($days as $day => $hours) { foreach ($hours as $hour => $minutes) { db_merge($this->minute_table_no_prefix)->key(array('unit_id' => $event->getUnitId(), 'year' => $year, 'month' => $month, 'day' => substr($day, 1), 'hour' => substr($hour, 1)))->fields($minutes)->execute(); } } } } } } catch (\Exception $e) { $stored = FALSE; $transaction->rollback(); watchdog_exception('BAT Event Save Exception', $e); } return $stored; }
/** * Delete a user from the system. * * This is a copy of user_delete() minus the user_load() call. */ private function delete_single(stdClass $account) { $uids = array($account->uid); $transaction = db_transaction(); try { module_invoke_all('user_delete', $account); module_invoke_all('entity_delete', $account, 'user'); field_attach_delete('user', $account); drupal_session_destroy_uid($account->uid); db_delete('users')->condition('uid', $uids, 'IN')->execute(); db_delete('users_roles')->condition('uid', $uids, 'IN')->execute(); db_delete('authmap')->condition('uid', $uids, 'IN')->execute(); } catch (Exception $e) { $transaction->rollback(); watchdog_exception('user', $e); throw $e; } $this->resetCache($uids); }
/** * Delete a list of memberships context entities. * * @param object $entities * An array of memberships contexts to be deleted. */ public function delete_multiple($entities) { $ids = array(); if (!empty($entities)) { $transaction = db_transaction(); try { foreach ($entities as $entity) { module_invoke_all('lti_tool_provider_memberships_context_delete', $entity); module_invoke_all('entity_delete', $entity, 'lti_tool_provider_memberships_context'); field_attach_delete('lti_tool_provider_memberships_context', $entity); $ids[] = $entity->lti_tool_provider_memberships_context_id; } db_delete('lti_tool_provider_memberships_context')->condition('lti_tool_provider_memberships_context_id', $ids, 'IN')->execute(); } catch (Exception $e) { $transaction->rollback(); watchdog_exception('lti_tool_provider_memberships_context', $e); throw $e; } } }
/** * Perform menu-specific rebuilding. */ protected function menuLinksRebuild() { if ($this->lock->acquire(__FUNCTION__)) { $transaction = db_transaction(); try { // Ensure the menu links are up to date. $this->menuLinkManager->rebuild(); // Ignore any database replicas temporarily. db_ignore_replica(); } catch (\Exception $e) { $transaction->rollback(); watchdog_exception('menu', $e); } $this->lock->release(__FUNCTION__); } else { // Wait for another request that is already doing this work. // We choose to block here since otherwise the router item may not // be available during routing resulting in a 404. $this->lock->wait(__FUNCTION__); } }
/** * Makes sure that every simple queue has a subqueue. */ protected function ensureSubqueue() { global $user; static $queues = array(); if (!isset($queues[$this->queue->name])) { $queues[$this->queue->name] = TRUE; $transaction = db_transaction(); $query = new EntityFieldQuery(); $query->entityCondition('entity_type', 'entityqueue_subqueue')->entityCondition('bundle', $this->queue->name); $result = $query->execute(); // If we don't have a subqueue already, create one now. if (empty($result['entityqueue_subqueue'])) { $subqueue = entityqueue_subqueue_create(); $subqueue->queue = $this->queue->name; $subqueue->name = $this->queue->name; $subqueue->label = $this->getSubqueueLabel($subqueue); $subqueue->module = 'entityqueue'; $subqueue->uid = $user->uid; entity_get_controller('entityqueue_subqueue')->save($subqueue, $transaction); } } }
/** * Perform menu-specific rebuilding. */ protected function menuLinksRebuild() { if ($this->lock->acquire(__FUNCTION__)) { $transaction = db_transaction(); try { // Ensure the menu links are up to date. menu_link_rebuild_defaults(); // Clear the menu cache. menu_cache_clear_all(); // Track which menu items are expanded. _menu_update_expanded_menus(); } catch (\Exception $e) { $transaction->rollback(); watchdog_exception('menu', $e); } $this->lock->release(__FUNCTION__); } else { // Wait for another request that is already doing this work. // We choose to block here since otherwise the router item may not // be available during routing resulting in a 404. $this->lock->wait(__FUNCTION__); } }
/** * @param DataControllerCallContext $callcontext * @param DatasetMetaData $dataset * @param DatasetStorageObserver[] $observers * @throws Exception */ protected function disableDatasetStorage(DataControllerCallContext $callcontext, DatasetMetaData $dataset, array $observers = NULL) { MetaModelFactory::getInstance()->startGlobalModification(); try { $transaction = db_transaction(); try { $dataset->used = FALSE; if (isset($observers)) { foreach ($observers as $observer) { $observer->disableDataset($callcontext, $dataset); } } } catch (Exception $e) { $transaction->rollback(); throw $e; } } catch (Exception $e) { MetaModelFactory::getInstance()->finishGlobalModification(FALSE); throw $e; } MetaModelFactory::getInstance()->finishGlobalModification(TRUE); }
public function __construct($message, $tag, $module, $variables = array(), $name = NULL, array $options = array()) { $this->message = $message; $this->tag = $tag; $this->module = $module; $this->variables = $variables; $this->txn = db_transaction($name, $options); }
/** * Import SQL from the file. * * @param string $file * * @return int */ function db_import($file) { if ($fp = fopen($file, 'r')) { $sql = ''; $i = 0; $flag = true; db_transaction(); while ($line = fgets($fp)) { $line = str_replace("\r\n", "\n", $line); $line = str_replace("\r", "\n", $line); if ((substr_count($line, '\'') - substr_count($line, '\\\'')) % 2 !== 0) { $flag = !$flag; } $sql .= $line; if (preg_match('/;$/', trim($line)) && $flag) { $resource = db_query($sql); if (!$resource) { db_rollback(); if (LOGGING_MESSAGE) { logging('message', 'db: Query error: ' . db_error()); } error('db: Query error' . (DEBUG_LEVEL ? ': ' . db_error() : '')); } $sql = ''; $i++; } } fclose($fp); db_commit(); } else { error('db: Import file can\'t read'); } return $i; }
/** * @param DataControllerCallContext $callcontext * @param DatasetMetaData $originalDataset * @param DatasetMetaData $modifiedDataset * @param DatasetStorageObserver[] $observers * @throws Exception */ protected function updateProperties(DataControllerCallContext $callcontext, DatasetMetaData $originalDataset, DatasetMetaData $modifiedDataset, array $observers = NULL) { $justPersistedColumns = NULL; ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->newIncludedColumns); ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->restoredColumns); ArrayHelper::merge($justPersistedColumns, $callcontext->changeAction->updatedDataTypeIncludedColumns); $columns = $justPersistedColumns; ArrayHelper::merge($columns, $callcontext->changeAction->updatedColumns); if ($callcontext->changeAction->isDatasetUpdated || isset($columns) || $callcontext->changeAction->isKeyUpdated) { MetaModelFactory::getInstance()->startGlobalModification(); try { $transaction = db_transaction(); try { if (isset($columns)) { foreach ($columns as $column) { if (isset($justPersistedColumns[$column->name])) { $column->used = TRUE; } if (isset($callcontext->changeAction->updatedColumns[$column->name])) { $modifiedColumn = $modifiedDataset->getColumn($column->name); $column->publicName = $modifiedColumn->publicName; $column->description = $modifiedColumn->description; $column->source = $modifiedColumn->source; $column->key = $modifiedColumn->key; } if (isset($observers)) { foreach ($observers as $observer) { $observer->updateColumn($callcontext, $originalDataset, $column->name); } } } } if ($callcontext->changeAction->isDatasetUpdated) { $originalDataset->publicName = $modifiedDataset->publicName; $originalDataset->description = $modifiedDataset->description; $originalDataset->initializeSourceFrom($modifiedDataset->source, TRUE); $originalDataset->initializeAliasesFrom($modifiedDataset->aliases, TRUE); if (isset($observers)) { foreach ($observers as $observer) { $observer->updateDataset($callcontext, $originalDataset); } } } if ($callcontext->changeAction->isKeyUpdated) { $modifiedDatasetKeyColumnNames = $modifiedDataset->findKeyColumnNames(); if (isset($modifiedDatasetKeyColumnNames)) { $this->executeDatasetUpdateOperations( $callcontext, $originalDataset, array(new CreateDatasetKeyOperation())); } } } catch (Exception $e) { $transaction->rollback(); throw $e; } } catch (Exception $e) { MetaModelFactory::getInstance()->finishGlobalModification(FALSE); throw $e; } MetaModelFactory::getInstance()->finishGlobalModification(TRUE); } }
protected function update(Import\ImportStream $stream, Import\ImportContext $context) { $datasets = $stream->get('datasets'); if (empty($datasets)) { return; } gd_datasource_set_active($context->get('datasourceName')); $metamodel = data_controller_get_metamodel(); $environment_metamodel = data_controller_get_environment_metamodel(); $datasource = $environment_metamodel->getDataSource($context->get('datasourceName')); foreach ( $datasets as $dataset ) { $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid); if ( !$existingDataset ) { // map for re-linking dependent objects $dataset->originalName = $dataset->name; // create new name $newDatasetName = GD_NamingConvention::generateDatasetName(); $dataset->name = $newDatasetName; $dataset->source = $newDatasetName; $dataset->datasourceName = $datasource->name; } else { // map for re-linking dependent objects $dataset->originalName = $dataset->name; $dataset->name = $existingDataset->name; $dataset->source = $existingDataset->source; $dataset->datasourceName = $existingDataset->datasourceName; } } // prepare dataset columns for import $this->prepareColumns($datasets); // prepares the metadata object, has to be of type RecordMetaData foreach ( $datasets as $key => $dataset ) { $metadata = new DatasetMetaData(); $metadata->initializeFrom($dataset); $datasets[$key] = $metadata; } // ensure datasets are created in order to satisfy dependencies usort($datasets, array(new ReferencedDatasetComparator(), 'compare')); foreach ( $datasets as $dataset ) { $existingDataset = GD_DatasetMetaModelLoaderHelper::findDatasetByUUID($metamodel->datasets, $dataset->uuid); if ($existingDataset) { gd_data_controller_ddl_modify_dataset($dataset); } else { MetaModelFactory::getInstance()->startGlobalModification(); try { $transaction = db_transaction(); try { gd_data_controller_ddl_create_dataset($dataset); } catch (Exception $e) { $transaction->rollback(); throw $e; } } catch (Exception $e) { MetaModelFactory::getInstance()->finishGlobalModification(false); throw $e; } MetaModelFactory::getInstance()->finishGlobalModification(true); } } $stream->set('datasets',$datasets); }
public function delete($fpids) { $transaction = db_transaction(); if (!empty($fpids)) { $entities = fieldable_panels_panes_load_multiple($fpids, array()); try { foreach ($entities as $fpid => $entity) { // Call the entity-specific callback (if any): module_invoke_all('entity_delete', $entity, 'fieldable_panels_pane'); field_attach_delete('fieldable_panels_pane', $entity); } // Delete after calling hooks so that they can query entity tables as needed. db_delete('fieldable_panels_panes')->condition('fpid', $fpids, 'IN')->execute(); db_delete('fieldable_panels_panes_revision')->condition('fpid', $fpids, 'IN')->execute(); } catch (Exception $e) { $transaction->rollback(); watchdog_exception('fieldable_panels_pane', $e); throw $e; } // Clear the page and block and entity_load_multiple caches. entity_get_controller('fieldable_panels_pane')->resetCache(); } }
/** * Do a fast delete without loading entities of firing delete hooks. * * @param array $ids * An array of entity IDs. * @param \DatabaseTransaction $transaction * Optionally a DatabaseTransaction object to use. Allows overrides to pass * in their transaction object. * * @throws \Exception * When there is a database error. */ protected function fastDelete($ids, \DatabaseTransaction $transaction = NULL) { $transaction = isset($transaction) ? $transaction : db_transaction(); try { db_delete($this::getTableName())->condition($this::getTableIdkey(), $ids, 'IN')->execute(); // Reset the cache as soon as the changes have been applied. $this->resetCache($ids); // Ignore slave server temporarily. db_ignore_slave(); } catch (\Exception $e) { $transaction->rollback(); watchdog_exception($this->entityType, $e); throw $e; } }
static function updateProposal($props, $proposal_id) { if (!$props) { drupal_set_message(t('Update requested with empty (filtered) data set'), 'error'); return false; } global $user; $txn = db_transaction(); try { $uid = Users::getMyId(); if (!Users::isOfType(_STUDENT_TYPE, $uid) && !Users::isAdmin()) { drupal_set_message(t('You must be a student to submit a proposal'), 'error'); return FALSE; } //$project = Project::getProjectById($project_id); // $student_details = Users::getStudentDetails($uid); // $props['owner_id'] = $uid; // $props['org_id'] = $project['org_id']; // $props['inst_id'] = $student_details->inst_id ; // $props['supervisor_id'] = $student_details->supervisor_id ; //$props['pid'] = $project['pid']; //$props['state'] = 'draft' ; $id = db_update(tableName(_PROPOSAL_OBJ))->fields($props)->condition(self::keyField(_PROPOSAL_OBJ), $proposal_id)->execute(); // if ($id){ // //TODO: notify mentor??? // drupal_set_message('You have saved your proposal. Later you can edit it.'); // return TRUE; // } else { // drupal_set_message(tt('We could not add your %1$s.', $type), 'error'); // } return TRUE; } catch (Exception $ex) { $txn->rollback(); drupal_set_message(t('We could not update your proposal.') . (_DEBUG ? $ex->__toString() : ''), 'error'); } return FALSE; }
/** * {@inheritdoc} */ public function addItem($plugin, $item_type, $item_id) { $transaction = db_transaction(); $is_new = FALSE; if ($this->isNew()) { $this->save(); $is_new = TRUE; } $item = tmgmt_job_item_create($plugin, $item_type, $item_id, array('tjid' => $this->id())); $item->save(); if ($item->getWordCount() == 0) { $transaction->rollback(); // In case we got word count 0 for the first job item, NULL tjid so that // if there is another addItem() call the rolled back job object will get // persisted. if ($is_new) { $this->tjid = NULL; } throw new TMGMTException('Job item @label (@type) has no translatable content.', array('@label' => $item->label(), '@type' => $item->getSourceType())); } return $item; }
static function addStudentGroup($group) { if (!$group) { drupal_set_message(t('Insert requested with empty (filtered) data set')); return false; } global $user; $txn = db_transaction(); try { $uid = $user->uid; $institute_ids = db_select('soc_user_membership')->fields('soc_user_membership', array('group_id'))->condition('uid', $uid)->condition('type', _INSTITUTE_GROUP)->execute()->fetchCol(); if ($institute_ids) { $inst_id = $institute_ids[0]; } else { $inst_id = 0; } $gid = db_insert('soc_studentgroups')->fields(array('name' => $group['name'], 'owner_id' => $uid, 'inst_id' => $inst_id, 'description' => $group['description'] ?: ''))->execute(); if ($gid) { $result = db_insert('soc_user_membership')->fields(array('uid' => $uid, 'type' => _STUDENT_GROUP, 'group_id' => $gid))->execute(); if ($result) { $result = $result && db_insert('soc_codes')->fields(array('type' => _STUDENT_GROUP, 'code' => createRandomCode(_STUDENT_GROUP, $gid), 'entity_id' => $inst_id, 'studentgroup_id' => $gid))->execute(); if (!$result) { drupal_set_message(t('We could not add a code for this group.'), 'error'); } } else { drupal_set_message(t('We could not add you to this group.'), 'error'); } } else { drupal_set_message(t('We could not add your group.'), 'error'); } return $result ? $gid : FALSE; } catch (Exception $ex) { $txn->rollback(); drupal_set_message(t('We could not add your group.') . (_DEBUG ? $ex->__toString() : ''), 'error'); } return FALSE; }
/** * 删除Entity */ public function delete($entity) { $this->beforeDelete($entity); if (is_numeric($entity)) { $entityId = $entity; } else { $entityId = $entity->{$this->primaryKey}; } $transaction = db_transaction(); try { db_delete($this->entityInfo['baseTable'])->condition($this->primaryKey, $entityId)->execute(); EntityField::fieldDelete($this->entityType, $entityId); $this->afterDelete($entityId); } catch (Exception $e) { $transaction->rollback(); throw $e; return false; } $this->cacheBin->resetCache(array($entityId)); return true; }
<?php // ワンタイムトークン if (!token('check')) { error('不正なアクセスです。'); } // トランザクションを開始 db_transaction(); // 教室を削除 $resource = delete_classes(array('where' => array('classes.id = :id', array('id' => $_POST['id']))), array('associate' => 'true')); if (!$resource) { error('データを削除できません。'); } // トランザクションを終了 db_commit(); // リダイレクト redirect('/admin/class?ok=delete');
function api_node_save($node) { $transaction = db_transaction(); try { // Load the stored entity, if any. if (!empty($node->nid) && !isset($node->original)) { $node->original = entity_load_unchanged('node', $node->nid); } field_attach_presave('node', $node); global $user; // Determine if we will be inserting a new node. if (!isset($node->is_new)) { $node->is_new = empty($node->nid); } /* // Set the timestamp fields. if (empty($node->created)) { $node->created = REQUEST_TIME; } // The changed timestamp is always updated for bookkeeping purposes, // for example: revisions, searching, etc. $node->changed = REQUEST_TIME; $node->timestamp = REQUEST_TIME; */ $update_node = TRUE; // Let modules modify the node before it is saved to the database. module_invoke_all('node_presave', $node); module_invoke_all('entity_presave', $node, 'node'); if ($node->is_new || !empty($node->revision)) { // When inserting either a new node or a new node revision, $node->log // must be set because {node_revision}.log is a text column and therefore // cannot have a default value. However, it might not be set at this // point (for example, if the user submitting a node form does not have // permission to create revisions), so we ensure that it is at least an // empty string in that case. // @todo: Make the {node_revision}.log column nullable so that we can // remove this check. if (!isset($node->log)) { $node->log = ''; } } elseif (!isset($node->log) || $node->log === '') { // If we are updating an existing node without adding a new revision, we // need to make sure $node->log is unset whenever it is empty. As long as // $node->log is unset, drupal_write_record() will not attempt to update // the existing database column when re-saving the revision; therefore, // this code allows us to avoid clobbering an existing log entry with an // empty one. unset($node->log); } // When saving a new node revision, unset any existing $node->vid so as to // ensure that a new revision will actually be created, then store the old // revision ID in a separate property for use by node hook implementations. if (!$node->is_new && !empty($node->revision) && $node->vid) { $node->old_vid = $node->vid; unset($node->vid); } // Save the node and node revision. if ($node->is_new) { // For new nodes, save new records for both the node itself and the node // revision. drupal_write_record('node', $node); _node_save_revision($node, $user->uid); $op = 'insert'; } else { // For existing nodes, update the node record which matches the value of // $node->nid. drupal_write_record('node', $node, 'nid'); // Then, if a new node revision was requested, save a new record for // that; otherwise, update the node revision record which matches the // value of $node->vid. if (!empty($node->revision)) { _node_save_revision($node, $user->uid); } else { _node_save_revision($node, $user->uid, 'vid'); $update_node = FALSE; } $op = 'update'; } if ($update_node) { db_update('node')->fields(array('vid' => $node->vid))->condition('nid', $node->nid)->execute(); } // Call the node specific callback (if any). This can be // node_invoke($node, 'insert') or // node_invoke($node, 'update'). node_invoke($node, $op); // Save fields. $function = "field_attach_{$op}"; $function('node', $node); module_invoke_all('node_' . $op, $node); module_invoke_all('entity_' . $op, $node, 'node'); // Update the node access table for this node. node_access_acquire_grants($node); // Clear internal properties. unset($node->is_new); unset($node->original); // Clear the static loading cache. entity_get_controller('node')->resetCache(array($node->nid)); // Ignore slave server temporarily to give time for the // saved node to be propagated to the slave. db_ignore_slave(); } catch (Exception $e) { $transaction->rollback(); watchdog_exception('node', $e); throw $e; } }
/** * Change a field's type, even if it has data. * * @param $field_name * The name of the field to change. * @param $type * The type of field to change it to. * @param array $column_renames * An array of existing field schema columns to rename. For example, if the * old field type has a column 'value' which maps to the new field type's * 'data' column, use array('value' => 'data') to ensure the old column * is just renamed instead of dropped. To ensure an old field column is * dropped, for example, if the same column name is used in the new * field type, but is used to store different data, use * array('old_column' => FALSE). * @param array $field_overrides * An optional array that overrides any of the values in the $field * definition array prior to saving. * @param array $field_instance_overrides * An optional array that overrides any of the values in any of the field's * instance definition array prior to saving. * * @return array * The change field if everything was successful. * * @throws Exception */ public static function changeType($field_name, $type, array $column_renames = array(), array $field_overrides = array(), array $field_instance_overrides = array()) { $field = $prior_field = field_read_field($field_name); if (empty($field)) { throw new Exception("Field {$field_name} does not exist or is inactive or deleted."); } if ($field['type'] === $type) { throw new Exception("Field {$field_name} is already type {$type}."); } if ($field['storage']['type'] !== 'field_sql_storage') { throw new Exception("Unable to change field type for field {$field_name} using storage {$field['storage']['type']}."); } $type_info = field_info_field_types($type); if (empty($type_info)) { throw new Exception("Invalid field type {$type}."); } $transaction = db_transaction(); try { // Serialize properties back into the data property so it can be saved // to the database. $field['data'] = array(); foreach ($field as $key => $value) { switch ($key) { case 'id': case 'field_name': case 'type': case 'module': case 'active': case 'locked': case 'cardinality': case 'deleted': case 'data': break; default: $field['data'][$key] =& $field[$key]; } } // Update basic information on the field config. $field['type'] = $type; $field['module'] = $type_info['module']; $field['settings'] = array_intersect_key($field['settings'], $type_info['settings']); $field['settings'] += $type_info['settings']; // @todo Check if $field['translatable'] needs to be changed. // Make any final field overrides before updating the schema and saving // the field config record back to the database. $field = drupal_array_merge_deep($field, $field_overrides); static::changeSchema($field, $column_renames); drupal_write_record('field_config', $field, array('id')); // Now update the instances for this field. static::changeInstances($field, $field_instance_overrides); // Clear caches field_cache_clear(); // Invoke external hooks after the cache is cleared for API consistency. $has_data = field_has_data($field); module_invoke_all('field_update_field', $field, $prior_field, $has_data); watchdog('helper', "Converted field {$field_name} from {$prior_field['type']} to {$type}."); return $field; } catch (Exception $e) { $transaction->rollback(); watchdog_exception('helper', $e); throw $e; } }
/** * Delete Resources. * * @param array $entities * An array of Resources to delete. * * @throws Exception */ public function deleteMultiple($entities) { $ids = array(); if (!empty($entities)) { $transaction = db_transaction(); try { foreach ($entities as $entity) { module_invoke_all('lti_tool_provider_outcomes_resource_delete', $entity); // Invoke hook_entity_delete(). module_invoke_all('entity_delete', $entity, 'lti_tool_provider_outcomes_resource'); field_attach_delete('lti_tool_provider_outcomes_resource', $entity); $ids[] = $entity->lti_tool_provider_outcomes_resource_id; } db_delete('lti_tool_provider_outcomes_resource')->condition('lti_tool_provider_outcomes_resource_id', $ids, 'IN')->execute(); } catch (Exception $e) { $transaction->rollback(); watchdog_exception('lti_tool_provider_outcomes_resource', $e); throw $e; } } }
/** * Tests transaction stacking, commit, and rollback. */ function testTransactionStacking() { // This test won't work right if transactions are not supported. if (!Database::getConnection()->supportsTransactions()) { return; } $database = Database::getConnection(); // Standard case: pop the inner transaction before the outer transaction. $transaction = db_transaction(); $this->insertRow('outer'); $transaction2 = db_transaction(); $this->insertRow('inner'); // Pop the inner transaction. unset($transaction2); $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the inner transaction'); // Pop the outer transaction. unset($transaction); $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the outer transaction'); $this->assertRowPresent('outer'); $this->assertRowPresent('inner'); // Pop the transaction in a different order they have been pushed. $this->cleanUp(); $transaction = db_transaction(); $this->insertRow('outer'); $transaction2 = db_transaction(); $this->insertRow('inner'); // Pop the outer transaction, nothing should happen. unset($transaction); $this->insertRow('inner-after-outer-commit'); $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction'); // Pop the inner transaction, the whole transaction should commit. unset($transaction2); $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction'); $this->assertRowPresent('outer'); $this->assertRowPresent('inner'); $this->assertRowPresent('inner-after-outer-commit'); // Rollback the inner transaction. $this->cleanUp(); $transaction = db_transaction(); $this->insertRow('outer'); $transaction2 = db_transaction(); $this->insertRow('inner'); // Now rollback the inner transaction. $transaction2->rollback(); unset($transaction2); $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction'); // Pop the outer transaction, it should commit. $this->insertRow('outer-after-inner-rollback'); unset($transaction); $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction'); $this->assertRowPresent('outer'); $this->assertRowAbsent('inner'); $this->assertRowPresent('outer-after-inner-rollback'); // Rollback the inner transaction after committing the outer one. $this->cleanUp(); $transaction = db_transaction(); $this->insertRow('outer'); $transaction2 = db_transaction(); $this->insertRow('inner'); // Pop the outer transaction, nothing should happen. unset($transaction); $this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction'); // Now rollback the inner transaction, it should rollback. $transaction2->rollback(); unset($transaction2); $this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction'); $this->assertRowPresent('outer'); $this->assertRowAbsent('inner'); // Rollback the outer transaction while the inner transaction is active. // In that case, an exception will be triggered because we cannot // ensure that the final result will have any meaning. $this->cleanUp(); $transaction = db_transaction(); $this->insertRow('outer'); $transaction2 = db_transaction(); $this->insertRow('inner'); $transaction3 = db_transaction(); $this->insertRow('inner2'); // Rollback the outer transaction. try { $transaction->rollback(); unset($transaction); $this->fail('Rolling back the outer transaction while the inner transaction is active resulted in an exception.'); } catch (TransactionOutOfOrderException $e) { $this->pass('Rolling back the outer transaction while the inner transaction is active resulted in an exception.'); } $this->assertFalse($database->inTransaction(), 'No more in a transaction after rolling back the outer transaction'); // Try to commit one inner transaction. unset($transaction3); $this->pass('Trying to commit an inner transaction resulted in an exception.'); // Try to rollback one inner transaction. try { $transaction->rollback(); unset($transaction2); $this->fail('Trying to commit an inner transaction resulted in an exception.'); } catch (TransactionNoActiveException $e) { $this->pass('Trying to commit an inner transaction resulted in an exception.'); } $this->assertRowAbsent('outer'); $this->assertRowAbsent('inner'); $this->assertRowAbsent('inner2'); }
static function addProject($props) { if (!$props) { drupal_set_message(t('Insert requested with empty (filtered) data set'), 'error'); return false; } // sort and process the datetime array structure // pre sql statement. Project::normaliseFormArrays($props); global $user; $txn = db_transaction(); try { $uid = $user->uid; $props['owner_id'] = $uid; //TODO: for now we assume the mentor is the same as creating the project. As long as we have not built //funcitonality to connect mentors to projects, this is a valid assumption $props['mentor_id'] = $uid; if (!isset($props['state'])) { $props['state'] = 'pending'; } //We normalise urls: if they start with http or https we assume the user inserted a full url //otherwise we assume a non-https full url if (isset($props['url']) && $props['url'] && stripos($props['url'], 'http') === FALSE) { $props['url'] = 'http://' . $props['url']; } $result = FALSE; $query = db_insert(tableName(_PROJECT_OBJ))->fields($props); $id = $query->execute(); if ($id) { $result = $id; } else { drupal_set_message(t('We could not add your project'), 'error'); } } catch (Exception $ex) { $txn->rollback(); drupal_set_message(t('We could not add your project. ') . (_DEBUG ? $ex->__toString() : ''), 'error'); } return $result; }
public function execute_logged($message, $tag, $module, array $variables = array(), $uid = 0, $referrer = '', $host = '', $timestamp = 0) { $transaction = Transaction::is_in_transaction() ? null : \db_transaction(); try { $retval = parent::execute(); if (!Transaction::is_in_transaction()) { \cvwobase_add_audit($message, $tag, $module, $variables, $uid, $referrer, $host, $timestamp); } } catch (Exception $e) { if (!empty($transaction)) { $transaction->rollback(); } throw $e; } return $retval; }
/** * Generates a database prefix for running tests. * * The generated database table prefix is used for the Backdrop installation * being performed for the test. It is also used as user agent HTTP header * value by the cURL-based browser of BackdropWebTestCase, which is sent * to the Backdrop installation of the test. During early Backdrop bootstrap, * the user agent HTTP header is parsed, and if it matches, all database * queries use the database table prefix that has been generated here. * * @see BackdropWebTestCase::curlInitialize() * @see backdrop_valid_test_ua() * @see BackdropWebTestCase::setUp() */ protected function prepareDatabasePrefix() { // Generate a temporary prefixed database to ensure that tests have a clean // starting point and confirm that random prefix isn't already in use. db_transaction(); do { $prefix = 'simpletest' . mt_rand(100000, 999999); $prefix_exists = db_query("SELECT COUNT(*) FROM {simpletest_prefix} WHERE prefix = :prefix", array(':prefix' => $prefix))->fetchField(); } while ($prefix_exists); $this->databasePrefix = $prefix; // As soon as the database prefix is set, the test might start to execute. // All assertions as well as the SimpleTest batch operations are associated // with the testId, so the database prefix has to be associated with it. db_insert('simpletest_prefix')->fields(array('test_id' => $this->testId, 'prefix' => $this->databasePrefix))->execute(); }
static function updateAgreement($props) { if (!$props) { drupal_set_message(t('Update requested with empty (filtered) data set'), 'error'); return false; } //echo var_dump($props); $txn = db_transaction(); try { $id = db_update(tableName(_AGREEMENT_OBJ))->fields($props)->condition(self::keyField(_AGREEMENT_OBJ), $props['agreement_id'])->execute(); if ($props['student_signed'] && $props['supervisor_signed'] && $props['mentor_signed']) { $res = db_update(tableName(_PROJECT_OBJ))->fields(array('state' => 'active'))->condition(self::keyField(_PROJECT_OBJ), $props['project_id'])->execute(); } return TRUE; } catch (Exception $ex) { $txn->rollback(); drupal_set_message(t('We could not update your agreement.') . (_DEBUG ? $ex->__toString() : ''), 'error'); } return FALSE; }