Exemplo n.º 1
0
 /**
  * {@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;
         }
     }
 }
Exemplo n.º 2
0
 /**
  * Tests that entity schema responds to changes in the entity type definition.
  */
 public function testEntitySchemaUpdate()
 {
     $this->installModule('entity_schema_test');
     $storage_definitions = $this->entityManager->getFieldStorageDefinitions('entity_test');
     $this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_base_field']);
     $this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_bundle_field']);
     $schema_handler = $this->database->schema();
     $tables = array('entity_test', 'entity_test_revision', 'entity_test_field_data', 'entity_test_field_revision');
     $dedicated_tables = array('entity_test__custom_bundle_field', 'entity_test_revision__custom_bundle_field');
     // Initially only the base table and the dedicated field data table should
     // exist.
     foreach ($tables as $index => $table) {
         $this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
     }
     $this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
     // Update the entity type definition and check that the entity schema now
     // supports translations and revisions.
     $this->updateEntityType(TRUE);
     foreach ($tables as $table) {
         $this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
     }
     foreach ($dedicated_tables as $table) {
         $this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
     }
     // Revert changes and check that the entity schema now does not support
     // neither translations nor revisions.
     $this->updateEntityType(FALSE);
     foreach ($tables as $index => $table) {
         $this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
     }
     $this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
 }
Exemplo n.º 3
0
 /**
  * Gets a redirect for given path, query and language.
  *
  * @param string $source_path
  *   The redirect source path.
  * @param array $query
  *   The redirect source path query.
  * @param $language
  *   The language for which is the redirect.
  *
  * @return \Drupal\redirect\Entity\Redirect
  *   The matched redirect entity.
  *
  * @throws \Drupal\redirect\Exception\RedirectLoopException
  */
 public function findMatchingRedirect($source_path, array $query = [], $language = Language::LANGCODE_NOT_SPECIFIED)
 {
     $hashes = [Redirect::generateHash($source_path, $query, $language)];
     if ($language != Language::LANGCODE_NOT_SPECIFIED) {
         $hashes[] = Redirect::generateHash($source_path, $query, Language::LANGCODE_NOT_SPECIFIED);
     }
     // Add a hash without the query string if using passthrough querystrings.
     if (!empty($query) && $this->config->get('passthrough_querystring')) {
         $hashes[] = Redirect::generateHash($source_path, [], $language);
         if ($language != Language::LANGCODE_NOT_SPECIFIED) {
             $hashes[] = Redirect::generateHash($source_path, [], Language::LANGCODE_NOT_SPECIFIED);
         }
     }
     // Load redirects by hash. A direct query is used to improve performance.
     $rid = $this->connection->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])->fetchField();
     if (!empty($rid)) {
         // Check if this is a loop.
         if (in_array($rid, $this->foundRedirects)) {
             throw new RedirectLoopException('/' . $source_path, $rid);
         }
         $this->foundRedirects[] = $rid;
         $redirect = $this->load($rid);
         // Find chained redirects.
         if ($recursive = $this->findByRedirect($redirect, $language)) {
             // Reset found redirects.
             $this->foundRedirects = [];
             return $recursive;
         }
         return $redirect;
     }
     return NULL;
 }
