/**
  * Displays a listing of migration messages.
  *
  * Messages are truncated at 56 chars.
  *
  * @return array
  *   A render array as expected by drupal_render().
  */
 public function overview($migration_group, $migration)
 {
     $rows = [];
     $classes = static::getLogLevelClassMap();
     /** @var MigrationInterface $migration */
     $migration = Migration::load($migration);
     $source_id_field_names = array_keys($migration->getSourcePlugin()->getIds());
     $column_number = 1;
     foreach ($source_id_field_names as $source_id_field_name) {
         $header[] = ['data' => $source_id_field_name, 'field' => 'sourceid' . $column_number++, 'class' => [RESPONSIVE_PRIORITY_MEDIUM]];
     }
     $header[] = ['data' => $this->t('Severity level'), 'field' => 'level', 'class' => [RESPONSIVE_PRIORITY_LOW]];
     $header[] = ['data' => $this->t('Message'), 'field' => 'message'];
     $message_table = $migration->getIdMap()->messageTableName();
     $query = $this->database->select($message_table, 'm')->extend('\\Drupal\\Core\\Database\\Query\\PagerSelectExtender')->extend('\\Drupal\\Core\\Database\\Query\\TableSortExtender');
     $query->fields('m');
     $result = $query->limit(50)->orderByHeader($header)->execute();
     foreach ($result as $message_row) {
         $column_number = 1;
         foreach ($source_id_field_names as $source_id_field_name) {
             $column_name = 'sourceid' . $column_number++;
             $row[$column_name] = $message_row->{$column_name};
         }
         $row['level'] = $message_row->level;
         $row['message'] = $message_row->message;
         $row['class'] = [Html::getClass('migrate-message-' . $message_row->level), $classes[$message_row->level]];
         $rows[] = $row;
     }
     $build['message_table'] = ['#type' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => ['id' => $message_table, 'class' => [$message_table]], '#empty' => $this->t('No messages for this migration.')];
     $build['message_pager'] = ['#type' => 'pager'];
     return $build;
 }
 private function get_sitemap_from_db()
 {
     /** @var SelectInterface $query */
     $query = $this->db->select('custom_sitemap', 's')->fields('s', array('sitemap_string'))->condition('language_code', $this->language->getId());
     $result = $query->execute()->fetchAll();
     return !empty($result[0]->sitemap_string) ? $result[0]->sitemap_string : NULL;
 }
Beispiel #3
0
 /**
  * {@inheritdoc}
  */
 public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL)
 {
     if (!isset($identifier)) {
         $identifier = $this->requestStack->getCurrentRequest()->getClientIp();
     }
     $number = $this->connection->select('flood', 'f')->condition('event', $name)->condition('identifier', $identifier)->condition('timestamp', REQUEST_TIME - $window, '>')->countQuery()->execute()->fetchField();
     return $number < $threshold;
 }
Beispiel #4
0
 /**
  * @inheritdoc
  */
 public function getUid($authname, $provider)
 {
     $authname = $this->connection->select('authmap', 'am')->fields('am', array('uid'))->condition('authname', $authname)->condition('provider', $provider)->range(0, 1)->execute()->fetchObject();
     if ($authname) {
         return $authname->uid;
     }
     return FALSE;
 }
 /**
  * Implements Drupal\file\FileUsage\FileUsageInterface::listUsage().
  */
 public function listUsage(FileInterface $file)
 {
     $result = $this->connection->select($this->tableName, 'f')->fields('f', array('module', 'type', 'id', 'count'))->condition('fid', $file->id())->condition('count', 0, '>')->execute();
     $references = array();
     foreach ($result as $usage) {
         $references[$usage->module][$usage->type][$usage->id] = $usage->count;
     }
     return $references;
 }
 /**
  * {@inheritdoc}
  */
 public function loadMultiple($nids, $access = TRUE)
 {
     $query = $this->connection->select('node', 'n', array('fetch' => \PDO::FETCH_ASSOC));
     $query->fields('n');
     $query->condition('n.nid', $nids, 'IN');
     if ($access) {
         $query->addTag('node_access');
     }
     return $query->execute();
 }
 /**
  * {@inheritdoc}
  */
 public function getRange($start, $stop = NULL)
 {
     $query = $this->connection->select($this->table, 't')->fields('t', array('value'))->condition('collection', $this->collection)->condition('name', $start, '>=');
     if ($stop !== NULL) {
         $query->condition('name', $stop, '<=');
     }
     $result = $query->orderBy('name', 'ASC')->execute();
     $values = array();
     foreach ($result as $item) {
         $values[] = $this->serializer->decode($item->value);
     }
     return $values;
 }
