database example


  private function auditEntityComplete(MigrationInterface $migration) {
    $map_table = $migration->getIdMap()->mapTableName();

    $database = \Drupal::database();
    if (!$database->schema()->tableExists($map_table)) {
      throw new \InvalidArgumentException();
    }

    $query = $database->select($map_table, 'map')
      ->fields('map', ['destid2'])
      ->range(0, 1)
      ->orderBy('destid2', 'DESC');
    $max = (int) $query->execute()->fetchField();

    // Make a migration based on node_complete but with an entity_revision

  protected $migrationPluginManager;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->database = \Drupal::database();
    $this->eventDispatcher = $this->prophesize(EventDispatcherInterface::class)
      ->reveal();
    $this->migrationPluginManager = \Drupal::service('plugin.manager.migration');

    $this->migrationDefinition = [
      'id' => 'test',
      'source' => [
        'plugin' => 'embedded_data',
        'data_rows' => [
          [
            'alpha' => '1',
            
/** * Tests the global login flood control for a given serialization format. * * @param string $format * The encoded format. * * @see \Drupal\basic_auth\Authentication\Provider\BasicAuthTest::testGlobalLoginFloodControl * @see \Drupal\Tests\user\Functional\UserLoginTest::testGlobalLoginFloodControl */
  public function doTestGlobalLoginFloodControl(string $format): void {
    $database = \Drupal::database();
    $this->config('user.flood')
      ->set('ip_limit', 2)
      // Set a high per-user limit out so that it is not relevant in the test.       ->set('user_limit', 4000)
      ->save();

    $user = $this->drupalCreateUser([]);
    $incorrect_user = clone $user;
    $incorrect_user->passRaw .= 'incorrect';

    // Try 2 failed logins.
// Accessing either endpoint as the anonymous user should return a 403.     $this->drupalLogout();
    $response = $this->getNodeReadTimestamps([$nid]);
    $this->assertEquals(403, $response->getStatusCode());
    $response = $this->getNodeReadTimestamps([]);
    $this->assertEquals(403, $response->getStatusCode());
    $response = $this->markNodeAsRead($nid);
    $this->assertEquals(403, $response->getStatusCode());

    // Additional check to ensure that we did not forget to verify anything.     $rows = \Drupal::database()->query('SELECT * FROM {history}')->fetchAll();
    $this->assertCount(1, $rows);
    $this->assertSame($this->user->id()$rows[0]->uid);
    $this->assertSame($this->testNode->id()$rows[0]->nid);
    $this->assertSame($timestamp(int) $rows[0]->timestamp);
  }

}

  public function testGetTableNames() {
    $storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('entity_test_mulrev');
    $dedicated_data_table = $this->tableMapping->getDedicatedDataTableName($storage_definitions['multivalued_base_field']);
    $dedicated_revision_table = $this->tableMapping->getDedicatedRevisionTableName($storage_definitions['multivalued_base_field']);

    // Check that both the data and the revision tables exist for a multi-valued     // base field.     $database_schema = \Drupal::database()->schema();
    $this->assertTrue($database_schema->tableExists($dedicated_data_table));
    $this->assertTrue($database_schema->tableExists($dedicated_revision_table));

    // Check that the table mapping contains both the data and the revision     // tables exist for a multi-valued base field.     $expected = [
      'entity_test_mulrev',
      'entity_test_mulrev_property_data',
      'entity_test_mulrev_revision',
      'entity_test_mulrev_property_revision',
      $dedicated_data_table,
      
/** * Test that twig errors are displayed correctly. */
  public function testMessageParsing() {
    $this->drupalLogin($this->adminUser);
    // Log a common twig error with {{ }} and { } variables.     \Drupal::service('logger.factory')->get("php")
      ->error('Incorrect parameter {{foo}} in path {path}: {value}',
        ['foo' => 'bar', 'path' => '/baz', 'value' => 'horse']
      );
    // View the log page to verify it's correct.     $wid = \Drupal::database()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField();
    $this->drupalGet('admin/reports/dblog/event/' . $wid);
    $this->assertSession()
      ->responseContains('Incorrect parameter {bar} in path /baz: horse');
  }

  /** * Verifies setting of the database log row limit. * * @param int $row_limit * The row limit. */
  
$this->drupalGet('test-table');

    $this->assertSession()->elementExists('xpath', '//tbody/tr/td[contains(., "Baby")]');
    $this->assertSession()->elementExists('xpath', '//tbody/tr/td[text()=0]');
  }

  /** * Tests that empty columns are hidden when empty_column is set. */
  public function testEmptyColumn() {
    // Empty the 'job' data.     \Drupal::database()->update('views_test_data')
      ->fields(['job' => ''])
      ->execute();

    $this->drupalGet('test-table');

    // Test that only one of the job columns still shows.     // Ensure that empty column header is hidden.     $this->assertSession()->elementsCount('xpath', '//thead/tr/th/a[text()="Job"]', 1);
    $this->assertSession()->elementNotExists('xpath', '//tbody/tr/td[contains(concat(" ", @class, " "), " views-field-job-1 ")]');
  }

  
$this->setMockContainerService('entity_type.manager');
    $this->assertNotNull(\Drupal::entityTypeManager());
  }

  /** * Tests the database() method. * * @covers ::database */
  public function testDatabase() {
    $this->setMockContainerService('database');
    $this->assertNotNull(\Drupal::database());
  }

  /** * Tests the cache() method. * * @covers ::cache */
  public function testCache() {
    $this->setMockContainerService('cache.test');
    $this->assertNotNull(\Drupal::cache('test'));
  }

  
$next_count = count($this->getBreadcrumbCacheEntries());
    $this->assertEquals($base_count$next_count);
  }

  /** * Gets the breadcrumb cache entries. * * @return array * The breadcrumb cache entries. */
  protected function getBreadcrumbCacheEntries() {
    $database = \Drupal::database();
    $cache_entries = $database->select('cache_render')
      ->fields('cache_render')
      ->condition('cid', $database->escapeLike('entity_view:block:breadcrumb') . '%', 'LIKE')
      ->execute()
      ->fetchAllAssoc('cid');
    return $cache_entries;
  }

}
/** * Queries the node_access table and checks for proper storage. * * @param int $count * The number of rows expected by the query (equal to the translation * count). * @param $langcode * The expected language code set as the fallback property. */
  public function checkRecords($count$langcode = 'hu') {
    $select = \Drupal::database()
      ->select('node_access', 'na')
      ->fields('na', ['nid', 'fallback', 'langcode', 'grant_view'])
      ->condition('na.realm', 'node_access_test', '=')
      ->condition('na.gid', 8888, '=');
    $records = $select->execute()->fetchAll();
    // Check that the expected record count is returned.     $this->assertCount($count$records);
    // The fallback value is 'hu' and should be set to 1. For other languages,     // it should be set to 0. Casting to boolean lets us run that comparison.     foreach ($records as $record) {
      $this->assertEquals((bool) $record->fallback, $record->langcode === $langcode);
    }
    \Drupal::service('cache.default')->set(__CLASS__, 'Test');

    /** @var \Drupal\Core\Update\UpdateHookRegistry $update_registry */
    $update_registry = \Drupal::service('update.update_hook_registry');
    foreach (['user' => 9301, 'node' => 8700, 'system' => 8901, 'update_test_schema' => 8000] as $module => $schema) {
      $this->assertEquals($schema$update_registry->getInstalledVersion($module)new FormattableMarkup('Module @module schema is @schema', ['@module' => $module, '@schema' => $schema]));
    }

    // Ensure that all {router} entries can be unserialized. If they cannot be     // unserialized a notice will be thrown by PHP.
    $result = \Drupal::database()->select('router', 'r')
      ->fields('r', ['name', 'route'])
      ->execute()
      ->fetchAllKeyed(0, 1);
    // For the purpose of fetching the notices and displaying more helpful error     // messages, let's override the error handler temporarily.     set_error_handler(function D$severity$message$filename$lineno) {
      throw new \ErrorException($message, 0, $severity$filename$lineno);
    });
    foreach ($result as $route_name => $route) {
      try {
        unserialize($route);
      }
break;

    case 'user_cancel_reassign':
      // Anonymize nodes (current revisions).       \Drupal::moduleHandler()->loadInclude('node', 'inc', 'node.admin');
      $nodes = \Drupal::entityQuery('node')
        ->accessCheck(FALSE)
        ->condition('uid', $account->id())
        ->execute();
      node_mass_update($nodes['uid' => 0], NULL, TRUE);
      // Anonymize old revisions.       \Drupal::database()->update('node_field_revision')
        ->fields(['uid' => 0])
        ->condition('uid', $account->id())
        ->execute();
      break;
  }
}