Exemplo n.º 4
0
 public function preRender(&$values)
 {
     $uids = array();
     $this->items = array();
     foreach ($values as $result) {
         $uids[] = $this->getValue($result);
     }
     if ($uids) {
         $roles = user_roles();
         $result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
         foreach ($result as $role) {
             $this->items[$role->uid][$role->rid]['role'] = $roles[$role->rid]->label();
             $this->items[$role->uid][$role->rid]['rid'] = $role->rid;
         }
         // Sort the roles for each user by role weight.
         $ordered_roles = array_flip(array_keys($roles));
         foreach ($this->items as &$user_roles) {
             // Create an array of rids that the user has in the role weight order.
             $sorted_keys = array_intersect_key($ordered_roles, $user_roles);
             // Merge with the unsorted array of role information which has the
             // effect of sorting it.
             $user_roles = array_merge($sorted_keys, $user_roles);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function collect(Request $request, Response $response, \Exception $exception = NULL)
 {
     $connections = [];
     foreach (Database::getAllConnectionInfo() as $key => $info) {
         $database = Database::getConnection('default', $key);
         $connections[$key] = $database->getLogger()->get('webprofiler');
     }
     $this->data['connections'] = array_keys($connections);
     $data = [];
     foreach ($connections as $key => $queries) {
         foreach ($queries as $query) {
             // Remove caller args.
             unset($query['caller']['args']);
             // Remove query args element if empty.
             if (empty($query['args'])) {
                 unset($query['args']);
             }
             // Save time in milliseconds.
             $query['time'] = $query['time'] * 1000;
             $query['database'] = $key;
             $data[] = $query;
         }
     }
     $querySort = $this->configFactory->get('webprofiler.config')->get('query_sort');
     if ('duration' === $querySort) {
         usort($data, ["Drupal\\webprofiler\\DataCollector\\DatabaseDataCollector", "orderQueryByTime"]);
     }
     $this->data['queries'] = $data;
     $options = $this->database->getConnectionOptions();
     // Remove password for security.
     unset($options['password']);
     $this->data['database'] = $options;
 }
Exemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $_SESSION['dblog_overview_filter'] = array();
     $this->connection->delete('watchdog')->execute();
     drupal_set_message($this->t('Database log cleared.'));
     $form_state->setRedirectUrl($this->getCancelUrl());
 }
 /**
  * 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;
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, array &$form_state)
 {
     $_SESSION['dblog_overview_filter'] = array();
     $this->connection->delete('watchdog')->execute();
     drupal_set_message($this->t('Database log cleared.'));
     $form_state['redirect_route'] = $this->getCancelRoute();
 }
Exemplo n.º 9
0
 /**
  * @param DrupalStyle $io
  * @param $eventType
  * @param $eventSeverity
  * @param $userId
  * @return bool
  */
 protected function clearEvents(DrupalStyle $io, $eventType, $eventSeverity, $userId)
 {
     $severity = RfcLogLevel::getLevels();
     $query = $this->database->delete('watchdog');
     if ($eventType) {
         $query->condition('type', $eventType);
     }
     if ($eventSeverity) {
         if (!in_array($eventSeverity, $severity)) {
             $io->error(sprintf($this->trans('commands.database.log.clear.messages.invalid-severity'), $eventSeverity));
             return false;
         }
         $query->condition('severity', array_search($eventSeverity, $severity));
     }
     if ($userId) {
         $query->condition('uid', $userId);
     }
     $result = $query->execute();
     if (!$result) {
         $io->error($this->trans('commands.database.log.clear.messages.clear-error'));
         return false;
     }
     $io->success($this->trans('commands.database.log.clear.messages.clear-sucess'));
     return true;
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $io = new DrupalStyle($input, $output);
     $uid = $input->getArgument('user');
     $user = User::load($uid);
     if (!$user) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
         return 1;
     }
     $password = $input->getArgument('password');
     if (!$password) {
         $io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
         return 1;
     }
     try {
         $user->setPassword($password);
         $user->save();
         $schema = $this->database->schema();
         $flood = $schema->findTables('flood');
         if ($flood) {
             $this - $this->chainQueue->addCommand('user:login:clear:attempts', ['uid' => $uid]);
         }
     } catch (\Exception $e) {
         $io->error($e->getMessage());
         return 1;
     }
     $io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
 }
Exemplo n.º 11
0
 /**
  * Create a new table from a Drupal table definition if it doesn't exist.
  *
  * @param string $name
  *   The name of the table to create.
  * @param array $table
  *   A Schema API table definition array.
  */
 protected function createTable($name, array $table)
 {
     // This must be on the database connection to be shared among classes.
     if (empty($this->database->migrateTables[$name])) {
         $this->database->migrateTables[$name] = TRUE;
         $this->database->schema()->createTable($name, $table);
     }
 }
Exemplo n.º 12
0
 /**
  * Drop the tables used for the sample data.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   The connection to use to drop the tables.
  */
 public function dropTables(Connection $connection)
 {
     $tables = $this->routingTableDefinition();
     $schema = $connection->schema();
     foreach ($tables as $name => $table) {
         $schema->dropTable($name);
     }
 }
Exemplo n.º 13
0
 /**
  * Constructs a Query object.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   Database connection object.
  * @param array $options
  *   Array of query options.
  */
 public function __construct(Connection $connection, $options)
 {
     $this->uniqueIdentifier = uniqid('', TRUE);
     $this->connection = $connection;
     $this->connectionKey = $this->connection->getKey();
     $this->connectionTarget = $this->connection->getTarget();
     $this->queryOptions = $options;
 }
 /**
  * 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;
 }
 /**
  * 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));
 }
Exemplo n.º 16
0
 /**
  * {@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();
 }
Exemplo n.º 17
0
 /**
  * {@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();
 }
Exemplo n.º 18
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->database->query("SELECT COUNT(*) FROM {node} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
     if ($num_nodes) {
         $caption = '<p>' . format_plural($num_nodes, '%type is used by 1 piece of content on your site. You can not remove this content type until you have removed all of the %type content.', '%type is used by @count pieces of content on your site. You may not remove %type until you have removed all of the %type content.', array('%type' => $this->entity->label())) . '</p>';
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => $caption);
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
Exemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $num_nodes = $this->database->query("SELECT COUNT(*) FROM {crm_core_contact} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
     if ($num_nodes) {
         $caption = \Drupal::translation()->formatPlural($num_nodes, '%type is used by one contact on your site. You can not remove this contact type until you have removed all of the %type contacts.', '%type is used by @count contacts on your site. You may not remove %type until you have removed all of the %type contacts.', array('%type' => $this->entity->label()));
         $form['#title'] = $this->getQuestion();
         $form['description'] = array('#markup' => '<p>' . $caption . '</p>');
         return $form;
     }
     return parent::buildForm($form, $form_state);
 }
Exemplo n.º 20
0
 /**
  * Sets up required mocks and the CommentStatistics service under test.
  */
 protected function setUp()
 {
     $this->statement = $this->getMockBuilder('Drupal\\Core\\Database\\Driver\\sqlite\\Statement')->disableOriginalConstructor()->getMock();
     $this->statement->expects($this->any())->method('fetchObject')->will($this->returnCallback(array($this, 'fetchObjectCallback')));
     $this->select = $this->getMockBuilder('Drupal\\Core\\Database\\Query\\Select')->disableOriginalConstructor()->getMock();
     $this->select->expects($this->any())->method('fields')->will($this->returnSelf());
     $this->select->expects($this->any())->method('condition')->will($this->returnSelf());
     $this->select->expects($this->any())->method('execute')->will($this->returnValue($this->statement));
     $this->database = $this->getMockBuilder('Drupal\\Core\\Database\\Connection')->disableOriginalConstructor()->getMock();
     $this->database->expects($this->once())->method('select')->will($this->returnValue($this->select));
     $this->commentStatistics = new CommentStatistics($this->database, $this->getMock('Drupal\\Core\\Session\\AccountInterface'), $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'), $this->getMock('Drupal\\Core\\State\\StateInterface'));
 }
 /**
  * {@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;
 }
Exemplo n.º 22
0
 /**
  * Run the database script.
  *
  * @param \Drupal\Core\Database\Connection $connection
  *   Connection used by the script when included.
  * @param string $script
  *   Path to dump script.
  */
 protected function runScript(Connection $connection, $script)
 {
     $old_key = Database::setActiveConnection($connection->getKey());
     if (substr($script, -3) == '.gz') {
         $script = "compress.zlib://{$script}";
     }
     try {
         require $script;
     } catch (SchemaObjectExistsException $e) {
         throw new \RuntimeException('An existing Drupal installation exists at this location. Try removing all tables or changing the database prefix in your settings.php file.');
     }
     Database::setActiveConnection($old_key);
 }
 /**
  * @param Profile $profile
  * @param int $qid
  *
  * @return JsonResponse
  */
 public function explainAction(Profile $profile, $qid)
 {
     $query = $this->getQuery($profile, $qid);
     $data = [];
     $result = $this->database->query('EXPLAIN ' . $query['query'], (array) $query['args'])->fetchAllAssoc('table');
     $i = 1;
     foreach ($result as $row) {
         foreach ($row as $key => $value) {
             $data[$i][$key] = $value;
         }
         $i++;
     }
     return new JsonResponse(['data' => $data]);
 }
Exemplo n.º 24
0
 /**
  * Checks if the table exists and create it if not.
  *
  * @return bool
  *   TRUE if the table was created, FALSE otherwise.
  */
 protected function ensureTableExists()
 {
     try {
         if (!$this->connection->schema()->tableExists($this->tableName)) {
             $this->connection->schema()->createTable($this->tableName, $this->schemaDefinition());
             return TRUE;
         }
     } catch (SchemaObjectExistsException $e) {
         // If another process has already created the table, attempting to
         // recreate it will throw an exception. In this case just catch the
         // exception and do nothing.
         return TRUE;
     }
     return FALSE;
 }
Exemplo n.º 25
0
 /**
  * Override the behavior of title(). Get the title of the revision.
  */
 public function titleQuery()
 {
     $titles = array();
     $results = $this->database->query('SELECT nr.vid, nr.nid, npr.title FROM {node_revision} nr WHERE nr.vid IN ( :vids[] )', array(':vids[]' => $this->value))->fetchAllAssoc('vid', PDO::FETCH_ASSOC);
     $nids = array();
     foreach ($results as $result) {
         $nids[] = $result['nid'];
     }
     $nodes = $this->nodeStorage->loadMultiple(array_unique($nids));
     foreach ($results as $result) {
         $nodes[$result['nid']]->set('title', $result['title']);
         $titles[] = String::checkPlain($nodes[$result['nid']]->label());
     }
     return $titles;
 }
Exemplo n.º 26
0
 /**
  * Override the behavior of title(). Get the title of the revision.
  */
 public function titleQuery()
 {
     $titles = array();
     $results = $this->database->query('SELECT nr.vid, nr.stid, npr.title FROM {support_ticket_revision} nr WHERE nr.vid IN ( :vids[] )', array(':vids[]' => $this->value))->fetchAllAssoc('vid', PDO::FETCH_ASSOC);
     $stids = array();
     foreach ($results as $result) {
         $stids[] = $result['stid'];
     }
     $support_tickets = $this->supportTicketStorage->loadMultiple(array_unique($stids));
     foreach ($results as $result) {
         $support_tickets[$result['stid']]->set('title', $result['title']);
         $titles[] = SafeMarkup::checkPlain($support_tickets[$result['stid']]->label());
     }
     return $titles;
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  */
 public function delete($module = NULL, $uid = NULL, $name = NULL)
 {
     $query = $this->connection->delete('users_data');
     // Cast scalars to array so we can consistently use an IN condition.
     if (isset($module)) {
         $query->condition('module', (array) $module, 'IN');
     }
     if (isset($uid)) {
         $query->condition('uid', (array) $uid, 'IN');
     }
     if (isset($name)) {
         $query->condition('name', (array) $name, 'IN');
     }
     $query->execute();
 }
Exemplo n.º 28
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 validateConfigurationForm(array &$form, FormStateInterface $form_state)
 {
     $exists = (bool) $this->connection->queryRange('SELECT 1 FROM {users_field_data} WHERE uid = :uid AND default_langcode = 1', 0, 1, array(':name' => $form_state->getValue('owner_uid')))->fetchField();
     if (!$exists) {
         $form_state->setErrorByName('owner_uid', t('Enter a valid username.'));
     }
 }