countQuery example

'langcode' => 'fr',
      'customized' => TRUE,
    ]);

    // The import should have created 6 strings.     $this->assertSession()->pageTextContains("One translation file imported. 6 translations were added, 0 translations were updated and 0 translations were removed.");

    // The database should now contain 6 customized strings (two imported     // strings are not translated).     $count = Database::getConnection()->select('locales_target')
      ->condition('customized', 1)
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertEquals(6, $count, 'Customized translations successfully imported.');

    // Try importing a .po file with overriding strings, and ensure existing     // customized strings are kept.     $this->importPoFile($this->getCustomOverwritePoFile()[
      'langcode' => 'fr',
      'overwrite_options[not_customized]' => TRUE,
      'overwrite_options[customized]' => FALSE,
    ]);

    
/** * Tests range queries. * * The SQL clause varies with the database. */
  public function testRange() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    $query->range(0, 2);
    $query_result = $query->countQuery()->execute()->fetchField();

    $this->assertEquals(2, $query_result, 'Returned the correct number of rows.');
  }

  /** * Tests whether the range property of a select clause can be undone. */
  public function testRangeUndo() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    

function hook_entity_predelete(\Drupal\Core\Entity\EntityInterface $entity) {
  $connection = \Drupal::database();
  // Count references to this entity in a custom table before they are removed   // upon entity deletion.   $id = $entity->id();
  $type = $entity->getEntityTypeId();
  $count = \Drupal::database()->select('example_entity_data')
    ->condition('type', $type)
    ->condition('id', $id)
    ->countQuery()
    ->execute()
    ->fetchField();

  // Log the count in a table that records this statistic for deleted entities.   $connection->merge('example_deleted_entity_statistics')
    ->key(['type' => $type, 'id' => $id])
    ->fields(['count' => $count])
    ->execute();
}

/** * Act before entity deletion of a particular entity type. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object for the entity that is about to be deleted. * * @ingroup entity_crud * @see hook_entity_predelete() */
'page',
      'test_content_type',
    ];
    foreach ($node_types as $node_type) {
      // Execute the rollback.       $this->migration = $this->getMigration("d7_node_complete:$node_type");
      (new MigrateExecutable($this->migration, $this))->rollback();

      // Assert there are no nodes of node_type.       $count = $db->select('node_field_data')
        ->condition('type', $node_type)
        ->countQuery()
        ->execute()
        ->fetchField();
      $this->assertSame($count, '0', "There are $count nodes of type $node_type");
    }
  }

  /** * Asserts various aspects of a node revision. * * @param array $revision * An array of revision data matching a node_field_revision table row. * @param array $data * An array of revision data. * * @internal */

class SelectTest extends DatabaseTestBase {

  /** * Tests rudimentary SELECT statements. */
  public function testSimpleSelect() {
    $query = $this->connection->select('test');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    $num_records = $query->countQuery()->execute()->fetchField();

    $this->assertEquals(4, $num_records, 'Returned the correct number of rows.');
  }

  /** * Tests rudimentary SELECT statement with a COMMENT. */
  public function testSimpleComment() {
    $query = $this->connection->select('test')->comment('Testing query comments');
    $query->addField('test', 'name');
    $query->addField('test', 'age', 'age');
    

  }

  /** * Tests migration of tracker node table. */
  public function testMigrateTrackerNode() {
    $connection = Database::getConnection('default', 'migrate');
    $num_rows = $connection
      ->select('tracker_node', 'tn')
      ->fields('tn', ['nid', 'published', 'changed'])
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertSame('1', $num_rows);

    $tracker_nodes = $connection
      ->select('tracker_node', 'tn')
      ->fields('tn', ['nid', 'published', 'changed'])
      ->execute();
    $row = $tracker_nodes->fetchAssoc();
    $this->assertSame('1', $row['nid']);
    $this->assertSame('1', $row['published']);
    

  public function testBigPipe() {
    // Simulate production.     $this->config('system.logging')->set('error_level', ERROR_REPORTING_HIDE)->save();

    $this->drupalLogin($this->rootUser);
    $this->assertSessionCookieExists(TRUE);
    $this->assertBigPipeNoJsCookieExists(FALSE);

    $connection = Database::getConnection();
    $log_count = $connection->select('watchdog')->countQuery()->execute()->fetchField();

    // By not calling performMetaRefresh() here, we simulate JavaScript being     // enabled, because as far as the BigPipe module is concerned, JavaScript is     // enabled in the browser as long as the BigPipe no-JS cookie is *not* set.     // @see setUp()     // @see performMetaRefresh()
    $this->drupalGet(Url::fromRoute('big_pipe_test'));
    $this->assertBigPipeResponseHeadersPresent();
    $this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'cache_tag_set_in_lazy_builder');

    
$this->connection->truncate('test')->execute();

    $num_records_after = $this->connection->query("SELECT COUNT(*) FROM {test}")->fetchField();
    $this->assertEquals(0, $num_records_after, 'Truncate really deletes everything.');
  }

