Initial Drupal 11 with DDEV setup

This commit is contained in:
gluebox
2025-10-08 11:39:17 -04:00
commit 89ef74b305
25344 changed files with 2599172 additions and 0 deletions

View File

@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for pgsql.
*
* @group pgsql
*/
class GenericTest extends GenericModuleTestBase {}

View File

@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel;
use Drupal\Core\Entity\Query\Sql\QueryFactory as BaseQueryFactory;
use Drupal\Core\Entity\Query\Sql\pgsql\QueryFactory as DeprecatedQueryFactory;
use Drupal\KernelTests\KernelTestBase;
use Drupal\pgsql\EntityQuery\QueryFactory;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\IgnoreDeprecations;
/**
* Tests the move of the 'pgsql.entity.query.sql' service.
*/
#[Group('Database')]
#[Group('pgsql')]
class EntityQueryServiceDeprecationTest extends KernelTestBase {
/**
* Tests that the core provided service is deprecated.
*/
#[IgnoreDeprecations]
public function testPostgresServiceDeprecated(): void {
$running_driver = $this->container->get('database')->driver();
if ($running_driver === 'pgsql') {
$this->markTestSkipped('The service is not deprecated for pgsql database driver.');
}
$this->expectDeprecation('The "pgsql.entity.query.sql" service is deprecated in drupal:11.2.0 and is removed from drupal:12.0.0. Install the pgsql module to replace this service. See https://www.drupal.org/node/3488580');
$this->expectDeprecation('\Drupal\Core\Entity\Query\Sql\pgsql\QueryFactory is deprecated in drupal:11.2.0 and is removed from drupal:12.0.0. The PostgreSQL override of the entity query has been moved to the pgsql module. See https://www.drupal.org/node/3488580');
$service = $this->container->get('pgsql.entity.query.sql');
$this->assertInstanceOf(DeprecatedQueryFactory::class, $service);
}
/**
* Tests that the pgsql provided service is not deprecated.
*/
public function testPostgresServiceNotDeprecated(): void {
$running_driver = $this->container->get('database')->driver();
if ($running_driver !== 'pgsql') {
$this->markTestSkipped('The service is deprecated for database drivers other than pgsql.');
}
$service = $this->container->get('pgsql.entity.query.sql');
$this->assertInstanceOf(QueryFactory::class, $service);
}
/**
* Tests getting the backend overridden service does not trigger deprecations.
*/
public function testFactoryOverriddenService(): void {
$service = $this->container->get('entity.query.sql');
$this->assertInstanceOf(BaseQueryFactory::class, $service);
}
}

View File

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificConnectionUnitTestBase;
// cspell:ignore processlist
/**
* PostgreSQL-specific connection unit tests.
*
* @group Database
*/
class ConnectionUnitTest extends DriverSpecificConnectionUnitTestBase {
/**
* Returns a set of queries specific for PostgreSQL.
*/
protected function getQuery(): array {
return [
'connection_id' => 'SELECT pg_backend_pid()',
'processlist' => 'SELECT pid FROM pg_stat_activity',
'show_tables' => 'SELECT * FROM pg_catalog.pg_tables',
];
}
}

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificKernelTestBase;
/**
* Tests exceptions thrown by queries.
*
* @group Database
*/
class DatabaseExceptionWrapperTest extends DriverSpecificKernelTestBase {
/**
* Tests Connection::prepareStatement exception on execution.
*/
public function testPrepareStatementFailOnExecution(): void {
$this->expectException(\PDOException::class);
$stmt = $this->connection->prepareStatement('bananas', []);
$stmt->execute();
}
}

View File

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificKernelTestBase;
/**
* @coversDefaultClass \Drupal\KernelTests\KernelTestBase
*
* @group KernelTests
* @group Database
*/
class KernelTestBaseTest extends DriverSpecificKernelTestBase {
/**
* @covers ::setUp
*/
public function testSetUp(): void {
// Ensure that the database tasks have been run during set up.
$this->assertSame('on', $this->connection->query("SHOW standard_conforming_strings")->fetchField());
$this->assertSame('escape', $this->connection->query("SHOW bytea_output")->fetchField());
}
}

