getDatabase example

foreach ($connection_info as $target => $value) {
      $prefix = $value['prefix'];
      // Tests use 7 character prefixes at most so this can't cause collisions.       $connection_info[$target]['prefix'] = $prefix . '0';
    }
    Database::addConnectionInfo('migrate', 'default', $connection_info['default']);

    // Make sure source plugins can be serialized.     foreach ($migration_plugins as $migration_plugin) {
      $source_plugin = $migration_plugin->getSourcePlugin();
      if ($source_plugin instanceof SqlBase) {
        $source_plugin->getDatabase();
      }
      $this->assertNotEmpty(serialize($source_plugin));
    }

    $migration_plugins = $this->container->get('plugin.manager.migration')->getDefinitions();
    // All the plugins provided by core depend on migrate_drupal.     $this->assertNotEmpty($migration_plugins);

    // Test that migrations derived by EntityReferenceTranslationDeriver are     // discovered now that migrate_drupal is enabled.     $this->assertArrayHasKey('d6_entity_reference_translation:user__user', $migration_plugins);
    

function hook_migrate_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  if ($migration->id() == 'd6_filter_formats') {
    $value = $source->getDatabase()->query('SELECT [value] FROM {variable} WHERE [name] = :name', [':name' => 'mymodule_filter_foo_' . $row->getSourceProperty('format')])->fetchField();
    if ($value) {
      $row->setSourceProperty('settings:mymodule:foo', unserialize($value));
    }
  }
}

/** * Allows adding data to a row for a migration with the specified ID. * * This provides the same functionality as hook_migrate_prepare_row() but * removes the need to check the value of $migration->id(). * * @param \Drupal\migrate\Row $row * The row being imported. * @param \Drupal\migrate\Plugin\MigrateSourceInterface $source * The source migration. * @param \Drupal\migrate\Plugin\MigrationInterface $migration * The current migration. * * @ingroup migration */


    public function update(Connection $connection): void
    {
        $columns = $connection->executeQuery(' SELECT COLUMN_NAME,EXTRA FROM information_schema.columns WHERE table_schema = :database AND table_name = \'state_machine_history\' AND (COLUMN_NAME = \'referenced_id\' OR COLUMN_NAME = \'referenced_version_id\' OR COLUMN_NAME = \'entity_id\'); ', ['database' => $connection->getDatabase()])->fetchAllAssociativeIndexed();

        if ($columns['referenced_id']['EXTRA'] === 'STORED GENERATED') {
            $connection->executeStatement(' ALTER TABLE `state_machine_history` MODIFY COLUMN `referenced_id` BINARY(16) NOT NULL; ');
        }

        if ($columns['referenced_version_id']['EXTRA'] === 'STORED GENERATED') {
            $connection->executeStatement(' ALTER TABLE `state_machine_history` MODIFY COLUMN `referenced_version_id` BINARY(16) NOT NULL; ');
private function getFullName(string $table): string
    {
        $alias = '';

        if (strpos($table, ' ') !== false) {
            $alias = explode(' ', $table);
            $table = array_shift($alias);
            $alias = ' ' . implode(' ', $alias);
        }

        if ($this->db->escapeChar === '"') {
            return '"' . $this->db->getDatabase() . '"."' . $this->db->schema . '"."' . str_replace('"', '', $table) . '"' . $alias;
        }

        return '[' . $this->db->getDatabase() . '].[' . $this->db->schema . '].[' . str_replace('"', '', $table) . ']' . str_replace('"', '', $alias);
    }

    /** * Add permision statements for index value inserts */
    private function addIdentity(string $fullTable, string $insert): string
    {
        return 'SET IDENTITY_INSERT ' . $fullTable . " ON\n" . $insert . "\nSET IDENTITY_INSERT " . $fullTable . ' OFF';
    }
$migration->update($this->connection);

        $sql = <<<SQL SELECT NUMERIC_PRECISION, NUMERIC_SCALE, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tax' AND COLUMN_NAME = 'tax_rate' AND TABLE_SCHEMA = :dbName; SQL;

        $dbName = $this->connection->getDatabase();

        /** @var array{NUMERIC_PRECISION: string, NUMERIC_SCALE: string, COLUMN_TYPE: string} $tableColumn */
        $tableColumn = $this->connection->fetchAssociative($sql['dbName' => $dbName]);

        static::assertEquals('10', $tableColumn['NUMERIC_PRECISION']);
        static::assertEquals('3', $tableColumn['NUMERIC_SCALE']);
        static::assertEquals('decimal(10,3)', $tableColumn['COLUMN_TYPE']);
    }

    public function testChangeColumnTaxRateOnTaxRuleTable(): void
    {
        

  protected function getFieldData(array $field, Row $node) {
    $field_table = 'content_' . $field['field_name'];
    $node_table = 'content_type_' . $node->getSourceProperty('type');

    /** @var \Drupal\Core\Database\Schema $db */
    $db = $this->getDatabase()->schema();

    if ($db->tableExists($field_table)) {
      $query = $this->select($field_table, 't');

      // If the delta column does not exist, add it as an expression to       // normalize the query results.       if ($db->fieldExists($field_table, 'delta')) {
        $query->addField('t', 'delta');
      }
      else {
        $query->addExpression(0, 'delta');
      }
'language',
        'plid',
        'plural',
      ])
      ->condition('i18n_mode', 1);
    $query->leftjoin($this->blockTable, 'b', ('[b].[delta] = [i18n].[objectid]'));
    $query->innerJoin('locales_target', 'lt', '[lt].[lid] = [i18n].[lid]');

    // The i18n_string module adds a status column to locale_target. It was     // originally 'status' in a later revision it was named 'i18n_status'.     /** @var \Drupal\Core\Database\Schema $db */
    if ($this->getDatabase()->schema()->fieldExists('locales_target', 'status')) {
      $query->addField('lt', 'status', 'i18n_status');
    }
    if ($this->getDatabase()->schema()->fieldExists('locales_target', 'i18n_status')) {
      $query->addField('lt', 'i18n_status', 'i18n_status');
    }

    return $query;
  }

  /** * {@inheritdoc} */