  /** * Confirms that we can truncate a whole table while in transaction. */
  public function testTruncateInTransaction() {
    $num_records_before = $this->connection->select('test')->countQuery()->execute()->fetchField();
    $this->assertGreaterThan(0, $num_records_before, 'The table is not empty.');

    $transaction = $this->connection->startTransaction('test_truncate_in_transaction');
    $this->connection->insert('test')
      ->fields([
        'name' => 'Freddie',
        'age' => 45,
        'job' => 'Great singer',
      ])
      ->execute();
    $num_records_after_insert = $this->connection->select('test')->countQuery()->execute()->fetchField();
    
// 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', 'entity_test_update');

    $table = $table_mapping->getDedicatedDataTableName($entity->getFieldDefinition('custom_bundle_field')->getFieldStorageDefinition(), TRUE);
    $result = $this->database->select($table, 'f')
      ->condition('f.entity_id', $entity->id())
      ->condition('deleted', 1)
      ->countQuery()
      ->execute();
    $this->assertEquals(1, $result->fetchField(), 'Field data has been deleted');

    // Ensure that the field no longer exists in the field map.     $field_map = \Drupal::service('entity_field.manager')->getFieldMap();
    $this->assertFalse(isset($field_map['entity_test_update']['custom_bundle_field']));

    // Purge field data, and check that the storage definition has been     // completely removed once the data is purged.     field_purge_batch(10);
    $this->assertFalse($this->database->schema()->tableExists($table), 'Custom field table was deleted');
  }
return $query->execute();
  }

  /** * {@inheritdoc} */
  public function countOriginalLinkChildren($original) {
    return $this->connection->select('book', 'b')
      ->condition('bid', $original['bid'])
      ->condition('pid', $original['pid'])
      ->condition('nid', $original['nid'], '<>')
      ->countQuery()
      ->execute()->fetchField();
  }

  /** * {@inheritdoc} */
  public function getBookSubtree($link$max_depth) {
    $query = $this->connection->select('book', 'b', ['fetch' => \PDO::FETCH_ASSOC]);
    $query->fields('b');
    $query->condition('b.bid', $link['bid']);

    
$this->assertStringNotContainsString("'pattern_outline' => 'test", $output, 'Insert pattern_outline field not found');
  }

  /** * Tests insert count option. */
  public function testInsertCount() {
    $command = new DbDumpCommand();
    $command_tester = new CommandTester($command);
    $command_tester->execute(['--insert-count' => '1']);

    $router_row_count = (int) $this->container->get('database')->select('router')->countQuery()->execute()->fetchField();

    $output = $command_tester->getDisplay();
    $this->assertSame($router_row_countsubstr_count($output, "insert('router"));
    $this->assertGreaterThan(1, $router_row_count);
  }

}
$additional_arguments = \Drupal::moduleHandler()->invokeAll('views_query_substitutions', [$view]);

      // Count queries must be run through the preExecute() method.       // If not, then hook_query_node_access_alter() may munge the count by       // adding a distinct against an empty query string       // (e.g. COUNT DISTINCT(1) ...) and no pager will return.       // See \Drupal\Core\Database\Query\PagerSelectExtender::execute()       // See https://www.drupal.org/node/1046170.       $count_query->preExecute();

      // Build the count query.       $count_query = $count_query->countQuery();

      // Add additional arguments as a fake condition.       // XXX: this doesn't work, because PDO mandates that all bound arguments       // are used on the query. TODO: Find a better way to do this.       if (!empty($additional_arguments)) {
        // $query->where('1 = 1', $additional_arguments);         // $count_query->where('1 = 1', $additional_arguments);       }

      $start = microtime(TRUE);

      


  /** * @return \Drupal\Core\Database\Query\SelectInterface */
  abstract public function query();

  /** * Gets the source count using countQuery(). */
  protected function doCount() {
    return (int) $this->query()->countQuery()->execute()->fetchField();
  }

  /** * Checks if we can join against the map table. * * This function specifically catches issues when we're migrating with * unique sets of credentials for the source and destination database. * * @return bool * TRUE if we can join against the map table otherwise FALSE. */
  
$edit["{$this->fieldName1}[]"] = $term_1->id();
    $edit["{$this->fieldName2}[]"] = $term_1->id();
    $this->drupalGet('node/add/article');
    $this->submitForm($edit, 'Save');

    // Check that the term is indexed, and only once.     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
    $connection = Database::getConnection();
    $index_count = $connection->select('taxonomy_index')
      ->condition('nid', $node->id())
      ->condition('tid', $term_1->id())
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertEquals(1, $index_count, 'Term 1 is indexed once.');

    // Update the article to change one term.     $edit["{$this->fieldName1}[]"] = $term_2->id();
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm($edit, 'Save');

    // Check that both terms are indexed.     $index_count = $connection->select('taxonomy_index')
      

  protected function countHelper($status = NULL, $table = NULL) {
    // Use database directly to avoid creating tables.     $query = $this->database->select($table ?: $this->mapTableName());
    if (isset($status)) {
      $query->condition('source_row_status', $statusis_array($status) ? 'IN' : '=');
    }
    try {
      $count = (int) $query->countQuery()->execute()->fetchField();
    }
    catch (DatabaseException $e) {
      // The table does not exist, therefore there are no records.       $count = 0;
    }
    return $count;
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.