indexExists example

$this->resetTableInformation($table);
    return TRUE;
  }

  /** * {@inheritdoc} */
  public function addIndex($table$name$fields, array $spec) {
    if (!$this->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException("Cannot add index '$name' to table '$table': table doesn't exist.");
    }
    if ($this->indexExists($table$name)) {
      throw new SchemaObjectExistsException("Cannot add index '$name' to table '$table': index already exists.");
    }

    $this->connection->query($this->_createIndexSql($table$name$fields));
    $this->resetTableInformation($table);
  }

  /** * {@inheritdoc} */
  public function dropIndex($table$name) {
    
$fixnull = FALSE;
    if (!empty($spec['not null']) && !isset($spec['default']) && !$is_primary_key) {
      $fixnull = TRUE;
      $spec['not null'] = FALSE;
    }
    $query = 'ALTER TABLE {' . $table . '} ADD ';
    $query .= $this->createFieldSql($field$this->processField($spec));
    if ($keys_sql = $this->createKeysSql($keys_new)) {
      // Make sure to drop the existing primary key before adding a new one.       // This is only needed when adding a field because this method, unlike       // changeField(), is supposed to handle primary keys automatically.       if (isset($keys_new['primary key']) && $this->indexExists($table, 'PRIMARY')) {
        $query .= ', DROP PRIMARY KEY';
      }

      $query .= ', ADD ' . implode(', ADD ', $keys_sql);
    }
    $this->connection->query($query);
    if (isset($spec['initial_from_field'])) {
      if (isset($spec['initial'])) {
        $expression = 'COALESCE(' . $spec['initial_from_field'] . ', :default_initial_value)';
        $arguments = [':default_initial_value' => $spec['initial']];
      }
      
public function getCreationTimestamp(): int
    {
        return 1673420896;
    }

    public function update(Connection $connection): void
    {
        foreach (self::ASSOCIATION_TABLES as $table) {
            $fkName = 'fk.' . $table . '.salutation_id';

            if (!$this->indexExists($connection$table$fkName)) {
                continue;
            }

            // Drop FK constraints to change from restrict delete to set null on delete             $connection->executeStatement('ALTER TABLE `' . $table . '` DROP FOREIGN KEY `' . $fkName . '`');
            $connection->executeStatement('ALTER TABLE `' . $table . '` ADD CONSTRAINT `' . $fkName . '` FOREIGN KEY (`salutation_id`) REFERENCES `salutation` (`id`) ON DELETE SET NULL ON UPDATE CASCADE');
        }

        /** @var string|false $undefinedSalutationId */
        $undefinedSalutationId = $connection->fetchOne('SELECT `id` FROM `salutation` WHERE `salutation_key` = "undefined"');

        
$this->assertEquals(0, $num_records_after, 'Truncate really deletes everything.');
  }

  /** * @covers ::addIndex * @covers ::indexExists * @covers ::dropIndex */
  public function testIndex(): void {
    $this->testingFakeConnection->schema()->addIndex('faking_table', 'test_field', ['test_field'][]);

    $this->assertTrue($this->testingFakeConnection->schema()->indexExists('faking_table', 'test_field'));

    $results = $this->testingFakeConnection->query("SELECT * FROM pg_indexes WHERE indexname = :indexname", [':indexname' => $this->testingFakeConnection->getPrefix() . 'faking_table__test_field__idx'])->fetchAll();

    $this->assertCount(1, $results);
    $this->assertSame('testing_fake', $results[0]->schemaname);
    $this->assertSame($this->testingFakeConnection->getPrefix() . 'faking_table', $results[0]->tablename);
    $this->assertStringContainsString('USING btree (test_field)', $results[0]->indexdef);

    $this->testingFakeConnection->schema()->dropIndex('faking_table', 'test_field');

    $this->assertFalse($this->testingFakeConnection->schema()->indexExists('faking_table', 'test_field'));
  }
$entity_type = clone $this->entityTypeManager->getDefinition('entity_test_update');

    // Remove the entity type definition. This is the same thing as removing the     // code that defines it.     $this->deleteEntityType();

    // Add an entity index, update the entity type and check that the index has     // been created.     $this->addEntityIndex();
    $this->entityDefinitionUpdateManager->updateEntityType($entity_type);

    $this->assertTrue($this->database->schema()->indexExists('entity_test_update', 'entity_test_update__new_index'), 'Index created.');
  }

  /** * Tests updating a fieldable entity type that doesn't exist in code anymore. * * @covers ::updateFieldableEntityType */
  public function testUpdateFieldableEntityTypeWithoutInCodeDefinition() {
    $entity_type = clone $this->entityTypeManager->getDefinition('entity_test_update');
    $field_storage_definitions = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('entity_test_update');

    
// Dropping an unique key     $this->schema->dropUniqueKey($table_name_new$unique_key_name);

    // Dropping a field.     $this->schema->dropField($table_name_new$field_name_new);
    $this->assertFalse($this->schema->fieldExists($table_name_new$field_name_new));

    // Adding an index.     $index_name = $index_introspect_name = 'index';
    $this->schema->addIndex($table_name_new$index_name['update']$table_specification);
    $this->assertTrue($this->schema->indexExists($table_name_new$index_name));

    // Check the index columns.     $index_introspect_name = $ensure_identifiers_length->invoke($this->schema, $table_name_new$index_name, 'idx');
    $this->assertEquals(['update']$introspect_index_schema->invoke($this->schema, $table_name_new)['indexes'][$index_introspect_name]);

    // Dropping an index.     $this->schema->dropIndex($table_name_new$index_name);
    $this->assertFalse($this->schema->indexExists($table_name_new$index_name));

    // Dropping a table.     $this->schema->dropTable($table_name_new);
    
unset($config['settings']['index']['number_of_replicas']);
            }
        }

        $this->config = $config;
    }

    public function createIndex(AbstractElasticsearchDefinition $definition, string $index, string $alias, Context $context): void
    {
        // NEXT-21735 - does not execute if there's no index yet         // @codeCoverageIgnoreStart         if ($this->indexExists($index)) {
            $this->client->indices()->delete(['index' => $index]);
        }
        // @codeCoverageIgnoreEnd
        $mapping = $this->mappingProvider->build($definition$context);

        $body = array_merge(
            $this->config,
            ['mappings' => $mapping]
        );

        
