Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,16 @@ public function export(): array
if (empty($tableExport)) {
continue;
}
$autoIncrementColumnName = null;
foreach ($table->getColumns() as $column) {
if ($column->getAutoincrement()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On PostgreSQL getAutoincrement() is only true for identity columns: 'autoincrement' => $tableColumn['attidentity'] === 'd' in DBAL 4.4 and in TYPO3\CMS\Core\Database\Schema\SchemaManager\PostgreSQLSchemaManager. A SERIAL column is not detected, so importTable() skips the reset and the sequence keeps its old position.

Reproduced on PostgreSQL 17:

$connection->executeStatement('CREATE TABLE tx_probe_serial (uid SERIAL PRIMARY KEY, title VARCHAR(20))');
$connection->insert('tx_probe_serial', ['uid' => 1, 'title' => 'a']);
$connection->insert('tx_probe_serial', ['uid' => 2, 'title' => 'b']);
$snapshot = $subject->export();
$connection->executeStatement('TRUNCATE tx_probe_serial RESTART IDENTITY');
$subject->import($snapshot);
$connection->insert('tx_probe_serial', ['title' => 'generated']);
// PR:   SQLSTATE[23505] duplicate key value violates unique constraint "tx_probe_serial_pkey"
// main: uid 3

The TYPO3 schema itself uses identity columns since DBAL 4, so the default tables are fine. But tests and extensions creating tables with raw SQL still use SERIAL a lot (the tests in #758 do), and on main this works.

Suggestion that keeps the gain: on PostgreSQL resolve the owned sequence column once in export() (which runs once per test case) with one catalog query for all tables, for example pg_depend with deptype IN ('a', 'i') joined to pg_attribute. That covers SERIAL and identity columns, and import() stays free of catalog lookups. Please add a SERIAL data set to the test as well.

$autoIncrementColumnName = $column->getName();
break;
}
}
$export[] = [
'tableName' => $tableName,
'autoIncrementColumnName' => $autoIncrementColumnName,
'columns' => $this->prepareColumns(
array_keys($tableExport[0]),
$table
Expand All @@ -74,7 +82,8 @@ public function import(array $import): void
$this->importTable(
$tableImport['tableName'] ?? '',
$tableImport['columns'] ?? [],
$tableImport['items'] ?? []
$tableImport['items'] ?? [],
$tableImport['autoIncrementColumnName'] ?? null
);
}
}
Expand All @@ -89,7 +98,7 @@ private function exportTable(string $tableName): array
/**
* @param array $columns [columnName => columnType]
*/
private function importTable(string $tableName, array $columns, array $items): void
private function importTable(string $tableName, array $columns, array $items, ?string $autoIncrementColumnName): void
{
if (empty($tableName) || empty($columns) || empty($items)) {
throw new \RuntimeException(
Expand All @@ -99,10 +108,10 @@ private function importTable(string $tableName, array $columns, array $items): v
}
$columnNames = array_keys($columns);
$this->connection->bulkInsert($tableName, $items, $columnNames, $columns);
// reset table sequences after inserting snapshot data. Dataset contains primary key column data which
// leads to out-of-sync sequence values for some dbms platforms, thus resetting sequence values
// is needed.
Testbase::resetTableSequences($this->connection, $tableName);
// Snapshot rows contain explicit IDs; advance the sequence before inserting new records.
if ($autoIncrementColumnName !== null) {
Testbase::resetTableSequences($this->connection, $tableName, $autoIncrementColumnName);
}
}

private function prepareColumns(array $columnNames, Table $table): array
Expand Down
92 changes: 92 additions & 0 deletions Tests/Functional/DatabaseAccessorSequenceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

declare(strict_types=1);

/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/

namespace TYPO3\TestingFramework\Tests\Functional;

use Doctrine\DBAL\Schema\Table;
use Doctrine\DBAL\Types\Types;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\TestingFramework\Core\Functional\Framework\DataHandling\Snapshot\DatabaseAccessor;
use TYPO3\TestingFramework\Core\Functional\FunctionalTestCase;

final class DatabaseAccessorSequenceTest extends FunctionalTestCase

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the summary: nothing in this repository executes Tests/Functional/. With a manual harness it passes for me on PostgreSQL 17, MariaDB 10.11 and SQLite, and on main it fails on PostgreSQL for the mixed-case data set, so the test is good. It just isn't run by CI yet.

{
public static function autoIncrementColumnsDataProvider(): iterable
{
yield 'uid' => ['uid', 'uid'];
yield 'custom column' => ['record_id', 'record_id'];
yield 'quoted mixed-case column' => ['entryId', '"entryId"'];
}

#[Test]
#[DataProvider('autoIncrementColumnsDataProvider')]
public function snapshotRestoresNextGeneratedId(string $columnName, string $schemaColumnName): void
{
$connection = $this->get(ConnectionPool::class)->getConnectionByName(ConnectionPool::DEFAULT_CONNECTION_NAME);
$schemaManager = $connection->createSchemaManager();
$table = new Table('tx_testingframework_sequence');
$table->addColumn($schemaColumnName, Types::INTEGER, ['autoincrement' => true]);
$table->addColumn('title', Types::STRING, ['length' => 255]);
$table->setPrimaryKey([$schemaColumnName]);
$schemaManager->createTable($table);

try {
$connection->insert($table->getName(), [$columnName => 7, 'title' => 'first']);
$connection->insert($table->getName(), [$columnName => 11, 'title' => 'last']);
$subject = new DatabaseAccessor($connection);
$snapshot = json_decode(json_encode($subject->export(), JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: DatabaseSnapshot keeps the export as a PHP array in memory and only uses json_encode() for the size check, so this round trip is not what happens in production and suggests that snapshots get serialized. Passing $subject->export() directly (same in line 82) mirrors DatabaseSnapshot::create() and restore().


for ($iteration = 0; $iteration < 2; ++$iteration) {
$connection->truncate($table->getName());
$subject->import($snapshot);
$connection->insert($table->getName(), ['title' => 'generated']);

self::assertSame(12, (int)$connection->select([$columnName], $table->getName(), ['title' => 'generated'])->fetchOne());
self::assertSame(3, $connection->count('*', $table->getName(), []));
}
} finally {
$schemaManager->dropTable($table->getName());
}
}

#[Test]
public function snapshotRestoresTableWithoutAutoIncrementColumn(): void
{
$connection = $this->get(ConnectionPool::class)->getConnectionByName(ConnectionPool::DEFAULT_CONNECTION_NAME);
$schemaManager = $connection->createSchemaManager();
$table = new Table('tx_testingframework_no_sequence');
$table->addColumn('identifier', Types::STRING, ['length' => 255]);
$table->addColumn('title', Types::STRING, ['length' => 255]);
$table->setPrimaryKey(['identifier']);
$schemaManager->createTable($table);

try {
$connection->insert($table->getName(), ['identifier' => 'example', 'title' => 'preserved']);
$subject = new DatabaseAccessor($connection);
$snapshot = json_decode(json_encode($subject->export(), JSON_THROW_ON_ERROR), true, 512, JSON_THROW_ON_ERROR);
$connection->truncate($table->getName());

$subject->import($snapshot);

self::assertSame('preserved', $connection->select(['title'], $table->getName(), ['identifier' => 'example'])->fetchOne());
} finally {
$schemaManager->dropTable($table->getName());
}
}
}