From ffc034886f502b91eb86f23f661b1409a9d0b849 Mon Sep 17 00:00:00 2001 From: vitaliyolos Date: Tue, 27 Oct 2026 13:56:35 +0200 Subject: [PATCH] feat: add locking reads, relation path ordering and native upserts ReadQuery::forUpdate() turns a read into a locking one: find(), findOneBy(), findBy(), rows(), exists() and iterateById() run SELECT ... FOR UPDATE and lock the rows they read until the transaction ends, and never answer from the snapshot of a REPEATABLE READ transaction. PostgreSQL and MySQL 8 lock only the rows of the read's table (FOR UPDATE OF). Aggregates and queryBuilder() of a locking read are rejected; relation loads read without locks. orderBy accepts dotted paths through BelongsTo relations to a field of the target, such as category.name, in reads, default relation orders and Load orders. Each target is LEFT JOINed once per statement over the rows a load of the same relation in the read sees, its active rows without one. Relation::joinCondition() now builds the key condition for related filters, string-key loads and these joins. Repository::upsert($key, $data, $onInsert) inserts the row of a unique key, or updates the row that already holds it, in one native statement. Its conflict clause is shared with translation upserts. insertMany() runs a batch that fits one statement without a transaction or savepoint; only a batch split into several statements is wrapped in one. --- CHANGELOG.md | 34 +- README.md | 4 +- docs/guide/api.md | 17 +- docs/guide/details.md | 18 +- docs/guide/migration.md | 2 +- src/Internal/Database.php | 83 +++++ src/Internal/FieldResolver.php | 71 ++++- src/Internal/Identifier.php | 12 + src/Internal/OrderBy.php | 7 +- src/Internal/PredicateCompiler.php | 5 +- src/Internal/ReadExecutor.php | 28 +- src/Internal/RelationLoader.php | 8 +- src/Load.php | 8 +- src/ReadQuery.php | 67 +++- src/Relations/Relation.php | 20 +- src/Repository.php | 116 +++++-- src/TranslationStore.php | 33 +- tests/Core/LoadPlanTest.php | 2 +- tests/Core/LockingReadTest.php | 281 +++++++++++++++++ tests/Core/RelationMetadataTest.php | 3 +- tests/Core/RelationOrderTest.php | 366 ++++++++++++++++++++++ tests/Core/RepositoryTest.php | 43 ++- tests/Core/UpsertTest.php | 311 ++++++++++++++++++ tests/Database/DatabaseTestCase.php | 12 + tests/Database/RelationsDatabaseTest.php | 89 ++++++ tests/Database/RepositoryDatabaseTest.php | 107 ++++++- tests/Fixtures/RecordsStatements.php | 53 ++++ tests/Types/PublicApiTypes.php | 6 + 28 files changed, 1673 insertions(+), 133 deletions(-) create mode 100644 tests/Core/LockingReadTest.php create mode 100644 tests/Core/RelationOrderTest.php create mode 100644 tests/Core/UpsertTest.php create mode 100644 tests/Fixtures/RecordsStatements.php diff --git a/CHANGELOG.md b/CHANGELOG.md index f3fbe49..e453a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,10 +32,40 @@ Initial release of **Solo Repository** (`solophp/repository`) with the - A bound-parameter budget that follows the platform limit and can be replaced per repository with `parameterLimit`; internal key lists stop at 5,000 keys per statement. IN lists are bound as one DBAL list parameter. -- Soft delete with `purge`/`purgeBy`, `lockForUpdate` row locks, transactional - `insertMany`, and many-to-many `LinkSet` operations. +- Soft delete with `purge`/`purgeBy`, `lockForUpdate` row locks and locking + reads, native upserts by a unique key, atomic `insertMany`, and many-to-many + `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-RC4 + +- `ReadQuery::forUpdate()` returns the same read as a locking one: `find()`, + `findOneBy()`, `findBy()`, `rows()`, `exists()` and `iterateById()` run + `SELECT ... FOR UPDATE` and lock the rows they read until the transaction + ends, and throw `LogicException` outside a transaction. Unlike + `lockForUpdate()` followed by a plain read, which a REPEATABLE READ + transaction answers from its snapshot, a locking read never returns an older + version of a row: MySQL reads the latest committed one, while PostgreSQL and + MariaDB report a serialization failure. PostgreSQL and MySQL 8 lock only the + rows of the read's table (`FOR UPDATE OF`); MariaDB also locks the rows the + statement joins. Relation loads read without locks, and aggregates and + `queryBuilder()` of a locking read throw `LogicException`. +- `orderBy` of `findBy()`, `findOneBy()` and `rows()` accepts dotted paths + through `BelongsTo` relations to a field of the target, such as + `category.name`. Each target is LEFT JOINed once per statement over the rows + a load of the same relation in the read sees (its active rows without one), + and translated target fields follow the locale of the query. Default relation + orders and `Load` orders take the same paths, resolved from the target mapping. +- `Repository::upsert($key, $data, $onInsert = [])` inserts the row of a unique + key, or updates the row that already holds it, in one native statement: + `ON CONFLICT` on PostgreSQL and SQLite, `ON DUPLICATE KEY UPDATE` on MySQL + and MariaDB. `$onInsert` values go only into a new row. +- **Behavior change:** `insertMany()` runs a batch that fits one statement + without a transaction or savepoint; only a batch split into several + statements is wrapped in one. Inside a caller's transaction on PostgreSQL, a + failure of such a batch now aborts that transaction, as a failed `insert()` + does, instead of rolling back to a savepoint the caller could continue from. + ### Changes since 1.0.0-RC3 - `Repository` is no longer final. An application can extend it with a diff --git a/README.md b/README.md index a3e312c..57c3b92 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,10 @@ fields are rejected. - `BelongsTo`, `HasOne`, `HasMany`, and `BelongsToMany` in the **`Relations`** namespace, including nested batch loading, default collection order, and inherited locale/fallback. +- Ordering by fields of `BelongsTo` targets, such as `category.name`. - Soft delete with explicit visibility, bounded ID iteration, atomic bulk - inserts, `lockForUpdate()` row locks, and `links()->attach/detach/sync()` for + inserts, native upserts by a unique key, `lockForUpdate()` row locks and + locking reads through `forUpdate()`, and `links()->attach/detach/sync()` for physical pivot writes. Schema migrations, multi-table reports, advisory locks, transaction boundaries diff --git a/docs/guide/api.md b/docs/guide/api.md index 0817513..5cbf72a 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -143,6 +143,7 @@ Constructing repositories, queries, link sets and translation stores never opens ReadQuery::withLocale(string $locale, ?string $fallback = null): self; ReadQuery::with(array $relations): self; ReadQuery::withVisibility(Visibility $visibility): self; +ReadQuery::forUpdate(): self; ReadQuery::find(int|string $id): ?object; // T|null ReadQuery::findOneBy(array|Filter $criteria, array $orderBy = []): ?object; @@ -169,7 +170,9 @@ ReadQuery::iterateById(array|Filter $criteria = [], int $batchSize = 500): itera ReadQuery::queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilder; ``` -`criteria` is an associative array or `Filter`. `orderBy` maps readable fields to `ASC`/`DESC`, case-insensitively. All `with*()` methods return a new query; executing a query does not consume its settings. `with()` replaces the complete include list, and `with([])` clears it. +`criteria` is an associative array or `Filter`. `orderBy` maps readable fields to `ASC`/`DESC`, case-insensitively. All `with*()` methods and `forUpdate()` return a new query; executing a query does not consume its settings. `with()` replaces the complete include list, and `with([])` clears it. + +In `findBy()`, `findOneBy()` and `rows()`, an `orderBy` key may also be a dotted path through `BelongsTo` relations to a readable field of their target, such as `category.name` or `category.parent.name`. Each target on a path is LEFT JOINed once per statement on its primary key, over the rows that a load of the same relation path in the read sees: its active rows, unless the read loads that relation with another visibility. A list that shows soft-deleted categories through `with([new Load('category', visibility: Visibility::All)])` thus also orders by their names; only the load's visibility applies, not its criteria. A row whose reference is NULL, dangling or not visible orders as one with NULL there; where NULL sorts follows the database (first in ascending order on MySQL, MariaDB and SQLite, last on PostgreSQL). A translated target field is read in the query locale and fallback, which the target inherits as relation loads do. Paths through `HasOne`, `HasMany` or `BelongsToMany`, which could match several rows, are rejected before SQL. The default order of a to-many relation and the order of a `Load` take the same paths, resolved from the target. - `find()` and `findOneBy()` return NULL when no visible row matches. They limit the root SELECT to one row. - `findBy()` materializes the requested models and their includes. No automatic pagination count is performed. @@ -177,6 +180,7 @@ ReadQuery::queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilde - `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. - 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 @@ -387,6 +391,7 @@ Visibility is applied outside the user's Boolean group. A condition on `deleted_ Repository::insert(array $data): int; Repository::insertGetId(array $data): int|string; Repository::insertMany(array $rows, int $batchSize = 500): int; +Repository::upsert(array $key, array $data, array $onInsert = []): void; Repository::update(int|string $id, array $patch): int; Repository::updateBy(array|Filter $criteria, array $patch): int; Repository::delete(int|string $id): int; @@ -409,7 +414,9 @@ With soft deletion, update methods affect only active rows. Delete methods set a `lockForUpdate()` locks the physical rows with the given primary keys until the surrounding transaction ends, regardless of visibility, and rejects calls outside a transaction. IDs are normalized and deduplicated, and rows are locked in key order, which keeps concurrent lockers from deadlocking. Large key sets are split into statements of at most 5,000 keys. Integer keys are sorted before splitting, so the order holds across statements; string keys follow the database collation within each statement. It uses the platform's `SELECT ... FOR UPDATE`; SQLite has no row locks and runs the plain SELECT. Cross-process advisory locks, such as one critical section per order, stay in the application. -`insertMany()` takes a list of rows with identical column sets; key order may differ. It validates row structure before writing, splits by both `batchSize` and the parameter budget, and wraps all chunks in one transaction/savepoint. A later chunk failure rolls back earlier chunks. An empty list returns zero; batch size must still be positive. It returns affected rows, not generated IDs. +`insertMany()` takes a list of rows with identical column sets; key order may differ. It validates row structure before writing and splits by both `batchSize` and the parameter budget. A batch that fits one statement runs as that statement, which is atomic on its own; a split batch wraps all its chunks in one transaction/savepoint, so a later chunk failure rolls back earlier chunks. Like a failed `insert()`, a one-statement batch that fails inside a caller's transaction on PostgreSQL aborts that transaction; only a split batch rolls back to its own savepoint. An empty list returns zero; batch size must still be positive. It returns affected rows, not generated IDs. + +`upsert()` writes the row of a unique key in one native statement: `ON CONFLICT` on PostgreSQL and SQLite, `ON DUPLICATE KEY UPDATE` on MySQL and MariaDB. It inserts `key + data + onInsert` as a new row or, when a row already holds the key, updates that row's `data` columns and leaves its key and other columns as they are. `onInsert` holds what only a new row gets, such as an explicit ID or a creation time; with empty `data` an existing row stays unchanged. The key must be nonempty, hold no NULL and name the columns of one unique index or of the primary key: PostgreSQL and SQLite use them as the conflict target and reject a key without such an index, while MySQL and MariaDB update the row on a conflict over any unique index of the table and insert another row when none covers the key. Each column appears once across the three arrays; `data` cannot change the primary key, and none of them the soft-delete column. The new row is validated like `insert()`, so a mapping without generated IDs needs the ID in `key` or `onInsert`. The row holding the key is updated even when it is soft-deleted, and stays deleted; `restore()` it explicitly. Affected-row counts of upserts differ between platforms, so `upsert()` returns nothing: read the row back by its key. ## LinkSet @@ -443,7 +450,7 @@ $db->transactional(static function () use ($products, $id): void { }); ``` -Single CRUD statements and translation upserts do not add transactions. Composite operations use DBAL transactions, including nested savepoints in an outer transaction. The package does not close the application connection. +Single CRUD statements, upserts, translation upserts and an `insertMany()` that fits one statement do not add transactions. Composite operations use DBAL transactions, including nested savepoints in an outer transaction. The package does not close the application connection. For joins, aggregates over several tables, advisory locks, raw projections, special types or other SQL features, use DBAL. To keep a mapping's criteria in such SQL, start from `ReadQuery::queryBuilder()`: @@ -465,11 +472,11 @@ Everything the caller adds is plain DBAL: joined tables get no visibility or loc | Failure | Expected category | |---|---| | Invalid metadata, unknown fields, unsupported filters/options, invalid IDs or parameter budget | `InvalidArgumentException` | -| Missing translation metadata, restore without soft deletion, unsupported generated-ID/upsert platform | `LogicException` | +| Missing translation metadata, restore without soft deletion, unsupported generated-ID/upsert platform, locking read outside a transaction, aggregate or query builder of a locking read | `LogicException` | | Non-object hydration/assignment result, invalid relation factory result, multiple HasOne matches, invalid generated-ID result | `UnexpectedValueException` | | SQL, FK, UNIQUE or DBAL type-conversion failure | Original DBAL/driver exception | | Application callback failure or incompatible PHP parameter/return declaration | Original exception or PHP `TypeError` | Validation happens before package SQL where possible; target relations are lazy, and custom callbacks/types can fail during execution. Exception messages and internal implementation types are not a parsing API. -SQLite is covered by the main suite; MySQL 8.4, MariaDB 12.3 and PostgreSQL 17 are covered by the real-database matrix. MariaDB uses the MySQL code paths for generated IDs and upserts. Other DBAL platforms are not supported. Migrations must supply correct PK/FK types and collation, nullable translation/soft-delete fields, translation/pivot uniqueness and HasOne uniqueness; the package does not introspect these guarantees. There are no composite primary keys, alternate-key relations, schema generation, caches, change tracking, cascaded object writes or model identity guarantees. +SQLite is covered by the main suite; MySQL 8.4, MariaDB 12.3 and PostgreSQL 17 are covered by the real-database matrix. MariaDB uses the MySQL code paths for generated IDs and upserts; its locking reads also lock the rows they join, since it has no `FOR UPDATE OF`. Other DBAL platforms are not supported. Migrations must supply correct PK/FK types and collation, nullable translation/soft-delete fields, translation/pivot uniqueness and HasOne uniqueness; the package does not introspect these guarantees. There are no composite primary keys, alternate-key relations, schema generation, caches, change tracking, cascaded object writes or model identity guarantees. diff --git a/docs/guide/details.md b/docs/guide/details.md index 33cf2e0..275a807 100644 --- a/docs/guide/details.md +++ b/docs/guide/details.md @@ -4,7 +4,7 @@ Solo Repository предоставляет типизированное чтен ## Реализовано -Доступны `Mapping`, `Repository`, `ReadQuery`, `Filter::all/any/not/related`, `Visibility`, `Translations`, `TranslationStore`, четыре вида связей, `Load` и `LinkSet`. Реализованы чтение моделей и проекций, count/exists, CRUD, атомарный insertMany, soft delete, пакетный обход по ID, переводы с единым fallback и пакетная загрузка вложенных связей. Исполняемые примеры `examples/crud.php`, `examples/translations.php` и `examples/relations.php` используют SQLite в памяти: +Доступны `Mapping`, `Repository`, `ReadQuery`, `Filter::all/any/not/related`, `Visibility`, `Translations`, `TranslationStore`, четыре вида связей, `Load` и `LinkSet`. Реализованы чтение моделей и проекций, сортировка по полям целей `BelongsTo`, блокирующее чтение, count/exists, CRUD, атомарный insertMany, native upsert по уникальному ключу, soft delete, пакетный обход по ID, переводы с единым fallback и пакетная загрузка вложенных связей. Исполняемые примеры `examples/crud.php`, `examples/translations.php` и `examples/relations.php` используют SQLite в памяти: ```sh composer install @@ -25,7 +25,7 @@ Solo Repository превращает строки БД в обычные PHP-о ## Проверка на MySQL, MariaDB и PostgreSQL -Общий набор из 25 тестов проверяет generated ID и CRUD, преобразование decimal/bool/date/JSON, soft delete и keyset, native PATCH upsert переводов, единый fallback, четыре типа связей и вложенные EXISTS. Отдельные сценарии проверяют пакетные границы, запрос с максимальным для сервера числом параметров (65 535), сортировку коллекции из 905 элементов, освобождение предыдущей страницы, строковые ключи и native PostgreSQL UUID, rollback позднего пакета и продолжение внешней транзакции после savepoint. Схемы содержат настоящие FK и UNIQUE; тесты выполняют SQL на серверах без моков платформ. +Общий набор из 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 на серверах без моков платформ. `.github/workflows/tests.yml` сохраняет три задания основного SQLite-набора и запускает `Database` на каждой из трёх СУБД для тех же комбинаций: @@ -64,7 +64,7 @@ docker compose -f compose.database.yml down --volumes --remove-orphans Compose дожидается healthcheck всех трёх БД. Команда runner — `php vendor/bin/phpunit -c phpunit.database.xml --do-not-cache-result`; ошибки соединения не превращаются в skip. Для выбора PHP передайте `PHP_VERSION=8.5` при сборке. Для локальной проверки минимальной ветки DBAL можно вместо `composer install` выполнить в том же runner `composer update --with='doctrine/dbal:4.3.*'`; это изменит локальные `composer.lock` и `vendor`. После такой проверки верните нужную версию зависимостей. -MySQL 8.4, MariaDB 12.3 и PostgreSQL 17 — проверяемые серверные платформы Solo Repository. MariaDB использует те же ветки кода, что и MySQL (generated ID и upsert переводов); другие платформы не поддерживаются. +MySQL 8.4, MariaDB 12.3 и PostgreSQL 17 — проверяемые серверные платформы Solo Repository. MariaDB использует те же ветки кода, что и MySQL (generated ID, upsert строк и переводов); в блокирующем чтении у неё нет `FOR UPDATE OF`. Другие платформы не поддерживаются. ## Основные решения @@ -145,6 +145,7 @@ with(array $relations): ReadQuery; // list withLocale(string $locale, ?string $fallback = null): self; with(array $relations): self; // list withVisibility(Visibility $visibility): self; +forUpdate(): self; // блокирующее чтение find(int|string $id): ?object; // T|null findOneBy(array|Filter $criteria, array $orderBy = []): ?object; @@ -181,6 +182,10 @@ queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilder; Без `orderBy` порядок не определён. Для стабильной страницы приложение добавляет уникальный ключ в конец сортировки. Отрицательные limit/offset и неизвестные направления сортировки отклоняются; `limit: 0` возвращает пустой список. Коллекции `findBy()` материализуются полностью в пределах указанного limit. +Ключ `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 блокирует все подходящие строки, а не только страницу. + ## Фильтры без второго QueryBuilder Обычный массив — AND по полям: @@ -308,6 +313,7 @@ Loader выполняет один запрос для to-one/has-many и два insert(array $data): int; // affected rows insertGetId(array $data): int|string; // ID, не affected rows insertMany(array $rows, int $batchSize = 500): int; // affected rows +upsert(array $key, array $data, array $onInsert = []): void; update(int|string $id, array $patch): int; updateBy(array|Filter $criteria, array $patch): int; delete(int|string $id): int; @@ -332,11 +338,13 @@ Patch не меняет пропущенные поля; NULL записывае Пустой критерий или критерий, свёрнутый простыми правилами к true, для массовой записи отклоняется до применения soft-delete условия. Это защита от пустого фильтра, а не доказательство безопасности любого логического выражения. Намеренное изменение всей таблицы выражается прямо через DBAL. -`insertMany` принимает строки с одним набором полей; порядок ключей неважен. Различающиеся наборы отклоняются до первой записи. Пустой список возвращает 0. Чанки учитывают лимит параметров; вся операция атомарна. Возвращаемый affected count зависит от драйвера: 0 от UPDATE не доказывает отсутствие записи. +`insertMany` принимает строки с одним набором полей; порядок ключей неважен. Различающиеся наборы отклоняются до первой записи. Пустой список возвращает 0. Чанки учитывают лимит параметров; вся операция атомарна: пакет, который помещается в один statement, выполняется этим statement без транзакции, а разбитый — в одной транзакции/savepoint. Как и неудачный `insert`, такой пакет, упавший внутри транзакции вызывающего на PostgreSQL, обрывает эту транзакцию; к своему savepoint откатывается только разбитый пакет. Возвращаемый affected count зависит от драйвера: 0 от UPDATE не доказывает отсутствие записи. + +`upsert(key, data, onInsert)` записывает строку уникального ключа одним native statement: `ON CONFLICT` на PostgreSQL и SQLite, `ON DUPLICATE KEY UPDATE` на MySQL и MariaDB. Новая строка получает `key + data + onInsert`; у существующей обновляются только колонки `data`, а ключ и остальные колонки остаются прежними. В `onInsert` — то, что нужно только новой строке: явный ID, время создания. С пустым `data` существующая строка не меняется. Ключ непустой, без NULL и называет колонки одного уникального индекса или первичного ключа: PostgreSQL и SQLite используют его как цель конфликта и отклоняют ключ без такого индекса, а MySQL и MariaDB обновляют строку при конфликте по любому уникальному индексу таблицы и вставляют ещё одну строку, если ключ не покрыт ни одним из них. Каждая колонка встречается в трёх массивах один раз; `data` не меняет первичный ключ, а колонку мягкого удаления не содержит ни один из них. Новая строка проверяется как в `insert`, поэтому при `generatedId: false` ID передаётся в `key` или `onInsert`. Строка ключа обновляется и тогда, когда она мягко удалена, и остаётся удалённой — восстанавливает её явный `restore`. Affected rows у upsert на разных платформах считаются по-разному, поэтому метод ничего не возвращает: строку перечитывают по ключу. `lockForUpdate(ids)` блокирует физические строки с этими PK до конца текущей транзакции через `SELECT ... FOR UPDATE`; вне транзакции вызов отклоняется. ID нормализуются и дедуплицируются, строки блокируются в порядке ключа (так конкурирующие транзакции не взаимоблокируются). Большие наборы делятся на statement по 5 000 ключей; целочисленные ключи сортируются до разбиения, поэтому порядок сохраняется и между statement, а строковые ключи следуют collation базы внутри каждого statement. В SQLite строковых блокировок нет, выполняется обычный SELECT. Межпроцессные advisory locks («одна критическая секция на заказ») остаются в приложении. -Несколько операций объединяются стандартным `$db->transactional(...)` на общем Connection. Одиночный CRUD не создаёт дополнительную транзакцию. Составные `insertMany` и операции `LinkSet` используют транзакцию/вложенный savepoint DBAL и пробрасывают ошибки. Автоматические retries отсутствуют. +Несколько операций объединяются стандартным `$db->transactional(...)` на общем Connection. Одиночный CRUD, upsert и `insertMany` в один statement не создают дополнительную транзакцию. Разбитый на несколько statement `insertMany` и операции `LinkSet` используют транзакцию/вложенный savepoint DBAL и пробрасывают ошибки. Автоматические retries отсутствуют. `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 пустого списка ничего не делают. diff --git a/docs/guide/migration.md b/docs/guide/migration.md index e59f772..375b9b0 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -459,7 +459,7 @@ $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` 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. 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. diff --git a/src/Internal/Database.php b/src/Internal/Database.php index e925c3e..df80359 100644 --- a/src/Internal/Database.php +++ b/src/Internal/Database.php @@ -8,7 +8,9 @@ use Doctrine\DBAL\Connection; use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Platforms\AbstractPlatform; +use Doctrine\DBAL\Platforms\MySQL80Platform; use Doctrine\DBAL\Query\QueryBuilder; +use Doctrine\DBAL\Result; use Doctrine\DBAL\Types\Type; use InvalidArgumentException; use LogicException; @@ -116,6 +118,38 @@ public function listParameter(string $type, array $values): ?array return [$converted, $listType]; } + /** Row locks end with the transaction that holds them; outside one they would end with their statement. */ + public function assertTransaction(): void + { + if (!$this->connection->isTransactionActive()) { + throw new LogicException('Row locks require an active transaction.'); + } + } + + /** + * Runs a SELECT that locks the rows it reads until the transaction ends. Given the alias of + * one table, PostgreSQL and MySQL 8 lock only the rows of that table (FOR UPDATE OF), as + * PostgreSQL cannot lock the nullable side of an outer join; MariaDB and MySQL 5.7 have no OF + * and also lock the rows the statement joins. SQLite has no row locks and runs the plain SELECT. + */ + public function executeLocked(QueryBuilder $query, ?string $alias = null): Result + { + $this->assertTransaction(); + $dialect = $this->dialect(); + if ($dialect === Dialect::SQLite) { + return $query->executeQuery(); + } + if ($alias !== null && ($dialect === Dialect::PostgreSQL || $this->platform() instanceof MySQL80Platform)) { + return $this->connection->executeQuery( + $query->getSQL() . ' FOR UPDATE OF ' . $this->quote($alias), + $query->getParameters(), + $query->getParameterTypes(), + ); + } + + return (clone $query)->forUpdate()->executeQuery(); + } + public function assertParameters(int $count): void { $limit = $this->parameterLimit(); @@ -186,6 +220,55 @@ public function insertSql(string $table, array $columns, int $rows, ?string $ali . implode(', ', array_fill(0, $rows, $tuple)); } + /** + * What turns an INSERT into an upsert: on a conflict over the key, the given columns of the + * existing row take their new values, or with none the row stays unchanged. MySQL binds the + * new values again after the rows; PostgreSQL and SQLite read them from the proposed row, + * which the INSERT keeps apart from a table named "excluded" by aliasing its own table. + * + * @param string $feature What the upsert writes, for the error on a platform without upserts. + * @param non-empty-list $key The conflict target; MySQL reacts to a conflict over any unique index. + * @param array $updates The new value and DBAL type of each updated column. + * @return array{?string, string, list, list} The alias for insertSql(), the clause that + * follows the INSERT, and the parameters with types that the clause binds. + */ + public function upsertClause(string $feature, array $key, array $updates): array + { + if ($this->requireDialect($feature) === Dialect::MySQL) { + $assignments = []; + $parameters = []; + $types = []; + foreach ($updates as $column => [$value, $type]) { + $assignments[] = $this->quote($column) . ' = ?'; + $parameters[] = $value; + $types[] = $type; + } + // Assigning a key column to itself leaves the existing row unchanged, and MySQL then + // reports it as unaffected (without CLIENT_FOUND_ROWS): affected rows count insertions. + $unchanged = $this->quote($key[0]) . ' = ' . $this->quote($key[0]); + + return [ + null, + ' ON DUPLICATE KEY UPDATE ' . ($assignments === [] ? $unchanged : implode(', ', $assignments)), + $parameters, + $types, + ]; + } + + $assignments = []; + foreach (array_keys($updates) as $column) { + $assignments[] = $this->quote($column) . ' = excluded.' . $this->quote($column); + } + + return [ + 'br_target', + ' ON CONFLICT (' . implode(', ', array_map($this->quote(...), $key)) . ')' + . ($assignments === [] ? ' DO NOTHING' : ' DO UPDATE SET ' . implode(', ', $assignments)), + [], + [], + ]; + } + public function quote(string $identifier): string { return $this->platform()->quoteSingleIdentifier($identifier); diff --git a/src/Internal/FieldResolver.php b/src/Internal/FieldResolver.php index c9448a8..8319195 100644 --- a/src/Internal/FieldResolver.php +++ b/src/Internal/FieldResolver.php @@ -6,11 +6,14 @@ use Doctrine\DBAL\Query\QueryBuilder; use Doctrine\DBAL\Types\Types; +use InvalidArgumentException; use LogicException; use Solo\Repository\Mapping; +use Solo\Repository\Relations\BelongsTo; +use Solo\Repository\Visibility; /** - * Resolves logical read fields and adds translation joins once per SQL statement. + * Resolves logical read fields and adds translation and ordering joins once per SQL statement. * * @internal */ @@ -20,9 +23,13 @@ final class FieldResolver private readonly ?Locale $locale; private readonly QueryBuilder $parameters; + /** @var array Fields of the BelongsTo targets joined for ordering, by relation path. */ + private array $targets = []; + /** * @param Mapping $mapping * @param QueryBuilder|null $parameters Statement that binds locale parameters; a subquery binds on its root. + * @param LoadPlan|null $loads The relations the read loads; an order join sees the rows its load sees. */ public function __construct( private readonly Database $db, @@ -31,6 +38,7 @@ public function __construct( private readonly string $alias, ?Locale $locale, ?QueryBuilder $parameters = null, + private readonly ?LoadPlan $loads = null, ) { $this->locale = Locale::effective($locale, $mapping); $this->parameters = $parameters ?? $query; @@ -65,6 +73,21 @@ public function expression(string $field): string : 'COALESCE(' . $primary . ', ' . $this->db->qualified($this->alias . '_fallback', $field) . ')'; } + /** + * A read field, or a field of a BelongsTo target named by a dotted relation path such as + * "category.name". Each target is joined once per statement over the rows a load of that + * relation in the same read sees (active ones without such a load), so a row without a + * visible target orders as one with NULL there. + */ + public function orderExpression(string $field): string + { + $dot = strrpos($field, '.'); + + return $dot === false + ? $this->expression($field) + : $this->target(substr($field, 0, $dot))->expression(substr($field, $dot + 1)); + } + /** A read field under its own name; without a locale, a translated field reads as NULL. */ public function projection(string $field): string { @@ -78,6 +101,52 @@ public function projection(string $field): string : $expression . ' AS ' . $this->db->quote($field); } + /** + * The fields of the BelongsTo target at the end of a relation path, LEFT JOINed on first use. + * The join sees the target rows its load in the same read sees, so a list that shows a + * soft-deleted category through a load of every row also orders by that category's name. + */ + private function target(string $path): self + { + if (isset($this->targets[$path])) { + return $this->targets[$path]; + } + + $dot = strrpos($path, '.'); + $owner = $dot === false ? $this : $this->target(substr($path, 0, $dot)); + $name = $dot === false ? $path : substr($path, $dot + 1); + $relation = $owner->mapping->relation($name); + if (!$relation instanceof BelongsTo) { + throw new InvalidArgumentException( + sprintf('An order path follows BelongsTo relations only; "%s" is not one.', $name), + ); + } + $target = $relation->resolve($owner->mapping); + $load = $owner->loads?->nodes[$name] ?? null; + $visibility = $load?->load->visibility ?? Visibility::Active; + SoftDelete::assertSupported($target, $visibility); + $alias = $this->alias . '_order' . (count($this->targets) + 1); + $fields = new self( + $this->db, + $target, + $this->query, + $alias, + $this->locale, + $this->parameters, + $load?->children, + ); + $condition = $relation->joinCondition($this->db, $owner->alias, $owner->mapping, $alias, $target); + $visible = SoftDelete::condition($target, $visibility, $fields->expression(...)); + $this->query->leftJoin( + $owner->alias, + $this->db->quote($target->table), + $alias, + $visible === null ? $condition : $condition . ' AND ' . $visible, + ); + + return $this->targets[$path] = $fields; + } + private function joinTranslations(Locale $locale): void { if ($this->joined) { diff --git a/src/Internal/Identifier.php b/src/Internal/Identifier.php index d8879ca..8b70510 100644 --- a/src/Internal/Identifier.php +++ b/src/Internal/Identifier.php @@ -20,6 +20,18 @@ public static function isValid(string $name): bool return preg_match('/\A' . self::PATTERN . '\z/', $name) === 1; } + /** One identifier or several joined by dots, such as a relation path or a path to a field. */ + public static function isPath(string $path): bool + { + foreach (explode('.', $path) as $segment) { + if (!self::isValid($segment)) { + return false; + } + } + + return true; + } + public static function assert(string $name): void { if (!self::isValid($name)) { diff --git a/src/Internal/OrderBy.php b/src/Internal/OrderBy.php index 7c2b8d9..48a6f64 100644 --- a/src/Internal/OrderBy.php +++ b/src/Internal/OrderBy.php @@ -10,7 +10,8 @@ final class OrderBy { /** - * Plain field names mapped to upper-case directions. + * Fields mapped to upper-case directions. A field is a field name or a dotted relation path + * to a field of a related mapping, such as "category.name"; reads resolve it. * * @param array $orderBy * @return array @@ -19,8 +20,8 @@ public static function normalize(array $orderBy): array { $normalized = []; foreach ($orderBy as $field => $direction) { - if (!is_string($field) || !Identifier::isValid($field)) { - throw new InvalidArgumentException('Order must use plain field names.'); + if (!is_string($field) || !Identifier::isPath($field)) { + throw new InvalidArgumentException('Order must use field names or relation paths to fields.'); } $direction = is_string($direction) ? strtoupper($direction) : null; if ($direction !== 'ASC' && $direction !== 'DESC') { diff --git a/src/Internal/PredicateCompiler.php b/src/Internal/PredicateCompiler.php index f1f71ae..9ed0f4e 100644 --- a/src/Internal/PredicateCompiler.php +++ b/src/Internal/PredicateCompiler.php @@ -257,10 +257,7 @@ private function renderExists(Exists $exists, FieldResolver $parent): string . ' = ' . $this->db->qualified($pivot, $relation->foreignPivotKey), ); } else { - $query->where($relation->keyCondition( - $this->db->qualified($parent->alias(), $relation->ownerKey($owner)), - $this->db->qualified($alias, $relation->targetKey($target)), - )); + $query->where($relation->joinCondition($this->db, $parent->alias(), $owner, $alias, $target)); } $visibility = SoftDelete::condition($target, $exists->visibility, $fields->expression(...)); diff --git a/src/Internal/ReadExecutor.php b/src/Internal/ReadExecutor.php index 1e1ad6f..50310e9 100644 --- a/src/Internal/ReadExecutor.php +++ b/src/Internal/ReadExecutor.php @@ -6,6 +6,7 @@ use Closure; use Doctrine\DBAL\Query\QueryBuilder; +use Doctrine\DBAL\Result; use Generator; use InvalidArgumentException; use Solo\Repository\Filter; @@ -29,12 +30,18 @@ /** @var RowMapper */ private RowMapper $mapper; - /** @param Mapping $mapping */ + /** + * @param Mapping $mapping + * @param bool $locked Whether the statements run as locking reads of this table's rows. + * @param LoadPlan|null $loads The relations loaded with the rows; an order path through one sees its rows. + */ public function __construct( private Database $db, private Mapping $mapping, private Visibility $visibility = Visibility::Active, ?Locale $locale = null, + private bool $locked = false, + private ?LoadPlan $loads = null, ) { SoftDelete::assertSupported($mapping, $visibility); $this->locale = Locale::effective($locale, $mapping); @@ -87,7 +94,7 @@ public function select( } $query->select(...$projection); foreach (OrderBy::normalize($orderBy) as $field => $direction) { - $query->addOrderBy($fields->expression($field), $direction); + $query->addOrderBy($fields->orderExpression($field), $direction); } $this->applyCriteria($query, $fields, $criteria); @@ -134,7 +141,7 @@ public function scalar(Closure $select, array|Filter $criteria, ?int $limit = nu [$query, $fields] = $this->createQuery(); $query->select($select($fields)); $this->applyCriteria($query, $fields, $criteria); - $result = $query->setMaxResults($limit)->executeQuery(); + $result = $this->execute($query->setMaxResults($limit)); try { return $result->fetchOne(); } finally { @@ -182,10 +189,7 @@ public function selectJoined( self::ALIAS, $this->db->quote($ownerMapping->table), 'br_owner', - $relation->keyCondition( - $this->db->qualified('br_owner', $relation->ownerKey($ownerMapping)), - $this->db->qualified(self::ALIAS, $relation->targetKey($this->mapping)), - ), + $relation->joinCondition($this->db, 'br_owner', $ownerMapping, self::ALIAS, $this->mapping), ) ->addSelect($ownerKey . ' AS ' . $this->db->quote($this->ownerColumn())) ->andWhere($this->db->inList( @@ -285,7 +289,7 @@ public function selectLinked( /** @return list> */ public function fetchRows(QueryBuilder $query): array { - $result = $query->executeQuery(); + $result = $this->execute($query); try { return $result->fetchAllAssociative(); } finally { @@ -379,6 +383,12 @@ private function releasedRows(QueryBuilder $query): Generator } } + /** Runs a read statement; a locking read locks the rows of this table that it reads. */ + private function execute(QueryBuilder $query): Result + { + return $this->locked ? $this->db->executeLocked($query, self::ALIAS) : $query->executeQuery(); + } + /** The owner key column of a joined result, named apart from every mapped field. */ private function ownerColumn(): string { @@ -395,7 +405,7 @@ private function ownerColumn(): string private function createQuery(string $alias = self::ALIAS): array { $query = $this->db->connection->createQueryBuilder(); - $fields = new FieldResolver($this->db, $this->mapping, $query, $alias, $this->locale); + $fields = new FieldResolver($this->db, $this->mapping, $query, $alias, $this->locale, loads: $this->loads); $query->from($this->db->quote($this->mapping->table), $alias); return [$query, $fields]; diff --git a/src/Internal/RelationLoader.php b/src/Internal/RelationLoader.php index 7d1fff3..6e092f4 100644 --- a/src/Internal/RelationLoader.php +++ b/src/Internal/RelationLoader.php @@ -38,7 +38,13 @@ public function prepare(Mapping $mapping, LoadPlan $plan, ?Locale $inherited): a $mapping->table, )); } - $executor = new ReadExecutor($this->db, $target, $node->load->visibility, $inherited); + $executor = new ReadExecutor( + $this->db, + $target, + $node->load->visibility, + $inherited, + loads: $node->children, + ); $query = $executor->selectAll($node->load->criteria, $node->load->orderBy ?: $relation->orderBy); $prepared[] = new PreparedLoad( diff --git a/src/Load.php b/src/Load.php index c14dcd5..46aec78 100644 --- a/src/Load.php +++ b/src/Load.php @@ -23,12 +23,8 @@ public function __construct( array $orderBy = [], public Visibility $visibility = Visibility::Active, ) { - foreach (explode('.', $name) as $segment) { - if (!Identifier::isValid($segment)) { - throw new InvalidArgumentException( - 'A load name must be a relation name or a dotted relation path.', - ); - } + if (!Identifier::isPath($name)) { + throw new InvalidArgumentException('A load name must be a relation name or a dotted relation path.'); } $this->orderBy = OrderBy::normalize($orderBy); diff --git a/src/ReadQuery.php b/src/ReadQuery.php index d1e85e2..7652b01 100644 --- a/src/ReadQuery.php +++ b/src/ReadQuery.php @@ -8,6 +8,7 @@ use Doctrine\DBAL\Types\Types; use Generator; use InvalidArgumentException; +use LogicException; use Solo\Repository\Internal\Database; use Solo\Repository\Internal\FieldResolver; use Solo\Repository\Internal\KeyType; @@ -51,20 +52,21 @@ public function __construct( private Visibility $visibility, private ?Locale $locale, private LoadPlan $loads, + private bool $locked = false, ) { - $this->executor = new ReadExecutor($db, $mapping, $visibility, $locale); + $this->executor = new ReadExecutor($db, $mapping, $visibility, $locale, $locked, $loads); } /** @return self */ public function withVisibility(Visibility $visibility): self { - return new self($this->db, $this->mapping, $visibility, $this->locale, $this->loads); + return $this->copy(visibility: $visibility); } /** @return self */ public function withLocale(string $locale, ?string $fallback = null): self { - return new self($this->db, $this->mapping, $this->visibility, new Locale($locale, $fallback), $this->loads); + return $this->copy(locale: new Locale($locale, $fallback)); } /** @@ -73,7 +75,25 @@ public function withLocale(string $locale, ?string $fallback = null): self */ public function with(array $relations): self { - return new self($this->db, $this->mapping, $this->visibility, $this->locale, LoadPlan::from($relations)); + return $this->copy(loads: LoadPlan::from($relations)); + } + + /** + * The same read as a locking one: find(), findOneBy(), findBy(), rows(), exists() and + * iterateById() run SELECT ... FOR UPDATE and lock the rows they read until the surrounding + * transaction ends; outside a transaction they throw LogicException. A locking read never + * answers from the snapshot of a REPEATABLE READ transaction: MySQL reads the latest + * committed rows, while PostgreSQL, and MariaDB with innodb_snapshot_isolation (its default + * since 11.6), reject a row changed since the snapshot as a serialization failure. The lock + * covers the rows of this table (MariaDB, which has no FOR UPDATE OF, also locks the rows + * the statement joins); relation loads read without locks. Aggregates and queryBuilder() + * throw LogicException. SQLite has no row locks and runs the plain SELECT. + * + * @return self + */ + public function forUpdate(): self + { + return $this->copy(locked: true); } /** @return T|null */ @@ -84,7 +104,7 @@ public function find(int|string $id): ?object /** * @param array|Filter $criteria - * @param array $orderBy + * @param array $orderBy Fields, or relation paths to fields of BelongsTo targets. * @return T|null */ public function findOneBy(array|Filter $criteria, array $orderBy = []): ?object @@ -94,7 +114,7 @@ public function findOneBy(array|Filter $criteria, array $orderBy = []): ?object /** * @param array|Filter $criteria - * @param array $orderBy + * @param array $orderBy Fields, or relation paths to fields of BelongsTo targets. * @return list */ public function findBy( @@ -130,6 +150,8 @@ public function exists(array|Filter $criteria = []): bool /** @param array|Filter $criteria */ public function count(array|Filter $criteria = []): int { + $this->assertUnlocked('Aggregates'); + return (int) self::number($this->executor->scalar(static fn(): string => 'COUNT(*)', $criteria), 'COUNT(*)'); } @@ -181,7 +203,7 @@ public function avg(string $field, array|Filter $criteria = []): ?float /** * @param list $columns * @param array|Filter $criteria - * @param array $orderBy + * @param array $orderBy Fields, or relation paths to fields of BelongsTo targets. * @return list> */ public function rows( @@ -217,6 +239,7 @@ public function rows( */ public function queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilder { + $this->assertUnlocked('Query builders'); if ($this->loads->nodes !== []) { throw new InvalidArgumentException('Query builders cannot load relations; use with([]) for SQL.'); } @@ -303,12 +326,42 @@ private function iterate( */ private function aggregate(string $function, string $field, array|Filter $criteria): mixed { + $this->assertUnlocked('Aggregates'); + return $this->executor->scalar( static fn(FieldResolver $fields): string => $function . '(' . $fields->expression($field) . ')', $criteria, ); } + /** + * The same read with the given settings replaced; a lock, once asked for, is kept. + * + * @return self + */ + private function copy( + ?Visibility $visibility = null, + ?Locale $locale = null, + ?LoadPlan $loads = null, + bool $locked = false, + ): self { + return new self( + $this->db, + $this->mapping, + $visibility ?? $this->visibility, + $locale ?? $this->locale, + $loads ?? $this->loads, + $locked || $this->locked, + ); + } + + private function assertUnlocked(string $operation): void + { + if ($this->locked) { + throw new LogicException($operation . ' do not lock rows; lock them with a locking findBy() or rows().'); + } + } + private function assertNumeric(string $field): void { if (!in_array($this->mapping->fieldType($field), self::NUMERIC_TYPES, true)) { diff --git a/src/Relations/Relation.php b/src/Relations/Relation.php index 3b279eb..5437e2c 100644 --- a/src/Relations/Relation.php +++ b/src/Relations/Relation.php @@ -6,6 +6,7 @@ use Closure; use InvalidArgumentException; +use Solo\Repository\Internal\Database; use Solo\Repository\Internal\KeyType; use Solo\Repository\Internal\OrderBy; use Solo\Repository\Mapping; @@ -121,13 +122,24 @@ public function targetKey(Mapping $target): string } /** - * Matches the qualified owner and target keys of a direct relation. The referenced primary - * key stays on the left, because SQLite compares under the collation of the left column. + * Matches the owner and target rows of a direct relation under their aliases in a statement. + * The referenced primary key stays on the left, because SQLite compares under the collation + * of the left column. * * @internal + * @param Mapping $owner + * @param Mapping $target */ - public function keyCondition(string $ownerKey, string $targetKey): string - { + public function joinCondition( + Database $db, + string $ownerAlias, + Mapping $owner, + string $targetAlias, + Mapping $target, + ): string { + $ownerKey = $db->qualified($ownerAlias, $this->ownerKey($owner)); + $targetKey = $db->qualified($targetAlias, $this->targetKey($target)); + return $this instanceof BelongsTo ? $targetKey . ' = ' . $ownerKey : $ownerKey . ' = ' . $targetKey; } diff --git a/src/Repository.php b/src/Repository.php index ef5d78e..698c31e 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -82,7 +82,7 @@ final public function translations(): TranslationStore /** @param array $data */ final public function insert(array $data): int { - return $this->executeInsert($this->validateInsert($data)); + return $this->executeInsert([$this->validateInsert($data)]); } /** @param array $data */ @@ -93,13 +93,13 @@ final public function insertGetId(array $data): int|string if (array_key_exists($key, $data)) { /** @var int|string $id Normalized by validateInsert(). */ $id = $data[$key]; - $this->executeInsert($data); + $this->executeInsert([$data]); return $id; } $dialect = $this->db->requireDialect('Generated IDs'); - [$sql, $parameters, $types] = $this->insertStatement(array_keys($data), [$data]); + [$sql, $parameters, $types] = $this->insertStatement([$data]); if ($dialect === Dialect::PostgreSQL) { $result = $this->db->connection->executeQuery( $sql . ' RETURNING ' . $this->db->quote($key), @@ -120,7 +120,9 @@ final public function insertGetId(array $data): int|string } /** - * Inserts one rectangular batch atomically, splitting SQL at the parameter limit. + * Inserts one rectangular batch atomically, splitting SQL at the parameter limit. A batch + * that fits one statement runs as that statement, which is atomic on its own; a split batch + * runs its statements in one transaction. * * @param list> $rows */ @@ -136,18 +138,75 @@ final public function insertMany(array $rows, int $batchSize = 500): int $columns = array_keys($rows[0]); // An empty row uses the platform's single-row default-values INSERT. $size = $columns === [] ? 1 : min($batchSize, $this->db->batchSize(count($columns))); + if (count($rows) <= $size) { + return $this->executeInsert($rows); + } - return $this->db->connection->transactional(function () use ($rows, $columns, $size): int { + return $this->db->connection->transactional(function () use ($rows, $size): int { $affected = 0; foreach (array_chunk($rows, $size) as $chunk) { - [$sql, $parameters, $types] = $this->insertStatement($columns, $chunk); - $affected += (int) $this->db->connection->executeStatement($sql, $parameters, $types); + $affected += $this->executeInsert($chunk); } return $affected; }); } + /** + * Inserts the row of a unique key, or updates the row that already holds the key, in one + * statement. $data is written either way and $onInsert only into a new row, such as its + * explicit ID or creation time; the key of an existing row stays as it is, and with empty + * $data so does the rest of the row. The row holding the key is updated even when it is + * soft-deleted, and stays deleted. + * + * The key names the columns of one unique index or of the primary key: PostgreSQL and SQLite + * reject a key without one, while MySQL updates the row on a conflict over any unique index + * and inserts another row when no unique index covers the key. + * + * @param array $key + * @param array $data + * @param array $onInsert + */ + final public function upsert(array $key, array $data, array $onInsert = []): void + { + if ($key === []) { + throw new InvalidArgumentException('An upsert requires the columns of a unique key.'); + } + if (in_array(null, $key, true)) { + throw new InvalidArgumentException('Upsert key values cannot be NULL.'); + } + $row = $key + $data + $onInsert; + if (count($row) !== count($key) + count($data) + count($onInsert)) { + throw new InvalidArgumentException( + 'An upsert names each column once: in the key, the data or the insert-only values.', + ); + } + // A new row may get an explicit ID, but no upsert changes one, and none changes visibility. + $this->assertUnreserved($data, $this->mapping->primaryKey); + $this->assertUnreserved($row, $this->mapping->softDeleteColumn); + $row = $this->validateInsert($row); + + $updates = []; + foreach ($data as $column => $value) { + $updates[$column] = [$value, $this->mapping->columnType($column)]; + } + /** @var non-empty-list $keyColumns */ + $keyColumns = array_keys($key); + [$alias, $conflict, $updateParameters, $updateTypes] = $this->db->upsertClause( + 'Upserts', + $keyColumns, + $updates, + ); + [$sql, $parameters, $types] = $this->insertStatement([$row], $alias); + $this->db->assertParameters(count($parameters) + count($updateParameters)); + + $this->db->connection->executeStatement( + $sql . $conflict, + [...$parameters, ...$updateParameters], + [...$types, ...$updateTypes], + ); + } + /** @param array $patch */ final public function update(int|string $id, array $patch): int { @@ -161,11 +220,7 @@ final public function update(int|string $id, array $patch): int final public function updateBy(array|Filter $criteria, array $patch): int { $this->validateColumns($patch); - foreach ([$this->mapping->primaryKey, $this->mapping->softDeleteColumn] as $reserved) { - if ($reserved !== null && array_key_exists($reserved, $patch)) { - throw new InvalidArgumentException('Use dedicated operations instead of changing ID or visibility.'); - } - } + $this->assertUnreserved($patch, $this->mapping->primaryKey, $this->mapping->softDeleteColumn); return $this->executeUpdate($criteria, $patch, Visibility::Active); } @@ -228,9 +283,7 @@ final public function lockForUpdate(int|string|array $ids): void { $column = $this->mapping->requirePrimaryKey('lockForUpdate()'); $ids = array_values($this->mapper->ids(is_array($ids) ? $ids : [$ids])); - if (!$this->db->connection->isTransactionActive()) { - throw new LogicException('Row locks require an active transaction.'); - } + $this->db->assertTransaction(); if ($this->mapper->keyType() === KeyType::Integer) { sort($ids); } @@ -243,10 +296,7 @@ final public function lockForUpdate(int|string|array $ids): void ->from($this->db->quote($this->mapping->table)) ->orderBy($key); $query->where($this->db->inList($query, $key, $type, $chunk)); - if ($this->db->dialect() !== Dialect::SQLite) { - $query->forUpdate(); - } - $result = $query->executeQuery(); + $result = $this->db->executeLocked($query); try { $result->fetchFirstColumn(); } finally { @@ -332,10 +382,10 @@ private function validateColumns(array $data): array return $data; } - /** @param array $data Validated insert data. */ - private function executeInsert(array $data): int + /** @param non-empty-list> $rows Validated rows with the same columns. */ + private function executeInsert(array $rows): int { - [$sql, $parameters, $types] = $this->insertStatement(array_keys($data), [$data]); + [$sql, $parameters, $types] = $this->insertStatement($rows); return (int) $this->db->connection->executeStatement($sql, $parameters, $types); } @@ -343,12 +393,13 @@ private function executeInsert(array $data): int /** * One multi-row INSERT with positional parameters; no columns means one default-values row. * - * @param list $columns - * @param non-empty-list> $rows Validated rows with exactly these columns. + * @param non-empty-list> $rows Validated rows with the same columns. + * @param string|null $alias The name of the target table within the statement, if not its own. * @return array{string, list, list} */ - private function insertStatement(array $columns, array $rows): array + private function insertStatement(array $rows, ?string $alias = null): array { + $columns = array_keys($rows[0]); if ($columns === []) { return [ $this->db->platform()->getEmptyIdentityInsertSQL( @@ -370,7 +421,20 @@ private function insertStatement(array $columns, array $rows): array } } - return [$this->db->insertSql($this->mapping->table, $columns, count($rows)), $parameters, $types]; + return [$this->db->insertSql($this->mapping->table, $columns, count($rows), $alias), $parameters, $types]; + } + + /** + * @param array $columns + * @param string|null ...$reserved Columns that only dedicated operations write. + */ + private function assertUnreserved(array $columns, ?string ...$reserved): void + { + foreach ($reserved as $column) { + if ($column !== null && array_key_exists($column, $columns)) { + throw new InvalidArgumentException('Use dedicated operations instead of changing ID or visibility.'); + } + } } /** diff --git a/src/TranslationStore.php b/src/TranslationStore.php index e7fcaa4..b676206 100644 --- a/src/TranslationStore.php +++ b/src/TranslationStore.php @@ -8,7 +8,6 @@ use InvalidArgumentException; use LogicException; use Solo\Repository\Internal\Database; -use Solo\Repository\Internal\Dialect; use Solo\Repository\Internal\Locale; use Solo\Repository\Internal\RowMapper; use UnexpectedValueException; @@ -191,35 +190,19 @@ private function validatePatch(array $patch): void */ private function upsert(int|string $id, array $locales, array $values, bool $update): int { - $mysql = $this->db->requireDialect('Translation upserts') === Dialect::MySQL; - $foreignKey = $this->db->quote($this->translations->foreignKey); $updates = []; - $updateParameters = []; - $updateTypes = []; if ($update) { foreach ($values as $column => $value) { - $quoted = $this->db->quote($column); - if ($mysql) { - $updates[] = $quoted . ' = ?'; - $updateParameters[] = $value; - $updateTypes[] = $this->translations->columns[$column]; - } else { - $updates[] = $quoted . ' = excluded.' . $quoted; - } + $updates[$column] = [$value, $this->translations->columns[$column]]; } } - - $localeColumn = $this->db->quote($this->translations->localeColumn); - $conflict = match (true) { - // MySQL reports a no-op duplicate update as zero affected rows (without CLIENT_FOUND_ROWS). - $mysql => ' ON DUPLICATE KEY UPDATE ' - . ($update ? implode(', ', $updates) : $foreignKey . ' = ' . $foreignKey), - default => ' ON CONFLICT (' . $foreignKey . ', ' . $localeColumn . ')' - . ($update ? ' DO UPDATE SET ' . implode(', ', $updates) : ' DO NOTHING'), - }; - // Keep a table named "excluded" distinct from the proposed-row pseudo-table. - $alias = $mysql ? null : 'br_target'; - $columns = [$this->translations->foreignKey, $this->translations->localeColumn, ...array_keys($values)]; + $key = [$this->translations->foreignKey, $this->translations->localeColumn]; + [$alias, $conflict, $updateParameters, $updateTypes] = $this->db->upsertClause( + 'Translation upserts', + $key, + $updates, + ); + $columns = [...$key, ...array_keys($values)]; $idType = $this->idType(); $statements = []; diff --git a/tests/Core/LoadPlanTest.php b/tests/Core/LoadPlanTest.php index c472e77..f8ea745 100644 --- a/tests/Core/LoadPlanTest.php +++ b/tests/Core/LoadPlanTest.php @@ -133,7 +133,7 @@ public static function invalidOrders(): iterable { yield [['name' => 'ASC NULLS LAST']]; yield [['name' => true]]; - yield [['category.name' => 'ASC']]; + yield [['category..name' => 'ASC']]; yield [['name']]; } } diff --git a/tests/Core/LockingReadTest.php b/tests/Core/LockingReadTest.php new file mode 100644 index 0000000..c0f1480 --- /dev/null +++ b/tests/Core/LockingReadTest.php @@ -0,0 +1,281 @@ +log = new QueryLog(); + $configuration = new Configuration(); + $configuration->setMiddlewares([new Middleware($this->log)]); + $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration); + $this->connection->executeStatement( + 'CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT NOT NULL)', + ); + $this->connection->executeStatement( + 'CREATE TABLE items (id INTEGER PRIMARY KEY, category_id INTEGER, amount INTEGER NOT NULL, ' + . 'deleted_at DATETIME)', + ); + $this->connection->executeStatement( + 'CREATE TABLE item_translations (item_id INTEGER NOT NULL, locale TEXT NOT NULL, name TEXT, ' + . 'PRIMARY KEY (item_id, locale))', + ); + $this->connection->insert('categories', ['id' => 1, 'name' => 'Chairs']); + foreach ([[1, 1, 10, null], [2, null, 20, null], [3, 1, 30, '2026-01-01 00:00:00']] as $row) { + $this->connection->insert( + 'items', + array_combine(['id', 'category_id', 'amount', 'deleted_at'], $row), + ); + } + $this->connection->insert('item_translations', ['item_id' => 1, 'locale' => 'en', 'name' => 'Chair']); + $this->items = new Repository($this->connection, $this->mapping()); + $this->log->reset(); + } + + protected function tearDown(): void + { + $this->connection->close(); + } + + #[DataProvider('lockingReads')] + public function testLockingReadsNeedATransactionAndRunThePlainSelectOnSqlite(\Closure $read, mixed $expected): void + { + try { + $read($this->items->read()->forUpdate()); + self::fail('A row lock outside a transaction would end with its statement.'); + } catch (LogicException $exception) { + self::assertSame('Row locks require an active transaction.', $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + + $this->connection->beginTransaction(); + try { + self::assertSame($expected, $read($this->items->read()->forUpdate())); + } finally { + $this->connection->rollBack(); + } + + self::assertNotSame([], $this->log->selects()); + foreach ($this->log->selects() as $select) { + self::assertStringNotContainsString('FOR UPDATE', $select['sql']); + } + } + + public static function lockingReads(): iterable + { + yield 'find' => [static fn(ReadQuery $read): ?int => $read->find(1)?->id, 1]; + yield 'findOneBy' => [static fn(ReadQuery $read): ?int => $read->findOneBy(['amount' => 20])?->id, 2]; + yield 'findBy' => [ + static fn(ReadQuery $read): array => array_column($read->findBy(orderBy: ['id' => 'DESC']), 'id'), + [2, 1], + ]; + yield 'rows' => [ + static fn(ReadQuery $read): array => $read->rows(['amount'], ['id' => 2]), + [['amount' => 20]], + ]; + yield 'exists' => [static fn(ReadQuery $read): bool => $read->exists(['amount' => 10]), true]; + yield 'iterateById' => [ + static fn(ReadQuery $read): array => array_column(iterator_to_array($read->iterateById(), false), 'id'), + [1, 2], + ]; + } + + #[DataProvider('readsWithoutRows')] + public function testAggregatesAndQueryBuildersCannotLock(\Closure $read, string $message): void + { + $this->connection->beginTransaction(); + try { + $read($this->items->read()->forUpdate()); + self::fail('Expected the locking read to be rejected.'); + } catch (LogicException $exception) { + self::assertStringStartsWith($message, $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } finally { + $this->connection->rollBack(); + } + } + + public static function readsWithoutRows(): iterable + { + yield 'count' => [static fn(ReadQuery $read): int => $read->count(), 'Aggregates do not lock rows']; + yield 'sum' => [static fn(ReadQuery $read): mixed => $read->sum('amount'), 'Aggregates do not lock rows']; + yield 'min' => [static fn(ReadQuery $read): mixed => $read->min('amount'), 'Aggregates do not lock rows']; + yield 'max' => [static fn(ReadQuery $read): mixed => $read->max('amount'), 'Aggregates do not lock rows']; + yield 'avg' => [static fn(ReadQuery $read): ?float => $read->avg('amount'), 'Aggregates do not lock rows']; + yield 'queryBuilder' => [ + static fn(ReadQuery $read): QueryBuilder => $read->queryBuilder('i'), + 'Query builders do not lock rows', + ]; + } + + public function testDerivedReadsKeepTheLockAndTheOriginalStaysPlain(): void + { + $plain = $this->items->read(); + $locked = $plain->forUpdate(); + + foreach ( + [ + $locked->withVisibility(Visibility::All), + $locked->withLocale('en'), + $locked->with(['category']), + ] as $derived + ) { + try { + $derived->find(1); + self::fail('A derived read must keep the lock.'); + } catch (LogicException) { + self::assertSame([], $this->log->statements()); + } + } + + self::assertSame(1, $plain->find(1)?->id); + self::assertSame(2, $plain->count()); + } + + public function testLockingReadKeepsVisibilityAndCriteria(): void + { + $this->connection->beginTransaction(); + try { + $read = $this->items->read()->forUpdate(); + self::assertNull($read->find(3)); + self::assertSame(3, $read->withVisibility(Visibility::Deleted)->find(3)?->id); + } finally { + $this->connection->rollBack(); + } + } + + public function testIterationChecksTheTransactionWhenItsStatementsRun(): void + { + $this->connection->beginTransaction(); + $batches = $this->items->read()->forUpdate()->iterateById(batchSize: 1); + $this->connection->rollBack(); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Row locks require an active transaction.'); + iterator_to_array($batches); + } + + #[DataProvider('lockClauses')] + public function testServerLockClauseLocksOnlyTheReadTableWhereThePlatformCan( + AbstractPlatform $platform, + string $clause, + ): void { + [$connection, $statements] = $this->recordingConnection($platform); + + (new Repository($connection, $this->mapping()))->read()->forUpdate()->find(5); + + $sql = array_column($statements->getArrayCopy(), 0); + self::assertCount(1, $sql); + self::assertStringEndsWith(' LIMIT 1 ' . $clause, $sql[0]); + self::assertSame(1, substr_count($sql[0], 'FOR UPDATE')); + self::assertSame([5], $statements->getArrayCopy()[0][1]); + } + + 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`']; + // 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']; + } + + public function testTranslationAndOrderJoinsStayOutsideThePostgresLock(): void + { + [$connection, $statements] = $this->recordingConnection(new PostgreSQLPlatform()); + + (new Repository($connection, $this->mapping()))->withLocale('uk', 'en')->forUpdate() + ->findBy(['amount >' => 0], ['category.name' => 'ASC', 'name' => 'DESC']); + + $sql = $statements->getArrayCopy()[0][0]; + self::assertStringContainsString('LEFT JOIN "item_translations" br_base_translation', $sql); + self::assertStringContainsString('LEFT JOIN "item_translations" br_base_fallback', $sql); + self::assertStringContainsString('LEFT JOIN "categories" br_base_order1', $sql); + self::assertStringEndsWith(' FOR UPDATE OF "br_base"', $sql); + self::assertSame(1, substr_count($sql, 'FOR UPDATE')); + } + + public function testExistsLocksTheRowItFindsAndRelationLoadsReadWithoutLocks(): void + { + $item = ['id' => 1, 'category_id' => 7, 'amount' => 10, 'deleted_at' => null, 'name' => null]; + [$connection, $statements] = $this->recordingConnection(new PostgreSQLPlatform(), [[$item], [$item]]); + $read = (new Repository($connection, $this->mapping()))->read()->forUpdate(); + + self::assertTrue($read->exists(['amount' => 10])); + self::assertSame([1], array_column($read->with(['category'])->findBy(['id' => 1]), 'id')); + + $sql = array_column($statements->getArrayCopy(), 0); + self::assertCount(3, $sql); + self::assertStringStartsWith('SELECT 1 FROM "items" br_base', $sql[0]); + self::assertStringEndsWith(' LIMIT 1 FOR UPDATE OF "br_base"', $sql[0]); + self::assertStringEndsWith(' FOR UPDATE OF "br_base"', $sql[1]); + self::assertStringContainsString(' FROM "categories" br_base', $sql[2]); + self::assertStringNotContainsString('FOR UPDATE', $sql[2]); + } + + private function mapping(): Mapping + { + $categories = new Mapping( + table: 'categories', + columns: ['id' => Types::INTEGER, 'name' => Types::STRING], + hydrate: static fn(array $row): object => (object) $row, + ); + + return new Mapping( + table: 'items', + columns: [ + 'id' => Types::INTEGER, + 'category_id' => Types::INTEGER, + 'amount' => Types::INTEGER, + 'deleted_at' => Types::DATETIME_IMMUTABLE, + ], + hydrate: static fn(array $row): object => (object) $row, + softDeleteColumn: 'deleted_at', + translations: new Translations('item_translations', 'item_id', ['name' => Types::STRING]), + relations: [ + 'category' => new BelongsTo( + static fn(): Mapping => $categories, + 'category_id', + static function (object $item, ?object $category): object { + $item->category = $category; + + return $item; + }, + ), + ], + ); + } +} diff --git a/tests/Core/RelationMetadataTest.php b/tests/Core/RelationMetadataTest.php index 7d5e535..24571eb 100644 --- a/tests/Core/RelationMetadataTest.php +++ b/tests/Core/RelationMetadataTest.php @@ -275,7 +275,8 @@ public function testDefaultCollectionOrderMustUsePlainFieldsAndDirections(array public static function invalidDefaultOrders(): iterable { yield 'SQL in direction' => [['position' => 'ASC NULLS LAST']]; - yield 'qualified field' => [['items.position' => 'ASC']]; + yield 'quoted field' => [['"position"' => 'ASC']]; + yield 'empty path segment' => [['items..position' => 'ASC']]; yield 'list instead of map' => [['position']]; } diff --git a/tests/Core/RelationOrderTest.php b/tests/Core/RelationOrderTest.php new file mode 100644 index 0000000..9038d6d --- /dev/null +++ b/tests/Core/RelationOrderTest.php @@ -0,0 +1,366 @@ +log = new QueryLog(); + $configuration = new Configuration(); + $configuration->setMiddlewares([new Middleware($this->log)]); + $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration); + foreach ( + [ + 'CREATE TABLE brands (id INTEGER PRIMARY KEY, name TEXT NOT NULL, deleted_at DATETIME)', + 'CREATE TABLE brand_translations (brand_id INTEGER NOT NULL, locale TEXT NOT NULL, title TEXT, ' + . 'PRIMARY KEY (brand_id, locale))', + 'CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT NOT NULL, brand_id INTEGER)', + 'CREATE TABLE products (id INTEGER PRIMARY KEY, sku TEXT NOT NULL, category_id INTEGER, ' + . 'brand_id INTEGER)', + 'CREATE TABLE variants (id INTEGER PRIMARY KEY, product_id INTEGER NOT NULL, sku TEXT NOT NULL)', + ] as $sql + ) { + $this->connection->executeStatement($sql); + } + $this->seed('brands', ['id', 'name', 'deleted_at'], [ + [1, 'Acme', null], [2, 'Zeta', null], [3, 'Bolt', '2026-01-01 00:00:00'], + ]); + $this->seed('brand_translations', ['brand_id', 'locale', 'title'], [ + [1, 'uk', 'Yankee UK'], [1, 'en', 'Alpha EN'], [2, 'en', 'Bravo EN'], [3, 'en', 'Aardvark EN'], + ]); + $this->seed('categories', ['id', 'name', 'brand_id'], [[10, 'Tables', 2], [20, 'Chairs', 1], [30, 'Lamps', null]]); + $this->seed('products', ['id', 'sku', 'category_id', 'brand_id'], [ + [1, 'p1', 10, 1], [2, 'p2', 20, 2], [3, 'p3', null, null], [4, 'p4', 30, 3], [5, 'p5', 20, 1], + ]); + $this->products = new Repository($this->connection, $this->productMapping()); + $this->log->reset(); + } + + protected function tearDown(): void + { + $this->connection->close(); + } + + public function testOrdersByAFieldOfABelongsToTarget(): void + { + $read = $this->products->read(); + + // SQLite orders NULL first; a product without a category orders as one with a NULL name. + self::assertSame([3, 2, 5, 4, 1], self::ids($read->findBy([], ['category.name' => 'ASC', 'id' => 'ASC']))); + self::assertSame([1, 4, 2, 5, 3], self::ids($read->findBy([], ['category.name' => 'DESC', 'id' => 'ASC']))); + self::assertStringContainsString( + 'LEFT JOIN "categories" br_base_order1 ON "br_base_order1"."id" = "br_base"."category_id"' + . ' WHERE 1 = 1 ORDER BY "br_base_order1"."name" ASC, "br_base"."id" ASC', + $this->log->statements()[0], + ); + } + + public function testFieldsOfOnePathShareOneJoinAndPathsNest(): void + { + $rows = $this->products->read()->rows( + ['id'], + ['sku !=' => 'none'], + ['category.brand.name' => 'ASC', 'category.name' => 'DESC', 'brand.name' => 'ASC', 'id' => 'ASC'], + ); + + // p4's category has no brand and p3 has no category; NULL orders last when descending. + self::assertSame([4, 3, 5, 2, 1], array_column($rows, 'id')); + $sql = $this->log->statements()[0]; + self::assertSame(1, substr_count($sql, 'JOIN "categories"')); + self::assertSame(2, substr_count($sql, 'JOIN "brands"')); + self::assertStringContainsString( + 'LEFT JOIN "brands" br_base_order2 ON "br_base_order2"."id" = "br_base_order1"."brand_id"', + $sql, + ); + self::assertStringContainsString( + 'LEFT JOIN "brands" br_base_order3 ON "br_base_order3"."id" = "br_base"."brand_id"', + $sql, + ); + self::assertStringContainsString( + 'ORDER BY "br_base_order2"."name" ASC, "br_base_order1"."name" DESC, "br_base_order3"."name" ASC', + $sql, + ); + } + + public function testSoftDeletedTargetsOrderAsMissingOnes(): void + { + // Bolt is deleted: p4 orders with p3, which has no brand, instead of between Acme and Zeta. + self::assertSame( + [3, 4, 1, 5, 2], + self::ids($this->products->read()->findBy([], ['brand.name' => 'ASC', 'id' => 'ASC'])), + ); + self::assertStringContainsString( + 'ON "br_base_order1"."id" = "br_base"."brand_id" AND "br_base_order1"."deleted_at" IS NULL', + $this->log->statements()[0], + ); + } + + public function testTranslatedTargetFieldsFollowTheLocaleOfTheRead(): void + { + $order = ['brand.title' => 'ASC', 'id' => 'ASC']; + + self::assertSame([3, 4, 2, 1, 5], self::ids($this->products->withLocale('uk', 'en')->findBy([], $order))); + self::assertSame([3, 4, 1, 5, 2], self::ids($this->products->withLocale('en')->findBy([], $order))); + self::assertStringContainsString( + 'COALESCE("br_base_order1_translation"."title", "br_base_order1_fallback"."title") ASC', + $this->log->statements()[0], + ); + + $this->log->reset(); + try { + $this->products->read()->findBy([], $order); + self::fail('A translated order field needs a locale.'); + } catch (LogicException $exception) { + self::assertStringStartsWith('Translated field "title" needs a locale', $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + } + + public function testOrderPathsSeeTheTargetRowsTheirLoadSees(): void + { + $order = ['brand.name' => 'ASC', 'id' => 'ASC']; + + // Bolt is deleted: a load of every brand shows it, so p4 orders between Acme and Zeta. + self::assertSame([3, 4, 1, 5, 2], self::ids($this->products->with(['brand'])->findBy([], $order))); + self::assertSame([3, 1, 5, 4, 2], self::ids( + $this->products->with([new Load('brand', visibility: Visibility::All)])->findBy([], $order), + )); + self::assertSame([1, 2, 3, 5, 4], self::ids( + $this->products->with([new Load('brand', visibility: Visibility::Deleted)])->findBy([], $order), + )); + [$active, $all, $deleted] = array_values(array_filter( + $this->log->statements(), + static fn(string $sql): bool => str_contains($sql, ' FROM "products" '), + )); + self::assertStringContainsString('"br_base_order1"."deleted_at" IS NULL', $active); + self::assertStringNotContainsString('"br_base_order1"."deleted_at"', $all); + self::assertStringContainsString('"br_base_order1"."deleted_at" IS NOT NULL', $deleted); + + // A nested load sets the visibility of its own segment; the direct path keeps the default. + $this->log->reset(); + $this->products->with([new Load('category.brand', visibility: Visibility::All)]) + ->findBy([], ['category.brand.name' => 'ASC', 'brand.name' => 'ASC']); + $sql = $this->log->statements()[0]; + self::assertStringNotContainsString('"br_base_order2"."deleted_at"', $sql); + self::assertStringContainsString('"br_base_order3"."deleted_at" IS NULL', $sql); + + // The default order of a collection follows the loads below it the same way. + $this->log->reset(); + $this->categoryRepository()->with(['products', new Load('products.brand', visibility: Visibility::All)]) + ->find(20); + self::assertStringNotContainsString('"br_base_order1"."deleted_at"', $this->log->statements()[1]); + } + + public function testOrderJoinsRejectAVisibilityTheirTargetCannotHave(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Deleted visibility requires a soft-delete column.'); + try { + $this->products->with([new Load('category', visibility: Visibility::Deleted)]) + ->findBy([], ['category.name' => 'ASC']); + } finally { + self::assertSame([], $this->log->statements()); + } + } + + public function testPathOrderCombinesWithCriteriaPagesAndRelationLoads(): void + { + $page = $this->products->with(['category'])->findBy( + ['sku IN' => ['p1', 'p2', 'p4', 'p5']], + ['category.name' => 'ASC', 'id' => 'DESC'], + 2, + 1, + ); + + self::assertSame([2, 4], self::ids($page)); + self::assertSame(['Chairs', 'Lamps'], array_map(static fn(object $product): string => $product->category->name, $page)); + self::assertSame(2, $this->products->read()->findOneBy([], ['brand.name' => 'DESC', 'id' => 'ASC'])?->id); + } + + public function testCollectionOrdersFollowPathsOfTheirTarget(): void + { + $categories = $this->categoryRepository(); + + self::assertSame([5, 2], self::ids($categories->with(['products'])->find(20)?->products ?? [])); + self::assertSame([2, 5], self::ids($categories->with([ + new Load('products', orderBy: ['brand.name' => 'DESC', 'id' => 'ASC']), + ])->find(20)?->products ?? [])); + + $this->log->reset(); + try { + $categories->with([new Load('products', orderBy: ['maker.name' => 'ASC'])])->find(20); + self::fail('An unknown relation in a collection order is rejected.'); + } catch (InvalidArgumentException $exception) { + self::assertSame('Unknown mapped relation "maker".', $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + } + + #[DataProvider('invalidOrders')] + public function testOrderPathsAreValidatedBeforeSql(array $orderBy, string $message): void + { + try { + $this->products->read()->findBy([], $orderBy); + self::fail('Expected the order to be rejected.'); + } catch (InvalidArgumentException $exception) { + self::assertSame($message, $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + } + + public static function invalidOrders(): iterable + { + $syntax = 'Order must use field names or relation paths to fields.'; + + yield 'unknown relation' => [['maker.name' => 'ASC'], 'Unknown mapped relation "maker".']; + yield 'collection relation' => [ + ['variants.sku' => 'ASC'], + 'An order path follows BelongsTo relations only; "variants" is not one.', + ]; + yield 'unknown target field' => [['category.missing' => 'ASC'], 'Unknown mapped field "missing".']; + yield 'relation without a field' => [['category' => 'ASC'], 'Unknown mapped field "category".']; + yield 'empty segment' => [['category..name' => 'ASC'], $syntax]; + yield 'trailing dot' => [['category.' => 'ASC'], $syntax]; + yield 'quoted segment' => [['category."name"' => 'ASC'], $syntax]; + yield 'direction' => [['category.name' => 'ASC NULLS LAST'], 'Order direction must be ASC or DESC.']; + } + + private static function assign(string $name): \Closure + { + return static function (object $owner, ?object $target) use ($name): object { + $owner->{$name} = $target; + + return $owner; + }; + } + + /** @param list $entities */ + private static function ids(array $entities): array + { + return array_map(static fn(object $entity): int => $entity->id, $entities); + } + + /** + * @param list $columns + * @param list> $rows + */ + private function seed(string $table, array $columns, array $rows): void + { + foreach ($rows as $row) { + $this->connection->insert($table, array_combine($columns, $row)); + } + } + + /** Categories whose products are ordered by the name of their brand unless a load says otherwise. */ + private function categoryRepository(): Repository + { + $model = static fn(array $row): object => (object) $row; + $brands = new Mapping( + table: 'brands', + columns: ['id' => Types::INTEGER, 'name' => Types::STRING, 'deleted_at' => Types::DATETIME_IMMUTABLE], + hydrate: $model, + softDeleteColumn: 'deleted_at', + ); + $products = new Mapping( + table: 'products', + columns: [ + 'id' => Types::INTEGER, + 'sku' => Types::STRING, + 'category_id' => Types::INTEGER, + 'brand_id' => Types::INTEGER, + ], + hydrate: $model, + relations: ['brand' => new BelongsTo(static fn(): Mapping => $brands, 'brand_id', self::assign('brand'))], + ); + + return new Repository($this->connection, new Mapping( + table: 'categories', + columns: ['id' => Types::INTEGER, 'name' => Types::STRING, 'brand_id' => Types::INTEGER], + hydrate: $model, + relations: [ + 'products' => new HasMany( + static fn(): Mapping => $products, + 'category_id', + static function (object $category, array $products): object { + $category->products = $products; + + return $category; + }, + ['brand.name' => 'ASC', 'id' => 'ASC'], + ), + ], + )); + } + + private function productMapping(): Mapping + { + $model = static fn(array $row): object => (object) $row; + $brands = new Mapping( + table: 'brands', + columns: ['id' => Types::INTEGER, 'name' => Types::STRING, 'deleted_at' => Types::DATETIME_IMMUTABLE], + hydrate: $model, + softDeleteColumn: 'deleted_at', + translations: new Translations('brand_translations', 'brand_id', ['title' => Types::STRING]), + ); + $categories = new Mapping( + table: 'categories', + columns: ['id' => Types::INTEGER, 'name' => Types::STRING, 'brand_id' => Types::INTEGER], + hydrate: $model, + relations: ['brand' => new BelongsTo(static fn(): Mapping => $brands, 'brand_id', self::assign('brand'))], + ); + $variants = new Mapping( + table: 'variants', + columns: ['id' => Types::INTEGER, 'product_id' => Types::INTEGER, 'sku' => Types::STRING], + hydrate: $model, + ); + + return new Mapping( + table: 'products', + columns: [ + 'id' => Types::INTEGER, + 'sku' => Types::STRING, + 'category_id' => Types::INTEGER, + 'brand_id' => Types::INTEGER, + ], + hydrate: $model, + relations: [ + 'category' => new BelongsTo( + static fn(): Mapping => $categories, + 'category_id', + static function (object $product, ?object $category): object { + $product->category = $category; + + return $product; + }, + ), + 'brand' => new BelongsTo(static fn(): Mapping => $brands, 'brand_id', self::assign('brand')), + 'variants' => new HasMany(static fn(): Mapping => $variants, 'product_id'), + ], + ); + } +} diff --git a/tests/Core/RepositoryTest.php b/tests/Core/RepositoryTest.php index eec6d0d..e0cdb87 100644 --- a/tests/Core/RepositoryTest.php +++ b/tests/Core/RepositoryTest.php @@ -4,7 +4,6 @@ namespace Solo\Repository\Tests\Core; -use ArrayObject; use DateTimeImmutable; use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\Configuration; @@ -24,11 +23,14 @@ use Solo\Repository\Filter; use Solo\Repository\Mapping; use Solo\Repository\Repository; +use Solo\Repository\Tests\Fixtures\RecordsStatements; use Solo\Repository\Visibility; use Stringable; final class RepositoryTest extends TestCase { + use RecordsStatements; + private Connection $db; private Repository $repository; private AbstractLogger $log; @@ -363,6 +365,20 @@ public function testInsertManyAcceptsAnyKeyOrderAndSplitsStatements(): void ], $this->repository->read()->rows(['sku', 'active'], orderBy: ['id' => 'ASC'])); } + public function testInsertManyRunsABatchThatFitsOneStatementWithoutATransaction(): void + { + $connection = $this->createMock(Connection::class); + $connection->method('getDatabasePlatform')->willReturn(new PostgreSQLPlatform()); + $connection->expects(self::never())->method('transactional'); + $connection->expects(self::once())->method('executeStatement')->with( + 'INSERT INTO "items" ("sku") VALUES (?), (?)', + ['a', 'b'], + [Types::STRING, Types::STRING], + )->willReturn(2); + + self::assertSame(2, (new Repository($connection, $this->mapping()))->insertMany([['sku' => 'a'], ['sku' => 'b']])); + } + public function testInsertManyCapsBoundParameters(): void { $rows = []; @@ -527,7 +543,7 @@ public static function invalidLockIds(): iterable public function testLockForUpdateUsesTheServerRowLockAndSplitsSortedKeySets(): void { - [$connection, $statements] = $this->lockingConnection(); + [$connection, $statements] = $this->recordingConnection(new PostgreSQLPlatform()); // Sorting before the split keeps one key order across statements. (new Repository($connection, $this->mapping(), parameterLimit: 2))->lockForUpdate([3, 1, 2]); @@ -542,7 +558,7 @@ public function testLockForUpdateUsesTheServerRowLockAndSplitsSortedKeySets(): v public function testLockForUpdateCapsKeysPerStatementBelowThePlatformBudget(): void { - [$connection, $statements] = $this->lockingConnection(); + [$connection, $statements] = $this->recordingConnection(new PostgreSQLPlatform()); // A longer IN list can make MySQL scan, and lock, the whole table. (new Repository($connection, $this->mapping()))->lockForUpdate(range(5001, 1, -1)); @@ -550,27 +566,6 @@ public function testLockForUpdateCapsKeysPerStatementBelowThePlatformBudget(): v self::assertSame([[range(1, 5000)], [[5001]]], array_column($statements->getArrayCopy(), 1)); } - /** @return array{Connection, ArrayObject, list}>} */ - private function lockingConnection(): array - { - $statements = new ArrayObject(); - $result = $this->createStub(Result::class); - $connection = $this->createStub(Connection::class); - $connection->method('getDatabasePlatform')->willReturn(new PostgreSQLPlatform()); - $connection->method('isTransactionActive')->willReturn(true); - $connection->method('createQueryBuilder')->willReturnCallback( - static fn() => new \Doctrine\DBAL\Query\QueryBuilder($connection), - ); - $connection->method('executeQuery')->willReturnCallback( - static function (string $query, array $parameters, array $types) use ($statements, $result): Result { - $statements[] = [$query, array_values($parameters), array_values($types)]; - return $result; - }, - ); - - return [$connection, $statements]; - } - public function testPurgeByDeletesPhysicallyRegardlessOfVisibility(): void { $repository = new Repository($this->db, $this->mapping(true)); diff --git a/tests/Core/UpsertTest.php b/tests/Core/UpsertTest.php new file mode 100644 index 0000000..36533f4 --- /dev/null +++ b/tests/Core/UpsertTest.php @@ -0,0 +1,311 @@ + 1, 'channel' => 'email']; + + private Connection $connection; + private QueryLog $log; + private Repository $settings; + + protected function setUp(): void + { + $this->log = new QueryLog(); + $configuration = new Configuration(); + $configuration->setMiddlewares([new Middleware($this->log)]); + $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration); + $this->connection->executeStatement('CREATE TABLE settings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + owner_id INTEGER NOT NULL, + channel TEXT NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT 0, + threshold INTEGER, + created_at DATETIME, + deleted_at DATETIME, + UNIQUE (owner_id, channel) + )'); + $this->settings = new Repository($this->connection, $this->mapping()); + $this->log->reset(); + } + + protected function tearDown(): void + { + $this->connection->close(); + } + + public function testInsertsTheRowOfANewKeyInOneStatement(): void + { + $created = new DateTimeImmutable('2026-01-02 03:04:05'); + + $this->settings->upsert(self::KEY, ['enabled' => true], ['threshold' => 5, 'created_at' => $created]); + + self::assertSame([ + 'INSERT INTO "settings" AS "br_target" ("owner_id", "channel", "enabled", "threshold", "created_at")' + . ' VALUES (?, ?, ?, ?, ?) ON CONFLICT ("owner_id", "channel")' + . ' DO UPDATE SET "enabled" = excluded."enabled"', + ], $this->log->statements()); + $row = $this->settings->read()->findOneBy(self::KEY); + self::assertSame(1, $row?->id); + self::assertTrue($row->enabled); + self::assertSame(5, $row->threshold); + self::assertEquals($created, $row->created_at); + } + + public function testUpdatesTheRowHoldingTheKeyAndKeepsTheRestOfIt(): void + { + $created = new DateTimeImmutable('2026-01-02 03:04:05'); + $this->settings->upsert(self::KEY, ['enabled' => true], ['threshold' => 5, 'created_at' => $created]); + $this->settings->upsert(['owner_id' => 2, 'channel' => 'email'], ['enabled' => true]); + + $this->settings->upsert( + self::KEY, + ['enabled' => false, 'threshold' => 9], + ['created_at' => new DateTimeImmutable('2027-01-01 00:00:00')], + ); + $this->settings->upsert(self::KEY, ['enabled' => true]); + + $row = $this->settings->read()->find(1); + self::assertTrue($row?->enabled); + self::assertSame(9, $row->threshold); + self::assertEquals($created, $row->created_at); + self::assertSame(2, $this->settings->read()->count()); + self::assertSame(2, $this->settings->read()->findOneBy(['owner_id' => 2])?->id); + } + + public function testEmptyDataOnlyInsertsAMissingRow(): void + { + $this->settings->upsert(self::KEY, [], ['threshold' => 1]); + $this->settings->upsert(self::KEY, [], ['threshold' => 2]); + + $row = $this->settings->read()->findOneBy(self::KEY); + self::assertSame(1, $row?->threshold); + self::assertFalse($row->enabled); + self::assertStringEndsWith(' ON CONFLICT ("owner_id", "channel") DO NOTHING', $this->log->statements()[1]); + } + + public function testASoftDeletedRowHoldingTheKeyIsUpdatedAndStaysDeleted(): void + { + $this->settings->upsert(self::KEY, ['threshold' => 1]); + $this->settings->delete(1); + + $this->settings->upsert(self::KEY, ['threshold' => 2]); + + self::assertNull($this->settings->read()->find(1)); + self::assertSame(2, $this->settings->read()->withVisibility(Visibility::Deleted)->find(1)?->threshold); + self::assertSame(1, $this->settings->read()->withVisibility(Visibility::All)->count()); + } + + public function testAnExplicitIdComesFromTheKeyOrTheInsertOnlyValues(): void + { + $settings = new Repository($this->connection, $this->mapping(generatedId: false)); + try { + $settings->upsert(self::KEY, ['enabled' => true]); + self::fail('A new row of this mapping needs its ID.'); + } catch (InvalidArgumentException $exception) { + self::assertSame('An explicit primary key is required by this mapping.', $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + + $settings->upsert(self::KEY, ['enabled' => true], ['id' => 70]); + $settings->upsert(['id' => 70], ['threshold' => 3], self::KEY); + + self::assertSame(3, $settings->read()->find(70)?->threshold); + self::assertSame(1, $settings->read()->count()); + self::assertStringEndsWith( + ' ON CONFLICT ("id") DO UPDATE SET "threshold" = excluded."threshold"', + $this->log->statements()[1], + ); + } + + public function testMappingsWithoutAPrimaryKeyUpsertByTheirUniqueColumns(): void + { + $this->connection->executeStatement( + 'CREATE TABLE memberships (group_id INTEGER NOT NULL, user_id INTEGER NOT NULL, ' + . 'role TEXT NOT NULL, PRIMARY KEY (group_id, user_id))', + ); + $memberships = new Repository($this->connection, new Mapping( + table: 'memberships', + columns: ['group_id' => Types::INTEGER, 'user_id' => Types::INTEGER, 'role' => Types::STRING], + primaryKey: null, + )); + + $memberships->upsert(['group_id' => 1, 'user_id' => 2], ['role' => 'member']); + $memberships->upsert(['group_id' => 1, 'user_id' => 3], [], ['role' => 'member']); + $memberships->upsert(['group_id' => 1, 'user_id' => 2], ['role' => 'owner']); + $memberships->upsert(['group_id' => 1, 'user_id' => 3], [], ['role' => 'owner']); + + self::assertSame( + [['user_id' => 2, 'role' => 'owner'], ['user_id' => 3, 'role' => 'member']], + $memberships->read()->rows(['user_id', 'role'], orderBy: ['user_id' => 'ASC']), + ); + } + + #[DataProvider('invalidUpserts')] + public function testInvalidUpsertsFailBeforeSql(array $key, array $data, array $onInsert, string $message): void + { + try { + $this->settings->upsert($key, $data, $onInsert); + self::fail('Expected the upsert to be rejected.'); + } catch (InvalidArgumentException $exception) { + self::assertSame($message, $exception->getMessage()); + self::assertSame([], $this->log->statements()); + } + } + + public static function invalidUpserts(): iterable + { + $overlap = 'An upsert names each column once: in the key, the data or the insert-only values.'; + $reserved = 'Use dedicated operations instead of changing ID or visibility.'; + $deleted = new DateTimeImmutable('2026-01-01 00:00:00'); + + yield 'empty key' => [[], ['enabled' => true], [], 'An upsert requires the columns of a unique key.']; + yield 'NULL in the key' => [['owner_id' => 1, 'channel' => null], [], [], 'Upsert key values cannot be NULL.']; + yield 'list key' => [[1], [], [], 'Data must be keyed by mapped column names.']; + yield 'unknown key column' => [['owner' => 1], [], [], 'Unknown mapped column "owner".']; + yield 'unknown data column' => [self::KEY, ['missing' => 1], [], 'Unknown mapped column "missing".']; + yield 'unknown insert-only column' => [self::KEY, [], ['missing' => 1], 'Unknown mapped column "missing".']; + yield 'key column in the data' => [self::KEY, ['channel' => 'sms'], [], $overlap]; + yield 'key column in the insert-only values' => [self::KEY, [], ['owner_id' => 2], $overlap]; + yield 'data in the insert-only values' => [self::KEY, ['threshold' => 1], ['threshold' => 2], $overlap]; + yield 'ID in the data' => [self::KEY, ['id' => 9], [], $reserved]; + yield 'soft-delete column in the data' => [self::KEY, ['deleted_at' => $deleted], [], $reserved]; + yield 'soft-delete column in the insert-only values' => [self::KEY, [], ['deleted_at' => $deleted], $reserved]; + yield 'soft-delete column in the key' => [['deleted_at' => $deleted], [], [], $reserved]; + yield 'value of another type' => [ + self::KEY, + ['threshold' => '12x'], + [], + 'Field "threshold" requires an integer or a canonical decimal string.', + ]; + yield 'insert-only value of another type' => [ + self::KEY, + [], + ['enabled' => 'yes'], + 'Field "enabled" requires a boolean, 0 or 1.', + ]; + } + + public function testMysqlBindsTheUpdatedValuesAndKeepsARowForEmptyData(): void + { + [$connection, $statements] = $this->recordingConnection(new MySQL84Platform()); + $settings = new Repository($connection, $this->mapping()); + $created = new DateTimeImmutable('2026-01-02 03:04:05'); + + $settings->upsert(self::KEY, ['enabled' => true, 'threshold' => 5], ['created_at' => $created]); + $settings->upsert(self::KEY, []); + + self::assertSame([ + [ + 'INSERT INTO `settings` (`owner_id`, `channel`, `enabled`, `threshold`, `created_at`)' + . ' VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE `enabled` = ?, `threshold` = ?', + [1, 'email', true, 5, $created, true, 5], + [Types::INTEGER, Types::STRING, Types::BOOLEAN, Types::INTEGER, Types::DATETIME_IMMUTABLE, + Types::BOOLEAN, Types::INTEGER], + ], + [ + 'INSERT INTO `settings` (`owner_id`, `channel`) VALUES (?, ?)' + . ' ON DUPLICATE KEY UPDATE `owner_id` = `owner_id`', + [1, 'email'], + [Types::INTEGER, Types::STRING], + ], + ], $statements->getArrayCopy()); + } + + public function testPostgresUpdatesFromTheProposedRow(): void + { + [$connection, $statements] = $this->recordingConnection(new PostgreSQLPlatform()); + $settings = new Repository($connection, $this->mapping()); + + $settings->upsert(self::KEY, ['enabled' => true, 'threshold' => 5]); + $settings->upsert(self::KEY, []); + + self::assertSame([ + [ + 'INSERT INTO "settings" AS "br_target" ("owner_id", "channel", "enabled", "threshold")' + . ' VALUES (?, ?, ?, ?) ON CONFLICT ("owner_id", "channel")' + . ' DO UPDATE SET "enabled" = excluded."enabled", "threshold" = excluded."threshold"', + [1, 'email', true, 5], + [Types::INTEGER, Types::STRING, Types::BOOLEAN, Types::INTEGER], + ], + [ + 'INSERT INTO "settings" AS "br_target" ("owner_id", "channel") VALUES (?, ?)' + . ' ON CONFLICT ("owner_id", "channel") DO NOTHING', + [1, 'email'], + [Types::INTEGER, Types::STRING], + ], + ], $statements->getArrayCopy()); + } + + public function testTheParameterBudgetCountsTheBoundUpdateValues(): void + { + [$connection, $statements] = $this->recordingConnection(new MySQL84Platform()); + $settings = new Repository($connection, $this->mapping(), parameterLimit: 3); + + $settings->upsert(self::KEY, [], ['enabled' => true]); + try { + $settings->upsert(self::KEY, ['enabled' => true]); + self::fail('Two key values, a data value and its update need four parameters.'); + } catch (InvalidArgumentException $exception) { + self::assertSame('The query exceeds the parameter limit of 3.', $exception->getMessage()); + } + + self::assertCount(1, $statements); + } + + public function testOtherPlatformsHaveNoUpsert(): void + { + [$connection, $statements] = $this->recordingConnection(new SQLServerPlatform()); + + $this->expectException(LogicException::class); + $this->expectExceptionMessage('Upserts are supported only on PostgreSQL, MySQL and SQLite.'); + try { + (new Repository($connection, $this->mapping()))->upsert(self::KEY, ['enabled' => true]); + } finally { + self::assertCount(0, $statements); + } + } + + private function mapping(bool $generatedId = true): Mapping + { + return new Mapping( + table: 'settings', + columns: [ + 'id' => Types::INTEGER, + 'owner_id' => Types::INTEGER, + 'channel' => Types::STRING, + 'enabled' => Types::BOOLEAN, + 'threshold' => Types::INTEGER, + 'created_at' => Types::DATETIME_IMMUTABLE, + 'deleted_at' => Types::DATETIME_IMMUTABLE, + ], + hydrate: static fn(array $row): object => (object) $row, + generatedId: $generatedId, + softDeleteColumn: 'deleted_at', + ); + } +} diff --git a/tests/Database/DatabaseTestCase.php b/tests/Database/DatabaseTestCase.php index d79b291..bd0145b 100644 --- a/tests/Database/DatabaseTestCase.php +++ b/tests/Database/DatabaseTestCase.php @@ -70,6 +70,18 @@ protected function createSchema(Schema $schema): void } } + /** Whether another session finds the rows of a SELECT locked: it asks for them without waiting. */ + protected static function isLocked(Connection $other, string $select, array $parameters = []): bool + { + try { + $other->fetchOne($select . ' FOR UPDATE NOWAIT', $parameters); + + return false; + } catch (\Doctrine\DBAL\Exception) { + return true; + } + } + /** Another session on the same database, for observing locks held by the main connection. */ protected function otherConnection(): Connection { diff --git a/tests/Database/RelationsDatabaseTest.php b/tests/Database/RelationsDatabaseTest.php index 0455df3..1b57c6f 100644 --- a/tests/Database/RelationsDatabaseTest.php +++ b/tests/Database/RelationsDatabaseTest.php @@ -7,6 +7,7 @@ use Closure; use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException; use Doctrine\DBAL\Platforms\AbstractMySQLPlatform; +use Doctrine\DBAL\Platforms\MariaDBPlatform; use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Types\Types; use Solo\Repository\Filter; @@ -96,6 +97,94 @@ public function testNestedLoadsAndNestedExistsShareInheritedLocaleAndFallback(): self::assertCount(3, $this->log->selects()); } + public function testOrderPathsSortByBelongsToTargetsInTheLocaleOfTheRead(): void + { + $this->insertRows('repo_rel_categories', [ + 'id' => Types::INTEGER, 'parent_id' => Types::INTEGER, 'deleted_at' => Types::STRING, + ], [[30, 10, null]]); + $this->insertRows('repo_rel_category_translations', [ + 'category_id' => Types::INTEGER, 'locale' => Types::STRING, 'name' => Types::STRING, + ], [[30, 'uk', 'Alpha UK'], [30, 'en', 'Zulu EN']]); + $this->insertRows('repo_rel_items', $this->itemTypes(), [[6, 30, 'SKU-6', null]]); + $this->log->reset(); + $criteria = ['category_id IN' => [10, 30]]; + $read = $this->items->withLocale('uk', 'en'); + + self::assertSame([6, 1, 2], self::ids($read->findBy($criteria, ['category.name' => 'ASC', 'id' => 'ASC']))); + self::assertSame([1, 2, 6], self::ids($read->findBy($criteria, ['category.name' => 'DESC', 'id' => 'ASC']))); + // Without a locale of its own the read orders in the default locale of the items. + self::assertSame( + [1, 2, 6], + self::ids($this->items->read()->findBy($criteria, ['category.name' => 'ASC', 'id' => 'ASC'])), + ); + // Category 30 belongs to category 10, whose own parent has no Ukrainian name. + self::assertSame([1, 2, 6], array_column( + $read->rows(['id'], $criteria, ['category.parent.name' => 'DESC', 'id' => 'ASC']), + 'id', + )); + + $locked = $this->connection->transactional( + fn(): array => $read->with(['category'])->forUpdate() + ->findBy($criteria, ['category.name' => 'ASC', 'id' => 'ASC']), + ); + self::assertSame([6, 1, 2], self::ids($locked)); + self::assertSame('Alpha UK', $locked[0]->relation('category')->value('name')); + } + + public function testOrderPathsSeeSoftDeletedTargetsTheReadLoads(): void + { + $this->insertRows('repo_rel_categories', [ + 'id' => Types::INTEGER, 'parent_id' => Types::INTEGER, 'deleted_at' => Types::STRING, + ], [[30, 100, null]]); + $this->insertRows('repo_rel_category_translations', [ + 'category_id' => Types::INTEGER, 'locale' => Types::STRING, 'name' => Types::STRING, + ], [[30, 'uk', 'Zulu UK']]); + $this->insertRows('repo_rel_items', $this->itemTypes(), [[6, 30, 'SKU-6', null]]); + $read = $this->items->withLocale('uk', 'en'); + $criteria = ['id IN' => [1, 3, 6]]; + $order = ['category.name' => 'ASC', 'id' => 'ASC']; + + // Item 3 belongs to the deleted category 20, "Hidden category" in English. + $all = $read->with([new Load('category', visibility: Visibility::All)])->findBy($criteria, $order); + self::assertSame([1, 3, 6], self::ids($all)); + self::assertSame(20, $all[1]->relation('category')->value('id')); + // Without that load the category is missing, and NULL sorts first or last by platform. + self::assertNotSame([1, 3, 6], self::ids($read->with(['category'])->findBy($criteria, $order))); + self::assertNotSame([1, 3, 6], self::ids($read->findBy($criteria, $order))); + } + + public function testLockingReadLocksTheRowsOfItsTableAndNotItsRelationLoads(): void + { + $other = $this->otherConnection(); + $probes = [ + 'item' => 'SELECT 1 FROM repo_rel_items WHERE id = 1', + 'translation' => "SELECT 1 FROM repo_rel_item_translations WHERE item_id = 1 AND locale = 'uk'", + 'category' => 'SELECT 1 FROM repo_rel_categories WHERE id = 10', + 'profile' => 'SELECT 1 FROM repo_rel_profiles WHERE item_id = 1', + ]; + // Each probe can lock its row while no transaction holds it. + foreach ($probes as $probe) { + self::assertFalse(self::isLocked($other, $probe)); + } + $joined = $this->connection->getDatabasePlatform() instanceof MariaDBPlatform; + + $this->connection->beginTransaction(); + try { + $items = $this->items->withLocale('uk', 'en')->with(['profile'])->forUpdate() + ->findBy(['id' => 1], ['category.name' => 'ASC']); + self::assertSame('One', $items[0]->relation('profile')->value('label')); + self::assertTrue(self::isLocked($other, $probes['item'])); + // MariaDB has no FOR UPDATE OF, so its lock also covers the rows the statement joins. + self::assertSame($joined, self::isLocked($other, $probes['translation'])); + self::assertSame($joined, self::isLocked($other, $probes['category'])); + self::assertFalse(self::isLocked($other, $probes['profile'])); + } finally { + $this->connection->rollBack(); + } + + self::assertFalse(self::isLocked($other, $probes['item'])); + } + public function testRelatedSameRowGroupingCountAndPagination(): void { self::assertSame([], $this->items->read()->rows(['id'], Filter::related('notes', [ diff --git a/tests/Database/RepositoryDatabaseTest.php b/tests/Database/RepositoryDatabaseTest.php index 30e78a1..d9291bc 100644 --- a/tests/Database/RepositoryDatabaseTest.php +++ b/tests/Database/RepositoryDatabaseTest.php @@ -6,8 +6,13 @@ use DateTimeImmutable; use DateTimeZone; +use Doctrine\DBAL\Exception\DeadlockException; +use Doctrine\DBAL\Exception\DriverException; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; +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 Solo\Repository\Mapping; use Solo\Repository\Repository; @@ -207,20 +212,108 @@ public function testLockForUpdateHoldsRowsUntilTheTransactionEnds(): void { $id = $this->repository->insertGetId(['sku' => 'locked']); $other = $this->otherConnection(); - $probe = 'SELECT id FROM repo_repository_items WHERE id = ? FOR UPDATE NOWAIT'; + $probe = 'SELECT id FROM repo_repository_items WHERE id = ?'; $this->connection->beginTransaction(); - $this->repository->lockForUpdate([$id, (string) $id]); try { - $other->fetchOne($probe, [$id]); - self::fail('A second session must not lock a row held by the first.'); - } catch (\Doctrine\DBAL\Exception) { - self::assertTrue($this->connection->isTransactionActive()); + $this->repository->lockForUpdate([$id, (string) $id]); + self::assertTrue(self::isLocked($other, $probe, [$id])); } finally { $this->connection->rollBack(); } - self::assertSame($id, (int) $other->fetchOne($probe, [$id])); + self::assertFalse(self::isLocked($other, $probe, [$id])); + } + + public function testLockingReadHoldsTheRowsItReadsUntilTheTransactionEnds(): void + { + $ids = [ + $this->repository->insertGetId(['sku' => 'read']), + $this->repository->insertGetId(['sku' => 'existing']), + $this->repository->insertGetId(['sku' => 'untouched']), + ]; + $other = $this->otherConnection(); + $probe = 'SELECT id FROM repo_repository_items WHERE id = ?'; + + $this->connection->beginTransaction(); + try { + $read = $this->repository->read()->forUpdate(); + self::assertSame('read', $read->find($ids[0])->sku); + self::assertTrue($read->exists(['sku' => 'existing'])); + self::assertTrue(self::isLocked($other, $probe, [$ids[0]])); + self::assertTrue(self::isLocked($other, $probe, [$ids[1]])); + self::assertFalse(self::isLocked($other, $probe, [$ids[2]])); + self::assertStringContainsString('FOR UPDATE', $this->log->selects()[0]['sql']); + } finally { + $this->connection->rollBack(); + } + + self::assertFalse(self::isLocked($other, $probe, [$ids[0]])); + } + + public function testLockingReadNeverAnswersWithTheSnapshotOfAPlainRead(): void + { + $id = $this->repository->insertGetId(['sku' => 'snapshot', 'amount' => '1.00']); + $other = $this->otherConnection(); + $platform = $this->connection->getDatabasePlatform(); + // PostgreSQL, and MariaDB with snapshot isolation (its default since 11.6), refuse to lock + // a row changed since the snapshot; MySQL reads the committed row. + $postgres = $platform instanceof PostgreSQLPlatform; + $refuses = $postgres || ( + $platform instanceof MariaDBPlatform + && (int) $this->connection->fetchOne('SELECT @@innodb_snapshot_isolation') === 1 + ); + + $this->connection->setTransactionIsolation(TransactionIsolationLevel::REPEATABLE_READ); + $this->connection->beginTransaction(); + try { + // The first plain read takes the snapshot the transaction then reads. + self::assertSame('1.00', $this->repository->read()->find($id)->amount); + $other->executeStatement('UPDATE repo_repository_items SET amount = ? WHERE id = ?', ['2.00', $id]); + self::assertSame('1.00', $this->repository->read()->find($id)->amount); + + try { + $locked = $this->repository->read()->forUpdate()->find($id); + self::assertFalse($refuses, 'Expected a serialization failure.'); + self::assertSame('2.00', $locked->amount); + } catch (DriverException $exception) { + // The transaction has to start over; a READ COMMITTED one reads the new row instead. + self::assertTrue($refuses, $exception->getMessage()); + self::assertTrue($postgres ? $exception instanceof DeadlockException : $exception->getCode() === 1020); + } + } finally { + $this->connection->rollBack(); + } + } + + public function testUpsertInsertsOrUpdatesTheRowOfAUniqueKeyOnTheServer(): void + { + $repository = new Repository($this->connection, $this->mapping(true)); + + $repository->upsert(['sku' => 'setting'], ['amount' => '1.00'], ['active' => true]); + $id = $repository->read()->findOneBy(['sku' => 'setting'])->id; + $repository->upsert(['sku' => 'setting'], ['amount' => '2.50'], ['active' => false]); + $repository->upsert(['sku' => 'setting'], [], ['amount' => '9.00']); + $row = $repository->read()->find($id); + self::assertSame('2.50', $row->amount); + self::assertTrue($row->active); + self::assertSame(1, $repository->read()->count()); + + // By primary key; a soft-deleted row is still the one holding its key. + $repository->upsert(['id' => $id], ['metadata' => ['by' => 'id']]); + $repository->delete($id); + $repository->upsert(['sku' => 'setting'], ['amount' => '3.00']); + self::assertNull($repository->read()->find($id)); + $deleted = $repository->read()->withVisibility(Visibility::Deleted)->find($id); + self::assertSame('3.00', $deleted->amount); + self::assertSame(['by' => 'id'], $deleted->metadata); + + $upserts = array_values(array_filter( + $this->log->statements(), + static fn(string $sql): bool => str_starts_with($sql, 'INSERT'), + )); + self::assertCount(5, $upserts); + self::assertSame(1, $repository->read()->withVisibility(Visibility::All)->count()); } public function testAggregatesAreTypedByTheFieldOnTheServer(): void diff --git a/tests/Fixtures/RecordsStatements.php b/tests/Fixtures/RecordsStatements.php new file mode 100644 index 0000000..9bfe605 --- /dev/null +++ b/tests/Fixtures/RecordsStatements.php @@ -0,0 +1,53 @@ +>> $answers + * @return array{Connection, ArrayObject, list}>} + */ + private function recordingConnection(AbstractPlatform $platform, array $answers = []): array + { + $statements = new ArrayObject(); + $connection = $this->createStub(Connection::class); + $connection->method('getDatabasePlatform')->willReturn($platform); + $connection->method('isTransactionActive')->willReturn(true); + $connection->method('createQueryBuilder')->willReturnCallback( + static fn(): QueryBuilder => new QueryBuilder($connection), + ); + $connection->method('executeQuery')->willReturnCallback( + function (string $sql, array $parameters = [], array $types = []) use ($statements, &$answers): Result { + $statements[] = [$sql, array_values($parameters), array_values($types)]; + $rows = array_shift($answers) ?? []; + $result = $this->createStub(Result::class); + $result->method('fetchAllAssociative')->willReturn($rows); + $result->method('fetchOne')->willReturn($rows === [] ? false : 1); + + return $result; + }, + ); + $connection->method('executeStatement')->willReturnCallback( + static function (string $sql, array $parameters = [], array $types = []) use ($statements): int { + $statements[] = [$sql, array_values($parameters), array_values($types)]; + + return 1; + }, + ); + + return [$connection, $statements]; + } +} diff --git a/tests/Types/PublicApiTypes.php b/tests/Types/PublicApiTypes.php index e23e27e..8d10861 100644 --- a/tests/Types/PublicApiTypes.php +++ b/tests/Types/PublicApiTypes.php @@ -112,6 +112,12 @@ function relationsAcceptTypedAssignCallbacks(Connection $connection): void assertType('float|null', $repository->read()->avg('id')); $repository->lockForUpdate([1, '2']); + assertType( + 'Solo\Repository\ReadQuery', + $repository->with(['category'])->forUpdate(), + ); + assertType('Solo\Repository\Tests\Types\Product|null', $repository->read()->forUpdate()->find(1)); + $repository->upsert(['category_id' => 1], [], ['id' => 2]); acceptsAnyRepository($repository); }