diff --git a/CHANGELOG.md b/CHANGELOG.md index 2523e7e..ace7866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Initial release of **Solo Repository** (`solophp/repository`) with the over the same criteria as `count`, bounded integer-ID iteration, and `queryBuilder()`, a DBAL `QueryBuilder` over the rows its criteria select. - Mappings without a primary key for tables with composite keys; their rows are - read and changed by criteria. + read and changed by criteria. A mapping read only as rows needs no hydrator. - `Filter::all`, `any`, `not`, and related `EXISTS` predicates. - Criteria values and written values must have a form of their field type before SQL, so a driver cannot silently turn `'12x'` into 12 or `'false'` into TRUE. @@ -30,11 +30,28 @@ Initial release of **Solo Repository** (`solophp/repository`) with the `HasMany` and `BelongsToMany` accept a default collection order. - 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. + 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. - SQLite tests, MySQL 8.4/MariaDB 12.3/PostgreSQL 17 integration tests, and a PHP/DBAL CI matrix. +### Changes since 1.0.0-RC2 + +- `IN` and `NOT IN` criteria and the key lists of relation loads and + `lockForUpdate()` are bound as one DBAL list parameter (`ArrayParameterType`) + of values converted through the field type, instead of one named parameter + per value. DBAL expands the list into the same SQL when it runs the statement. + A type without a DBAL list binding, such as boolean, still binds each value, + and the parameter budget still counts every value of a list. +- **Behavior change:** a `queryBuilder()` with IN criteria holds a list + parameter. Run the builder itself, or pass `getParameterTypes()` along with + `getParameters()` when its SQL becomes part of another statement. +- The `hydrate` callback of a `Mapping` is optional, and `Mapping::$hydrate` is + nullable. A mapping without one is read through `rows()`, aggregates, + `queryBuilder()` and related filters, and written as usual; `find()`, + `findOneBy()`, `findBy()`, `iterateById()` and loading it as a relation + target throw `LogicException` before SQL. + ### Changes since 1.0.0-RC1 - `ReadQuery::queryBuilder($alias, $criteria)` returns a DBAL `QueryBuilder` diff --git a/README.md b/README.md index 0369b6b..a3e312c 100644 --- a/README.md +++ b/README.md @@ -71,8 +71,9 @@ fields are rejected. ## What it provides - Reusable `ReadQuery` settings; `withLocale()`, `with()` and `withVisibility()` - return new queries. Projection reads use `rows()` without hydrating models; - `count()`, `sum()`, `min()`, `max()` and `avg()` share the same criteria. + return new queries. Projection reads use `rows()` without hydrating models, + and a mapping read only that way needs no hydrator; `count()`, `sum()`, + `min()`, `max()` and `avg()` share the same criteria. - `Filter::all/any/not/related`, with related predicates compiled as `EXISTS`. - Field-by-field translation fallback shared by reads, filters, and sorting; explicit translation PATCH upserts through `translations()->save()` and diff --git a/docs/guide/api.md b/docs/guide/api.md index 6a53403..36b9f5d 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -54,7 +54,7 @@ $products->update($id, ['price' => '179.90']); // affected rows; no model reread Mapping::__construct( string $table, array $columns, // array: column => DBAL type name - callable $hydrate, // callable(array): T + ?callable $hydrate = null, // callable(array): T; NULL reads rows only ?string $primaryKey = 'id', // NULL for a table without a single-column key bool $generatedId = true, ?string $softDeleteColumn = null, @@ -68,7 +68,7 @@ Mapping::readColumns(): array; // array Mapping::relation(string $name): Relations\Relation; ``` -All constructor settings are public readonly properties; `hydrate` is stored as a `Closure`. `columnType()` accepts only base columns. `fieldType()` accepts base or translated fields. `readColumns()` returns their combined type map, and `relation()` looks up a configured relation. Unknown names throw `InvalidArgumentException`. +All constructor settings are public readonly properties; `hydrate` is stored as a `Closure`, or NULL. A mapping without a hydrator, such as one for a link table that no model represents, is read as rows: `rows()`, aggregates, `queryBuilder()`, related filters and writes work, while `find()`, `findOneBy()`, `findBy()`, `iterateById()` and loading it as a relation target throw `LogicException` before SQL. `columnType()` accepts only base columns. `fieldType()` accepts base or translated fields. `readColumns()` returns their combined type map, and `relation()` looks up a configured relation. Unknown names throw `InvalidArgumentException`. Names in `columns`, criteria, projections, sorting and write data are database column names. A hydrator can convert them to camelCase properties or invoke any application constructor. Names form an allowlist, not SQL expressions. Table names, column names and relation names must match `[A-Za-z_][A-Za-z0-9_]*`; schema-qualified tables are not supported. Identifiers are quoted through DBAL and values are bound separately. @@ -168,7 +168,7 @@ An array combines its entries with AND. A bare field name means equality: ['status' => 'active', 'price >=' => '50.00', 'id IN' => [1, 2, 3]] ``` -Supported operators are `=`, `!=`, `>`, `>=`, `<`, `<=`, `IN`, `NOT IN`, `LIKE`, `NOT LIKE`. Operator spelling is case-insensitive. `= null` and `!= null` become `IS NULL` and `IS NOT NULL`. NULL with other operators is rejected. Arrays require explicit `IN`/`NOT IN`; their elements cannot be NULL or arrays. `IN []` is false, `NOT IN []` is true, and an empty criteria array is true. +Supported operators are `=`, `!=`, `>`, `>=`, `<`, `<=`, `IN`, `NOT IN`, `LIKE`, `NOT LIKE`. Operator spelling is case-insensitive. `= null` and `!= null` become `IS NULL` and `IS NOT NULL`. NULL with other operators is rejected. Arrays require explicit `IN`/`NOT IN`; their elements cannot be NULL or arrays. `IN []` is false, `NOT IN []` is true, and an empty criteria array is true. A list is bound as one DBAL list parameter of values converted through the field type, which DBAL expands into one placeholder per value when the statement runs; a type without a DBAL list binding, such as boolean, binds each value separately. A key holds both the field and the operator, so build criteria keys only from fixed strings in your code, never from request parameters or other external input. Whoever controls a key chooses its operator: `filter[price >=]=0` would turn an equality into a comparison. When users choose the fields to filter by, map each allowed name to a fixed key: @@ -209,7 +209,7 @@ $criteria = Filter::all( Related predicates filter owners without duplicating their rows. They do not restrict what `with()` loads. Field paths such as `tags.slug`, raw SQL, implicit scopes and collection sorting are not accepted. LIKE wildcards, case sensitivity, collation and NULL ordering follow the database. -Every statement has a budget of bound parameters, including locale JOINs and nested EXISTS. By default it is the platform limit: 65,535 for PostgreSQL and MySQL/MariaDB, 32,766 for SQLite 3.32 or later, and 900 for older SQLite and other platforms. `new Repository($db, $mapping, parameterLimit: 2000)` replaces it for that repository, its queries and its relation loads, for example to reject large root IN filters early. The value must be positive and must not exceed what the server accepts; raise it only on a platform whose real limit is above the default. Keyset iteration reserves one parameter for continuation. Oversized root criteria are rejected rather than split: splitting would change ordering, pagination or Boolean semantics. Loader batches, `insertMany()` and `LinkSet` split their own internal work within this budget; an operation whose single row does not fit, such as a two-parameter pivot row under a budget of 1, throws InvalidArgumentException. Internal key lists (relation loads, `lockForUpdate()` and `LinkSet` deletes) also hold at most 5,000 keys per statement, because longer IN lists can exceed MySQL's range-optimizer memory and turn index lookups into full scans. +Every statement has a budget of bound parameters, including locale JOINs and nested EXISTS, in which every value of an IN list counts. By default it is the platform limit: 65,535 for PostgreSQL and MySQL/MariaDB, 32,766 for SQLite 3.32 or later, and 900 for older SQLite and other platforms. `new Repository($db, $mapping, parameterLimit: 2000)` replaces it for that repository, its queries and its relation loads, for example to reject large root IN filters early. The value must be positive and must not exceed what the server accepts; raise it only on a platform whose real limit is above the default. Keyset iteration reserves one parameter for continuation. Oversized root criteria are rejected rather than split: splitting would change ordering, pagination or Boolean semantics. Loader batches, `insertMany()` and `LinkSet` split their own internal work within this budget; an operation whose single row does not fit, such as a two-parameter pivot row under a budget of 1, throws InvalidArgumentException. Internal key lists (relation loads, `lockForUpdate()` and `LinkSet` deletes) also hold at most 5,000 keys per statement, because longer IN lists can exceed MySQL's range-optimizer memory and turn index lookups into full scans. ## Translation metadata and locale @@ -423,7 +423,7 @@ $value = $query ->fetchOne(); // a raw driver value ``` -The builder has the mapped table under the alias in FROM, the criteria and the query's visibility in WHERE, and the translation joins the criteria need under the query locale. It selects nothing. Add your own conditions with `andWhere()`, never `where()`: DBAL's `where()` replaces the whole WHERE clause and silently drops the criteria and the soft-delete condition. Name the table by the alias, a lowercase SQL identifier, so that unquoted references such as `s.product_id` match it on every platform; the translation joins are named `_translation` and `_fallback`. Criteria values are bound as named parameters, so bind further values with `createNamedParameter()`. Each call validates the criteria and returns a new builder; nothing runs until the caller executes it. +The builder has the mapped table under the alias in FROM, the criteria and the query's visibility in WHERE, and the translation joins the criteria need under the query locale. It selects nothing. Add your own conditions with `andWhere()`, never `where()`: DBAL's `where()` replaces the whole WHERE clause and silently drops the criteria and the soft-delete condition. Name the table by the alias, a lowercase SQL identifier, so that unquoted references such as `s.product_id` match it on every platform; the translation joins are named `_translation` and `_fallback`. Criteria values are bound as named parameters, so bind further values with `createNamedParameter()`. An IN list is one `ArrayParameterType` parameter that DBAL expands when it runs the statement: run the builder itself, or pass `getParameterTypes()` along with `getParameters()` when its SQL becomes part of another statement. Each call validates the criteria and returns a new builder; nothing runs until the caller executes it. Everything the caller adds is plain DBAL: joined tables get no visibility or locale, and fetched rows are raw driver values, not converted through the mapping's types. Other DBAL queries, from `$db->createQueryBuilder()` or DBAL's execution methods, must apply any desired visibility, locale, parameter typing and result conversion explicitly. diff --git a/docs/guide/details.md b/docs/guide/details.md index 69f2e47..c28d12b 100644 --- a/docs/guide/details.md +++ b/docs/guide/details.md @@ -107,12 +107,14 @@ Repository ── Mapping + Connection - `RelationLoader`: группирует строки, пакетно получает связи и вызывает `assign`. - `Repository`, `TranslationStore` и `LinkSet`: явные операции записи, включая узкие платформенные варианты upsert и получения generated ID. -У пакета нет собственного общего SQL AST, диалектного движка и публичных методов `select/from/join/groupBy/having`. Для таких запросов приложение использует DBAL напрямую. Чтобы сохранить в таком SQL критерии Mapping, `ReadQuery::queryBuilder($alias, $criteria)` отдаёт DBAL `QueryBuilder` с таблицей под псевдонимом во FROM, критериями и видимостью в WHERE и JOIN переводов, которые нужны критериям при locale запроса. SELECT в нём нет: его, как и JOIN, группировку и сортировку, добавляет приложение. Свои условия добавляются через `andWhere()`, а не `where()`: `where()` в DBAL заменяет всё условие WHERE, и критерии вместе с мягким удалением молча пропадут. Псевдоним — SQL-идентификатор в нижнем регистре, чтобы ссылки без кавычек вроде `s.product_id` совпадали с ним на всех платформах; JOIN переводов называются `_translation` и `_fallback`. Значения критериев привязаны именованными параметрами, поэтому свои значения тоже привязываются через `createNamedParameter()`. Всё добавленное приложением — обычный DBAL: присоединённые таблицы не получают видимости и locale, а строки результата не преобразуются типами Mapping. Непустой `with()` вызывает ошибку. +У пакета нет собственного общего SQL AST, диалектного движка и публичных методов `select/from/join/groupBy/having`. Для таких запросов приложение использует DBAL напрямую. Чтобы сохранить в таком SQL критерии Mapping, `ReadQuery::queryBuilder($alias, $criteria)` отдаёт DBAL `QueryBuilder` с таблицей под псевдонимом во FROM, критериями и видимостью в WHERE и JOIN переводов, которые нужны критериям при locale запроса. SELECT в нём нет: его, как и JOIN, группировку и сортировку, добавляет приложение. Свои условия добавляются через `andWhere()`, а не `where()`: `where()` в DBAL заменяет всё условие WHERE, и критерии вместе с мягким удалением молча пропадут. Псевдоним — SQL-идентификатор в нижнем регистре, чтобы ссылки без кавычек вроде `s.product_id` совпадали с ним на всех платформах; JOIN переводов называются `_translation` и `_fallback`. Значения критериев привязаны именованными параметрами, поэтому свои значения тоже привязываются через `createNamedParameter()`. Список `IN` — один параметр типа `ArrayParameterType`, который DBAL разворачивает при выполнении, поэтому SQL построителя выполняется самим построителем или вместе с `getParameterTypes()`. Всё добавленное приложением — обычный DBAL: присоединённые таблицы не получают видимости и locale, а строки результата не преобразуются типами Mapping. Непустой `with()` вызывает ошибку. ## Mapping и модели `Mapping` содержит `table`, `columns`, `hydrate`, `primaryKey = 'id'` (NULL для таблицы без одноколоночного ключа), `generatedId = true`, а также необязательные `translations`, `relations` и `softDeleteColumn`. +`hydrate` может быть NULL у таблицы, которую читают только строками, например у таблицы связей без своей модели. Для неё работают `rows()`, агрегаты, `queryBuilder()`, связанные фильтры и запись, а `find()`, `findOneBy()`, `findBy()`, `iterateById()` и загрузка её как цели связи бросают `LogicException` до SQL. + `columns` — ассоциативный массив `имя_колонки => DBAL type name`. Эти имена используются в фильтрах, сортировке, записи и строковых результатах. Это одновременно allowlist: неизвестное поле вызывает ошибку до SQL. CamelCase, приватные свойства и конструкторы остаются задачей mapper. SQL-идентификаторы проверяются и экранируются средствами DBAL; значения всегда передаются параметрами. Поддерживается один первичный ключ `int|string` либо его отсутствие. `primaryKey: null` описывает таблицу без одноколоночного ключа, например с составным ключом: её строки читаются, вставляются и меняются по критериям (`findBy`, `rows`, `count`, агрегаты, `queryBuilder`, `insert`, `insertMany`, `updateBy`, `deleteBy`, `purgeBy`). Операции по ID (`find`, `insertGetId`, `update`, `delete`, `restore`, `purge`, `lockForUpdate`) бросают `LogicException`, а `iterateById` — `InvalidArgumentException`, всё до SQL. Сгенерированного ID у такой таблицы нет, а вставляемая строка содержит хотя бы одну колонку. @@ -121,7 +123,7 @@ Repository ── Mapping + Connection Заданный PK обязательно входит в `columns`; FK связи входит в `columns` соответствующей стороны. `generatedId: true` допустим только для совместимого целочисленного PK. Собственный Mapping проверяется сразу, требования к ленивой целевой стороне — при первом разрешении связи. -После чтения типы преобразуются через DBAL перед вызовом `hydrate`. Например, `decimal` остаётся строкой, а `datetime_immutable` становится `DateTimeImmutable`. На запись и в сравнения DBAL получает имя типа и выполняет преобразование один раз. Для `IN` каждый элемент связывается с типом поля. Пользовательские типы регистрируются в DBAL; второй реестр codecs не создаётся. Типы, требующие специальных SQL-обёрток, в первый контракт не входят. +После чтения типы преобразуются через DBAL перед вызовом `hydrate`. Например, `decimal` остаётся строкой, а `datetime_immutable` становится `DateTimeImmutable`. На запись и в сравнения DBAL получает имя типа и выполняет преобразование один раз. Список `IN` после проверки каждого элемента преобразуется типом поля в значения БД и связывается одним параметром-списком DBAL, который DBAL разворачивает при выполнении; тип без списочного связывания, например boolean, связывает каждый элемент отдельно. В бюджет параметров список входит каждым значением. Пользовательские типы регистрируются в DBAL; второй реестр codecs не создаётся. Типы, требующие специальных SQL-обёрток, в первый контракт не входят. Для загрузки связей ключи сохраняются из **преобразованных строк**, до `hydrate`. Loader не читает `$model->id` или `$model->category_id`. Типы связанных ключей должны быть совместимы. Для строковых ключей FK и соответствующий PK должны использовать одинаковые правила сравнения (collation). Фабрика `target` возвращает Mapping цели и вызывается отложенно, что допускает циклическую конфигурацию; отдельный registry не нужен. Связанные строки читаются через соединение репозитория владельца. diff --git a/docs/guide/migration.md b/docs/guide/migration.md index b7e7e55..b0cc97c 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -500,7 +500,7 @@ $total = $query ->fetchOne(); ``` -The builder applies the mapping's criteria and visibility only to the mapped table; joined tables and everything else the SQL adds own their soft-delete and locale semantics. V3 criteria keys for joined tables, such as `so.status`, become your own `andWhere()` conditions; `where()` would replace the mapping's criteria and soft-delete condition. Bind values with `createNamedParameter()` and validate/quote dynamic identifiers. Raw DBAL results do not automatically pass through the repository's mapping. +The builder applies the mapping's criteria and visibility only to the mapped table; joined tables and everything else the SQL adds own their soft-delete and locale semantics. V3 criteria keys for joined tables, such as `so.status`, become your own `andWhere()` conditions; `where()` would replace the mapping's criteria and soft-delete condition. Bind values with `createNamedParameter()` and validate/quote dynamic identifiers. IN criteria are one DBAL list parameter, so run the builder itself or pass `getParameterTypes()` with `getParameters()`. Raw DBAL results do not automatically pass through the repository's mapping. For cache invalidation or outgoing events, decide whether they belong after a successful statement or after the encompassing transaction commits. V3's `afterWrite()` ran before commit and only observed that repository's base-table writes; blindly moving its body after every new call would still miss translation/pivot changes and rollback behavior. Keep that policy in the service orchestrating the workflow; no event bus or unit of work is added. diff --git a/src/Internal/Database.php b/src/Internal/Database.php index 29b85d8..e925c3e 100644 --- a/src/Internal/Database.php +++ b/src/Internal/Database.php @@ -4,9 +4,12 @@ namespace Solo\Repository\Internal; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\Connection; +use Doctrine\DBAL\ParameterType; use Doctrine\DBAL\Platforms\AbstractPlatform; use Doctrine\DBAL\Query\QueryBuilder; +use Doctrine\DBAL\Types\Type; use InvalidArgumentException; use LogicException; @@ -68,6 +71,51 @@ public function parameterLimit(): int }; } + /** + * Placeholders the query binds once DBAL expands its list parameters: a list counts every value. + */ + public static function boundCount(QueryBuilder $query): int + { + $types = $query->getParameterTypes(); + $count = 0; + foreach ($query->getParameters() as $key => $value) { + $count += is_array($value) && ($types[$key] ?? null) instanceof ArrayParameterType ? count($value) : 1; + } + + return $count; + } + + /** + * A list of typed values as one DBAL list parameter: the values converted to their database form and the + * list type of their binding, or NULL when DBAL has no list type for that binding (booleans, large objects). + * One list parameter costs a fraction of one named parameter per value, and DBAL expands it to the same SQL. + * + * @param list $values + * @return array{list, ArrayParameterType}|null + */ + public function listParameter(string $type, array $values): ?array + { + $dbalType = Type::getType($type); + $listType = match ($dbalType->getBindingType()) { + ParameterType::INTEGER => ArrayParameterType::INTEGER, + ParameterType::STRING => ArrayParameterType::STRING, + ParameterType::ASCII => ArrayParameterType::ASCII, + ParameterType::BINARY => ArrayParameterType::BINARY, + default => null, + }; + if ($listType === null) { + return null; + } + + $platform = $this->platform(); + $converted = []; + foreach ($values as $value) { + $converted[] = $dbalType->convertToDatabaseValue($value, $platform); + } + + return [$converted, $listType]; + } + public function assertParameters(int $count): void { $limit = $this->parameterLimit(); @@ -110,7 +158,12 @@ public function keyBatchSize(int $reserved = 0): int */ public function inList(QueryBuilder $query, string $field, string $type, array $keys): string { - $this->assertParameters(count($query->getParameters()) + count($keys)); + $this->assertParameters(self::boundCount($query) + count($keys)); + $list = $this->listParameter($type, $keys); + if ($list !== null) { + return $field . ' IN (' . $query->createNamedParameter($list[0], $list[1]) . ')'; + } + $parameters = []; foreach ($keys as $key) { $parameters[] = $query->createNamedParameter($key, $type); diff --git a/src/Internal/FieldResolver.php b/src/Internal/FieldResolver.php index b43faf2..c9448a8 100644 --- a/src/Internal/FieldResolver.php +++ b/src/Internal/FieldResolver.php @@ -91,7 +91,7 @@ private function joinTranslations(Locale $locale): void if ($locale->fallback !== null) { $locales[$this->alias . '_fallback'] = $locale->fallback; } - $this->db->assertParameters(count($this->parameters->getParameters()) + count($locales)); + $this->db->assertParameters(Database::boundCount($this->parameters) + count($locales)); $parameterIndex = 0; foreach ($locales as $alias => $language) { diff --git a/src/Internal/PredicateCompiler.php b/src/Internal/PredicateCompiler.php index bb855e4..f1f71ae 100644 --- a/src/Internal/PredicateCompiler.php +++ b/src/Internal/PredicateCompiler.php @@ -4,6 +4,7 @@ namespace Solo\Repository\Internal; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\Query\QueryBuilder; use InvalidArgumentException; use Solo\Repository\Filter; @@ -48,9 +49,9 @@ public function compile(array|Filter $criteria): string|bool } // Reject oversized criteria before binding them; translation joins bind their locales while rendering. - $this->db->assertParameters(count($this->builder->getParameters()) + self::countValues($predicate)); + $this->db->assertParameters(Database::boundCount($this->builder) + self::countValues($predicate)); $sql = $this->render($predicate, $this->fields); - $this->db->assertParameters(count($this->builder->getParameters())); + $this->db->assertParameters(Database::boundCount($this->builder)); return $sql; } @@ -216,6 +217,11 @@ private function render(Condition|Group|Exists $predicate, ?FieldResolver $field return $field . ' ' . $predicate->operator . ' ' . $this->bind($predicate->value, $predicate->type); } + $list = $this->db->listParameter($predicate->type, array_values($predicate->value)); + if ($list !== null) { + return $field . ' ' . $predicate->operator . ' (' . $this->bind($list[0], $list[1]) . ')'; + } + $parameters = []; foreach ($predicate->value as $element) { $parameters[] = $this->bind($element, $predicate->type); @@ -269,7 +275,7 @@ private function renderExists(Exists $exists, FieldResolver $parent): string return 'EXISTS (' . $query->getSQL() . ')'; } - private function bind(mixed $value, string $type): string + private function bind(mixed $value, string|ArrayParameterType $type): string { do { $name = 'predicate' . ++$this->parameterIndex; diff --git a/src/Internal/RelationLoader.php b/src/Internal/RelationLoader.php index 823b88a..7d1fff3 100644 --- a/src/Internal/RelationLoader.php +++ b/src/Internal/RelationLoader.php @@ -30,6 +30,7 @@ public function prepare(Mapping $mapping, LoadPlan $plan, ?Locale $inherited): a throw new LogicException(sprintf('Relation "%s" has no assign callback to load into.', $name)); } $target = $relation->resolve($mapping); + $target->requireHydrator(sprintf('Loading relation "%s"', $name)); if ($mapping->primaryKey === null && !self::matchesInPhp($relation, $target)) { throw new LogicException(sprintf( 'Loading relation "%s" by string keys requires a primary key; mapping "%s" has none.', @@ -46,7 +47,7 @@ public function prepare(Mapping $mapping, LoadPlan $plan, ?Locale $inherited): a $executor, $query, $this->prepare($target, $node->children, $executor->locale()), - $this->db->keyBatchSize(count($query->getParameters())), + $this->db->keyBatchSize(Database::boundCount($query)), ); } diff --git a/src/Internal/RowMapper.php b/src/Internal/RowMapper.php index 49e106b..fa7e66d 100644 --- a/src/Internal/RowMapper.php +++ b/src/Internal/RowMapper.php @@ -85,7 +85,7 @@ public function convert(array $row): array public function hydrate(array $row): object { /** @var mixed $entity */ - $entity = ($this->mapping->hydrate)($row); + $entity = ($this->mapping->hydrate ?? $this->mapping->requireHydrator('Reading entities'))($row); if (!is_object($entity)) { throw new UnexpectedValueException('The mapping hydrator must return an object.'); diff --git a/src/Mapping.php b/src/Mapping.php index b777f88..33d6c0c 100644 --- a/src/Mapping.php +++ b/src/Mapping.php @@ -19,8 +19,8 @@ */ final readonly class Mapping { - /** @var Closure(array): T */ - public Closure $hydrate; + /** @var (Closure(array): T)|null NULL for a mapping that is never read into entities. */ + public ?Closure $hydrate; /** Whether the database generates the primary key; always false without one. */ public bool $generatedId; @@ -30,7 +30,9 @@ /** * @param array $columns - * @param callable(array): T $hydrate + * @param (callable(array): T)|null $hydrate NULL for a table read only through rows(), + * aggregates and queryBuilder(); reads that build + * entities then throw before SQL. * @param string|null $primaryKey NULL for a table without a single-column key, such as one with a * composite key; its rows are then read and changed by criteria only. * @param array $relations @@ -38,7 +40,7 @@ public function __construct( public string $table, public array $columns, - callable $hydrate, + ?callable $hydrate = null, public ?string $primaryKey = 'id', bool $generatedId = true, public ?string $softDeleteColumn = null, @@ -78,7 +80,7 @@ public function __construct( } } - $this->hydrate = Closure::fromCallable($hydrate); + $this->hydrate = $hydrate === null ? null : Closure::fromCallable($hydrate); $this->readColumns = $columns + ($translations->columns ?? []); } @@ -90,6 +92,17 @@ public function requirePrimaryKey(string $operation): string ); } + /** + * @internal The hydrator that an operation builds entities with. + * @return Closure(array): T + */ + public function requireHydrator(string $operation): Closure + { + return $this->hydrate ?? throw new LogicException( + sprintf('%s requires a hydrator; mapping "%s" has none.', $operation, $this->table), + ); + } + public function columnType(string $column): string { if (!array_key_exists($column, $this->columns)) { diff --git a/src/ReadQuery.php b/src/ReadQuery.php index b2b447b..d1e85e2 100644 --- a/src/ReadQuery.php +++ b/src/ReadQuery.php @@ -103,6 +103,7 @@ public function findBy( ?int $limit = null, int $offset = 0, ): array { + $this->mapping->requireHydrator('Reading entities'); $query = $this->executor->selectAll($criteria, $orderBy, $limit, $offset); if ($this->loads->nodes === []) { return $limit === 0 ? [] : $this->executor->entities($query); @@ -206,7 +207,9 @@ public function rows( * express. It selects nothing: add the SELECT and any joins, grouping or order, naming this * table by the alias. Add conditions with andWhere(), never where(): where() replaces the * whole WHERE clause and silently drops the criteria and the soft-delete condition. Values - * are bound as named parameters, so bind further values with createNamedParameter(). Its rows + * are bound as named parameters, so bind further values with createNamedParameter(). An IN + * list is one ArrayParameterType parameter that DBAL expands when it runs the statement, so + * run the builder itself or pass getParameterTypes() along with getParameters(). Its rows * are not converted through the mapping. * * @param string $alias A lowercase SQL identifier, so that unquoted references match it on every platform. @@ -238,6 +241,7 @@ public function iterateById(array|Filter $criteria = [], int $batchSize = 500): if ($batchSize < 1) { throw new InvalidArgumentException('Batch size must be greater than zero.'); } + $this->mapping->requireHydrator('Reading entities'); $key = $this->mapping->primaryKey; if ($key === null || $this->executor->mapper()->keyType() !== KeyType::Integer) { throw new InvalidArgumentException('Keyset iteration requires an integer primary key.'); @@ -245,7 +249,7 @@ public function iterateById(array|Filter $criteria = [], int $batchSize = 500): $query = $this->executor->selectAll($criteria, [$key => 'ASC'], $batchSize); // Later batches bind one more parameter: the key to continue after. - $this->db->assertParameters(count($query->getParameters()) + 1); + $this->db->assertParameters(Database::boundCount($query) + 1); $loader = new RelationLoader($this->db); $loads = $loader->prepare($this->mapping, $this->loads, $this->executor->locale()); diff --git a/tests/Core/PredicateCompilerTest.php b/tests/Core/PredicateCompilerTest.php index 189e631..cd3542b 100644 --- a/tests/Core/PredicateCompilerTest.php +++ b/tests/Core/PredicateCompilerTest.php @@ -5,6 +5,7 @@ namespace Solo\Repository\Tests\Core; use DateTimeImmutable; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Query\QueryBuilder; @@ -132,7 +133,7 @@ public function testValuesAreBoundAndCannotChangeThePredicate(): void self::assertSame([4], $this->executeIds($builder->where($sql))); } - public function testDbalTypesAreKeptUntilExecutionIncludingEveryInElement(): void + public function testScalarsKeepTheirDbalTypeAndInListsBindAsOneList(): void { $date = new DateTimeImmutable('2026-01-03 12:00:00'); $builder = $this->builder(); @@ -143,17 +144,38 @@ public function testDbalTypesAreKeptUntilExecutionIncludingEveryInElement(): voi ]); self::assertIsString($sql); - self::assertSame($date, array_values($builder->getParameters())[0]); - self::assertSame([ - Types::DATETIME_IMMUTABLE, - Types::INTEGER, - Types::INTEGER, - Types::INTEGER, - Types::BOOLEAN, - ], array_values($builder->getParameterTypes())); + self::assertSame([$date, [3, 4, 5], true], array_values($builder->getParameters())); + self::assertSame( + [Types::DATETIME_IMMUTABLE, ArrayParameterType::INTEGER, Types::BOOLEAN], + array_values($builder->getParameterTypes()), + ); self::assertSame([3, 4], $this->executeIds($builder->where($sql))); } + public function testInListsHoldDatabaseValuesAndBooleanListsBindEveryValue(): void + { + $builder = $this->builder(); + $sql = $this->compiler($builder)->compile([ + 'created_at IN' => [ + new DateTimeImmutable('2026-01-02 12:00:00'), + new DateTimeImmutable('2026-01-04 12:00:00'), + ], + // DBAL has no list type for booleans. + 'enabled NOT IN' => [false], + ]); + + self::assertIsString($sql); + self::assertSame( + [['2026-01-02 12:00:00', '2026-01-04 12:00:00'], false], + array_values($builder->getParameters()), + ); + self::assertSame( + [ArrayParameterType::STRING, Types::BOOLEAN], + array_values($builder->getParameterTypes()), + ); + self::assertSame([4], $this->executeIds($builder->where($sql))); + } + #[DataProvider('invalidCriteria')] public function testInvalidCriteriaAreRejectedBeforeBinding(array|Filter $criteria): void { @@ -321,10 +343,24 @@ public function testParameterLimitIncludesExistingBuilderParameters(): void $sql = $this->compiler($builder)->compile(['id IN' => range(1, 899)]); self::assertIsString($sql); - self::assertCount(900, $builder->getParameters()); + self::assertCount(2, $builder->getParameters()); + self::assertSame(900, Database::boundCount($builder)); self::assertSame([1], $this->executeIds($builder->andWhere($sql))); } + public function testParameterLimitCountsEveryValueOfAnExistingList(): void + { + $builder = $this->builder(); + $builder->setParameter('existing', range(1, 899), ArrayParameterType::INTEGER); + $builder->where('i.id IN (:existing)'); + + self::assertSame(899, Database::boundCount($builder)); + self::assertIsString($this->compiler($builder)->compile(['name' => 'Alpha'])); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('parameter limit'); + $this->compiler($builder)->compile(['id' => 1]); + } + public function testParameterLimitRejectsBeforeAddingAnyBindings(): void { $builder = $this->builder(); diff --git a/tests/Core/RepositoryTest.php b/tests/Core/RepositoryTest.php index 8e92a3d..eec6d0d 100644 --- a/tests/Core/RepositoryTest.php +++ b/tests/Core/RepositoryTest.php @@ -6,6 +6,7 @@ use ArrayObject; use DateTimeImmutable; +use Doctrine\DBAL\ArrayParameterType; use Doctrine\DBAL\Configuration; use Doctrine\DBAL\Connection; use Doctrine\DBAL\DriverManager; @@ -531,9 +532,11 @@ public function testLockForUpdateUsesTheServerRowLockAndSplitsSortedKeySets(): v // Sorting before the split keeps one key order across statements. (new Repository($connection, $this->mapping(), parameterLimit: 2))->lockForUpdate([3, 1, 2]); + // DBAL expands each key list into one placeholder per key when it executes the statement. + $sql = 'SELECT "id" FROM "items" WHERE "id" IN (:dcValue1) ORDER BY "id" FOR UPDATE'; self::assertSame([ - ['SELECT "id" FROM "items" WHERE "id" IN (:dcValue1, :dcValue2) ORDER BY "id" FOR UPDATE', [1, 2]], - ['SELECT "id" FROM "items" WHERE "id" IN (:dcValue1) ORDER BY "id" FOR UPDATE', [3]], + [$sql, [[1, 2]], [ArrayParameterType::INTEGER]], + [$sql, [[3]], [ArrayParameterType::INTEGER]], ], $statements->getArrayCopy()); } @@ -544,10 +547,10 @@ public function testLockForUpdateCapsKeysPerStatementBelowThePlatformBudget(): v // A longer IN list can make MySQL scan, and lock, the whole table. (new Repository($connection, $this->mapping()))->lockForUpdate(range(5001, 1, -1)); - self::assertSame([range(1, 5000), [5001]], array_column($statements->getArrayCopy(), 1)); + self::assertSame([[range(1, 5000)], [[5001]]], array_column($statements->getArrayCopy(), 1)); } - /** @return array{Connection, ArrayObject}>} */ + /** @return array{Connection, ArrayObject, list}>} */ private function lockingConnection(): array { $statements = new ArrayObject(); @@ -559,8 +562,8 @@ private function lockingConnection(): array static fn() => new \Doctrine\DBAL\Query\QueryBuilder($connection), ); $connection->method('executeQuery')->willReturnCallback( - static function (string $query, array $parameters) use ($statements, $result): Result { - $statements[] = [$query, array_values($parameters)]; + static function (string $query, array $parameters, array $types) use ($statements, $result): Result { + $statements[] = [$query, array_values($parameters), array_values($types)]; return $result; }, ); diff --git a/tests/Core/RowsOnlyMappingTest.php b/tests/Core/RowsOnlyMappingTest.php new file mode 100644 index 0000000..31747b4 --- /dev/null +++ b/tests/Core/RowsOnlyMappingTest.php @@ -0,0 +1,192 @@ +logger = new class extends AbstractLogger { + /** @var list */ + public array $queries = []; + + public function log($level, string|Stringable $message, array $context = []): void + { + if (isset($context['sql'])) { + $this->queries[] = $context['sql']; + } + } + }; + $configuration = new Configuration(); + $configuration->setMiddlewares([new Middleware($this->logger)]); + $this->connection = DriverManager::getConnection( + ['driver' => 'pdo_sqlite', 'memory' => true], + $configuration, + ); + $statements = [ + 'CREATE TABLE products (id INTEGER PRIMARY KEY, code TEXT NOT NULL)', + 'CREATE TABLE product_categories (product_id INTEGER NOT NULL, category_id INTEGER NOT NULL, ' + . 'is_primary BOOLEAN NOT NULL, PRIMARY KEY (product_id, category_id))', + "INSERT INTO products VALUES (1, 'chair'), (2, 'table'), (3, 'lamp')", + ]; + foreach ($statements as $sql) { + $this->connection->executeStatement($sql); + } + + $this->links = new Repository($this->connection, self::linkMapping()); + $this->links->insertMany([ + ['product_id' => 1, 'category_id' => 10, 'is_primary' => true], + ['product_id' => 1, 'category_id' => 20, 'is_primary' => false], + ['product_id' => 2, 'category_id' => 20, 'is_primary' => true], + ]); + $this->products = new Repository($this->connection, new Mapping( + 'products', + ['id' => Types::INTEGER, 'code' => Types::STRING], + static fn (array $row): object => (object) $row, + relations: ['categories' => new HasMany( + self::linkMapping(...), + 'product_id', + static function (object $product, array $links): object { + $product->categories = $links; + + return $product; + }, + )], + )); + $this->logger->queries = []; + } + + protected function tearDown(): void + { + $this->connection->close(); + } + + public function testRowsAggregatesQueryBuildersAndWritesNeedNoHydrator(): void + { + self::assertNull(self::linkMapping()->hydrate); + + $read = $this->links->read(); + self::assertSame( + [['category_id' => 10, 'is_primary' => true], ['category_id' => 20, 'is_primary' => false]], + $read->rows(['category_id', 'is_primary'], ['product_id IN' => [1, 3]], ['category_id' => 'ASC']), + ); + self::assertSame(2, $read->count(['category_id' => 20])); + self::assertTrue($read->exists(['product_id' => 2])); + self::assertSame(50, $read->sum('category_id')); + self::assertSame( + [1, 2], + array_map('intval', $read->queryBuilder('pc', ['category_id' => 20]) + ->select('pc.product_id') + ->orderBy('pc.product_id') + ->fetchFirstColumn()), + ); + + self::assertSame(1, $this->links->updateBy(['product_id' => 1, 'category_id' => 20], ['is_primary' => true])); + self::assertSame(1, $this->links->deleteBy(['product_id' => 2])); + self::assertSame( + [['product_id' => 1, 'category_id' => 10], ['product_id' => 1, 'category_id' => 20]], + $read->rows(['product_id', 'category_id'], ['is_primary' => true], ['category_id' => 'ASC']), + ); + } + + public function testOwnersFilterByARelationWhoseTargetHasNoHydrator(): void + { + $products = $this->products->read(); + + self::assertSame([['id' => 1]], $products->rows(['id'], Filter::related('categories', ['category_id' => 10]))); + self::assertSame( + ['chair', 'table'], + array_map( + static fn (object $product): string => $product->code, + $products->findBy(Filter::related('categories'), ['id' => 'ASC']), + ), + ); + } + + #[DataProvider('entityReads')] + public function testEntityReadsRequireAHydratorBeforeSql(Closure $read, string $table, string $operation): void + { + try { + $read($this->links, $this->products, $this->connection); + self::fail('Reading entities must be rejected without a hydrator.'); + } catch (LogicException $exception) { + self::assertSame( + sprintf('%s requires a hydrator; mapping "%s" has none.', $operation, $table), + $exception->getMessage(), + ); + self::assertSame([], $this->logger->queries); + } + } + + public static function entityReads(): iterable + { + $links = 'product_categories'; + yield 'findBy' => [static fn (Repository $rows): mixed => $rows->read()->findBy(), $links, 'Reading entities']; + yield 'findOneBy' => [ + static fn (Repository $rows): mixed => $rows->read()->findOneBy(['product_id' => 1]), + $links, + 'Reading entities', + ]; + yield 'an empty page' => [ + static fn (Repository $rows): mixed => $rows->read()->findBy(limit: 0), + $links, + 'Reading entities', + ]; + yield 'keyset iteration' => [ + static fn (Repository $rows): mixed => $rows->read()->iterateById(), + $links, + 'Reading entities', + ]; + yield 'find by primary key' => [ + static fn (Repository $rows, Repository $products, Connection $connection): mixed => (new Repository( + $connection, + new Mapping('products', ['id' => Types::INTEGER, 'code' => Types::STRING]), + ))->read()->find(1), + 'products', + 'Reading entities', + ]; + yield 'loading a relation' => [ + static fn (Repository $rows, Repository $products): mixed => $products->with(['categories'])->findBy(), + $links, + 'Loading relation "categories"', + ]; + } + + /** @return Mapping */ + private static function linkMapping(): Mapping + { + return new Mapping( + table: 'product_categories', + columns: [ + 'product_id' => Types::INTEGER, + 'category_id' => Types::INTEGER, + 'is_primary' => Types::BOOLEAN, + ], + primaryKey: null, + ); + } +} diff --git a/tests/Database/RepositoryDatabaseTest.php b/tests/Database/RepositoryDatabaseTest.php index 73af660..30e78a1 100644 --- a/tests/Database/RepositoryDatabaseTest.php +++ b/tests/Database/RepositoryDatabaseTest.php @@ -98,6 +98,30 @@ public function testDecimalBooleanDateAndJsonRoundTripAndPatchKeepsOmittedFields self::assertEquals($item->occurred_at, $updated->occurred_at); } + public function testTypedInListsMatchOnTheServer(): void + { + $utc = new DateTimeZone('UTC'); + $dates = [ + new DateTimeImmutable('2026-01-02 03:04:05', $utc), + new DateTimeImmutable('2026-01-03 03:04:05', $utc), + new DateTimeImmutable('2026-01-04 03:04:05', $utc), + ]; + $this->repository->insertMany([ + ['sku' => 'a', 'amount' => '1.50', 'active' => true, 'occurred_at' => $dates[0]], + ['sku' => 'b', 'amount' => '2.00', 'active' => false, 'occurred_at' => $dates[1]], + ['sku' => 'c', 'amount' => '3.25', 'active' => true, 'occurred_at' => $dates[2]], + ]); + $read = $this->repository->read(); + $skus = static fn (array $criteria): array => array_column( + $read->rows(['sku'], $criteria, ['sku' => 'ASC']), + 'sku', + ); + + self::assertSame(['a', 'c'], $skus(['occurred_at IN' => [$dates[0], $dates[2]]])); + self::assertSame(['b'], $skus(['amount IN' => ['2.00', '9.99']])); + self::assertSame(['a', 'c'], $skus(['sku NOT IN' => ['b', 'z'], 'active IN' => [true]])); + } + public function testSoftDeleteVisibilityRestorePurgeAndFilteredKeyset(): void { $repository = new Repository($this->connection, $this->mapping(true)); diff --git a/tests/Types/PublicApiTypes.php b/tests/Types/PublicApiTypes.php index 5119e8d..fd6e327 100644 --- a/tests/Types/PublicApiTypes.php +++ b/tests/Types/PublicApiTypes.php @@ -116,6 +116,21 @@ function relationsAcceptTypedAssignCallbacks(Connection $connection): void acceptsAnyRepository($repository); } +function mappingsWithoutAHydratorReadRows(Connection $connection): void +{ + $links = new Mapping( + table: 'product_categories', + columns: ['product_id' => Types::INTEGER, 'category_id' => Types::INTEGER], + primaryKey: null, + ); + assertType('Solo\Repository\Mapping', $links); + + $repository = new Repository($connection, $links); + assertType('list>', $repository->read()->rows(['category_id'], ['product_id IN' => [1, 2]])); + + acceptsAnyRepository($repository); +} + function relationsInferTheirOwnerAndTarget(): void { $categories = categoryMapping();