/** * Modify account cancellation methods. * * By implementing this hook, modules are able to add, customize, or remove * account cancellation methods. All defined methods are turned into radio * button form elements by user_cancel_methods() after this hook is invoked. * The following properties can be defined for each method: * - title: The radio button's title. * - description: (optional) A description to display on the confirmation form * if the user is not allowed to select the account cancellation method. The * description is NOT used for the radio button, but instead should provide * additional explanation to the user seeking to cancel their account. * - access: (optional) A boolean value indicating whether the user can access * a method. If 'access' is defined, the method cannot be configured as * default method. * * @param array $methods * An array containing user account cancellation methods, keyed by method id. * * @see user_cancel_methods() * @see \Drupal\user\Form\UserCancelForm */
parent::tearDown();
  }

  /** * @covers ::extensionExists * @covers ::tableExists */
  public function testExtensionExists(): void {
    // Check if PG_trgm extension is present.     $this->assertTrue($this->testingFakeConnection->schema()->extensionExists('pg_trgm'));
    // Asserting that the Schema testing_fake exist in the database.     $this->assertCount(1, \Drupal::database()->query("SELECT * FROM pg_catalog.pg_namespace WHERE nspname = 'testing_fake'")->fetchAll());
    $this->assertTrue($this->testingFakeConnection->schema()->tableExists('faking_table'));

    // Hardcoded assertion that we created the table in the non-public schema.     $this->assertCount(1, $this->testingFakeConnection->query("SELECT * FROM pg_tables WHERE schemaname = 'testing_fake' AND tablename = :prefixedTable", [':prefixedTable' => $this->testingFakeConnection->getPrefix() . "faking_table"])->fetchAll());
  }

  /** * @covers ::addField * @covers ::fieldExists * @covers ::dropField * @covers ::changeField */
