getConnection example

$this->installEntitySchema('user');
    $this->installEntitySchema('file');
    $this->installEntitySchema('menu_link_content');
    $this->installEntitySchema('path_alias');
    $this->installSchema('system', 'sequences');

    // Place some sample config to test for in the export.     $this->data = [
      'foo' => $this->randomMachineName(),
      'bar' => $this->randomMachineName(),
    ];
    $storage = new DatabaseStorage(Database::getConnection(), 'config');
    $storage->write('test_config', $this->data);

    // Create user account with some potential syntax issues.     // cspell:disable-next-line     $account = User::create(['mail' => 'q\'uote$dollar@example.com', 'name' => '$dollar']);
    $account->save();

    // Create a path alias.     $this->createPathAlias('/user/' . $account->id(), '/user/example');

    // Create a cache table (this will create 'cache_discovery').
public function testDateFormats() {
    $short_date_format = DateFormat::load('short');
    $this->assertSame('\S\H\O\R\T m/d/Y - H:i', $short_date_format->getPattern());

    $medium_date_format = DateFormat::load('medium');
    $this->assertSame('\M\E\D\I\U\M D, m/d/Y - H:i', $medium_date_format->getPattern());

    $long_date_format = DateFormat::load('long');
    $this->assertSame('\L\O\N\G l, F j, Y - H:i', $long_date_format->getPattern());

    // Test that we can re-import using the EntityDateFormat destination.     Database::getConnection('default', 'migrate')
      ->update('variable')
      ->fields(['value' => serialize('\S\H\O\R\T d/m/Y - H:i')])
      ->condition('name', 'date_format_short')
      ->execute();

    $migration = $this->getMigration('d6_date_formats');
    \Drupal::database()
      ->truncate($migration->getIdMap()->mapTableName())
      ->execute();

    $this->executeMigration($migration);

    
'id' => '809c1844f4734243b6aa04aba860cd45'],
            ],
        ];

        $data = $indexer->globalData($result$context);

        static::assertEquals($result['total']$data['total']);
    }

    public function testFetching(): void
    {
        $connection = $this->getConnection();

        $indexer = new NewsletterRecipientAdminSearchIndexer(
            $connection,
            $this->createMock(IteratorFactory::class),
            $this->createMock(EntityRepository::class),
            100
        );

        $id = '809c1844f4734243b6aa04aba860cd45';
        $documents = $indexer->fetch([$id]);

        
protected function loadMigration(array $result, string $migrationPath): AbstractMigration
    {
        $migrationClassName = 'Migrations_Migration' . $result['1'];
        if (!class_exists($migrationClassName, false)) {
            $file = $migrationPath . '/' . $result['0'];
            require $file;
        }

        try {
            /** @var AbstractMigration $migrationClass */
            $migrationClass = new $migrationClassName($this->getConnection());
        } catch (Exception $e) {
            throw new RuntimeException(sprintf('Could not instantiate Object of class "%s"', $migrationClassName));
        }

        $this->validateMigration($migrationClass$result);

        return $migrationClass;
    }

    protected function insertMigration(AbstractMigration $migration): void
    {
        
$account
      ->block()
      ->save();

    $response = $this->passwordRequest(['name' => $account->getAccountName()]$format);
    $this->assertEquals(200, $response->getStatusCode());

    // Check that the proper warning has been logged.     $arguments = [
      '%identifier' => $account->getAccountName(),
    ];
    $logged = Database::getConnection()->select('watchdog')
      ->fields('watchdog', ['variables'])
      ->condition('type', 'user')
      ->condition('message', 'Unable to send password reset email for blocked or not yet activated user %identifier.')
      ->orderBy('wid', 'DESC')
      ->range(0, 1)
      ->execute()
      ->fetchField();
    $this->assertEquals(serialize($arguments)$logged);

    $response = $this->passwordRequest(['mail' => $account->getEmail()]$format);
    $this->assertEquals(200, $response->getStatusCode());

    
'comments' => 0,
        'promote' => 0,
        'relevance' => 2,
        'sticky' => 0,
        'views' => 0,
      ],
    ];
    $this->assertEntity('node_search', 'node', TRUE, $configuration);
    $this->assertEntity('user_search', 'user');

    // Test that we can re-import using the EntitySearchPage destination.     Database::getConnection('default', 'migrate')
      ->update('variable')
      ->fields(['value' => serialize(4)])
      ->condition('name', 'node_rank_comments')
      ->execute();

    /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
    $migration = $this->getMigration('d7_search_page');
    // Indicate we're rerunning a migration that's already run.     $migration->getIdMap()->prepareUpdate();
    $this->executeMigration($migration);
    $configuration['rankings']['comments'] = 4;
    