$container_cannot_be_saved_messages = array_filter(iterator_to_array($select->execute())function D$row) {
      return str_contains($row->message, 'Container cannot be saved to cache.');
    });
    $this->assertEquals([]$container_cannot_be_saved_messages);

    // Ensure schema has changed.     /** @var \Drupal\Core\Update\UpdateHookRegistry $update_registry */
    $update_registry = \Drupal::service('update.update_hook_registry');
    $this->assertEquals(8001, $update_registry->getInstalledVersion('update_test_schema'));
    $this->assertEquals(8001, $update_registry->getInstalledVersion('update_test_semver_update_n'));
    // Ensure the index was added for column a.     $this->assertTrue($connection->schema()->indexExists('update_test_schema_table', 'test'), 'Version 8001 of the update_test_schema module is installed.');
    // Ensure update_test_semver_update_n_update_8001 was run.     $this->assertEquals('Yes, I was run. Thanks for testing!', \Drupal::state()->get('update_test_semver_update_n_update_8001'));
  }

  /** * Tests that path aliases are not processed during database updates. */
  public function testPathAliasProcessing() {
    // Add a path alias for the '/admin' system path.     $values = [
      'path' => '/admin/structure',
      

    $field_storage->save();
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $entity_type,
    ]);
    $field->save();
    $tables = [$this->tableMapping->getDedicatedDataTableName($field_storage)$this->tableMapping->getDedicatedRevisionTableName($field_storage)];

    // Verify the indexes we will create do not exist yet.     foreach ($tables as $table) {
      $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value'), 'No index named value exists in $table');
      $this->assertFalse(Database::getConnection()->schema()->indexExists($table, 'value_format'), 'No index named value_format exists in $table');
    }

    // Add data so the table cannot be dropped.     $entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->create([
        'id' => 1,
        'revision_id' => 1,
      ]);
    $entity->$field_name->value = 'field data';
    

