databaseType example


class Mysql8RequirePrimaryKeyUpdateTest extends UpdatePathTestBase {

  /** * {@inheritdoc} */
  protected function runDbTasks() {
    parent::runDbTasks();
    $database = Database::getConnection();
    $is_maria = method_exists($database, 'isMariaDb') && $database->isMariaDb();
    if ($database->databaseType() !== 'mysql' || $is_maria || version_compare($database->version(), '8.0.13', '<')) {
      $this->markTestSkipped('This test only runs on MySQL 8.0.13 and above');
    }

    $database->query("SET sql_require_primary_key = 1;")->execute();
  }

  /** * {@inheritdoc} */
  protected function prepareSettings() {
    parent::prepareSettings();

    

  public function getFormula() {
    $formula = "SUBSTRING($this->tableAlias.$this->realField, 1, " . intval($this->options['limit']) . ")";

    if ($this->options['case'] != 'none') {
      // Support case-insensitive substring comparisons for SQLite by using the       // 'NOCASE_UTF8' collation.       // @see Drupal\sqlite\Driver\Database\sqlite\Connection::open()       if (Database::getConnection()->databaseType() == 'sqlite') {
        $formula .= ' COLLATE NOCASE_UTF8';
      }

      // Support case-insensitive substring comparisons for PostgreSQL by       // converting the formula to lowercase.       if (Database::getConnection()->databaseType() == 'pgsql') {
        $formula = 'LOWER(' . $formula . ')';
      }
    }
    return $formula;
  }

  

  protected $databaseName;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    /** @var \Drupal\Core\Database\Connection $connection */
    $this->connection = \Drupal::service('database');
    if ($this->connection->databaseType() == 'pgsql') {
      $this->databaseName = 'public';
    }
    else {
      $this->databaseName = $this->connection->getConnectionOptions()['database'];
    }
  }

  /** * {@inheritdoc} */
  protected function setDatabaseDumpFiles() {
    
$previous = $edit['alias[0][value]'];
    // Lower-case letters.     $edit['alias[0][value]'] = '/alias' .
      // "Special" ASCII characters.       "- ._~!$'\"()*@[]?&+%#,;=:" .
      // Characters that look like a percent-escaped string.       "%23%25%26%2B%2F%3F" .
      // Characters from various non-ASCII alphabets.       "中國書۞";
    $connection = Database::getConnection();
    if ($connection->databaseType() != 'sqlite') {
      // When using LIKE for case-insensitivity, the SQLite driver is       // currently unable to find the upper-case versions of non-ASCII       // characters.       // @todo fix this in https://www.drupal.org/node/2607432       // cSpell:disable-next-line       $edit['alias[0][value]'] .= "ïвβéø";
    }
    $this->drupalGet('admin/config/search/path/edit/' . $pid);
    $this->submitForm($edit, 'Save');

    // Confirm that the alias works.


use Drupal\Core\Database\Database;

$connection = Database::getConnection();
// Ensure any tables with a serial column with a value of 0 are created as // expected. if ($connection->databaseType() === 'mysql') {
  $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
  $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
}

