本文整理汇总了PHP中Drupal\Core\Database\Connection::insert方法的典型用法代码示例。如果您正苦于以下问题:PHP Connection::insert方法的具体用法?PHP Connection::insert怎么用?PHP Connection::insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Database\Connection
的用法示例。
在下文中一共展示了Connection::insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: register
/**
* {@inheritdoc}
*/
public function register($name, $window = 3600, $identifier = NULL)
{
if (!isset($identifier)) {
$identifier = $this->requestStack->getCurrentRequest()->getClientIp();
}
$this->connection->insert('flood')->fields(array('event' => $name, 'identifier' => $identifier, 'timestamp' => REQUEST_TIME, 'expiration' => REQUEST_TIME + $window))->execute();
}
示例2: create
/**
* {@inheritdoc}
*/
public function create(ContentEntityInterface $entity, $fields)
{
$query = $this->database->insert('comment_entity_statistics')->fields(array('entity_id', 'entity_type', 'field_name', 'cid', 'last_comment_timestamp', 'last_comment_name', 'last_comment_uid', 'comment_count'));
foreach ($fields as $field_name => $detail) {
// Skip fields that entity does not have.
if (!$entity->hasField($field_name)) {
continue;
}
// Get the user ID from the entity if it's set, or default to the
// currently logged in user.
$last_comment_uid = 0;
if ($entity instanceof EntityOwnerInterface) {
$last_comment_uid = $entity->getOwnerId();
}
if (!isset($last_comment_uid)) {
// Default to current user when entity does not implement
// EntityOwnerInterface or author is not set.
$last_comment_uid = $this->currentUser->id();
}
// Default to REQUEST_TIME when entity does not have a changed property.
$last_comment_timestamp = REQUEST_TIME;
if ($entity instanceof EntityChangedInterface) {
$last_comment_timestamp = $entity->getChangedTime();
}
$query->values(array('entity_id' => $entity->id(), 'entity_type' => $entity->getEntityTypeId(), 'field_name' => $field_name, 'cid' => 0, 'last_comment_timestamp' => $last_comment_timestamp, 'last_comment_name' => NULL, 'last_comment_uid' => $last_comment_uid, 'comment_count' => 0));
}
$query->execute();
}
示例3: save
/**
* {@inheritdoc}
*/
public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
{
if ($source[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
}
if ($alias[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
}
$fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
// Insert or update the alias.
if (empty($pid)) {
$query = $this->connection->insert('url_alias')->fields($fields);
$pid = $query->execute();
$fields['pid'] = $pid;
$operation = 'insert';
} else {
// Fetch the current values so that an update hook can identify what
// exactly changed.
$original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
$fields['pid'] = $pid;
$query = $this->connection->update('url_alias')->fields($fields)->condition('pid', $pid);
$pid = $query->execute();
$fields['original'] = $original;
$operation = 'update';
}
if ($pid) {
// @todo Switch to using an event for this instead of a hook.
$this->moduleHandler->invokeAll('path_' . $operation, array($fields));
Cache::invalidateTags(['route_match']);
return $fields;
}
return FALSE;
}
示例4: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Remove any backtraces since they may contain an unserializable variable.
unset($context['backtrace']);
// Convert PSR3-style messages to SafeMarkup::format() style, so they can be
// translated too in runtime.
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
try {
$this->connection->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => $context['link'], 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
} catch (\Exception $e) {
// When running Drupal on MySQL or MariaDB you can run into several errors
// that corrupt the database connection. Some examples for these kind of
// errors on the database layer are "1100 - Table 'xyz' was not locked
// with LOCK TABLES" and "1153 - Got a packet bigger than
// 'max_allowed_packet' bytes". If such an error happens, the MySQL server
// invalidates the connection and answers all further requests in this
// connection with "2006 - MySQL server had gone away". In that case the
// insert statement above results in a database exception. To ensure that
// the causal error is written to the log we try once to open a dedicated
// connection and write again.
if (($e instanceof DatabaseException || $e instanceof \PDOException) && $this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET) {
// Open a dedicated connection for logging.
$key = $this->connection->getKey();
$info = Database::getConnectionInfo($key);
Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']);
$this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key);
// Now try once to log the error again.
$this->log($level, $message, $context);
} else {
throw $e;
}
}
}
示例5: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Remove any backtraces since they may contain an unserializable variable.
unset($context['backtrace']);
// Convert PSR3-style messages to String::format() style, so they can be
// translated too in runtime.
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
$this->database->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => substr($context['link'], 0, 255), 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
}
示例6: insert
/**
* {@inheritdoc}
*/
public function insert($entry)
{
$return_value = NULL;
try {
$return_value = $this->connection->insert('dbtng_example')->fields($entry)->execute();
} catch (\Exception $e) {
drupal_set_message(t('db_insert failed. Message = %message, query= %query', array('%message' => $e->getMessage(), '%query' => $e->query_string)), 'error');
}
return $return_value;
}
示例7: save
/**
* {@inheritdoc}
*/
public function save($source, $alias, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $pid = NULL)
{
if ($source[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $source));
}
if ($alias[0] !== '/') {
throw new \InvalidArgumentException(sprintf('Alias path %s has to start with a slash.', $alias));
}
$fields = array('source' => $source, 'alias' => $alias, 'langcode' => $langcode);
// Insert or update the alias.
if (empty($pid)) {
$try_again = FALSE;
try {
$query = $this->connection->insert(static::TABLE)->fields($fields);
$pid = $query->execute();
} catch (\Exception $e) {
// If there was an exception, try to create the table.
if (!($try_again = $this->ensureTableExists())) {
// If the exception happened for other reason than the missing table,
// propagate the exception.
throw $e;
}
}
// Now that the table has been created, try again if necessary.
if ($try_again) {
$query = $this->connection->insert(static::TABLE)->fields($fields);
$pid = $query->execute();
}
$fields['pid'] = $pid;
$operation = 'insert';
} else {
// Fetch the current values so that an update hook can identify what
// exactly changed.
try {
$original = $this->connection->query('SELECT source, alias, langcode FROM {url_alias} WHERE pid = :pid', array(':pid' => $pid))->fetchAssoc();
} catch (\Exception $e) {
$this->catchException($e);
$original = FALSE;
}
$fields['pid'] = $pid;
$query = $this->connection->update(static::TABLE)->fields($fields)->condition('pid', $pid);
$pid = $query->execute();
$fields['original'] = $original;
$operation = 'update';
}
if ($pid) {
// @todo Switch to using an event for this instead of a hook.
$this->moduleHandler->invokeAll('path_' . $operation, array($fields));
Cache::invalidateTags(['route_match']);
return $fields;
}
return FALSE;
}
示例8: setMultiple
/**
* {@inheritdoc}
*/
public function setMultiple(array $items)
{
// Use a transaction so that the database can write the changes in a single
// commit.
$transaction = $this->connection->startTransaction();
try {
// Delete all items first so we can do one insert. Rather than multiple
// merge queries.
$this->deleteMultiple(array_keys($items));
$query = $this->connection->insert($this->bin)->fields(array('cid', 'data', 'expire', 'created', 'serialized', 'tags', 'checksum'));
foreach ($items as $cid => $item) {
$item += array('expire' => CacheBackendInterface::CACHE_PERMANENT, 'tags' => array());
Cache::validateTags($item['tags']);
$item['tags'] = array_unique($item['tags']);
// Sort the cache tags so that they are stored consistently in the DB.
sort($item['tags']);
$fields = array('cid' => $cid, 'expire' => $item['expire'], 'created' => round(microtime(TRUE), 3), 'tags' => implode(' ', $item['tags']), 'checksum' => $this->checksumProvider->getCurrentChecksum($item['tags']));
if (!is_string($item['data'])) {
$fields['data'] = serialize($item['data']);
$fields['serialized'] = 1;
} else {
$fields['data'] = $item['data'];
$fields['serialized'] = 0;
}
$query->values($fields);
}
$query->execute();
} catch (\Exception $e) {
$transaction->rollback();
// @todo Log something here or just re throw?
throw $e;
}
}
示例9: doSave
/**
* Saves a link without clearing caches.
*
* @param array $link
* A definition, according to $definitionFields, for a
* \Drupal\Core\Menu\MenuLinkInterface plugin.
*
* @return array
* The menu names affected by the save operation. This will be one menu
* name if the link is saved to the sane menu, or two if it is saved to a
* new menu.
*
* @throws \Exception
* Thrown if the storage back-end does not exist and could not be created.
* @throws \Drupal\Component\Plugin\Exception\PluginException
* Thrown if the definition is invalid, for example, if the specified parent
* would cause the links children to be moved to greater than the maximum
* depth.
*/
protected function doSave(array $link)
{
$original = $this->loadFull($link['id']);
// @todo Should we just return here if the link values match the original
// values completely?
// https://www.drupal.org/node/2302137
$affected_menus = array();
$transaction = $this->connection->startTransaction();
try {
if ($original) {
$link['mlid'] = $original['mlid'];
$link['has_children'] = $original['has_children'];
$affected_menus[$original['menu_name']] = $original['menu_name'];
} else {
// Generate a new mlid.
$options = array('return' => Database::RETURN_INSERT_ID) + $this->options;
$link['mlid'] = $this->connection->insert($this->table, $options)->fields(array('id' => $link['id'], 'menu_name' => $link['menu_name']))->execute();
}
$fields = $this->preSave($link, $original);
// We may be moving the link to a new menu.
$affected_menus[$fields['menu_name']] = $fields['menu_name'];
$query = $this->connection->update($this->table, $this->options);
$query->condition('mlid', $link['mlid']);
$query->fields($fields)->execute();
if ($original) {
$this->updateParentalStatus($original);
}
$this->updateParentalStatus($link);
} catch (\Exception $e) {
$transaction->rollback();
throw $e;
}
return $affected_menus;
}
示例10: acquire
/**
* {@inheritdoc}
*/
public function acquire($name, $timeout = 30.0)
{
// Insure that the timeout is at least 1 ms.
$timeout = max($timeout, 0.001);
$expire = microtime(TRUE) + $timeout;
if (isset($this->locks[$name])) {
// Try to extend the expiration of a lock we already acquired.
$success = (bool) $this->database->update('semaphore')->fields(array('expire' => $expire))->condition('name', $name)->condition('value', $this->getLockId())->execute();
if (!$success) {
// The lock was broken.
unset($this->locks[$name]);
}
return $success;
} else {
// Optimistically try to acquire the lock, then retry once if it fails.
// The first time through the loop cannot be a retry.
$retry = FALSE;
// We always want to do this code at least once.
do {
try {
$this->database->insert('semaphore')->fields(array('name' => $name, 'value' => $this->getLockId(), 'expire' => $expire))->execute();
// We track all acquired locks in the global variable.
$this->locks[$name] = TRUE;
// We never need to try again.
$retry = FALSE;
} catch (IntegrityConstraintViolationException $e) {
// Suppress the error. If this is our first pass through the loop,
// then $retry is FALSE. In this case, the insert failed because some
// other request acquired the lock but did not release it. We decide
// whether to retry by checking lockMayBeAvailable(). This will clear
// the offending row from the database table in case it has expired.
$retry = $retry ? FALSE : $this->lockMayBeAvailable($name);
} catch (\Exception $e) {
// Create the semaphore table if it does not exist and retry.
if ($this->ensureTableExists()) {
// Retry only once.
$retry = !$retry;
} else {
throw $e;
}
}
// We only retry in case the first attempt failed, but we then broke
// an expired lock.
} while ($retry);
}
return isset($this->locks[$name]);
}
示例11: saveMap
/**
* Saves a single ID mapping row in the database.
*
* @param array $map
* The row to save.
*/
protected function saveMap(array $map)
{
$table = 'migrate_map_sql_idmap_test';
$schema = $this->database->schema();
// If the table already exists, add any columns which are in the map array,
// but don't yet exist in the table. Yay, flexibility!
if ($schema->tableExists($table)) {
foreach (array_keys($map) as $field) {
if (!$schema->fieldExists($table, $field)) {
$schema->addField($table, $field, ['type' => 'text']);
}
}
} else {
$schema->createTable($table, $this->createSchemaFromRow($map));
}
$this->database->insert($table)->fields($map)->execute();
}
示例12: index
/**
* Index.
* @param \Drupal\user\UserInterface $user
* @return array
* @throws \Exception
* @internal param string $uid
*/
public function index(UserInterface $user)
{
// See if the user already has an API key.
$q = $this->database->select('api_keys', 'a')->fields('a');
$q->condition('a.uid', $user->id());
$user_key_object = $q->execute()->fetchObject();
if (!$user_key_object) {
// The user does not have a key. Generate one for them.
$user_key = sha1(uniqid());
// Insert it to the database.
$this->database->insert('api_keys')->fields(array('uid' => $user->id(), 'user_key' => $user_key))->execute();
} else {
$user_key = $user_key_object->user_key;
}
// Generate the URL which we should use in the CURL explaination.
// @todo
return ['#theme' => 'api-keys-user-keys', '#api_key' => $user_key, '#post_url' => 'example.com/entity/log', '#base_url' => Url::fromUserInput('/')->setOption('absolute', TRUE), '#markup' => $this->t('URL : !url and key: !key', ['!url' => $post_url, '!key' => $user_key])];
}
示例13: storeLoginSessionData
/**
* Store the Session ID and ticket for single-log-out purposes.
*
* @param string $session_id
* The session ID, to be used to kill the session later.
* @param string $ticket
* The CAS service ticket to be used as the lookup key.
*
* @codeCoverageIgnore
*/
protected function storeLoginSessionData($session_id, $ticket)
{
if ($this->settings->get('cas.settings')->get('logout.enable_single_logout') === TRUE) {
$plainsid = $session_id;
} else {
$plainsid = '';
}
$this->connection->insert('cas_login_data')->fields(array('sid', 'plainsid', 'ticket'), array(Crypt::hashBase64($session_id), $plainsid, $ticket))->execute();
}
示例14: post
/**
* Responds to POST requests and saves the new record.
*
* @param array $record
* An associative array of fields to insert into the database.
*
* @return \Drupal\rest\ModifiedResourceResponse
* The HTTP response object.
*/
public function post($record)
{
$this->validate($record);
$id = $this->dbConnection->insert('example_foo')->fields($record)->execute();
$this->logger->notice('New record has been created.');
$created_record = $this->loadRecord($id);
// Return the newly created record in the response body.
return new ModifiedResourceResponse($created_record, 201);
}
示例15: updateIndex
/**
* {@inheritdoc}
*/
public function updateIndex() {
// Interpret the cron limit setting as the maximum number of nodes to index
// per cron run.
$limit = (int)$this->searchSettings->get('index.cron_limit');
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$topics = $this->getSids($this->advancedHelp->getTopics());
// If we got interrupted by limit, this will contain the last module
// and topic we looked at.
$last = \Drupal::state()->get($this->getPluginId() . '.last_cron', ['time' => 0]);
$count = 0;
foreach ($topics as $module => $module_topics) {
// Fast forward if necessary.
if (!empty($last['module']) && $last['module'] != $module) {
continue;
}
foreach ($module_topics as $topic => $info) {
// Fast forward if necessary.
if (!empty($last['topic']) && $last['topic'] != $topic) {
continue;
}
//If we've been looking to catch up, and we have, reset so we
// stop fast forwarding.
if (!empty($last['module'])) {
unset($last['topic']);
unset($last['module']);
}
$file = $this->advancedHelp->getTopicFileName($module, $topic);
if ($file && (empty($info['sid']) || filemtime($file) > $last['time'])) {
if (empty($info['sid'])) {
$info['sid'] = $this->database->insert('advanced_help_index')
->fields([
'module' => $module,
'topic' => $topic,
'langcode' => $language
])
->execute();
}
}
// Update index, using search index "type" equal to the plugin ID.
search_index($this->getPluginId(), $info['sid'], $language, file_get_contents($file));
$count++;
if ($count >= $limit) {
$last['module'] = $module;
$last['topic'] = $topic;
\Drupal::state()->set($this->getPluginId() . '.last_cron', $last);
return;
}
}
}
\Drupal::state()->set($this->getPluginId() . '.last_cron', ['time' => time()]);
}