#[Package('core')] class Migration1661759290AddDateAndCurrencyIndexToOrderTable extends MigrationStep
{
    public function getCreationTimestamp(): int
    {
        return 1661759290;
    }

    public function update(Connection $connection): void
    {
        if ($this->indexExists($connection, 'order', 'idx.order_date_currency_id')) {
            return;
        }

        $connection->executeStatement(' ALTER TABLE `order` ADD INDEX `idx.order_date_currency_id` (`order_date`, `currency_id`) ');
    }

    public function updateDestructive(Connection $connection): void
    {
        // implement update destructive

  public function testDBFieldExists() {
    $schema = $this->connection->schema();
    $this->assertTrue($schema->fieldExists('test', 'name'), 'Returns true for existent column.');
    $this->assertFalse($schema->fieldExists('test', 'no_such_column'), 'Returns false for nonexistent column.');
  }

  /** * Tests the Schema::indexExists() method. */
  public function testDBIndexExists() {
    $this->assertTrue($this->connection->schema()->indexExists('test', 'ages'), 'Returns true for existent index.');
    $this->assertFalse($this->connection->schema()->indexExists('test', 'no_such_index'), 'Returns false for nonexistent index.');
  }

}

    return $key_definition;
  }

  /** * {@inheritdoc} */
  public function addIndex($table$name$fields, array $spec) {
    if (!$this->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException("Cannot add index '$name' to table '$table': table doesn't exist.");
    }
    if ($this->indexExists($table$name)) {
      throw new SchemaObjectExistsException("Cannot add index '$name' to table '$table': index already exists.");
    }

    $schema['indexes'][$name] = $fields;
    $statements = $this->createIndexSql($table$schema);
    foreach ($statements as $statement) {
      $this->connection->query($statement);
    }
  }

  /** * {@inheritdoc} */
// Add a default value to the column.     $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE, 'default' => 0]);
    // The insert should now succeed.     $this->assertTrue($this->tryInsert(), 'Insert with a default succeeded.');

    // Remove the default.     $this->schema->changeField('test_table', 'test_field', 'test_field', ['type' => 'int', 'not null' => TRUE]);
    // The insert should fail again.     $this->assertFalse($this->tryInsert(), 'Insert without a default failed.');

    // Test for fake index and test for the boolean result of indexExists().     $index_exists = $this->schema->indexExists('test_table', 'test_field');
    $this->assertFalse($index_exists, 'Fake index does not exist');
    // Add index.     $this->schema->addIndex('test_table', 'test_field', ['test_field']$table_specification);
    // Test for created index and test for the boolean result of indexExists().     $index_exists = $this->schema->indexExists('test_table', 'test_field');
    $this->assertTrue($index_exists, 'Index created.');

    // Rename the table.     $this->assertNull($this->schema->renameTable('test_table', 'test_table2'));

    // Index should be renamed.
/** * Tests that update hooks are properly run. */
  public function testUpdateHooks() {
    $connection = Database::getConnection();

    /** @var \Drupal\Core\Update\UpdateHookRegistry $update_registry */
    $update_registry = \Drupal::service('update.update_hook_registry');

    // Verify that the 8000 schema is in place.     $this->assertEquals(8000, $update_registry->getInstalledVersion('update_test_schema'));
    $this->assertFalse($connection->schema()->indexExists('update_test_schema_table', 'test'), 'Version 8000 of the update_test_schema module is installed.');

    // Increment the schema version.     \Drupal::state()->set('update_test_schema_version', 8001);

    $this->drupalLogin($this->user);
    $this->drupalGet($this->updateUrl, ['external' => TRUE]);
    $this->updateRequirementsProblem();
    $this->clickLink('Continue');
    $this->assertSession()->pageTextContains('Schema version 8001.');
    // Run the update hooks.     $this->clickLink('Apply pending updates');
    
Home | Imprint | This part of the site doesn't use cookies.