createTable example



    /** * Adds the Table to the Schema if it doesn't exist. */
    public function configureSchema(Schema $schema, \Closure $isSameDatabase = null): void
    {
        if ($schema->hasTable($this->table) || ($isSameDatabase && !$isSameDatabase($this->getConnection()->exec(...)))) {
            return;
        }

        $table = $schema->createTable($this->table);
        switch ($this->driver) {
            case 'mysql':
                $table->addColumn($this->idCol, Types::BINARY)->setLength(128)->setNotnull(true);
                $table->addColumn($this->dataCol, Types::BLOB)->setNotnull(true);
                $table->addColumn($this->lifetimeCol, Types::INTEGER)->setUnsigned(true)->setNotnull(true);
                $table->addColumn($this->timeCol, Types::INTEGER)->setUnsigned(true)->setNotnull(true);
                $table->addOption('collate', 'utf8mb4_bin');
                $table->addOption('engine', 'InnoDB');
                break;
            case 'sqlite':
                $table->addColumn($this->idCol, Types::TEXT)->setNotnull(true);
                
protected static string $dbFile;

    public static function setUpBeforeClass(): void
    {
        if (!\extension_loaded('pdo_sqlite')) {
            throw new SkippedTestSuiteError('Extension pdo_sqlite required.');
        }

        self::$dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_cache');

        $pool = new PdoAdapter('sqlite:'.self::$dbFile);
        $pool->createTable();
    }

    public static function tearDownAfterClass(): void
    {
        @unlink(self::$dbFile);
    }

    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new PdoAdapter('sqlite:'.self::$dbFile, 'ns', $defaultLifetime);
    }

    
'migrate',
    'migrate_track_changes_test',
    'text',
  ];

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Create source test table.     $this->sourceDatabase->schema()->createTable('track_changes_term', [
      'fields' => [
        'tid' => [
          'description' => 'Serial',
          'type' => 'serial',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ],
        'name' => [
          'description' => 'Name',
          'type' => 'varchar',
          'length' => 128,
          
$this->markTestSkipped('The pdo_sqlite extension is not available.');
    }

    // Initialize the DIC with a fake module handler for alterable queries.     $container = new ContainerBuilder();
    $container->set('module_handler', $this->createMock('\Drupal\Core\Extension\ModuleHandlerInterface'));
    \Drupal::setContainer($container);

    // Create the tables and load them up with data, skipping empty ones.     foreach (array_filter($database_contents) as $table => $rows) {
      $pilot_row = reset($rows);
      $connection->schema()->createTable($table$this->createSchemaFromRow($pilot_row));

      $insert = $connection->insert($table)->fields(array_keys($pilot_row));
      array_walk($rows[$insert, 'values']);
      $insert->execute();
    }

    return $connection;
  }

  /** * Generates a table schema from a row. * * @param array $row * The reference row on which to base the schema. * * @return array * The Schema API-ready table schema. */
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',
    ),
    'sid' => array(
      'type' => 'varchar',
      'not null' => TRUE,
      'length' => '128',
      'default' => '',
    ),

    public function save(Key $key)
    {
        $key->reduceLifetime($this->initialTtl);

        $sql = "INSERT INTO $this->table ($this->idCol, $this->tokenCol, $this->expirationCol) VALUES (:id, :token, {$this->getCurrentTimestampStatement()} + $this->initialTtl)";
        $conn = $this->getConnection();
        try {
            $stmt = $conn->prepare($sql);
        } catch (\PDOException) {
            if (!$conn->inTransaction() || \in_array($this->driver, ['pgsql', 'sqlite', 'sqlsrv'], true)) {
                $this->createTable();
            }
            $stmt = $conn->prepare($sql);
        }

        $stmt->bindValue(':id', $this->getHashedKey($key));
        $stmt->bindValue(':token', $this->getUniqueToken($key));

        try {
            $stmt->execute();
        } catch (\PDOException) {
            // the lock is already acquired. It could be us. Let's try to put off.
$schema = $this->database->schema();
    // If the table already exists, add any columns which are in the map array,     // but don't yet exist in the table. Yay, flexibility!     if ($schema->tableExists($table)) {
      foreach (array_keys($map) as $field) {
        if (!$schema->fieldExists($table$field)) {
          $schema->addField($table$field['type' => 'text']);
        }
      }
    }
    else {
      $schema->createTable($table$this->createSchemaFromRow($map));
    }

    $this->database->insert($table)->fields($map)->execute();
  }

  /** * Creates a test SQL ID map plugin. * * @return \Drupal\Tests\migrate\Unit\TestSqlIdMap * A SQL ID map plugin test instance. */
  
$keys = ['sourceid2', 'sourceid3', 'destid2', 'destid3'];
      foreach ($keys as $key) {
        unset($fields[$key]);
        unset($values[$key]);
        if (strstr($key, 'sourceid')) {
          $index_key = substr($key, -1) - 1;
          unset($indexes['source'][$index_key]);
        }
      }
    }
    $connection = \Drupal::database();
    $connection->schema()->createTable($name[
      'fields' => $fields,
      'primary key' => [
        'source_ids_hash',
      ],
      'indexes' => $indexes,
      'mysql_character_set' => 'utf8mb4',
    ]);

    $field_names = array_keys($fields);
    $connection->insert($name)
      ->fields($field_names)
      