View File

@ -0,0 +1,384 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Connection;
use Drupal\KernelTests\Core\Database\DatabaseTestSchemaDataTrait;
use Drupal\KernelTests\Core\Database\DatabaseTestSchemaInstallTrait;
use Drupal\KernelTests\Core\Database\DriverSpecificKernelTestBase;
// cSpell:ignore nspname schemaname upserting indexdef
/**
* Tests schema API for non-public schema for the PostgreSQL driver.
*
* @group Database
* @coversDefaultClass \Drupal\pgsql\Driver\Database\pgsql\Schema
*/
class NonPublicSchemaTest extends DriverSpecificKernelTestBase {
use DatabaseTestSchemaDataTrait;
use DatabaseTestSchemaInstallTrait;
/**
* The database connection for testing.
*
* @var \Drupal\Core\Database\Connection
*/
protected Connection $testingFakeConnection;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create a connection to the non-public schema.
$info = Database::getConnectionInfo('default');
$info['default']['schema'] = 'testing_fake';
Database::getConnection()->query('CREATE SCHEMA IF NOT EXISTS testing_fake');
Database::addConnectionInfo('default', 'testing_fake', $info['default']);
$this->testingFakeConnection = Database::getConnection('testing_fake', 'default');
$table_specification = [
'description' => 'Schema table description may contain "quotes" and could be long—very long indeed.',
'fields' => [
'id' => [
'type' => 'serial',
'not null' => TRUE,
],
'test_field' => [
'type' => 'int',
'not null' => TRUE,
],
],
'primary key' => ['id'],
];
$this->testingFakeConnection->schema()->createTable('faking_table', $table_specification);
$this->testingFakeConnection->insert('faking_table')
->fields(
[
'id' => '1',
'test_field' => '123',
]
)->execute();
$this->testingFakeConnection->insert('faking_table')
->fields(
[
'id' => '2',
'test_field' => '456',
]
)->execute();
$this->testingFakeConnection->insert('faking_table')
->fields(
[
'id' => '3',
'test_field' => '789',
]
)->execute();
}
/**
* {@inheritdoc}
*/
protected function tearDown(): void {
// We overwrite this function because the regular teardown will not drop the
// tables from a specified schema.
$tables = $this->testingFakeConnection->schema()->findTables('%');
foreach ($tables as $table) {
if ($this->testingFakeConnection->schema()->dropTable($table)) {
unset($tables[$table]);
}
}
$this->assertEmpty($this->testingFakeConnection->schema()->findTables('%'));
Database::removeConnection('testing_fake');
parent::tearDown();
}
/**
* @covers ::extensionExists
* @covers ::tableExists
*/
public function testExtensionExists(): void {
// Check if PG_trgm extension is present.
$this->assertTrue($this->testingFakeConnection->schema()->extensionExists('pg_trgm'));
// Asserting that the Schema testing_fake exist in the database.
$this->assertCount(1, \Drupal::database()->query("SELECT * FROM pg_catalog.pg_namespace WHERE nspname = 'testing_fake'")->fetchAll());
$this->assertTrue($this->testingFakeConnection->schema()->tableExists('faking_table'));
// Hardcoded assertion that we created the table in the non-public schema.
$this->assertCount(1, $this->testingFakeConnection->query("SELECT * FROM pg_tables WHERE schemaname = 'testing_fake' AND tablename = :prefixedTable", [':prefixedTable' => $this->testingFakeConnection->getPrefix() . "faking_table"])->fetchAll());
}
/**
* @covers ::addField
* @covers ::fieldExists
* @covers ::dropField
* @covers ::changeField
*/
public function testField(): void {
$this->testingFakeConnection->schema()
->addField(
'faking_table',
'added_field',
[
'type' => 'int',
'not null' => FALSE,
]);
$this->assertTrue($this->testingFakeConnection->schema()->fieldExists('faking_table', 'added_field'));
$this->testingFakeConnection->schema()
->changeField(
'faking_table',
'added_field',
'changed_field',
[
'type' => 'int',
'not null' => FALSE,
]);
$this->assertFalse($this->testingFakeConnection->schema()->fieldExists('faking_table', 'added_field'));
$this->assertTrue($this->testingFakeConnection->schema()->fieldExists('faking_table', 'changed_field'));
$this->testingFakeConnection->schema()->dropField('faking_table', 'changed_field');
$this->assertFalse($this->testingFakeConnection->schema()->fieldExists('faking_table', 'changed_field'));
}
/**
* @covers \Drupal\Core\Database\Connection::insert
* @covers \Drupal\Core\Database\Connection::select
*/
public function testInsert(): void {
$num_records_before = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->testingFakeConnection->insert('faking_table')
->fields([
'id' => '123',
'test_field' => '55',
])->execute();
// Testing that the insert is correct.
$results = $this->testingFakeConnection->select('faking_table')->fields('faking_table')->condition('id', '123')->execute()->fetchAll();
$this->assertIsArray($results);
$num_records_after = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->assertEquals($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
$this->assertSame('123', $results[0]->id);
$this->assertSame('55', $results[0]->test_field);
}
/**
* @covers \Drupal\Core\Database\Connection::update
*/
public function testUpdate(): void {
$updated_record = $this->testingFakeConnection->update('faking_table')
->fields(['test_field' => 321])
->condition('id', 1)
->execute();
$this->assertSame(1, $updated_record, 'Updated 1 record.');
$updated_results = $this->testingFakeConnection->select('faking_table')->fields('faking_table')->condition('id', '1')->execute()->fetchAll();
$this->assertSame('321', $updated_results[0]->test_field);
}
/**
* @covers \Drupal\Core\Database\Connection::upsert
*/
public function testUpsert(): void {
$num_records_before = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$upsert = $this->testingFakeConnection->upsert('faking_table')
->key('id')
->fields(['id', 'test_field']);
// Upserting a new row.
$upsert->values([
'id' => '456',
'test_field' => '444',
]);
// Upserting an existing row.
$upsert->values([
'id' => '1',
'test_field' => '898',
]);
$result = $upsert->execute();
$this->assertSame(2, $result, 'The result of the upsert operation should report that at exactly two rows were affected.');
$num_records_after = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->assertEquals($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
// Check if new row has been added with upsert.
$result = $this->testingFakeConnection->query('SELECT * FROM {faking_table} WHERE [id] = :id', [':id' => '456'])->fetch();
$this->assertEquals('456', $result->id, 'ID set correctly.');
$this->assertEquals('444', $result->test_field, 'test_field set correctly.');
// Check if new row has been edited with upsert.
$result = $this->testingFakeConnection->query('SELECT * FROM {faking_table} WHERE [id] = :id', [':id' => '1'])->fetch();
$this->assertEquals('1', $result->id, 'ID set correctly.');
$this->assertEquals('898', $result->test_field, 'test_field set correctly.');
}
/**
* @covers \Drupal\Core\Database\Connection::merge
*/
public function testMerge(): void {
$num_records_before = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->testingFakeConnection->merge('faking_table')
->key('id', '789')
->fields([
'test_field' => 343,
])
->execute();
$num_records_after = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->assertEquals($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
$merge_results = $this->testingFakeConnection->select('faking_table')->fields('faking_table')->condition('id', '789')->execute()->fetchAll();
$this->assertSame('789', $merge_results[0]->id);
$this->assertSame('343', $merge_results[0]->test_field);
}
/**
* @covers \Drupal\Core\Database\Connection::delete
* @covers \Drupal\Core\Database\Connection::truncate
*/
public function testDelete(): void {
$num_records_before = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$num_deleted = $this->testingFakeConnection->delete('faking_table')
->condition('id', 3)
->execute();
$this->assertSame(1, $num_deleted, 'Deleted 1 record.');
$num_records_after = $this->testingFakeConnection->query('SELECT COUNT(*) FROM {faking_table}')->fetchField();
$this->assertEquals($num_records_before, $num_records_after + $num_deleted, 'Deletion adds up.');
$num_records_before = $this->testingFakeConnection->query("SELECT COUNT(*) FROM {faking_table}")->fetchField();
$this->assertNotEmpty($num_records_before);
$this->testingFakeConnection->truncate('faking_table')->execute();
$num_records_after = $this->testingFakeConnection->query("SELECT COUNT(*) FROM {faking_table}")->fetchField();
$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'));
}
/**
* @covers ::addUniqueKey
* @covers ::indexExists
* @covers ::dropUniqueKey
*/
public function testUniqueKey(): void {
$this->testingFakeConnection->schema()->addUniqueKey('faking_table', 'test_field', ['test_field']);
// This should work, but currently indexExist() only searches for keys that
// end with idx.
// @todo remove comments when:
// https://www.drupal.org/project/drupal/issues/3325358 is committed.
// phpcs:ignore
// $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__key'])->fetchAll();
// Check the unique key columns.
$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()->dropUniqueKey('faking_table', 'test_field');
// This function will not work due to a the fact that indexExist() does not
// search for keys without idx tag.
// @todo remove comments when:
// https://www.drupal.org/project/drupal/issues/3325358 is committed.
// phpcs:ignore
// $this->assertFalse($this->testingFakeConnection->schema()->indexExists('faking_table', 'test_field'));
}
/**
* @covers ::addPrimaryKey
* @covers ::dropPrimaryKey
*/
public function testPrimaryKey(): void {
$this->testingFakeConnection->schema()->dropPrimaryKey('faking_table');
$results = $this->testingFakeConnection->query("SELECT * FROM pg_indexes WHERE schemaname = 'testing_fake'")->fetchAll();
$this->assertCount(0, $results);
$this->testingFakeConnection->schema()->addPrimaryKey('faking_table', ['id']);
$results = $this->testingFakeConnection->query("SELECT * FROM pg_indexes WHERE schemaname = 'testing_fake'")->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 (id)', $results[0]->indexdef);
$find_primary_keys_columns = new \ReflectionMethod(get_class($this->testingFakeConnection->schema()), 'findPrimaryKeyColumns');
$results = $find_primary_keys_columns->invoke($this->testingFakeConnection->schema(), 'faking_table');
$this->assertCount(1, $results);
$this->assertSame('id', $results[0]);
}
/**
* @covers ::renameTable
* @covers ::tableExists
* @covers ::findTables
* @covers ::dropTable
*/
public function testTable(): void {
$this->testingFakeConnection->schema()->renameTable('faking_table', 'new_faking_table');
$tables = $this->testingFakeConnection->schema()->findTables('%');
$result = $this->testingFakeConnection->query("SELECT * FROM information_schema.tables WHERE table_schema = 'testing_fake'")->fetchAll();
$this->assertFalse($this->testingFakeConnection->schema()->tableExists('faking_table'));
$this->assertTrue($this->testingFakeConnection->schema()->tableExists('new_faking_table'));
$this->assertEquals($this->testingFakeConnection->getPrefix() . 'new_faking_table', $result[0]->table_name);
$this->assertEquals('testing_fake', $result[0]->table_schema);
sort($tables);
$this->assertEquals(['new_faking_table'], $tables);
$this->testingFakeConnection->schema()->dropTable('new_faking_table');
$this->assertFalse($this->testingFakeConnection->schema()->tableExists('new_faking_table'));
$this->assertCount(0, $this->testingFakeConnection->query("SELECT * FROM information_schema.tables WHERE table_schema = 'testing_fake'")->fetchAll());
}
}

View File

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql\Plugin\views;
use Drupal\Tests\views\Kernel\Plugin\CastedIntFieldJoinTestBase;
/**
* Tests PostgreSQL specific cast handling.
*
* @group Database
*/
class PgsqlCastedIntFieldJoinTest extends CastedIntFieldJoinTestBase {
/**
* The db type that should be used for casting fields as integers.
*/
protected string $castingType = 'INTEGER';
}

View File

@ -0,0 +1,416 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificSchemaTestBase;
// cSpell:ignore attname attnum attrelid objid refobjid refobjsubid regclass
// cspell:ignore relkind relname
/**
* Tests schema API for the PostgreSQL driver.
*
* @group Database
*/
class SchemaTest extends DriverSpecificSchemaTestBase {
/**
* {@inheritdoc}
*/
public function checkSchemaComment(string $description, string $table, ?string $column = NULL): void {
$this->assertSame($description, $this->schema->getComment($table, $column), 'The comment matches the schema description.');
}
/**
* {@inheritdoc}
*/
protected function checkSequenceRenaming(string $tableName): void {
// For PostgreSQL, we also need to check that the sequence has been renamed.
// The initial name of the sequence has been generated automatically by
// PostgreSQL when the table was created, however, on subsequent table
// renames the name is generated by Drupal and can not be easily
// re-constructed. Hence we can only check that we still have a sequence on
// the new table name.
$sequenceExists = (bool) $this->connection->query("SELECT pg_get_serial_sequence('{" . $tableName . "}', 'id')")->fetchField();
$this->assertTrue($sequenceExists, 'Sequence was renamed.');
// Rename the table again and repeat the check.
$anotherTableName = strtolower($this->getRandomGenerator()->name(63 - strlen($this->getDatabasePrefix())));
$this->schema->renameTable($tableName, $anotherTableName);
$sequenceExists = (bool) $this->connection->query("SELECT pg_get_serial_sequence('{" . $anotherTableName . "}', 'id')")->fetchField();
$this->assertTrue($sequenceExists, 'Sequence was renamed.');
}
/**
* {@inheritdoc}
*/
public function testTableWithSpecificDataType(): void {
$table_specification = [
'description' => 'Schema table description.',
'fields' => [
'timestamp' => [
'pgsql_type' => 'timestamp',
'not null' => FALSE,
'default' => NULL,
],
],
];
$this->schema->createTable('test_timestamp', $table_specification);
$this->assertTrue($this->schema->tableExists('test_timestamp'));
}
/**
* @covers \Drupal\pgsql\Driver\Database\pgsql\Schema::introspectIndexSchema
*/
public function testIntrospectIndexSchema(): void {
$table_specification = [
'fields' => [
'id' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
],
'test_field_1' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
],
'test_field_2' => [
'type' => 'int',
'default' => 0,
],
'test_field_3' => [
'type' => 'int',
'default' => 0,
],
'test_field_4' => [
'type' => 'int',
'default' => 0,
],
'test_field_5' => [
'type' => 'int',
'default' => 0,
],
],
'primary key' => ['id', 'test_field_1'],
'unique keys' => [
'test_field_2' => ['test_field_2'],
'test_field_3_test_field_4' => ['test_field_3', 'test_field_4'],
],
'indexes' => [
'test_field_4' => ['test_field_4'],
'test_field_4_test_field_5' => ['test_field_4', 'test_field_5'],
],
];
$table_name = strtolower($this->getRandomGenerator()->name());
$this->schema->createTable($table_name, $table_specification);
unset($table_specification['fields']);
$introspect_index_schema = new \ReflectionMethod(get_class($this->schema), 'introspectIndexSchema');
$index_schema = $introspect_index_schema->invoke($this->schema, $table_name);
// The PostgreSQL driver is using a custom naming scheme for its indexes, so
// we need to adjust the initial table specification.
$ensure_identifier_length = new \ReflectionMethod(get_class($this->schema), 'ensureIdentifiersLength');
foreach ($table_specification['unique keys'] as $original_index_name => $columns) {
unset($table_specification['unique keys'][$original_index_name]);
$new_index_name = $ensure_identifier_length->invoke($this->schema, $table_name, $original_index_name, 'key');
$table_specification['unique keys'][$new_index_name] = $columns;
}
foreach ($table_specification['indexes'] as $original_index_name => $columns) {
unset($table_specification['indexes'][$original_index_name]);
$new_index_name = $ensure_identifier_length->invoke($this->schema, $table_name, $original_index_name, 'idx');
$table_specification['indexes'][$new_index_name] = $columns;
}
$this->assertEquals($table_specification, $index_schema);
}
/**
* {@inheritdoc}
*/
public function testReservedKeywordsForNaming(): void {
$table_specification = [
'description' => 'A test table with an ANSI reserved keywords for naming.',
'fields' => [
'primary' => [
'description' => 'Simple unique ID.',
'type' => 'int',
'not null' => TRUE,
],
'update' => [
'description' => 'A column with reserved name.',
'type' => 'varchar',
'length' => 255,
],
],
'primary key' => ['primary'],
'unique keys' => [
'having' => ['update'],
],
'indexes' => [
'in' => ['primary', 'update'],
],
];
// Creating a table.
$table_name = 'select';
$this->schema->createTable($table_name, $table_specification);
$this->assertTrue($this->schema->tableExists($table_name));
// Finding all tables.
$tables = $this->schema->findTables('%');
sort($tables);
$this->assertEquals(['config', 'select'], $tables);
// Renaming a table.
$table_name_new = 'from';
$this->schema->renameTable($table_name, $table_name_new);
$this->assertFalse($this->schema->tableExists($table_name));
$this->assertTrue($this->schema->tableExists($table_name_new));
// Adding a field.
$field_name = 'delete';
$this->schema->addField($table_name_new, $field_name, ['type' => 'int', 'not null' => TRUE]);
$this->assertTrue($this->schema->fieldExists($table_name_new, $field_name));
// Dropping a primary key.
$this->schema->dropPrimaryKey($table_name_new);
// Adding a primary key.
$this->schema->addPrimaryKey($table_name_new, [$field_name]);
// Check the primary key columns.
$find_primary_key_columns = new \ReflectionMethod(get_class($this->schema), 'findPrimaryKeyColumns');
$this->assertEquals([$field_name], $find_primary_key_columns->invoke($this->schema, $table_name_new));
// Dropping a primary key.
$this->schema->dropPrimaryKey($table_name_new);
// Changing a field.
$field_name_new = 'where';
$this->schema->changeField($table_name_new, $field_name, $field_name_new, ['type' => 'int', 'not null' => FALSE]);
$this->assertFalse($this->schema->fieldExists($table_name_new, $field_name));
$this->assertTrue($this->schema->fieldExists($table_name_new, $field_name_new));
// Adding an unique key
$unique_key_name = $unique_key_introspect_name = 'unique';
$this->schema->addUniqueKey($table_name_new, $unique_key_name, [$field_name_new]);
// Check the unique key columns.
$introspect_index_schema = new \ReflectionMethod(get_class($this->schema), 'introspectIndexSchema');
$ensure_identifiers_length = new \ReflectionMethod(get_class($this->schema), 'ensureIdentifiersLength');
$unique_key_introspect_name = $ensure_identifiers_length->invoke($this->schema, $table_name_new, $unique_key_name, 'key');
$this->assertEquals([$field_name_new], $introspect_index_schema->invoke($this->schema, $table_name_new)['unique keys'][$unique_key_introspect_name]);
// 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);
$this->assertFalse($this->schema->tableExists($table_name_new));
}
/**
* @covers \Drupal\pgsql\Driver\Database\pgsql\Schema::extensionExists
*/
public function testPgsqlExtensionExists(): void {
// Test the method for a non existing extension.
$this->assertFalse($this->schema->extensionExists('non_existing_extension'));
// Test the method for an existing extension.
$this->assertTrue($this->schema->extensionExists('pg_trgm'));
}
/**
* Tests if the new sequences get the right ownership.
*/
public function testPgsqlSequences(): void {
$table_specification = [
'description' => 'A test table with an ANSI reserved keywords for naming.',
'fields' => [
'uid' => [
'description' => 'Simple unique ID.',
'type' => 'serial',
'not null' => TRUE,
],
'update' => [
'description' => 'A column with reserved name.',
'type' => 'varchar',
'length' => 255,
],
],
'primary key' => ['uid'],
'unique keys' => [
'having' => ['update'],
],
'indexes' => [
'in' => ['uid', 'update'],
],
];
// Creating a table.
$table_name = 'sequence_test';
$this->schema->createTable($table_name, $table_specification);
$this->assertTrue($this->schema->tableExists($table_name));
// Retrieves a sequence name that is owned by the table and column.
$sequence_name = $this->connection
->query("SELECT pg_get_serial_sequence(:table, :column)", [
':table' => $this->connection->getPrefix() . 'sequence_test',
':column' => 'uid',
])
->fetchField();
$schema = $this->connection->getConnectionOptions()['schema'] ?? 'public';
$this->assertEquals($schema . '.' . $this->connection->getPrefix() . 'sequence_test_uid_seq', $sequence_name);
// Checks if the sequence exists.
$this->assertTrue((bool) \Drupal::database()
->query("SELECT c.relname FROM pg_class as c WHERE c.relkind = 'S' AND c.relname = :name", [
':name' => $this->connection->getPrefix() . 'sequence_test_uid_seq',
])
->fetchField());
// Retrieves the sequence owner object.
$sequence_owner = \Drupal::database()->query("SELECT d.refobjid::regclass as table_name, a.attname as field_name
FROM pg_depend d
JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid
WHERE d.objid = :seq_name::regclass
AND d.refobjsubid > 0
AND d.classid = 'pg_class'::regclass", [':seq_name' => $sequence_name])->fetchObject();
$this->assertEquals($this->connection->getPrefix() . 'sequence_test', $sequence_owner->table_name);
$this->assertEquals('uid', $sequence_owner->field_name, 'New sequence is owned by its table.');
}
/**
* Tests the method tableExists().
*/
public function testTableExists(): void {
$table_name = 'test_table';
$table_specification = [
'fields' => [
'id' => [
'type' => 'int',
'default' => NULL,
],
],
];
$this->schema->createTable($table_name, $table_specification);
$prefixed_table_name = $this->connection->getPrefix($table_name) . $table_name;
// Three different calls to the method Schema::tableExists() with an
// unprefixed table name.
$this->assertTrue($this->schema->tableExists($table_name));
$this->assertTrue($this->schema->tableExists($table_name, TRUE));
$this->assertFalse($this->schema->tableExists($table_name, FALSE));
// Three different calls to the method Schema::tableExists() with a
// prefixed table name.
$this->assertFalse($this->schema->tableExists($prefixed_table_name));
$this->assertFalse($this->schema->tableExists($prefixed_table_name, TRUE));
$this->assertTrue($this->schema->tableExists($prefixed_table_name, FALSE));
}
/**
* Tests renaming a table where the new index name is equal to the table name.
*/
public function testRenameTableWithNewIndexNameEqualsTableName(): void {
// Special table names for colliding with the PostgreSQL new index name.
$table_name_old = 'some_new_table_name__id__idx';
$table_name_new = 'some_new_table_name';
$table_specification = [
'fields' => [
'id' => [
'type' => 'int',
'default' => NULL,
],
],
'indexes' => [
'id' => ['id'],
],
];
$this->schema->createTable($table_name_old, $table_specification);
// Renaming the table can fail for PostgreSQL, when a new index name is
// equal to the old table name.
$this->schema->renameTable($table_name_old, $table_name_new);
$this->assertTrue($this->schema->tableExists($table_name_new));
}
/**
* Tests renaming a table which name contains drupal_ with multiple indexes.
*/
public function testRenameTableWithNameContainingDrupalUnderscoreAndMultipleIndexes(): void {
$table_name_old = 'field_drupal_foo';
$table_name_new = 'field_drupal_bar';
$table_specification = [
'fields' => [
'one' => [
'type' => 'int',
'default' => NULL,
],
'two' => [
'type' => 'int',
'default' => NULL,
],
],
'indexes' => [
'one' => ['one'],
'two' => ['two'],
],
];
$this->schema->createTable($table_name_old, $table_specification);
$this->schema->renameTable($table_name_old, $table_name_new);
$this->assertTrue($this->schema->tableExists($table_name_new));
}
/**
* Tests column name escaping in field constraints.
*/
public function testUnsignedField(): void {
$table_name = 'unsigned_table';
$table_spec = [
'fields' => [
'order' => [
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
],
],
'primary key' => ['order'],
];
$this->schema->createTable($table_name, $table_spec);
$this->assertTrue($this->schema->tableExists($table_name));
}
}

View File

@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\SchemaUniquePrefixedKeysIndexTestBase;
/**
* Tests adding UNIQUE keys to tables.
*
* @group Database
*/
class SchemaUniquePrefixedKeysIndexTest extends SchemaUniquePrefixedKeysIndexTestBase {
/**
* {@inheritdoc}
*/
protected string $columnValue = '1234567890 foo';
}

View File

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificSyntaxTestBase;
/**
* Tests PostgreSQL syntax interpretation.
*
* @group Database
*/
class SyntaxTest extends DriverSpecificSyntaxTestBase {
}

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\TemporaryQueryTestBase;
// cspell:ignore relname relpersistence
/**
* Tests the temporary query functionality.
*
* @group Database
*/
class TemporaryQueryTest extends TemporaryQueryTestBase {
/**
* Confirms that temporary tables work.
*/
public function testTemporaryQuery(): void {
parent::testTemporaryQuery();
$connection = $this->getConnection();
$table_name_test = $connection->queryTemporary('SELECT [name] FROM {test}', []);
// Assert that the table is indeed a temporary one.
$temporary_table_info = $connection->query("SELECT * FROM pg_class WHERE relname LIKE '%$table_name_test%'")->fetch();
$this->assertEquals("t", $temporary_table_info->relpersistence);
// Assert that both have the same field names.
$normal_table_fields = $connection->query("SELECT * FROM {test}")->fetch();
$temp_table_name = $connection->queryTemporary('SELECT * FROM {test}');
$temp_table_fields = $connection->query("SELECT * FROM {" . $temp_table_name . "}")->fetch();
$normal_table_fields = array_keys(get_object_vars($normal_table_fields));
$temp_table_fields = array_keys(get_object_vars($temp_table_fields));
$this->assertEmpty(array_diff($normal_table_fields, $temp_table_fields));
}
}

View File

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificTransactionTestBase;
/**
* Tests transaction for the PostgreSQL driver.
*
* @group Database
*/
class TransactionTest extends DriverSpecificTransactionTestBase {
}

View File

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Unit;
use Drupal\pgsql\Driver\Database\pgsql\Schema;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\pgsql\Driver\Database\pgsql\Schema
* @group Database
*/
class SchemaTest extends UnitTestCase {
/**
* Tests whether the actual constraint name is correctly computed.
*
* @param string $table_name
* The table name the constrained column belongs to.
* @param string $name
* The constraint name.
* @param string $expected
* The expected computed constraint name.
*
* @covers ::constraintExists
* @dataProvider providerComputedConstraintName
*/
public function testComputedConstraintName($table_name, $name, $expected): void {
$max_identifier_length = 63;
$connection = $this->prophesize('\Drupal\pgsql\Driver\Database\pgsql\Connection');
$connection->getConnectionOptions()->willReturn([]);
$connection->getPrefix()->willReturn('');
$statement = $this->prophesize('\Drupal\Core\Database\StatementInterface');
$statement->fetchField()->willReturn($max_identifier_length);
$connection->query('SHOW max_identifier_length')->willReturn($statement->reveal());
$connection->query(Argument::containingString($expected))
->willReturn($this->prophesize('\Drupal\Core\Database\StatementInterface')->reveal())
->shouldBeCalled();
$schema = new Schema($connection->reveal());
$schema->constraintExists($table_name, $name);
}
/**
* Data provider for ::testComputedConstraintName().
*/
public static function providerComputedConstraintName() {
return [
['user_field_data', 'pkey', 'user_field_data____pkey'],
['user_field_data', 'name__key', 'user_field_data__name__key'],
[
'user_field_data',
'a_very_very_very_very_super_long_field_name__key',
'drupal_WW_a8TlbZ3UQi20UTtRlJFaIeSa6FEtQS5h4NRA3UeU_key',
],
];
}
}