/** * Loads watchdog entries by channel. * * @param string $channel * The logger channel. * * @return string[] * Watchdog entries. */
  protected function getLogs(string $channel): array {
    $logs = \Drupal::database()->query("SELECT * FROM {watchdog} WHERE type = :type", [':type' => $channel])->fetchAll();
    return array_map(function Dobject $log) {
      return (string) new FormattableMarkup($log->message, unserialize($log->variables));
    }$logs);
  }

  /** * Count number of revisions for an entity type. * * @param string $entityTypeId * The entity type. * * @return int * Number of revisions for an entity type. */
$queue = $this->container->get('queue')->get('cron_queue_test_lease_time');
    $queue->createItem([$this->randomMachineName() => $this->randomMachineName()]);
    // Run initial queue job and ensure lease time variable is initialized.     $this->cron->run();
    static::assertEquals(1, \Drupal::state()->get('cron_queue_test_lease_time'));
    // Ensure the same queue job is not picked up due to the extended lease.     $this->cron->run();
    static::assertEquals(1, \Drupal::state()->get('cron_queue_test_lease_time'));

    // Set the expiration time to 3 seconds ago, so the lease should     // automatically expire.     \Drupal::database()
      ->update(DatabaseQueue::TABLE_NAME)
      ->fields(['expire' => $this->currentTime - 3])
      ->execute();

    // The queue job should now be picked back up since it's lease has expired,     // and the state variable should be consequently incremented.     $this->cron->run();
    static::assertEquals(2, \Drupal::state()->get('cron_queue_test_lease_time'));
    // Ensure the same queue job is not picked up again due to the extended     // lease.     $this->cron->run();
    
Home | Imprint | This part of the site doesn't use cookies.