$schema = new Schema();

        $connection = new Connection([]$driverConnection);
        $connection->configureSchema($schema$driverConnection2fn () => false);
        $this->assertFalse($schema->hasTable('messenger_messages'));
    }

    public function testConfigureSchemaTableExists()
    {
        $driverConnection = $this->getDBALConnectionMock();
        $schema = new Schema();
        $schema->createTable('messenger_messages');

        $connection = new Connection([]$driverConnection);
        $connection->configureSchema($schema$driverConnectionfn () => true);
        $table = $schema->getTable('messenger_messages');
        $this->assertEmpty($table->getColumns(), 'The table was not overwritten');
    }

    /** * @dataProvider provideFindAllSqlGeneratedByPlatform */
    public function testFindAllSqlGenerated(AbstractPlatform $platform, string $expectedSql)
    {
$platformName = null;
                $sql = "UPDATE $this->table SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ? WHERE $this->idCol = ?";
                break;
        }

        $now = time();
        $lifetime = $lifetime ?: null;
        try {
            $stmt = $this->conn->prepare($sql);
        } catch (TableNotFoundException) {
            if (!$this->conn->isTransactionActive() || \in_array($platformName['pgsql', 'sqlite', 'sqlsrv'], true)) {
                $this->createTable();
            }
            $stmt = $this->conn->prepare($sql);
        }

        if ('sqlsrv' === $platformName || 'oci' === $platformName) {
            $bind = static function D$id$data) use ($stmt) {
                $stmt->bindValue(1, $id);
                $stmt->bindValue(2, $id);
                $stmt->bindValue(3, $data, ParameterType::LARGE_OBJECT);
                $stmt->bindValue(6, $data, ParameterType::LARGE_OBJECT);
            };
            

        $this->dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_sessions');

        return 'sqlite:'.$this->dbFile;
    }

    protected function getMemorySqlitePdo()
    {
        $pdo = new \PDO('sqlite::memory:');
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $storage = new PdoSessionHandler($pdo);
        $storage->createTable();

        return $pdo;
    }

    public function testWrongPdoErrMode()
    {
        $this->expectException(\InvalidArgumentException::class);
        $pdo = $this->getMemorySqlitePdo();
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);

        new PdoSessionHandler($pdo);
    }
'null'       => false,
            ],
            'batch' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => false,
            ],
        ]);

        $forge->addPrimaryKey('id');
        $forge->createTable($this->table, true);

        $this->tableChecked = true;
    }

    /** * Handles the actual running of a migration. * * @param string $direction "up" or "down" * @param object $migration The migration to run */
    protected function migrate($direction$migration): bool
    {
$this->assertNotEmpty($request);
    $this->assertEquals('/', $request->getPathInfo());

    $this->assertSame($request, \Drupal::request());

    $this->assertEquals($this$GLOBALS['conf']['container_service_providers']['test']);

    $GLOBALS['destroy-me'] = TRUE;
    $this->assertArrayHasKey('destroy-me', $GLOBALS);

    $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());
  }


    /** * Adds the Table to the Schema if it doesn't exist. */
    public function configureSchema(Schema $schema, \Closure $isSameDatabase = null): void
    {
        if ($schema->hasTable($this->table) || ($isSameDatabase && !$isSameDatabase($this->getConnection()->exec(...)))) {
            return;
        }

        $table = $schema->createTable($this->table);
        switch ($this->driver) {
            case 'mysql':
                $table->addColumn($this->idCol, Types::BINARY)->setLength(128)->setNotnull(true);
                $table->addColumn($this->dataCol, Types::BLOB)->setNotnull(true);
                $table->addColumn($this->lifetimeCol, Types::INTEGER)->setUnsigned(true)->setNotnull(true);
                $table->addColumn($this->timeCol, Types::INTEGER)->setUnsigned(true)->setNotnull(true);
                $table->addOption('collate', 'utf8mb4_bin');
                $table->addOption('engine', 'InnoDB');
                break;
            case 'sqlite':
                $table->addColumn($this->idCol, Types::TEXT)->setNotnull(true);
                
/** * {@inheritdoc} */
  public function buildTestingResultsEnvironment(bool $keep_results): void {
    $schema = $this->connection->schema();
    foreach (static::testingResultsSchema() as $name => $table_spec) {
      $table_exists = $schema->tableExists($name);
      if (!$keep_results && $table_exists) {
        $this->connection->truncate($name)->execute();
      }
      if (!$table_exists) {
        $schema->createTable($name$table_spec);
      }
    }
  }

  /** * {@inheritdoc} */
  public function validateTestingResultsEnvironment(): bool {
    $schema = $this->connection->schema();
    return $schema->tableExists('simpletest') && $schema->tableExists('simpletest_test_id');
  }

  
Home | Imprint | This part of the site doesn't use cookies.