/** * Returns the database connection to use for inserting assertions. * * @return \Drupal\Core\Database\Connection * The database connection to use for inserting assertions. */
  public static function getConnection(): Connection {
    // Check whether there is a test runner connection.     // @see run-tests.sh     // @todo Convert Simpletest UI runner to create + use this connection, too.     try {
      $connection = Database::getConnection('default', 'test-runner');
    }
    catch (ConnectionNotDefinedException $e) {
      // Check whether there is a backup of the original default connection.       // @see FunctionalTestSetupTrait::prepareEnvironment()       try {
        $connection = Database::getConnection('default', 'simpletest_original_default');
      }
      catch (ConnectionNotDefinedException $e) {
        // If FunctionalTestSetupTrait::prepareEnvironment() failed, the         // test-specific database connection does not exist yet/anymore, so         // fall back to the default of the (UI) test runner.
use Shopware\Core\Migration\V6_5\Migration1669124190AddDoctrineMessengerTable;

/** * @internal * * @covers \Shopware\Core\Migration\V6_5\Migration1669124190AddDoctrineMessengerTable */
class Migration1669124190AddDoctrineMessengerTableTest extends TestCase
{
    public function testItCreatesTable(): void
    {
        $connection = KernelLifecycleManager::getConnection();
        $connection->executeStatement('DROP TABLE IF EXISTS `messenger_messages`');

        $migration = new Migration1669124190AddDoctrineMessengerTable();

        $migration->update($connection);
        // check that it can be executed multiple times         $migration->update($connection);

        $tableExists = (bool) $connection->fetchOne('SHOW TABLES LIKE "messenger_messages"');
        static::assertTrue($tableExists);
    }
}
public function testTagInvalidations() {
    // Create cache entry in multiple bins.     $tags = ['test_tag:1', 'test_tag:2', 'test_tag:3'];
    $bins = ['data', 'bootstrap', 'render'];
    foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $bin->set('test', 'value', Cache::PERMANENT, $tags);
      $this->assertNotEmpty($bin->get('test'), 'Cache item was set in bin.');
    }

    $connection = Database::getConnection();
    $invalidations_before = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
    Cache::invalidateTags(['test_tag:2']);

    // Test that cache entry has been invalidated in multiple bins.     foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $this->assertFalse($bin->get('test'), 'Tag invalidation affected item in bin.');
    }

    // Test that only one tag invalidation has occurred.     $invalidations_after = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
    
/** * @package content * * @internal * * @covers \Shopware\Core\Migration\V6_5\Migration1659425718AddFlagsToCustomEntities */
class Migration1659425718AddFlagsToCustomEntitiesTest extends TestCase
{
    public function testMultipleExecution(): void
    {
        $connection = KernelLifecycleManager::getConnection();

        $migration = new Migration1659425718AddFlagsToCustomEntities();
        $migration->update($connection);
        $migration->update($connection);

        static::assertTrue(EntityDefinitionQueryHelper::columnExists($connection, 'custom_entity', 'flags'));
    }

    public function testColumnGetsCreated(): void
    {
        $connection = KernelLifecycleManager::getConnection();
        
case str_starts_with($connection, 'pdo_oci://'):
                if (!class_exists(DriverManager::class)) {
                    throw new \InvalidArgumentException('Unsupported PDO OCI DSN. Try running "composer require doctrine/dbal".');
                }
                $connection[3] = '-';
                $params = class_exists(DsnParser::class) ? (new DsnParser())->parse($connection) : ['url' => $connection];
                $config = new Configuration();
                if (class_exists(DefaultSchemaManagerFactory::class)) {
                    $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory());
                }

