tableExists example

catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /** * Check if the cache bin exists and create it if not. */
  protected function ensureBinExists() {
    try {
      $database_schema = $this->connection->schema();
      if (!$database_schema->tableExists($this->bin)) {
        $schema_definition = $this->schemaDefinition();
        $database_schema->createTable($this->bin, $schema_definition);
        return TRUE;
      }
    }
    // If another process has already created the cache table, attempting to     // recreate it will throw an exception. In this case just catch the     // exception and do nothing.     catch (DatabaseException $e) {
      return TRUE;
    }
    
/** * Determines if this menu_link has an i18n translation. * * @param string $mlid * The menu id. * * @return bool * True if the menu_link has an i18n translation. */
  public function hasTranslation($mlid) {
    if ($this->getDatabase()->schema()->tableExists('i18n_string')) {
      $results = $this->select('i18n_string', 'i18n')
        ->fields('i18n')
        ->condition('textgroup', 'menu')
        ->condition('type', 'item')
        ->condition('objectid', $mlid)
        ->execute()
        ->fetchAll();
      if ($results) {
        return TRUE;
      }
    }
    
$command_tester = new CommandTester($command);
    $command_tester->execute([
      'script' => __DIR__ . '/../../../fixtures/update/drupal-9.4.0.bare.standard.php.gz',
      '--database' => $this->databasePrefix,
    ]);

    // The tables should now exist.     $connection = Database::getConnection('default', $this->databasePrefix);
    foreach ($this->tables as $table) {
      $this->assertTrue($connection
        ->schema()
        ->tableExists($table)strtr('Table @table created by the database script.', ['@table' => $table]));
    }
  }

}
// Check that the two field storages have different tables.     $storage = \Drupal::entityTypeManager()->getStorage($this->entityTypeId);
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage->getTableMapping();
    $deleted_table_name = $table_mapping->getDedicatedDataTableName($deleted_field_storage, TRUE);
    $active_table_name = $table_mapping->getDedicatedDataTableName($field_storage);

    field_purge_batch(50);

    // Ensure the new field still has its table and the deleted one has been     // removed.     $this->assertTrue(\Drupal::database()->schema()->tableExists($active_table_name));
    $this->assertFalse(\Drupal::database()->schema()->tableExists($deleted_table_name));

    // The field has been removed from the system.     $fields = \Drupal::entityTypeManager()->getStorage('field_config')->loadByProperties(['field_storage_uuid' => $deleted_field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
    $this->assertCount(0, $fields, 'The field is gone');

    // Verify there are still 10 entries in the main table.     $count = \Drupal::database()
      ->select('entity_test__' . $field_name, 'f')
      ->fields('f', ['entity_id'])
      ->condition('bundle', $bundle)
      
$database = $this->container->get('database');
    $database->schema()->createTable('foo', [
      'fields' => [
        'number' => [
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ],
      ],
    ]);
    $this->assertTrue($database->schema()->tableExists('foo'));

    $this->assertNotNull(FileCacheFactory::getPrefix());
  }

  /** * @covers ::setUp * @depends testSetUp */
  public function testSetUpDoesNotLeak() {
    $this->assertArrayNotHasKey('destroy-me', $GLOBALS);

    

        $m = new Migration1675082889DropUnusedTables();

        $m->update($this->connection);
        $m->update($this->connection);

        $triggers = array_flip(array_column($this->connection->fetchAllAssociative('SHOW TRIGGERS'), 'Trigger'));
        static::assertArrayNotHasKey('customer_address_vat_id_insert', $triggers);
        static::assertArrayNotHasKey('customer_address_vat_id_update', $triggers);
        static::assertArrayNotHasKey('order_cash_rounding_insert', $triggers);

        static::assertFalse(EntityDefinitionQueryHelper::tableExists($this->connection, 'message_queue_stats'));
        static::assertFalse(EntityDefinitionQueryHelper::tableExists($this->connection, 'mail_template_sales_channel'));
        static::assertFalse(EntityDefinitionQueryHelper::tableExists($this->connection, 'sales_channel_rule'));
        static::assertFalse(EntityDefinitionQueryHelper::columnExists($this->connection, 'customer_address', 'vat_id'));
        static::assertFalse(EntityDefinitionQueryHelper::columnExists($this->connection, 'customer', 'newsletter'));
        static::assertFalse(EntityDefinitionQueryHelper::columnExists($this->connection, 'product', 'whitelist_ids'));
        static::assertFalse(EntityDefinitionQueryHelper::columnExists($this->connection, 'product', 'blacklist_ids'));
    }
}

  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     // destination.