$connection->schema()->createTable('accesslog', array(
  'fields' => array(
    'aid' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'size' => 'normal',
    ),
    


use Drupal\Core\Database\Database;

$connection = Database::getConnection();
// Ensure any tables with a serial column with a value of 0 are created as // expected. if ($connection->databaseType() === 'mysql') {
  $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
  $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
}

$connection->schema()->createTable('actions', array(
  'fields' => array(
    'aid' => array(
      'type' => 'varchar',
      'not null' => TRUE,
      'length' => '255',
      'default' => '0',
    ),
// Check that the 'all_fields' statement is handled properly.     $tables = $query->getTables();
    $this->assertEquals(1, $tables['test']['all_fields'], 'Query correctly sets \'all_fields\' statement.');
    $tables = $count->getTables();
    $this->assertFalse(isset($tables['test']['all_fields']), 'Count query correctly unsets \'all_fields\' statement.');

    // Check that the ordering clause is handled properly.     $orderby = $query->getOrderBy();
    // The orderby string is different for PostgreSQL.     // @see Drupal\pgsql\Driver\Database\pgsql\Select::orderBy()     $db_type = Database::getConnection()->databaseType();
    $this->assertEquals($db_type == 'pgsql' ? 'ASC NULLS FIRST' : 'ASC', $orderby['name'], 'Query correctly sets ordering clause.');
    $orderby = $count->getOrderBy();
    $this->assertFalse(isset($orderby['name']), 'Count query correctly unsets ordering clause.');

    // Make sure that the count query works.     $count = $count->execute()->fetchField();

    $this->assertEquals(4, $count, 'Counted the correct number of records.');
  }

  /** * Tests that countQuery properly removes fields and expressions. */


use Drupal\Core\Database\Database;

$connection = Database::getConnection();
// Ensure any tables with a serial column with a value of 0 are created as // expected. if ($connection->databaseType() === 'mysql') {
  $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
  $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
}

$connection->schema()->createTable('access', array(
  'fields' => array(
    'aid' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'size' => 'normal',
    ),
    
// Check that the deprecated theme link was rendered correctly.     $this->assertSession()->elementExists('xpath', "//a[contains(@href, 'http://example.com/deprecated_theme')]");

    // Uninstall a deprecated theme and confirm the warning is not displayed.     $theme_installer->uninstall(['test_deprecated_theme']);
    $this->drupalGet('admin/reports/status');
    $session->pageTextNotContains('Deprecated themes enabled');
    $session->pageTextNotContains('Deprecated themes found: Test deprecated theme.');
    $this->assertSession()->elementNotExists('xpath', "//a[contains(@href, 'http://example.com/deprecated_theme')]");

    // Check if pg_trgm extension is enabled on postgres.     if ($this->getDatabaseConnection()->databaseType() == 'pgsql') {
      $this->assertSession()->pageTextContains('PostgreSQL pg_trgm extension');
      $elements = $this->xpath('//details[@class="system-status-report__entry"]//div[contains(text(), :text)]', [
        ':text' => 'The pg_trgm PostgreSQL extension is present.',
      ]);
      $this->assertCount(1, $elements);
      $this->assertStringStartsWith('Available', $elements[0]->getParent()->getText());
    }
  }

  /** * Tests that the Error counter matches the displayed number of errors. */


use Drupal\Core\Database\Database;

$connection = Database::getConnection();
// Ensure any tables with a serial column with a value of 0 are created as // expected. if ($connection->databaseType() === 'mysql') {
  $sql_mode = $connection->query("SELECT @@sql_mode;")->fetchField();
  $connection->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
}

$connection->schema()->createTable('accesslog', array(
  'fields' => array(
    'aid' => array(
      'type' => 'serial',
      'not null' => TRUE,
      'size' => 'normal',
    ),
    
/** * {@inheritdoc} */
  protected function doSaveFieldItems(ContentEntityInterface $entity, array $names = []) {
    // The anonymous user account is saved with the fixed user ID of 0. MySQL     // does not support inserting an ID of 0 into serial field unless the SQL     // mode is set to NO_AUTO_VALUE_ON_ZERO.     // @todo https://drupal.org/i/3222123 implement a generic fix for all entity     // types.     if ($entity->id() === 0) {
      $database = \Drupal::database();
      if ($database->databaseType() === 'mysql') {
        $sql_mode = $database->query("SELECT @@sql_mode;")->fetchField();
        $database->query("SET sql_mode = '$sql_mode,NO_AUTO_VALUE_ON_ZERO'");
      }
    }
    parent::doSaveFieldItems($entity$names);

    // Reset the SQL mode if we've changed it.     if (isset($sql_mode$database)) {
      $database->query("SET sql_mode = '$sql_mode'");
    }
  }

  
/** * {@inheritdoc} */
  protected function tearDown(): void {
    parent::tearDown();

    // Check that all tables of the test instance have been deleted. At this     // point the original database connection is restored so we need to prefix     // the tables.     $connection = Database::getConnection();
    if ($connection->databaseType() === 'sqlite') {
      $result = $connection->query("SELECT name FROM " . $this->databasePrefix .
        ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [
          ':type' => 'table',
          ':table_name' => '%',
          ':pattern' => 'sqlite_%',
        ]
      )->fetchAllKeyed(0, 0);
      $this->assertEmpty($result, 'All test tables have been removed.');
    }
    else {
      $tables = $connection->schema()->findTables($this->databasePrefix . '%');
      

    ];
  }

  /** * Tests exception is thrown in ensureTables fails. * * @dataProvider providerTestFailEnsureTables */
  public function testFailEnsureTables($ids) {
    // This just tests mysql, as other PDO integrations allow longer indexes.     if (Database::getConnection()->databaseType() !== 'mysql') {
      $this->markTestSkipped("This test only runs for MySQL");
    }

    $this->migrationDefinition['source']['ids'] = $ids;
    $migration = $this->container
      ->get('plugin.manager.migration')
      ->createStubMigration($this->migrationDefinition);

    // Use local id map plugin to force an error.     $map = new SqlIdMapTest($this->database, [], 'test', []$migration$this->eventDispatcher, $this->migrationPluginManager);

    

  protected function getTableSchema(Connection $connection$table) {
    // Check this is MySQL.     if ($connection->databaseType() !== 'mysql') {
      throw new \RuntimeException('This script can only be used with MySQL database backends.');
    }

    $query = $connection->query("SHOW FULL COLUMNS FROM {" . $table . "}");
    $definition = [];
    while (($row = $query->fetchAssoc()) !== FALSE) {
      $name = $row['Field'];
      // Parse out the field type and meta information.       preg_match('@([a-z]+)(?:\((\d+)(?:,(\d+))?\))?\s*(unsigned)?@', $row['Type']$matches);
      $type = $this->fieldTypeMap($connection$matches[1]);
      if ($row['Extra'] === 'auto_increment') {
        
$driver_backend = NULL;
    if ($container->hasParameter('default_backend')) {
      $default_backend = $container->getParameter('default_backend');
      // Opt out from the default backend.       if (!$default_backend) {
        return;
      }
    }
    else {
      try {
        $driver_backend = $container->get('database')->driver();
        $default_backend = $container->get('database')->databaseType();
        $container->set('database', NULL);
      }
      catch (\Exception $e) {
        // If Drupal is not installed or a test doesn't define database there         // is nothing to override.         return;
      }
    }

    foreach ($container->findTaggedServiceIds('backend_overridable') as $id => $attributes) {
      // If the service is already an alias it is not the original backend, so
Home | Imprint | This part of the site doesn't use cookies.