                $connection = DriverManager::getConnection($params$config);
                $connection = method_exists($connection, 'getNativeConnection') ? $connection->getNativeConnection() : $connection->getWrappedConnection();
                // no break;
            case str_starts_with($connection, 'mssql://'):
            case str_starts_with($connection, 'mysql://'):
            case str_starts_with($connection, 'mysql2://'):
            case str_starts_with($connection, 'pgsql://'):
            case str_starts_with($connection, 'postgres://'):
            case str_starts_with($connection, 'postgresql://'):
            case str_starts_with($connection, 'sqlsrv://'):
            case str_starts_with($connection, 'sqlite://'):
            
if ($replicaUrl) {
            $parameters['wrapperClass'] = PrimaryReadReplicaConnection::class;
            $parameters['primary'] = ['url' => $url, 'driverOptions' => $parameters['driverOptions']];
            $parameters['replica'] = [];

            for ($i = 0; $replicaUrl = (string) EnvironmentHelper::getVariable('DATABASE_REPLICA_' . $i . '_URL'); ++$i) {
                $parameters['replica'][] = ['url' => $replicaUrl, 'charset' => $parameters['charset'], 'driverOptions' => $parameters['driverOptions']];
            }
        }

        return DriverManager::getConnection($parameters$config);
    }
}


class Migrations_Migration456 extends Shopware\Components\Migrations\AbstractMigration
{
    public function up($modus)
    {
        $statement = $this->getConnection()->prepare("SELECT id FROM s_core_plugins WHERE `name` = 'HttpCache' AND installation_date IS NOT NULL LIMIT 1;");
        $statement->execute();
        $data = $statement->fetchAll();

        if (empty($data)) {
            return;
        }

        $sql = "SET @pluginID = (SELECT id FROM s_core_plugins WHERE `name` = 'HttpCache' AND installation_date IS NOT NULL LIMIT 1);";
        $this->addSql($sql);

        $sql = <<<'SQL'


    $long_name = str_repeat('a', $max_allowed_packet + 1);
    try {
      $this->connection->query('SELECT [name] FROM {test} WHERE [name] = :name', [':name' => $long_name]);
      $this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'");
    }
    catch (DatabaseException $e) {
      // Close and re-open the connection. Otherwise we will run into error       // 2006 "MySQL server had gone away" afterwards.       Database::closeConnection();
      Database::getConnection();
      // Got a packet bigger than 'max_allowed_packet' bytes exception thrown.       $this->assertEquals(1153, $e->getPrevious()->errorInfo[1]);
      // 'max_allowed_packet' exception message truncated.       // Use strlen() to count the bytes exactly, not the unicode chars.       $this->assertLessThanOrEqual($max_allowed_packetstrlen($e->getMessage()));
    }
  }

}
$entity->field_int[] = mt_rand(1, 99);
      $entity->field_int[] = mt_rand(1, 99);
      $entity->name[] = $this->randomMachineName();
      $entity->save();
    }

    $storage = \Drupal::entityTypeManager()->getStorage('entity_test');
    if ($storage instanceof SqlContentEntityStorage) {
      // Count the actual number of rows in the field table.       $table_mapping = $storage->getTableMapping();
      $field_table_name = $table_mapping->getDedicatedDataTableName($field_storage);
      $result = Database::getConnection()->select($field_table_name, 't')
        ->fields('t')
        ->countQuery()
        ->execute()
        ->fetchField();
      $this->assertEquals(24, $result, 'The field table has 24 rows.');
    }

    $this->assertTrue($field_storage->hasdata(), 'There are entities with field data.');
    $this->assertEquals(12, $this->storage->countFieldData($field_storage), 'There are 12 entities with field data.');

    // Ensure the methods work on deleted fields.
Home | Imprint | This part of the site doesn't use cookies.