$field = FieldConfig::create([
      'field_name' => $field_storage->getName(),
      'entity_type' => 'entity_test',
      'bundle' => 'entity_test',
    ]);
    $field->save();

    \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Check that no table has been created for the field.     $this->assertFalse(\Drupal::database()->schema()->tableExists('entity_test__' . $field_storage->getName()));

    // Save an entity with a value in the custom storage field and verify no     // data is retrieved on load.     $entity = EntityTest::create(['name' => $this->randomString()$field_name => 'Test value']);
    $this->assertSame('Test value', $entity->{$field_name}->value, 'The test value is set on the field.');

    $entity->save();
    $entity = EntityTest::load($entity->id());

    $this->assertNull($entity->{$field_name}->value, 'The loaded entity field value is NULL.');
  }

  

  protected function catchException(\Exception $e) {
    if ($this->database->schema()->tableExists(static::TABLE_NAME)) {
      throw $e;
    }
  }

  /** * Normalizes a lock name in order to comply with database limitations. * * @param string $name * The passed in lock name. * * @return string * An ASCII-encoded lock name that is at most 255 characters long. */
$table_specification = [
      'description' => 'Schema table description.',
      'fields' => [
        'timestamp'  => [
          'mysql_type' => 'timestamp',
          'not null' => FALSE,
          'default' => NULL,
        ],
      ],
    ];
    $this->schema->createTable('test_timestamp', $table_specification);
    $this->assertTrue($this->schema->tableExists('test_timestamp'));
  }

  /** * Tests that indexes on string fields are limited to 191 characters on MySQL. * * @see \Drupal\mysql\Driver\Database\mysql\Schema::getNormalizedIndexes() */
  public function testIndexLength(): void {
    $table_specification = [
      'fields' => [
        'id'  => [
          
      // are run and if migrations using the node migrations in a       // migration_lookup are altered.       $bases = ['node', 'node_complete'];
      $tables = $connection->schema()
        ->findTables('migrate_map_d' . $version . '_node%');
      foreach ($bases as $base) {
        $has_rows = $base . '_has_rows';
        $base_tables = preg_grep('/^migrate_map_d' . $version . '_' . $base . '_{2}.*$/', $tables);
        // Set the has_rows True when a map table has rows with a positive         // count for the matched migration.         foreach ($base_tables as $base_table) {
          if ($connection->schema()->tableExists($base_table)) {
            $count = $connection->select($base_table)->countQuery()
              ->execute()->fetchField();
            if ($count > 0) {
              $$has_rows = TRUE;
              break;
            }
          }
        }
      }

      // Set the node migration type to use.

  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');
      }
    }
    
    // expression and escape the delimiter that will be used for matching.     $table_expression = str_replace(['%', '_']['.*?', '.']preg_quote($table_expression, '/'));
    $tables = preg_grep('/^' . $table_expression . '$/i', $tables);

    return $tables;
  }

  /** * {@inheritdoc} */
  public function renameTable($table$new_name) {
    if (!$this->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException("Cannot rename '$table' to '$new_name': table '$table' doesn't exist.");
    }
    if ($this->tableExists($new_name)) {
      throw new SchemaObjectExistsException("Cannot rename '$table' to '$new_name': table '$new_name' already exists.");
    }

    // Get the schema and tablename for the old table.     $table_name = $this->connection->getPrefix() . $table;
    // Index names and constraint names are global in PostgreSQL, so we need to     // rename them when renaming the table.     $indexes = $this->connection->query('SELECT indexname FROM pg_indexes WHERE schemaname = :schema AND tablename = :table', [':schema' => $this->defaultSchema, ':table' => $table_name]);

    
$entity_type_manager = \Drupal::entityTypeManager();
    $entity_type = $entity_type_manager->getDefinition($entity_type_id);
    \Drupal::service('entity_type.listener')->onEntityTypeCreate($entity_type);

    // For test runs, the most common storage backend is a SQL database. For     // this case, ensure the tables got created.     $storage = $entity_type_manager->getStorage($entity_type_id);
    if ($storage instanceof SqlEntityStorageInterface) {
      $tables = $storage->getTableMapping()->getTableNames();
      $db_schema = $this->container->get('database')->schema();
      foreach ($tables as $table) {
        $this->assertTrue($db_schema->tableExists($table), "The entity type table '$table' for the entity type '$entity_type_id' should exist.");
      }
    }
  }

  /** * Enables modules for this test. * * This method does not install modules fully. Services and hooks for the * module are available, but the install process is not performed. * * To install test modules outside of the testing environment, add * @code * $settings['extension_discovery_scan_tests'] = TRUE; * @endcode * to your settings.php. * * @param string[] $modules * A list of modules to enable. Dependencies are not resolved; i.e., * multiple modules have to be specified individually. The modules are only * added to the active module list and loaded; i.e., their database schema * is not installed. hook_install() is not invoked. A custom module weight * is not applied. * * @throws \LogicException * If any module in $modules is already enabled. * @throws \RuntimeException * If a module is not enabled after enabling it. */

        $this->cliMessages = [];

        return $this;
    }

    /** * Truncates the history table. */
    public function clearHistory()
    {
        if ($this->db->tableExists($this->table)) {
            $this->db->table($this->table)->truncate();
        }
    }

    /** * Add a history to the table. * * @param object $migration */
    protected function addHistory($migration, int $batch)
    {
        
Home | Imprint | This part of the site doesn't use cookies.