private readonly string $defaultDirectory,
        private readonly Connection $connection
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        system('mkdir -p ' . escapeshellarg($this->defaultDirectory));

        /** @var string $dbName */
        $dbName = $this->connection->getDatabase();
        /** @var Params&OverrideParams $params */
        $params = $this->connection->getParams();

        $path = sprintf('%s/%s_%s.sql', $this->defaultDirectory, $params['host'] ?? '', $dbName);

        $portString = '';
        if ($params['password'] ?? '') {
            $portString = '-p' . escapeshellarg($params['password']);
        }

        file_put_contents($path, 'SET unique_checks=0;SET foreign_key_checks=0;');
        

  public function testSource(array $source_data, array $expected_data$expected_count = NULL, array $configuration = []$high_water = NULL, $expected_cache_key = NULL) {
    $plugin = $this->getPlugin($configuration);

    // Since we don't yet inject the database connection, we need to use a     // reflection hack to set it in the plugin instance.     $reflector = new \ReflectionObject($plugin);
    $property = $reflector->getProperty('database');
    $property->setValue($plugin$this->getDatabase($source_data));

    /** @var MemoryCounterBackend $cache **/
    $cache = \Drupal::cache('migrate');
    if ($expected_cache_key) {
      // Verify the computed cache key.       $property = $reflector->getProperty('cacheKey');
      $this->assertSame($expected_cache_key$property->getValue($plugin));

      // Cache miss prior to calling ::count().       $this->assertFalse($cache->get($expected_cache_key, 'cache'));

      

        $delete = [['id' => Uuid::randomHex()]];

        $connection = $this->getContainer()->get(Connection::class);

        $connection = $this->getMockBuilder(Connection::class)
            ->setConstructorArgs([
                array_merge(
                    $connection->getParams(),
                    [
                        'url' => $_SERVER['DATABASE_URL'],
                        'dbname' => $connection->getDatabase(),
                    ]
                ),
                $connection->getDriver(),
                $connection->getConfiguration(),
            ])
            ->onlyMethods(['delete'])
            ->getMock();

        $connection->method('delete')->willThrowException(new Exception('test'));

        $successSpy = $this->callbackSpy();
        

class LanguageContentSettingsTaxonomyVocabulary extends DrupalSqlBase {

  /** * {@inheritdoc} */
  public function query() {
    $query = $this->select('vocabulary', 'v')
      ->fields('v', ['vid']);
    if ($this->getDatabase()
      ->schema()
      ->fieldExists('vocabulary', 'language')) {
      $query->addField('v', 'language');
    }
    return $query;
  }

  /** * {@inheritdoc} */
  public function fields() {
    
// Get Field API field values.     foreach ($this->getFields('user') as $field_name => $field) {
      // Ensure we're using the right language if the entity and the field are       // translatable.       $field_language = $entity_translatable && $field['translatable'] ? $language : NULL;
      $row->setSourceProperty($field_name$this->getFieldValues('user', $field_name$uid, NULL, $field_language));
    }

    // Get profile field values. This code is lifted directly from the D6     // ProfileFieldValues plugin.     if ($this->getDatabase()->schema()->tableExists('profile_value')) {
      $query = $this->select('profile_value', 'pv')
        ->fields('pv', ['fid', 'value']);
      $query->leftJoin('profile_field', 'pf', '[pf].[fid] = [pv].[fid]');
      $query->fields('pf', ['name', 'type']);
      $query->condition('uid', $row->getSourceProperty('uid'));
      $results = $query->execute();

      foreach ($results as $profile_value) {
        if ($profile_value['type'] == 'date') {
          $date = unserialize($profile_value['value']);
          $date = date('Y-m-d', mktime(0, 0, 0, $date['month']$date['day']$date['year']));
          
SQL;

    protected function setUp(): void
    {
        $this->connection = KernelLifecycleManager::getConnection();
        if ($this->connection->fetchOne('SHOW COLUMNS FROM `cart` LIKE \'name\'') !== 'name') {
            $this->connection->executeStatement(
                'ALTER TABLE `cart` ADD COLUMN `name` VARCHAR(500) COLLATE utf8mb4_unicode_ci NOT NULL'
            );
        }

        if ($this->connection->fetchOne(self::$isCartNameNullable[$this->connection->getDatabase()]) === 'YES') {
            $this->connection->executeStatement(
                'ALTER TABLE `cart` CHANGE `name` `name` VARCHAR(500) COLLATE utf8mb4_unicode_ci NOT NULL'
            );
        }
    }

    public function testMigrate(): void
    {
        static::assertEquals(
            'NO',
            $this->connection->fetchOne(self::$isCartNameNullable[$this->connection->getDatabase()])
        );
/** * {@inheritdoc} */
  public function fields() {
    return array_combine($this->variables, $this->variables);
  }

  /** * {@inheritdoc} */
  public function query() {
    return $this->getDatabase()
      ->select('variable', 'v')
      ->fields('v', ['name', 'value'])
      ->condition('name', $this->variables, 'IN');
  }

  /** * {@inheritdoc} */
  public function getIds() {
    $ids['id']['type'] = 'string';
    return $ids;
  }
public function messageTableName() {
    return $this->messageTableName;
  }

  /** * Get the fully qualified map table name. * * @return string * The fully qualified map table name. */
  public function getQualifiedMapTableName() {
    return $this->getDatabase()->getFullQualifiedTableName($this->mapTableName);
  }

  /** * Gets the database connection. * * @return \Drupal\Core\Database\Connection * The database connection object. */
  public function getDatabase() {
    $this->init();
    return $this->database;
  }
Home | Imprint | This part of the site doesn't use cookies.