first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
<?php
// @codingStandardsIgnoreFile
use Drupal\Core\Database\Database;
$connection = Database::getConnection();
$db_type = $connection->databaseType();
// Creates a table, then adds a sequence without ownership to simulate tables
// that were altered from integer to serial columns.
$connection
->schema()
->createTable('pgsql_sequence_test', [
'fields' => [
'sequence_field' => [
'type' => 'int',
'not null' => TRUE,
'unsigned' => TRUE,
],
],
'primary key' => ['sequence_field'],
]);
$seq = $connection
->makeSequenceName('pgsql_sequence_test', 'sequence_field');
$connection->query('CREATE SEQUENCE ' . $seq);
// Enables the pgsql_test module so that the pgsql_sequence_test schema will
// be available.
$extensions = $connection
->query("SELECT data FROM {config} where name = 'core.extension'")
->fetchField();
$extensions = unserialize($extensions);
$extensions['module']['pgsql_test'] = 1;
$connection
->update('config')
->fields(['data' => serialize($extensions)])
->condition('name', 'core.extension')
->execute();
$connection
->delete('cache_config')
->condition('cid', 'core.extension')
->execute();

View File

@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Functional\Database;
use Drupal\FunctionalTests\Update\UpdatePathTestBase;
use Drupal\Core\Database\Database;
use Drupal\pgsql\Update10101;
// cSpell:ignore objid refobjid regclass attname attrelid attnum refobjsubid
/**
* Tests that any unowned sequences created previously have a table owner.
*
* The update path only applies to Drupal sites using the pgsql driver.
*
* @group Database
*/
class PostgreSqlSequenceUpdateTest extends UpdatePathTestBase {
/**
* The database connection to use.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* {@inheritdoc}
*/
protected function runDbTasks() {
parent::runDbTasks();
$this->connection = Database::getConnection();
if ($this->connection->driver() !== 'pgsql') {
$this->markTestSkipped('This test only works with the pgsql driver');
}
}
/**
* {@inheritdoc}
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../../system/tests/fixtures/update/drupal-9.4.0.bare.standard.php.gz',
__DIR__ . '/../../../fixtures/update/drupal-9.pgsql-orphan-sequence.php',
];
}
/**
* Asserts that a newly created sequence has the correct ownership.
*/
public function testPostgreSqlSequenceUpdate(): void {
$this->assertFalse($this->getSequenceOwner('pgsql_sequence_test', 'sequence_field'));
// Run the updates.
$this->runUpdates();
$seq_owner = $this->getSequenceOwner('pgsql_sequence_test', 'sequence_field');
$this->assertEquals($this->connection->getPrefix() . 'pgsql_sequence_test', $seq_owner->table_name);
$this->assertEquals('sequence_field', $seq_owner->field_name, 'Sequence is owned by the table and column.');
}
/**
* Retrieves the sequence owner object.
*
* @return object|bool
* Returns the sequence owner object or bool if it does not exist.
*/
protected function getSequenceOwner(string $table, string $field): object|bool {
$update_sequence = \Drupal::classResolver(Update10101::class);
$seq_name = $update_sequence->getSequenceName($table, $field);
return \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' => $seq_name])->fetchObject();
}
}

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,27 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificConnectionUnitTestBase;
/**
* 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,363 @@
<?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.
// $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.
// $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,108 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\Core\Database\Driver\pgsql\Connection;
use Drupal\Core\Database\Driver\pgsql\Delete;
use Drupal\Core\Database\Driver\pgsql\Install\Tasks;
use Drupal\Core\Database\Driver\pgsql\Insert;
use Drupal\Core\Database\Driver\pgsql\Schema;
use Drupal\Core\Database\Driver\pgsql\Select;
use Drupal\Core\Database\Driver\pgsql\Truncate;
use Drupal\Core\Database\Driver\pgsql\Update;
use Drupal\Core\Database\Driver\pgsql\Upsert;
use Drupal\KernelTests\Core\Database\DriverSpecificDatabaseTestBase;
use Drupal\Tests\Core\Database\Stub\StubPDO;
/**
* Tests the deprecations of the PostgreSQL database driver classes in Core.
*
* @group legacy
* @group Database
*/
class PgsqlDriverLegacyTest extends DriverSpecificDatabaseTestBase {
/**
* @covers Drupal\Core\Database\Driver\pgsql\Install\Tasks
*/
public function testDeprecationInstallTasks(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Install\Tasks is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$tasks = new Tasks();
$this->assertInstanceOf(Tasks::class, $tasks);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Connection
*/
public function testDeprecationConnection(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Connection is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$connection = new Connection($this->createMock(StubPDO::class), []);
$this->assertInstanceOf(Connection::class, $connection);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Delete
*/
public function testDeprecationDelete(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Delete is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$delete = new Delete($this->connection, 'test');
$this->assertInstanceOf(Delete::class, $delete);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Insert
*/
public function testDeprecationInsert(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Insert is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$insert = new Insert($this->connection, 'test');
$this->assertInstanceOf(Insert::class, $insert);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Schema
*/
public function testDeprecationSchema(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Schema is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$schema = new Schema($this->connection);
$this->assertInstanceOf(Schema::class, $schema);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Select
*/
public function testDeprecationSelect(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Select is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$select = new Select($this->connection, 'test');
$this->assertInstanceOf(Select::class, $select);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Truncate
*/
public function testDeprecationTruncate(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Truncate is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$truncate = new Truncate($this->connection, 'test');
$this->assertInstanceOf(Truncate::class, $truncate);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Update
*/
public function testDeprecationUpdate(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Update is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$update = new Update($this->connection, 'test');
$this->assertInstanceOf(Update::class, $update);
}
/**
* @covers Drupal\Core\Database\Driver\pgsql\Upsert
*/
public function testDeprecationUpsert(): void {
$this->expectDeprecation('\Drupal\Core\Database\Driver\pgsql\Upsert is deprecated in drupal:9.4.0 and is removed from drupal:11.0.0. The PostgreSQL database driver has been moved to the pgsql module. See https://www.drupal.org/node/3129492');
$upsert = new Upsert($this->connection, 'test');
$this->assertInstanceOf(Upsert::class, $upsert);
}
}

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,386 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\DriverSpecificSchemaTestBase;
// cSpell:ignore relkind objid refobjid regclass attname attrelid attnum
// cSpell:ignore refobjsubid
/**
* 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\Core\Database\Driver\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 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);
}
}

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,41 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\pgsql\Kernel\pgsql;
use Drupal\KernelTests\Core\Database\TemporaryQueryTestBase;
/**
* 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,60 @@
<?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'],
];
}
}