diff --git a/CHANGELOG.md b/CHANGELOG.md index e453a5f..876f993 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,8 @@ Initial release of **Solo Repository** (`solophp/repository`) with the - Explicit, typed `Mapping` and `Repository`; constructing repositories and queries never opens a database connection. An application can extend - `Repository` into a typed repository per table; its public methods are final. + `Repository` into a typed repository per table; its public methods are final, + and minor releases may add new ones. - Reusable `ReadQuery` with projection reads, `sum`/`min`/`max`/`avg` aggregates over the same criteria as `count`, bounded integer-ID iteration, and `queryBuilder()`, a DBAL `QueryBuilder` over the rows its criteria select. @@ -37,6 +38,32 @@ Initial release of **Solo Repository** (`solophp/repository`) with the `LinkSet` operations. - SQLite tests, MySQL 8.4/MariaDB 12.3/PostgreSQL 17 integration tests, and a PHP/DBAL CI matrix. +### Changes since 1.0.0-RC5 + +- The compatibility rules for subclasses of `Repository` are documented. + Throughout 1.x it stays a non-final `readonly` class whose public methods, + except the constructor, are final and whose state is private. A minor release + may add public methods, and a subclass that declares a method of the same + name then fails to load. Constructor parameters keep their names and order; + a parameter added in a minor release is optional and comes last. +- **Behavior change:** `LinkSet::attach()` and `sync()` skip a pair that + another writer stored after the operation read the set, instead of failing + on the pivot's unique key. Their INSERT carries `ON CONFLICT (pair) DO NOTHING` + on PostgreSQL and SQLite and `ON DUPLICATE KEY UPDATE` on MySQL and MariaDB; + foreign-key violations still propagate. Concurrent attaches of one pair now + both succeed on MySQL and on PostgreSQL in READ COMMITTED. MariaDB with + snapshot isolation (error 1020) and PostgreSQL in REPEATABLE READ or + SERIALIZABLE (a serialization failure) still refuse a transaction whose + snapshot is older than the other writer's commit, and an exact final set + still needs an owner lock. On PostgreSQL and SQLite these writes now fail on a + pivot without the UNIQUE pair that the guide already required. +- A locking read on MySQL tells `FOR UPDATE OF` support by the server version, + 8.0.1 or later, instead of by DBAL's `MySQL80Platform`. DBAL deprecates its + MySQL 8 platform classes and drops them with MySQL 5.7 support, after which + `MySQLPlatform` itself stands for MySQL 8; the lock keeps covering only the + read's table there. MySQL 5.7 and MariaDB keep the plain `FOR UPDATE`. The + package no longer refers to a deprecated DBAL platform class. + ### Changes since 1.0.0-RC4 - `ReadQuery::forUpdate()` returns the same read as a locking one: `find()`, diff --git a/docs/guide/api.md b/docs/guide/api.md index 5cbf72a..4c0c714 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -4,7 +4,7 @@ This reference describes Solo Repository 1.0: PHP 8.3+, Doctrine DBAL `^4.3`, an `Repository`, `Mapping` and `ReadQuery` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository` is accepted where `Repository` is expected. Relation definitions are generic over their owner and target models, so static analysis checks every `assign` callback against the target mapping. The runtime checks that hydration and relation assignment return objects; it does not enforce their concrete class. `Mapping`, `ReadQuery`, the configuration objects and the write helpers are `final readonly`; `Repository` is `readonly` and may be extended into a [typed repository](#typed-repositories). Readonly configuration does not make the shared DBAL connection, returned models or objects captured by callbacks immutable. -The public API consists of the types and methods documented below. The `Internal` namespace and members marked `@internal` are implementation details without a semantic-versioning compatibility promise: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (obtain them from a `Repository`), the properties of `Filter`, and `Relations\Relation::resolve()`. The abstract `Relation` base is not an extension point: use the four supplied final definitions. The legacy `BaseRepository`, `RepositoryInterface` and singular `Relation` namespace belong to the separate `solophp/base-repository` package; see the [migration guide](migration.md). +The public API consists of the types and methods documented below. The `Internal` namespace and members marked `@internal` are implementation details without a semantic-versioning compatibility promise: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (obtain them from a `Repository`), the properties of `Filter`, and `Relations\Relation::resolve()`. The abstract `Relation` base is not an extension point: use the four supplied final definitions. `Repository` may be extended under the compatibility rules of [typed repositories](#typed-repositories). The legacy `BaseRepository`, `RepositoryInterface` and singular `Relation` namespace belong to the separate `solophp/base-repository` package; see the [migration guide](migration.md). ## A minimal repository @@ -81,6 +81,12 @@ $product = (new ProductRepository($db))->read()->find($id); // Product|null A `readonly` class can only be extended by a `readonly` class. A static `mapping()` also gives relations a target factory: `target: ProductRepository::mapping(...)`. +Subclasses can rely on these rules throughout 1.x: + +- `Repository` stays a non-final `readonly` class. Its public methods, except the constructor, stay final, and its state stays private, so a subclass depends only on the public API. +- A minor release may add public methods to `Repository`. PHP refuses to load a subclass that declares a method of the same name, so name a subclass's methods after its table's domain, such as `cheaperThan()`, and read the changelog before upgrading. +- The constructor keeps the names, order and meaning of its parameters. A parameter added in a minor release is optional and comes last. + ## Mapping and types ```php @@ -180,7 +186,7 @@ In `findBy()`, `findOneBy()` and `rows()`, an `orderBy` key may also be a dotted - `count()` and `exists()` do not hydrate models or resolve/load includes. Relation predicates in their criteria still apply. `exists()` selects a constant with a one-row limit. - `sum()`, `min()`, `max()` and `avg()` aggregate one readable field, including a translated field under the query locale, over the rows `count()` would count. `sum()`, `min()` and `max()` convert the result through the field's DBAL type, so a decimal sum is an exact string and `max('created_at')` a `DateTimeImmutable`. `sum()` returns zero of that type when nothing matches; `min()`, `max()` and `avg()` return NULL. `avg()` returns a float. `sum()` and `avg()` require a smallint, integer, bigint, decimal, float or smallfloat field and reject other fields before SQL. - `queryBuilder()` returns a new DBAL `QueryBuilder` over the rows `count()` would count, for SQL the other methods cannot express; see [the DBAL escape hatch](#transactions-and-the-dbal-escape-hatch). It rejects nonempty includes. -- `forUpdate()` returns the same read as a locking one: `find()`, `findOneBy()`, `findBy()`, `rows()`, `exists()` and every batch of `iterateById()` run `SELECT ... FOR UPDATE` and lock the rows they read until the surrounding transaction ends; outside a transaction they throw `LogicException`. Unlike a plain read in a REPEATABLE READ transaction, which answers from the transaction's snapshot, a locking read never returns an older version of a row: MySQL reads the latest committed row, while PostgreSQL and MariaDB (with `innodb_snapshot_isolation`, its default since 11.6) reject a row changed since the snapshot with a serialization failure, after which the transaction must start over. The lock covers rows of the read's own table: PostgreSQL and MySQL 8 lock with `FOR UPDATE OF`, while MariaDB, which lacks it, also locks the translation and order rows the statement joins. Relation loads read without locks. Aggregates and `queryBuilder()` of a locking read throw `LogicException`. SQLite has no row locks and runs the plain SELECT. Rows lock in the order the database reads them; where transactions lock overlapping sets of rows, read them in key order or take `lockForUpdate()` first. MySQL and MariaDB lock every row they read to answer the statement, so with an order no index serves, such as a relation path, a limited locking read locks all matching rows, not just the page. +- `forUpdate()` returns the same read as a locking one: `find()`, `findOneBy()`, `findBy()`, `rows()`, `exists()` and every batch of `iterateById()` run `SELECT ... FOR UPDATE` and lock the rows they read until the surrounding transaction ends; outside a transaction they throw `LogicException`. Unlike a plain read in a REPEATABLE READ transaction, which answers from the transaction's snapshot, a locking read never returns an older version of a row: MySQL reads the latest committed row, while PostgreSQL and MariaDB (with `innodb_snapshot_isolation`, its default since 11.6) reject a row changed since the snapshot with a serialization failure, after which the transaction must start over. The lock covers rows of the read's own table: PostgreSQL and MySQL from 8.0.1, which is told by the server version, lock with `FOR UPDATE OF`, while MariaDB and MySQL 5.7, which lack it, also lock the translation and order rows the statement joins. Relation loads read without locks. Aggregates and `queryBuilder()` of a locking read throw `LogicException`. SQLite has no row locks and runs the plain SELECT. Rows lock in the order the database reads them; where transactions lock overlapping sets of rows, read them in key order or take `lockForUpdate()` first. MySQL and MariaDB lock every row they read to answer the statement, so with an order no index serves, such as a relation path, a limited locking read locks all matching rows, not just the page. - Without `orderBy`, ordering is unspecified. Add the primary key as a final tie-breaker for stable pages. Negative limit/offset values are rejected. `limit: 0` validates query settings and returns an empty list without executing the read. ```php @@ -434,9 +440,9 @@ The relation must be `BelongsToMany`. Owner and target IDs are normalized using - `detach()` removes the specified links; absent links are unchanged. - `sync()` makes the physical set exactly match the supplied IDs; `sync($id, [])` removes all links for that owner. -Empty attach/detach lists execute no SQL after ID validation. Existing-link attach is a no-op in state, but can perform reads. These operations use physical pivot rows, including soft-deleted owners/targets; read visibility and Load criteria do not apply. String keys are resolved through SQL so comparisons respect the database's collation. Foreign-key and unique violations propagate, and orphan cleanup for a schema without the required FKs is not promised. +Empty attach/detach lists execute no SQL after ID validation. Existing-link attach is a no-op in state, but can perform reads. These operations use physical pivot rows, including soft-deleted owners/targets; read visibility and Load criteria do not apply. String keys are resolved through SQL so comparisons respect the database's collation. Foreign-key violations propagate, and orphan cleanup for a schema without the required FKs is not promised. A pair that another writer stored after the operation read the set is skipped rather than raised as a unique violation: the INSERT carries `ON CONFLICT (foreignPivotKey, relatedPivotKey) DO NOTHING` on PostgreSQL and SQLite, which therefore need the required UNIQUE pair, and `ON DUPLICATE KEY UPDATE` on MySQL and MariaDB, which treat a conflict over any unique index of the pivot as that pair. -All nonempty attach/detach operations and every sync use a transaction/savepoint and split large statements. This provides rollback, not serialization of concurrent edits to the same set. Coordinate concurrent writers with an application lock or transaction strategy. No automatic retries or blanket `INSERT IGNORE` are used. +All nonempty attach/detach operations and every sync use a transaction/savepoint and split large statements. This provides rollback, not serialization of concurrent edits to the same set. Concurrent attaches of one pair both succeed on MySQL and on PostgreSQL in READ COMMITTED. A transaction whose snapshot is older than the other writer's commit is refused instead by MariaDB with `innodb_snapshot_isolation` (its default since 11.6, error 1020) and by PostgreSQL in REPEATABLE READ or SERIALIZABLE (a serialization failure), and two syncs of one set can still interleave. Writers that must agree on a final set need an application lock, such as `lockForUpdate()` of the owner row as the first statement of their transaction. No automatic retries or blanket `INSERT IGNORE` are used: only the conflict over the pair itself is skipped. ## Transactions and the DBAL escape hatch diff --git a/docs/guide/details.md b/docs/guide/details.md index 275a807..5dc3720 100644 --- a/docs/guide/details.md +++ b/docs/guide/details.md @@ -25,7 +25,7 @@ Solo Repository превращает строки БД в обычные PHP-о ## Проверка на MySQL, MariaDB и PostgreSQL -Общий набор из 37 тестов проверяет generated ID и CRUD, преобразование decimal/bool/date/JSON, soft delete и keyset, native upsert строк и PATCH upsert переводов, единый fallback, четыре типа связей, вложенные EXISTS и сортировку по путям `BelongsTo`. Блокирующее чтение проверяется второй сессией: какие строки держит блокировка и чем такое чтение отличается от снимка транзакции REPEATABLE READ на каждой СУБД. Отдельные сценарии проверяют пакетные границы, запрос с максимальным для сервера числом параметров (65 535), сортировку коллекции из 905 элементов, освобождение предыдущей страницы, строковые ключи и native PostgreSQL UUID, rollback позднего пакета и продолжение внешней транзакции после savepoint. Схемы содержат настоящие FK и UNIQUE; тесты выполняют SQL на серверах без моков платформ. +Общий набор из 39 тестов проверяет generated ID и CRUD, преобразование decimal/bool/date/JSON, soft delete и keyset, native upsert строк и PATCH upsert переводов, единый fallback, четыре типа связей, вложенные EXISTS и сортировку по путям `BelongsTo`. Блокирующее чтение проверяется второй сессией: какие строки держит блокировка и чем такое чтение отличается от снимка транзакции REPEATABLE READ на каждой СУБД. Вторая сессия также сохраняет пару между чтением и вставкой `attach()`: на уровне изоляции сервера и на REPEATABLE READ проверяется, где конфликт пропускается, а где транзакция отклоняется. Отдельные сценарии проверяют пакетные границы, запрос с максимальным для сервера числом параметров (65 535), сортировку коллекции из 905 элементов, освобождение предыдущей страницы, строковые ключи и native PostgreSQL UUID, rollback позднего пакета и продолжение внешней транзакции после savepoint. Схемы содержат настоящие FK и UNIQUE; тесты выполняют SQL на серверах без моков платформ. `.github/workflows/tests.yml` сохраняет три задания основного SQLite-набора и запускает `Database` на каждой из трёх СУБД для тех же комбинаций: @@ -184,7 +184,7 @@ queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilder; Ключ `orderBy` в `findBy`, `findOneBy` и `rows` может быть путём через связи `BelongsTo` к полю цели: `['category.name' => 'ASC']`, `['category.parent.name' => 'DESC']`. Каждая цель пути присоединяется LEFT JOIN по первичному ключу один раз на statement — по тем строкам, которые видит загрузка той же связи в этом чтении: по активным, если чтение не загружает связь с другой видимостью. Поэтому список, который показывает мягко удалённые категории через `with([new Load('category', visibility: Visibility::All)])`, сортируется и по их именам; от загрузки берётся только видимость, не её критерии. Строка с пустой, висячей или невидимой ссылкой сортируется как строка с NULL в этом поле, а место NULL задаёт БД (в начале по возрастанию на MySQL, MariaDB и SQLite, в конце на PostgreSQL). Переводимое поле цели читается в locale и fallback запроса — цель наследует их так же, как загрузка связей. Пути через `HasOne`, `HasMany` и `BelongsToMany` могли бы дать несколько строк и отклоняются до SQL. Порядок to-many связи по умолчанию и порядок `Load` принимают те же пути, от маппинга цели. -`forUpdate()` даёт то же чтение блокирующим: `find`, `findOneBy`, `findBy`, `rows`, `exists` и каждый пакет `iterateById` выполняют `SELECT ... FOR UPDATE` и держат прочитанные строки до конца транзакции; вне транзакции они бросают `LogicException`. Обычное чтение в транзакции REPEATABLE READ отвечает из её снимка, а блокирующее никогда не возвращает устаревшую версию строки: MySQL читает последнюю зафиксированную, PostgreSQL и MariaDB (с `innodb_snapshot_isolation`, по умолчанию начиная с 11.6) отклоняют строку, изменённую после снимка, ошибкой сериализации — транзакцию нужно начать заново. Блокируются строки таблицы самого чтения: PostgreSQL и MySQL 8 получают `FOR UPDATE OF`, а MariaDB, где его нет, блокирует и присоединённые строки переводов и сортировки. Загрузки связей читаются без блокировок. Агрегаты и `queryBuilder()` блокирующего чтения бросают `LogicException`. В SQLite строковых блокировок нет, выполняется обычный SELECT. Строки блокируются в том порядке, в каком их читает БД; транзакции, которые блокируют пересекающиеся наборы строк, читают их в порядке ключа или сначала берут `lockForUpdate()`. MySQL и MariaDB блокируют каждую строку, прочитанную ради ответа, поэтому при сортировке, которую не обслуживает индекс (например, по пути связи), чтение с limit блокирует все подходящие строки, а не только страницу. +`forUpdate()` даёт то же чтение блокирующим: `find`, `findOneBy`, `findBy`, `rows`, `exists` и каждый пакет `iterateById` выполняют `SELECT ... FOR UPDATE` и держат прочитанные строки до конца транзакции; вне транзакции они бросают `LogicException`. Обычное чтение в транзакции REPEATABLE READ отвечает из её снимка, а блокирующее никогда не возвращает устаревшую версию строки: MySQL читает последнюю зафиксированную, PostgreSQL и MariaDB (с `innodb_snapshot_isolation`, по умолчанию начиная с 11.6) отклоняют строку, изменённую после снимка, ошибкой сериализации — транзакцию нужно начать заново. Блокируются строки таблицы самого чтения: PostgreSQL и MySQL начиная с 8.0.1 (это определяется по версии сервера) получают `FOR UPDATE OF`, а MariaDB и MySQL 5.7, где его нет, блокируют и присоединённые строки переводов и сортировки. Загрузки связей читаются без блокировок. Агрегаты и `queryBuilder()` блокирующего чтения бросают `LogicException`. В SQLite строковых блокировок нет, выполняется обычный SELECT. Строки блокируются в том порядке, в каком их читает БД; транзакции, которые блокируют пересекающиеся наборы строк, читают их в порядке ключа или сначала берут `lockForUpdate()`. MySQL и MariaDB блокируют каждую строку, прочитанную ради ответа, поэтому при сортировке, которую не обслуживает индекс (например, по пути связи), чтение с limit блокирует все подходящие строки, а не только страницу. ## Фильтры без второго QueryBuilder @@ -348,7 +348,7 @@ Patch не меняет пропущенные поля; NULL записывае `LinkSet` предоставляет `attach(id, ids): void`, `detach(id, ids): void`, `sync(id, ids): void`. Входные IDs нормализуются по типу target PK и дедуплицируются; порядок IDs не сохраняется. Attach уже существующей связи и detach отсутствующей — no-op; `sync` устанавливает точное множество, `sync(id, [])` очищает его. Attach/detach пустого списка ничего не делают. -Синхронизация читает все физические pivot-строки владельца, включая ссылки на скрытые soft-delete цели. Фильтры отображения не превращаются в фильтры записи. Для строковых ID LinkSet дополнительно читает канонические ключи через SQL, чтобы attach/detach/sync учитывали collation БД и разные написания одного ID. Ошибки FK/unique не скрываются. Транзакция гарантирует rollback частичного изменения, но не сериализует конкурентные sync/attach автоматически. Если несколько процессов меняют один набор, приложение согласует блокировку владельца или иную стратегию конкурентной записи в общей транзакции. +Синхронизация читает все физические pivot-строки владельца, включая ссылки на скрытые soft-delete цели. Фильтры отображения не превращаются в фильтры записи. Для строковых ID LinkSet дополнительно читает канонические ключи через SQL, чтобы attach/detach/sync учитывали collation БД и разные написания одного ID. Ошибки FK не скрываются. Пара, которую другой писатель сохранил после того, как операция прочитала набор, пропускается, а не становится ошибкой unique: INSERT идёт с `ON CONFLICT (foreignPivotKey, relatedPivotKey) DO NOTHING` в PostgreSQL и SQLite, поэтому им нужен обязательный UNIQUE пары, и с `ON DUPLICATE KEY UPDATE` в MySQL и MariaDB, где такой парой считается конфликт по любому уникальному индексу pivot. Транзакция гарантирует rollback частичного изменения, но не сериализует конкурентные sync/attach. Параллельные attach одной пары проходят в MySQL и в PostgreSQL на READ COMMITTED. Транзакцию, чей снимок старше чужого коммита, MariaDB со snapshot isolation (по умолчанию с 11.6) отклоняет ошибкой 1020, а PostgreSQL на REPEATABLE READ и SERIALIZABLE — ошибкой сериализации; два sync одного набора по-прежнему могут перемежаться. Если несколько процессов должны прийти к одному набору, приложение берёт блокировку владельца (`lockForUpdate()` первым действием транзакции) или иную стратегию конкурентной записи в общей транзакции. ## Большие выборки и сложный SQL diff --git a/docs/guide/migration.md b/docs/guide/migration.md index 375b9b0..9737500 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -459,9 +459,9 @@ $db->transactional(function () use ($products, $id): void { }); ``` -All repositories and write services must share that connection. CRUD uses the current transaction without adding one. `insertMany` split into several statements and nonempty LinkSet operations use DBAL transactions/nested savepoints; translation save is a single native upsert that participates in the caller's transaction. Database errors, including FK and unique violations, propagate. Catch exceptions outside the transaction boundary when the entire workflow must roll back. +All repositories and write services must share that connection. CRUD uses the current transaction without adding one. `insertMany` split into several statements and nonempty LinkSet operations use DBAL transactions/nested savepoints; translation save is a single native upsert that participates in the caller's transaction. Database errors, including FK and unique violations, propagate; the one exception is a LinkSet pair that another writer stored after the operation read the set, which the INSERT skips. Catch exceptions outside the transaction boundary when the entire workflow must roll back. -Atomic rollback does not serialize concurrent sync/attach calls or provide automatic retries. If concurrent writers must agree on a final tag set, apply the application's locking/versioning policy in the transaction. Physical string-key operations may read canonical IDs to respect database collation; do not assume that LinkSet is a write-only operation. Missing/orphan targets are not an orphan-cleanup feature; enforce the required FKs. +Atomic rollback does not serialize concurrent sync/attach calls or provide automatic retries. Concurrent attaches of one pair no longer fail on the pivot key on MySQL and on PostgreSQL in READ COMMITTED, but MariaDB with snapshot isolation and PostgreSQL above READ COMMITTED refuse a transaction whose snapshot is older than the other writer's commit. If concurrent writers must agree on a final tag set, apply the application's locking/versioning policy in the transaction. Physical string-key operations may read canonical IDs to respect database collation; do not assume that LinkSet is a write-only operation. Missing/orphan targets are not an orphan-cleanup feature; enforce the required FKs. ## 10. Replace repository wrappers with application code and DBAL diff --git a/src/Internal/Database.php b/src/Internal/Database.php index df80359..8cf614c 100644 --- a/src/Internal/Database.php +++ b/src/Internal/Database.php @@ -8,7 +8,7 @@ use Doctrine\DBAL\Connection; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Platforms\AbstractPlatform; -use Doctrine\DBAL\Platforms\MySQL80Platform; +use Doctrine\DBAL\Platforms\MySQLPlatform; use Doctrine\DBAL\Query\QueryBuilder; use Doctrine\DBAL\Result; use Doctrine\DBAL\Types\Type; @@ -139,7 +139,7 @@ public function executeLocked(QueryBuilder $query, ?string $alias = null): Resul if ($dialect === Dialect::SQLite) { return $query->executeQuery(); } - if ($alias !== null && ($dialect === Dialect::PostgreSQL || $this->platform() instanceof MySQL80Platform)) { + if ($alias !== null && ($dialect === Dialect::PostgreSQL || $this->mysqlLocksOneTable())) { return $this->connection->executeQuery( $query->getSQL() . ' FOR UPDATE OF ' . $this->quote($alias), $query->getParameters(), @@ -150,6 +150,18 @@ public function executeLocked(QueryBuilder $query, ?string $alias = null): Resul return (clone $query)->forUpdate()->executeQuery(); } + /** + * Whether the server is a MySQL that takes FOR UPDATE OF, as MySQL does from 8.0.1. Its + * version tells, not DBAL's MySQL 8 platform classes: DBAL deprecates them and drops them + * with MySQL 5.7, after which MySQLPlatform itself stands for MySQL 8. MariaDB, whose + * platform is not a MySQLPlatform, has no OF. + */ + private function mysqlLocksOneTable(): bool + { + return $this->platform() instanceof MySQLPlatform + && version_compare($this->connection->getServerVersion(), '8.0.1', '>='); + } + public function assertParameters(int $count): void { $limit = $this->parameterLimit(); diff --git a/src/LinkSet.php b/src/LinkSet.php index 82ec5e2..640738a 100644 --- a/src/LinkSet.php +++ b/src/LinkSet.php @@ -11,7 +11,8 @@ use Solo\Repository\Relations\BelongsToMany; /** - * Physical pivot writes. Transactions provide rollback, not concurrent set serialization. + * Physical pivot writes. A pair another writer stored first is skipped, not raised; transactions + * provide rollback, not serialization of concurrent edits to one set. */ final readonly class LinkSet { @@ -200,10 +201,20 @@ private function ownerCondition(int|string $id, ?string $alias = null): array return [$condition, [$id], [$type]]; } - /** @param array $ids */ + /** + * Inserts the pairs the operation found missing. Another writer may store one of them after + * that read: the pair then conflicts over the pivot's required UNIQUE pair and is skipped, + * since it is the link the caller asked for. Every other error, a foreign-key violation + * among them, still propagates. Platforms without upserts insert the pairs as they are. + * + * @param array $ids + */ private function insertLinks(int|string $id, array $ids): void { $columns = [$this->relation->foreignPivotKey, $this->relation->relatedPivotKey]; + [$alias, $skipStored] = $this->db->dialect() === null + ? [null, ''] + : $this->db->upsertClause('Link inserts', $columns, []); $ownerType = $this->ownerType(); $targetType = $this->targetType(); foreach (array_chunk($ids, $this->db->batchSize(2)) as $chunk) { @@ -214,7 +225,7 @@ private function insertLinks(int|string $id, array $ids): void array_push($types, $ownerType, $targetType); } $this->db->connection->executeStatement( - $this->db->insertSql($this->relation->pivotTable, $columns, count($chunk)), + $this->db->insertSql($this->relation->pivotTable, $columns, count($chunk), $alias) . $skipStored, $values, $types, ); diff --git a/tests/Core/DatabaseTest.php b/tests/Core/DatabaseTest.php index ea147bc..09959c3 100644 --- a/tests/Core/DatabaseTest.php +++ b/tests/Core/DatabaseTest.php @@ -137,7 +137,9 @@ public function testReadsAndWritesUseNoDeprecatedDbalApi(): void . 'UNIQUE(product_id, locale))', ); $connection->executeStatement('CREATE TABLE tags (id INTEGER PRIMARY KEY)'); - $connection->executeStatement('CREATE TABLE product_tag (product_id INTEGER, tag_id INTEGER)'); + $connection->executeStatement( + 'CREATE TABLE product_tag (product_id INTEGER, tag_id INTEGER, UNIQUE(product_id, tag_id))', + ); $connection->executeStatement('INSERT INTO tags VALUES (1), (2)'); $repository = new Repository($connection, $this->productMapping()); diff --git a/tests/Core/LinkSetTest.php b/tests/Core/LinkSetTest.php index 415ac47..8e1f20d 100644 --- a/tests/Core/LinkSetTest.php +++ b/tests/Core/LinkSetTest.php @@ -4,11 +4,18 @@ namespace Solo\Repository\Tests\Core; +use Closure; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException; use Doctrine\DBAL\Logging\Middleware; +use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\MariaDBPlatform; +use Doctrine\DBAL\Platforms\MySQLPlatform; +use Doctrine\DBAL\Platforms\PostgreSQLPlatform; +use Doctrine\DBAL\Platforms\SQLitePlatform; +use Doctrine\DBAL\Platforms\SQLServerPlatform; use Doctrine\DBAL\Types\Types; use InvalidArgumentException; use PHPUnit\Framework\Attributes\DataProvider; @@ -19,10 +26,13 @@ use Solo\Repository\Relations\BelongsToMany; use Solo\Repository\Relations\HasMany; use Solo\Repository\Repository; +use Solo\Repository\Tests\Fixtures\RecordsStatements; use Stringable; final class LinkSetTest extends TestCase { + use RecordsStatements; + private Connection $db; private Mapping $mapping; private Mapping $tags; @@ -322,6 +332,45 @@ public static function invalidIds(): iterable yield [['id' => 1]]; } + /** + * A pair another writer stores between the operation's read and its INSERT conflicts over the + * pivot's UNIQUE pair; the INSERT skips it instead of failing. Platforms without upserts keep + * the plain INSERT. + */ + #[DataProvider('pairInserts')] + public function testInsertsSkipPairsStoredSinceTheRead(AbstractPlatform $platform, string $insert): void + { + [$connection, $statements] = $this->recordingConnection($platform); + $connection->method('transactional')->willReturnCallback( + static fn (Closure $operation): mixed => $operation($connection), + ); + + (new Repository($connection, $this->mapping))->links('tags')->attach(1, [3, 4]); + + $inserts = array_values(array_filter( + $statements->getArrayCopy(), + static fn (array $statement): bool => str_starts_with($statement[0], 'INSERT'), + )); + self::assertSame([[$insert, [1, 3, 1, 4], array_fill(0, 4, Types::INTEGER)]], $inserts); + } + + /** @return iterable */ + public static function pairInserts(): iterable + { + $mysql = 'INSERT INTO `product_tag` (`product_id`, `tag_id`) VALUES (?, ?), (?, ?)' + . ' ON DUPLICATE KEY UPDATE `product_id` = `product_id`'; + $conflict = 'INSERT INTO "product_tag" AS "br_target" ("product_id", "tag_id") VALUES (?, ?), (?, ?)' + . ' ON CONFLICT ("product_id", "tag_id") DO NOTHING'; + yield 'MySQL' => [new MySQLPlatform(), $mysql]; + yield 'MariaDB' => [new MariaDBPlatform(), $mysql]; + yield 'PostgreSQL' => [new PostgreSQLPlatform(), $conflict]; + yield 'SQLite' => [new SQLitePlatform(), $conflict]; + yield 'other platforms' => [ + new SQLServerPlatform(), + 'INSERT INTO [product_tag] ([product_id], [tag_id]) VALUES (?, ?), (?, ?)', + ]; + } + public function testNonManyToManyRelationsAreRejected(): void { $mapping = new Mapping( diff --git a/tests/Core/LockingReadTest.php b/tests/Core/LockingReadTest.php index c0f1480..46d0f86 100644 --- a/tests/Core/LockingReadTest.php +++ b/tests/Core/LockingReadTest.php @@ -10,7 +10,6 @@ use Doctrine\DBAL\Logging\Middleware; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Platforms\MariaDBPlatform; -use Doctrine\DBAL\Platforms\MySQL84Platform; use Doctrine\DBAL\Platforms\MySQLPlatform; use Doctrine\DBAL\Platforms\PostgreSQLPlatform; use Doctrine\DBAL\Query\QueryBuilder; @@ -190,9 +189,11 @@ public function testIterationChecksTheTransactionWhenItsStatementsRun(): void #[DataProvider('lockClauses')] public function testServerLockClauseLocksOnlyTheReadTableWhereThePlatformCan( AbstractPlatform $platform, + string $serverVersion, string $clause, ): void { [$connection, $statements] = $this->recordingConnection($platform); + $connection->method('getServerVersion')->willReturn($serverVersion); (new Repository($connection, $this->mapping()))->read()->forUpdate()->find(5); @@ -206,11 +207,13 @@ public function testServerLockClauseLocksOnlyTheReadTableWhereThePlatformCan( public static function lockClauses(): iterable { // PostgreSQL cannot lock the nullable side of an outer join, so the lock names the read's table. - yield 'PostgreSQL' => [new PostgreSQLPlatform(), 'FOR UPDATE OF "br_base"']; - yield 'MySQL 8' => [new MySQL84Platform(), 'FOR UPDATE OF `br_base`']; + yield 'PostgreSQL' => [new PostgreSQLPlatform(), '17.2', 'FOR UPDATE OF "br_base"']; + // MySQL takes OF from 8.0.1, told by the server version on any MySQL platform class. + yield 'MySQL 8.4' => [new MySQLPlatform(), '8.4.6', 'FOR UPDATE OF `br_base`']; + yield 'MySQL 8.0' => [new MySQLPlatform(), '8.0.1', 'FOR UPDATE OF `br_base`']; // MariaDB and MySQL 5.7 have no OF: their lock also covers the rows the statement joins. - yield 'MariaDB' => [new MariaDBPlatform(), 'FOR UPDATE']; - yield 'MySQL 5.7' => [new MySQLPlatform(), 'FOR UPDATE']; + yield 'MariaDB' => [new MariaDBPlatform(), '12.3.1-MariaDB', 'FOR UPDATE']; + yield 'MySQL 5.7' => [new MySQLPlatform(), '5.7.44', 'FOR UPDATE']; } public function testTranslationAndOrderJoinsStayOutsideThePostgresLock(): void diff --git a/tests/Core/UpsertTest.php b/tests/Core/UpsertTest.php index 36533f4..cbaa295 100644 --- a/tests/Core/UpsertTest.php +++ b/tests/Core/UpsertTest.php @@ -9,7 +9,7 @@ use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Logging\Middleware; -use Doctrine\DBAL\Platforms\MySQL84Platform; +use Doctrine\DBAL\Platforms\MySQLPlatform; use Doctrine\DBAL\Platforms\PostgreSQLPlatform; use Doctrine\DBAL\Platforms\SQLServerPlatform; use Doctrine\DBAL\Types\Types; @@ -212,7 +212,7 @@ public static function invalidUpserts(): iterable public function testMysqlBindsTheUpdatedValuesAndKeepsARowForEmptyData(): void { - [$connection, $statements] = $this->recordingConnection(new MySQL84Platform()); + [$connection, $statements] = $this->recordingConnection(new MySQLPlatform()); $settings = new Repository($connection, $this->mapping()); $created = new DateTimeImmutable('2026-01-02 03:04:05'); @@ -263,7 +263,7 @@ public function testPostgresUpdatesFromTheProposedRow(): void public function testTheParameterBudgetCountsTheBoundUpdateValues(): void { - [$connection, $statements] = $this->recordingConnection(new MySQL84Platform()); + [$connection, $statements] = $this->recordingConnection(new MySQLPlatform()); $settings = new Repository($connection, $this->mapping(), parameterLimit: 3); $settings->upsert(self::KEY, [], ['enabled' => true]); diff --git a/tests/Database/RelationsDatabaseTest.php b/tests/Database/RelationsDatabaseTest.php index 1b57c6f..7d1f14f 100644 --- a/tests/Database/RelationsDatabaseTest.php +++ b/tests/Database/RelationsDatabaseTest.php @@ -5,11 +5,16 @@ namespace Solo\Repository\Tests\Database; use Closure; +use Doctrine\DBAL\Exception\DeadlockException; +use Doctrine\DBAL\Exception\DriverException; use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException; use Doctrine\DBAL\Platforms\AbstractMySQLPlatform; use Doctrine\DBAL\Platforms\MariaDBPlatform; +use Doctrine\DBAL\Platforms\PostgreSQLPlatform; use Doctrine\DBAL\Schema\Schema; +use Doctrine\DBAL\TransactionIsolationLevel; use Doctrine\DBAL\Types\Types; +use PHPUnit\Framework\Attributes\DataProvider; use Solo\Repository\Filter; use Solo\Repository\Load; use Solo\Repository\Mapping; @@ -351,6 +356,50 @@ public function testLinkSetRepeatedWritesUsePhysicalMembershipIncludingDeletedRo self::assertFalse($this->connection->isTransactionActive()); } + /** @return iterable */ + public static function isolationLevels(): iterable + { + yield 'server default' => [null]; + yield 'repeatable read' => [TransactionIsolationLevel::REPEATABLE_READ]; + } + + #[DataProvider('isolationLevels')] + public function testAttachSkipsALinkAnotherSessionStoredAfterItsRead(?TransactionIsolationLevel $isolation): void + { + if ($isolation !== null) { + $this->connection->setTransactionIsolation($isolation); + } + $platform = $this->connection->getDatabasePlatform(); + // A snapshot taken before the other session's commit makes PostgreSQL above READ COMMITTED, + // and MariaDB with snapshot isolation (its default since 11.6), refuse the write instead. + $postgres = $platform instanceof PostgreSQLPlatform; + $refuses = ($postgres && $isolation !== null) || ( + $platform instanceof MariaDBPlatform + && (int) $this->connection->fetchOne('SELECT @@innodb_snapshot_isolation') === 1 + ); + $other = $this->otherConnection(); + $stored = false; + // The other session stores one of the pairs between attach()'s read and its INSERT. + $this->log->beforeStatement = static function (string $sql) use ($other, &$stored): void { + if (!$stored && str_starts_with($sql, 'INSERT INTO ')) { + $stored = true; + $other->insert('repo_rel_item_tags', ['item_id' => 2, 'tag_id' => 101]); + } + }; + + try { + $this->items->links('tags')->attach(2, [101, 103]); + self::assertFalse($refuses, 'Expected a serialization failure.'); + self::assertSame([101, 102, 103], $this->linkedIds(2)); + } catch (DriverException $exception) { + // The whole attach() rolls back, and the transaction has to start over. + self::assertTrue($refuses, $exception->getMessage()); + self::assertTrue($postgres ? $exception instanceof DeadlockException : $exception->getCode() === 1020); + self::assertSame([101, 102], $this->linkedIds(2)); + } + self::assertTrue($stored); + } + public function testLateForeignKeyFailureRollsBackSyncAndPreservesOuterTransaction(): void { $rows = []; diff --git a/tests/Fixtures/QueryLog.php b/tests/Fixtures/QueryLog.php index a2db424..62f18da 100644 --- a/tests/Fixtures/QueryLog.php +++ b/tests/Fixtures/QueryLog.php @@ -4,6 +4,7 @@ namespace Solo\Repository\Tests\Fixtures; +use Closure; use Psr\Log\AbstractLogger; use Stringable; @@ -12,10 +13,21 @@ final class QueryLog extends AbstractLogger /** @var list */ public array $queries = []; + /** + * Called with the SQL of each statement before the connection sends it, so a test can act + * between two statements of one call. + * + * @var (Closure(string): void)|null + */ + public ?Closure $beforeStatement = null; + public function log($level, string|Stringable $message, array $context = []): void { if (isset($context['sql'])) { $this->queries[] = ['sql' => $context['sql'], 'params' => $context['params'] ?? []]; + if ($this->beforeStatement !== null) { + ($this->beforeStatement)($context['sql']); + } } }