Beispiel #8
0
 public function query($group_by = FALSE)
 {
     $this->ensureMyTable();
     // Use the table definition to correctly add this user ID condition.
     if ($this->table != 'comment_field_data') {
         $subselect = $this->database->select('comment_field_data', 'c');
         $subselect->addField('c', 'cid');
         $subselect->condition('c.uid', $this->argument);
         $entity_id = $this->definition['entity_id'];
         $entity_type = $this->definition['entity_type'];
         $subselect->where("c.entity_id = {$this->tableAlias}.{$entity_id}");
         $subselect->condition('c.entity_type', $entity_type);
         $condition = db_or()->condition("{$this->tableAlias}.uid", $this->argument, '=')->exists($subselect);
         $this->query->addWhere(0, $condition);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function update(CommentInterface $comment)
 {
     // Allow bulk updates and inserts to temporarily disable the maintenance of
     // the {comment_entity_statistics} table.
     if (!$this->state->get('comment.maintain_entity_statistics')) {
         return;
     }
     $query = $this->database->select('comment_field_data', 'c');
     $query->addExpression('COUNT(cid)');
     $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->execute()->fetchField();
     if ($count > 0) {
         // Comments exist.
         $last_reply = $this->database->select('comment_field_data', 'c')->fields('c', array('cid', 'name', 'changed', 'uid'))->condition('c.entity_id', $comment->getCommentedEntityId())->condition('c.entity_type', $comment->getCommentedEntityTypeId())->condition('c.field_name', $comment->getFieldName())->condition('c.status', CommentInterface::PUBLISHED)->condition('default_langcode', 1)->orderBy('c.created', 'DESC')->range(0, 1)->execute()->fetchObject();
         // Use merge here because entity could be created before comment field.
         $this->database->merge('comment_entity_statistics')->fields(array('cid' => $last_reply->cid, 'comment_count' => $count, 'last_comment_timestamp' => $last_reply->changed, 'last_comment_name' => $last_reply->uid ? '' : $last_reply->name, 'last_comment_uid' => $last_reply->uid))->keys(array('entity_id' => $comment->getCommentedEntityId(), 'entity_type' => $comment->getCommentedEntityTypeId(), 'field_name' => $comment->getFieldName()))->execute();
     } else {
         // Comments do not exist.
         $entity = $comment->getCommentedEntity();
         // Get the user ID from the entity if it's set, or default to the
         // currently logged in user.
         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();
         }
         $this->database->update('comment_entity_statistics')->fields(array('cid' => 0, 'comment_count' => 0, 'last_comment_timestamp' => $entity instanceof EntityChangedInterface ? $entity->getChangedTime() : REQUEST_TIME, 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid))->condition('entity_id', $comment->getCommentedEntityId())->condition('entity_type', $comment->getCommentedEntityTypeId())->condition('field_name', $comment->getFieldName())->execute();
     }
     // Reset the cache of the commented entity so that when the entity is loaded
     // the next time, the statistics will be loaded again.
     $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->resetCache(array($comment->getCommentedEntityId()));
 }
 /**
  * {@inheritdoc}
  */
 public function count()
 {
     if (!isset($this->count)) {
         $this->count = (int) $this->database->select($this->tableName)->countQuery()->execute();
     }
     return $this->count;
 }
  /**
   * Decrements count of flagged entities.
   *
   * @param \Drupal\flag\Event\FlaggingEvent $event
   *   The flagging Event.
   */
  public function decrementFlagCounts(FlaggingEvent $event) {

    /* @var \Drupal\flag\FlaggingInterface flag */
    $flag = $event->getFlag();
    /* @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $event->getEntity();

    $count_result = $this->connection->select('flag_counts')
      ->fields(NULL, ['flag_id', 'entity_id', 'entity_type', 'count'])
      ->condition('flag_id', $flag->id())
      ->condition('entity_id', $entity->id())
      ->condition('entity_type', $entity->getEntityTypeId())
      ->execute()
      ->fetchAll();
    if ($count_result[0]->count == '1') {
      $this->connection->delete('flag_counts')
        ->condition('flag_id', $flag->id())
        ->condition('entity_id', $entity->id())
        ->condition('entity_type', $entity->getEntityTypeId())
        ->execute();
    }
    else {
      $this->connection->update('flag_counts')
        ->expression('count', 'count - 1')
        ->condition('flag_id', $flag->id())
        ->condition('entity_id', $entity->id())
        ->condition('entity_type', $entity->getEntityTypeId())
        ->execute();
    }
    $this->resetLoadedCounts($entity, $flag);
  }
Beispiel #12
0
 /**
  * {@inheritdoc}
  */
 public function execute()
 {
     $results = array();
     if (!$this->isSearchExecutable()) {
         return $results;
     }
     $keys = $this->keywords;
     // Replace wildcards with MySQL/PostgreSQL wildcards.
     $keys = preg_replace('!\\*+!', '%', $keys);
     $query = $this->database->select('users')->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender');
     $query->fields('users', array('uid'));
     if ($this->currentUser->hasPermission('administer users')) {
         // Administrators can also search in the otherwise private email field, and
         // they don't need to be restricted to only active users.
         $query->fields('users', array('mail'));
         $query->condition($query->orConditionGroup()->condition('name', '%' . $this->database->escapeLike($keys) . '%', 'LIKE')->condition('mail', '%' . $this->database->escapeLike($keys) . '%', 'LIKE'));
     } else {
         // Regular users can only search via usernames, and we do not show them
         // blocked accounts.
         $query->condition('name', '%' . $this->database->escapeLike($keys) . '%', 'LIKE')->condition('status', 1);
     }
     $uids = $query->limit(15)->execute()->fetchCol();
     $accounts = $this->entityManager->getStorage('user')->loadMultiple($uids);
     foreach ($accounts as $account) {
         $result = array('title' => $account->getUsername(), 'link' => url('user/' . $account->id(), array('absolute' => TRUE)));
         if ($this->currentUser->hasPermission('administer users')) {
             $result['title'] .= ' (' . $account->getEmail() . ')';
         }
         $results[] = $result;
     }
     return $results;
 }
Beispiel #13
0
 /**
  * Queries to find search results, and sets status messages.
  *
  * This method can assume that $this->isSearchExecutable() has already been
  * checked and returned TRUE.
  *
  * @return \Drupal\Core\Database\StatementInterface|null
  *   Results from search query execute() method, or NULL if the search
  *   failed.
  */
 protected function findResults()
 {
     $keys = $this->keywords;
     // Build matching conditions.
     $query = $this->database->select('search_index', 'i', array('target' => 'replica'))->extend('Drupal\\search\\SearchQuery')->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender');
     $query->join('node_field_data', 'n', 'n.nid = i.sid');
     $query->condition('n.status', 1)->addTag('node_access')->searchExpression($keys, $this->getPluginId());
     // Handle advanced search filters in the f query string.
     // \Drupal::request()->query->get('f') is an array that looks like this in
     // the URL: ?f[]=type:page&f[]=term:27&f[]=term:13&f[]=langcode:en
     // So $parameters['f'] looks like:
     // array('type:page', 'term:27', 'term:13', 'langcode:en');
     // We need to parse this out into query conditions, some of which go into
     // the keywords string, and some of which are separate conditions.
     $parameters = $this->getParameters();
     if (!empty($parameters['f']) && is_array($parameters['f'])) {
         $filters = array();
         // Match any query value that is an expected option and a value
         // separated by ':' like 'term:27'.
         $pattern = '/^(' . implode('|', array_keys($this->advanced)) . '):([^ ]*)/i';
         foreach ($parameters['f'] as $item) {
             if (preg_match($pattern, $item, $m)) {
                 // Use the matched value as the array key to eliminate duplicates.
                 $filters[$m[1]][$m[2]] = $m[2];
             }
         }
         // Now turn these into query conditions. This assumes that everything in
         // $filters is a known type of advanced search.
         foreach ($filters as $option => $matched) {
             $info = $this->advanced[$option];
             // Insert additional conditions. By default, all use the OR operator.
             $operator = empty($info['operator']) ? 'OR' : $info['operator'];
             $where = new Condition($operator);
             foreach ($matched as $value) {
                 $where->condition($info['column'], $value);
             }
             $query->condition($where);
             if (!empty($info['join'])) {
                 $query->join($info['join']['table'], $info['join']['alias'], $info['join']['condition']);
             }
         }
     }
     // Add the ranking expressions.
     $this->addNodeRankings($query);
     // Run the query.
     $find = $query->fields('i', array('langcode'))->groupBy('i.langcode')->limit(10)->execute();
     // Check query status and set messages if needed.
     $status = $query->getStatus();
     if ($status & SearchQuery::EXPRESSIONS_IGNORED) {
         drupal_set_message($this->t('Your search used too many AND/OR expressions. Only the first @count terms were included in this search.', array('@count' => $this->searchSettings->get('and_or_limit'))), 'warning');
     }
     if ($status & SearchQuery::LOWER_CASE_OR) {
         drupal_set_message($this->t('Search for either of the two terms with uppercase <strong>OR</strong>. For example, <strong>cats OR dogs</strong>.'), 'warning');
     }
     if ($status & SearchQuery::NO_POSITIVE_KEYWORDS) {
         drupal_set_message($this->formatPlural($this->searchSettings->get('index.minimum_word_size'), 'You must include at least one keyword to match in the content, and punctuation is ignored.', 'You must include at least one keyword to match in the content. Keywords must be at least @count characters, and punctuation is ignored.'), 'warning');
     }
     return $find;
 }
Beispiel #14
0
 /**
  * {@inheritdoc}
  */
 public function unreadTopics($term, $uid)
 {
     $query = $this->connection->select('node_field_data', 'n');
     $query->join('forum', 'f', 'n.vid = f.vid AND f.tid = :tid', array(':tid' => $term));
     $query->leftJoin('history', 'h', 'n.nid = h.nid AND h.uid = :uid', array(':uid' => $uid));
     $query->addExpression('COUNT(n.nid)', 'count');
     return $query->condition('status', 1)->condition('n.default_langcode', 1)->condition('n.created', HISTORY_READ_LIMIT, '>')->isNull('h.nid')->addTag('node_access')->execute()->fetchField();
 }
Beispiel #15
0
 /**
  * Tests making use of a custom bundle field.
  */
 public function testCustomBundleFieldUsage()
 {
     entity_test_create_bundle('custom');
     // Check that an entity with bundle entity_test does not have the custom
     // field.
     $storage = $this->entityManager->getStorage('entity_test');
     $entity = $storage->create(['type' => 'entity_test']);
     $this->assertFalse($entity->hasField('custom_bundle_field'));
     // Check that the custom bundle has the defined custom field and check
     // saving and deleting of custom field data.
     $entity = $storage->create(['type' => 'custom']);
     $this->assertTrue($entity->hasField('custom_bundle_field'));
     // Ensure that the field exists in the field map.
     $field_map = \Drupal::entityManager()->getFieldMap();
     $this->assertEqual($field_map['entity_test']['custom_bundle_field'], ['type' => 'string', 'bundles' => ['custom' => 'custom']]);
     $entity->custom_bundle_field->value = 'swanky';
     $entity->save();
     $storage->resetCache();
     $entity = $storage->load($entity->id());
     $this->assertEqual($entity->custom_bundle_field->value, 'swanky', 'Entity was saved correctly');
     $entity->custom_bundle_field->value = 'cozy';
     $entity->save();
     $storage->resetCache();
     $entity = $storage->load($entity->id());
     $this->assertEqual($entity->custom_bundle_field->value, 'cozy', 'Entity was updated correctly.');
     $entity->delete();
     /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
     $table_mapping = $storage->getTableMapping();
     $table = $table_mapping->getDedicatedDataTableName($entity->getFieldDefinition('custom_bundle_field'));
     $result = $this->database->select($table, 'f')->fields('f')->condition('f.entity_id', $entity->id())->execute();
     $this->assertFalse($result->fetchAssoc(), 'Field data has been deleted');
     // Create another entity to test that values are marked as deleted when a
     // bundle is deleted.
     $entity = $storage->create(['type' => 'custom', 'custom_bundle_field' => 'new']);
     $entity->save();
     entity_test_delete_bundle('custom');
     $table = $table_mapping->getDedicatedDataTableName($entity->getFieldDefinition('custom_bundle_field'));
     $result = $this->database->select($table, 'f')->condition('f.entity_id', $entity->id())->condition('deleted', 1)->countQuery()->execute();
     $this->assertEqual(1, $result->fetchField(), 'Field data has been deleted');
     // Ensure that the field no longer exists in the field map.
     $field_map = \Drupal::entityManager()->getFieldMap();
     $this->assertFalse(isset($field_map['entity_test']['custom_bundle_field']));
     // @todo Test field purge and table deletion once supported. See
     //   https://www.drupal.org/node/2282119.
     // $this->assertFalse($this->database->schema()->tableExists($table), 'Custom field table was deleted');
 }
 /**
  * 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])];
 }
 /**
  * {@inheritdoc}
  */
 public function write(Profile $profile)
 {
     $args = ['token' => $profile->getToken(), 'parent' => $profile->getParentToken(), 'data' => base64_encode(serialize($profile->getCollectors())), 'ip' => $profile->getIp(), 'method' => $profile->getMethod(), 'url' => $profile->getUrl(), 'time' => $profile->getTime(), 'created_at' => time()];
     try {
         $query = $this->database->select('webprofiler', 'w')->fields('w', ['token']);
         $query->condition('token', $profile->getToken());
         $count = $query->countQuery()->execute()->fetchAssoc();
         if ($count['expression']) {
             $this->database->update('webprofiler')->fields($args)->condition('token', $profile->getToken())->execute();
         } else {
             $this->database->insert('webprofiler')->fields($args)->execute();
         }
         $status = TRUE;
     } catch (\Exception $e) {
         $status = FALSE;
     }
     return $status;
 }
 /**
  * Checks whether the expected logging entry got written.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   The database collection.
  */
 protected function doTestEntry(Connection $connection)
 {
     $result = $connection->select('watchdog')->fields('watchdog')->execute()->fetchAll();
     $this->assertEqual(1, count($result));
     $this->assertEqual(WATCHDOG_INFO, $result[0]->severity);
     $this->assertEqual('system', $result[0]->type);
     $this->assertEqual('Hello world @key', $result[0]->message);
     $this->assertEqual(array('@key' => 'value'), unserialize($result[0]->variables));
 }
Beispiel #19
0
 /**
  * Prepares the basic query with proper metadata/tags and base fields.
  *
  * @throws \Drupal\Core\Entity\Query\QueryException
  *   Thrown if the base table does not exists.
  *
  * @return \Drupal\Core\Entity\Query\Sql\Query
  *   Returns the called object.
  */
 protected function prepare()
 {
     if ($this->allRevisions) {
         if (!($base_table = $this->entityType->getRevisionTable())) {
             throw new QueryException("No revision table for " . $this->entityTypeId . ", invalid query.");
         }
     } else {
         if (!($base_table = $this->entityType->getBaseTable())) {
             throw new QueryException("No base table for " . $this->entityTypeId . ", invalid query.");
         }
     }
     $simple_query = TRUE;
     if ($this->entityType->getDataTable()) {
         $simple_query = FALSE;
     }
     $this->sqlQuery = $this->connection->select($base_table, 'base_table', array('conjunction' => $this->conjunction));
     $this->sqlQuery->addMetaData('entity_type', $this->entityTypeId);
     $id_field = $this->entityType->getKey('id');
     // Add the key field for fetchAllKeyed().
     if (!($revision_field = $this->entityType->getKey('revision'))) {
         // When there is no revision support, the key field is the entity key.
         $this->sqlFields["base_table.{$id_field}"] = array('base_table', $id_field);
         // Now add the value column for fetchAllKeyed(). This is always the
         // entity id.
         $this->sqlFields["base_table.{$id_field}" . '_1'] = array('base_table', $id_field);
     } else {
         // When there is revision support, the key field is the revision key.
         $this->sqlFields["base_table.{$revision_field}"] = array('base_table', $revision_field);
         // Now add the value column for fetchAllKeyed(). This is always the
         // entity id.
         $this->sqlFields["base_table.{$id_field}"] = array('base_table', $id_field);
     }
     if ($this->accessCheck) {
         $this->sqlQuery->addTag($this->entityTypeId . '_access');
     }
     $this->sqlQuery->addTag('entity_query');
     $this->sqlQuery->addTag('entity_query_' . $this->entityTypeId);
     // Add further tags added.
     if (isset($this->alterTags)) {
         foreach ($this->alterTags as $tag => $value) {
             $this->sqlQuery->addTag($tag);
         }
     }
     // Add further metadata added.
     if (isset($this->alterMetaData)) {
         foreach ($this->alterMetaData as $key => $value) {
             $this->sqlQuery->addMetaData($key, $value);
         }
     }
     // This now contains first the table containing entity properties and
     // last the entity base table. They might be the same.
     $this->sqlQuery->addMetaData('all_revisions', $this->allRevisions);
     $this->sqlQuery->addMetaData('simple_query', $simple_query);
     return $this;
 }
 /**
  * {@inheritdoc}
  */
 public function pathHasMatchingAlias($initial_substring)
 {
     $query = $this->connection->select(static::TABLE, 'u');
     $query->addExpression(1);
     try {
         return (bool) $query->condition('u.source', $this->connection->escapeLike($initial_substring) . '%', 'LIKE')->range(0, 1)->execute()->fetchField();
     } catch (\Exception $e) {
         $this->catchException($e);
         return FALSE;
     }
 }
  /**
   * {@inheritdoc}
   */
  public function titleQuery() {
    $titles = [];

    $flag = $this->getFlag();
    $entity_type = $flag->getFlaggableEntityTypeId();

    $def = \Drupal::entityTypeManager()->getDefinition($entity_type);
    $entity_keys = $def->getKeys();

    $result = $this->database->select($def->getBaseTable(), 'o')
      ->fields('o', $entity_keys['label'])
      ->condition('o.' . $entity_keys['id'], $this->value, 'IN')
      ->execute();

    foreach ($result as $title) {
      $titles[] = SafeMarkup::checkPlain($title->$entity_keys['label']);
    }

    return $titles;
  }
 /**
  * {@inheritdoc}
  */
 public function advancedLoad()
 {
     $select = $this->connection->select('dbtng_example', 'e');
     // Join the users table, so we can get the entry creator's username.
     $select->join('users_field_data', 'u', 'e.uid = u.uid');
     // Select these specific fields for the output.
     $select->addField('e', 'pid');
     $select->addField('u', 'name', 'username');
     $select->addField('e', 'name');
     $select->addField('e', 'surname');
     $select->addField('e', 'age');
     // Filter only persons named "John".
     $select->condition('e.name', 'John');
     // Filter only persons older than 18 years.
     $select->condition('e.age', 18, '>');
     // Make sure we only get items 0-49, for scalability reasons.
     $select->range(0, 50);
     $entries = $select->execute()->fetchAll();
     return $entries;
 }
 /**
  * Builds the query to load the entity.
  *
  * @param array|null $ids
  *   An array of entity IDs, or NULL to load all entities.
  *
  * @return \Drupal\Core\Database\Query\Select
  *   A SelectQuery object for loading the entity.
  */
 protected function buildQuery($ids)
 {
     $query = $this->database->select($this->entityType->getBaseTable(), 'base');
     $query->addTag($this->entityTypeId . '_load_multiple');
     // Add fields from the {entity} table.
     $entity_fields = drupal_schema_fields_sql($this->entityType->getBaseTable());
     $query->fields('base', $entity_fields);
     if ($ids) {
         $query->condition("base.{$this->idKey}", $ids, 'IN');
     }
     return $query;
 }
 /**
  * Generates a sample content page.
  *
  * Function body from "Generating paged output", in Chapter 4.
  */
 public function generateMyPage()
 {
     // Note: You should really use the Views module to do this! Code is
     // only here to illustrate using PagerSelectExtender on a query,
     // and 'pager' item in a render array.
     $query = $this->database->select('node', 'n');
     $query->innerJoin('node_field_data', 'nd', 'n.nid = nd.nid AND n.vid = nd.vid');
     $query = $query->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')->addMetaData('base_table', 'node')->limit(10)->fields('nd', array('title', 'nid'))->orderBy('nd.created', 'DESC')->addTag('node_access')->condition('nd.status', 1);
     $result = $query->execute();
     // Extract the information from the query result.
     $titles = array();
     foreach ($result as $row) {
         $titles[] = $row->title;
     }
     // Make the render array for a paged list of titles.
     $build = array();
     $build['items'] = array('#theme' => 'item_list', '#items' => $titles);
     // Add the pager.
     $build['item_pager'] = array('#type' => 'pager');
     return $build;
 }
 /**
  * Get test results for $test_id.
  *
  * @param int $test_id
  *   The test_id to retrieve results of.
  *
  * @return array
  *  Array of results grouped by test_class.
  */
 protected function getResults($test_id)
 {
     $results = $this->database->select('simpletest')->fields('simpletest')->condition('test_id', $test_id)->orderBy('test_class')->orderBy('message_id')->execute();
     $test_results = array();
     foreach ($results as $result) {
         if (!isset($test_results[$result->test_class])) {
             $test_results[$result->test_class] = array();
         }
         $test_results[$result->test_class][] = $result;
     }
     return $test_results;
 }
 /**
  * {@inheritdoc}
  */
 public function listAll($prefix = '')
 {
     try {
         $query = $this->connection->select($this->table);
         $query->fields($this->table, array('name'));
         $query->condition('collection', $this->collection, '=');
         $query->condition('name', $prefix . '%', 'LIKE');
         return $query->execute()->fetchCol();
     } catch (\Exception $e) {
         return array();
     }
 }
Beispiel #27
0
 /**
  * Retrieves the contents of an ID map.
  *
  * @return array
  *   The contents of an ID map.
  */
 private function getIdMapContents()
 {
     $result = $this->database->select('migrate_map_sql_idmap_test', 't')->fields('t')->execute();
     // The return value needs to be countable, or it will fail certain
     // assertions. iterator_to_array() will not suffice because it won't
     // respect the PDO fetch mode, if specified.
     $contents = [];
     foreach ($result as $row) {
         $contents[] = (array) $row;
     }
     return $contents;
 }
 /**
  * {@inheritdoc}
  */
 public function authenticate(Request $request)
 {
     // See if we can find the API key.
     $q = $this->database->select('api_keys', 'a')->fields('a');
     // @todo. Hardcoded header ahead.
     $q->condition('a.user_key', $request->headers->get('x-drupal-api-key'));
     $res = $q->execute()->fetchObject();
     if (!$res) {
         return [];
     } else {
         return $this->entityManager->getStorage('user')->load($res->uid);
     }
 }
Beispiel #29
0
 /**
  * {@inheritdoc}
  */
 public function getRoutesPaged($offset, $length = NULL)
 {
     $select = $this->connection->select($this->tableName, 'router')->fields('router', ['name', 'route']);
     if (isset($length)) {
         $select->range($offset, $length);
     }
     $routes = $select->execute()->fetchAllKeyed();
     $result = [];
     foreach ($routes as $name => $route) {
         $result[$name] = unserialize($route);
     }
     return $result;
 }
 /**
  * Gets the system data from the system table of the source Drupal database.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   Database connection to the source Drupal database.
  *
  * @return array
  *   The system data from the system table of the source Drupal database.
  */
 protected function getSystemData(Connection $connection)
 {
     $system_data = [];
     try {
         $results = $connection->select('system', 's', ['fetch' => \PDO::FETCH_ASSOC])->fields('s')->execute();
         foreach ($results as $result) {
             $system_data[$result['type']][$result['name']] = $result;
         }
     } catch (\Exception $e) {
         // The table might not exist for example in tests.
     }
     return $system_data;
 }