From 973efd0bb22a46f4e3eb9bc088371880b6981d02 Mon Sep 17 00:00:00 2001 From: vitaliyolos Date: Tue, 27 Oct 2026 23:42:02 +0200 Subject: [PATCH] docs: prepare the 1.0.0 release The README keeps what a visitor needs before the documentation: what the package does, installation from Packagist, one example and links to the documentation's sections. The detailed guide is in English like the rest of the documentation, the changelog has one dated 1.0.0 entry, and the license and the site footer carry 2026, the year the package started. Solo Repository stands on its own: the guide and the example for moving from another package, and the internal release checklist, are gone, and nothing refers to that package any more. The documentation now deploys to GitHub Pages on every push to main. --- .gitattributes | 2 - .github/workflows/docs.yml | 10 +- .github/workflows/tests.yml | 1 - CHANGELOG.md | 147 ++-------- LICENSE | 2 +- README.md | 112 ++------ RELEASING.md | 75 ------ docs/.vitepress/config.js | 9 +- docs/guide/api.md | 2 +- docs/guide/details.md | 313 ++++++++++----------- docs/guide/index.md | 9 +- docs/guide/migration.md | 522 ------------------------------------ docs/index.md | 8 +- docs/package-lock.json | 4 +- docs/package.json | 2 +- examples/migration.php | 275 ------------------- 16 files changed, 205 insertions(+), 1288 deletions(-) delete mode 100644 RELEASING.md delete mode 100644 docs/guide/migration.md delete mode 100644 examples/migration.php diff --git a/.gitattributes b/.gitattributes index 9871396..8435fc1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,10 +8,8 @@ /phpunit.database.xml export-ignore /phpstan.neon export-ignore /compose.database.yml export-ignore -/RELEASING.md export-ignore /vendor export-ignore /composer.lock export-ignore -/experiments export-ignore /.idea export-ignore /.vscode export-ignore /.phpunit.cache export-ignore diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 17d1435..64ff8ab 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -7,12 +7,6 @@ on: branches: [main] paths: ['docs/**', '.github/workflows/docs.yml'] workflow_dispatch: - inputs: - deploy: - description: Publish documentation to GitHub Pages - type: boolean - default: false - required: false permissions: contents: read @@ -34,12 +28,12 @@ jobs: - run: npm run build working-directory: docs - uses: actions/upload-pages-artifact@v3 - if: github.event_name == 'workflow_dispatch' && inputs.deploy == true && github.ref == 'refs/heads/main' && github.repository == 'SoloPHP/Repository' + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'SoloPHP/Repository' with: path: docs/.vitepress/dist deploy: - if: github.event_name == 'workflow_dispatch' && inputs.deploy == true && github.ref == 'refs/heads/main' && github.repository == 'SoloPHP/Repository' + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && github.repository == 'SoloPHP/Repository' needs: build runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 35f9dc8..e9b3318 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -34,7 +34,6 @@ jobs: - run: php examples/crud.php - run: php examples/translations.php - run: php examples/relations.php - - run: php examples/migration.php database: name: ${{ matrix.database.engine }} / PHP ${{ matrix.runtime.php }} / DBAL ${{ matrix.runtime.dbal }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 876f993..f84a7ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,8 @@ # Changelog -## 1.0.0 — Unreleased +## 1.0.0 — 2026-10-27 -Initial release of **Solo Repository** (`solophp/repository`) with the +First stable release of **Solo Repository** (`solophp/repository`) with the `Solo\Repository` namespace. ### Features @@ -14,6 +14,10 @@ Initial release of **Solo Repository** (`solophp/repository`) with the - Reusable `ReadQuery` with projection reads, `sum`/`min`/`max`/`avg` aggregates over the same criteria as `count`, bounded integer-ID iteration, and `queryBuilder()`, a DBAL `QueryBuilder` over the rows its criteria select. +- Ordering by fields of `BelongsTo` targets through dotted paths such as + `category.name`, in reads, default relation orders and `Load` orders. +- Locking reads with `forUpdate()`, which never return an older version of a + row, next to `lockForUpdate()` row locks. - Mappings without a primary key for tables with composite keys; their rows are read and changed by criteria. A mapping read only as rows needs no hydrator. - `Filter::all`, `any`, `not`, and related `EXISTS` predicates. @@ -27,138 +31,23 @@ Initial release of **Solo Repository** (`solophp/repository`) with the target, with lazy target-`Mapping` factories called once per owner mapping, nested batch loading, locale inheritance, and explicit per-relation visibility and loading criteria. A relation without `assign` can be filtered - by and linked but not loaded. - A `BelongsTo` target shared by many owners is fetched and hydrated once; - `HasMany` and `BelongsToMany` accept a default collection order. + by and linked but not loaded. A `BelongsTo` target shared by many owners is + fetched and hydrated once; `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. IN lists are bound as one DBAL list parameter. -- 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-RC5 - -- The compatibility rules for subclasses of `Repository` are documented. - Throughout 1.x it stays a non-final `readonly` class whose public methods, - except the constructor, are final and whose state is private. A minor release - may add public methods, and a subclass that declares a method of the same - name then fails to load. Constructor parameters keep their names and order; - a parameter added in a minor release is optional and comes last. -- **Behavior change:** `LinkSet::attach()` and `sync()` skip a pair that - another writer stored after the operation read the set, instead of failing - on the pivot's unique key. Their INSERT carries `ON CONFLICT (pair) DO NOTHING` - on PostgreSQL and SQLite and `ON DUPLICATE KEY UPDATE` on MySQL and MariaDB; - foreign-key violations still propagate. Concurrent attaches of one pair now - both succeed on MySQL and on PostgreSQL in READ COMMITTED. MariaDB with - snapshot isolation (error 1020) and PostgreSQL in REPEATABLE READ or - SERIALIZABLE (a serialization failure) still refuse a transaction whose - snapshot is older than the other writer's commit, and an exact final set - still needs an owner lock. On PostgreSQL and SQLite these writes now fail on a - pivot without the UNIQUE pair that the guide already required. -- A locking read on MySQL tells `FOR UPDATE OF` support by the server version, - 8.0.1 or later, instead of by DBAL's `MySQL80Platform`. DBAL deprecates its - MySQL 8 platform classes and drops them with MySQL 5.7 support, after which - `MySQLPlatform` itself stands for MySQL 8; the lock keeps covering only the - read's table there. MySQL 5.7 and MariaDB keep the plain `FOR UPDATE`. The - package no longer refers to a deprecated DBAL platform class. - -### Changes since 1.0.0-RC4 - -- `ReadQuery::forUpdate()` returns the same read as a locking one: `find()`, - `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 - `readonly` class that fixes the mapping in its own constructor, so a - container injects each table's repository by type and static analysis reads - the model from `@extends Repository`. Every public method except the - constructor is final: a subclass adds methods and cannot change the - inherited reads and writes. - -### 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` - with the mapped table under the alias in FROM, the criteria and visibility in - WHERE, and the translation joins the criteria need. It selects nothing; the - caller adds the SELECT, joins and grouping, and adds conditions with - `andWhere()`, because `where()` replaces the criteria and visibility. -- `Mapping::$primaryKey` may be NULL. Operations by ID then throw before SQL, - translations and `HasOne`/`HasMany`/`BelongsToMany` relations of that owner - are rejected, and `BelongsTo`/`BelongsToMany` targets must have a key. -- `Translations::$defaultLocale` is optional. Without it, a read that names no - locale joins no translations and returns NULL translated fields; conditions, - sorts and aggregates on translated fields then throw `LogicException`. -- `TranslationStore::all($id)` returns the translations of every locale of one - owner, keyed by locale in ascending order. -- **Behavior change:** `save()` and `seed()` insert only the given fields into - a new translation row, so omitted fields take their column defaults instead - of NULL. `save()` still keeps the omitted fields of an existing row. -- The `assign` callback of a relation is optional. Loading a relation without - one throws `LogicException` before SQL. -- A relation's target factory runs once per owner mapping instead of on every - load, filter and link set. -- Reads without relation loads hydrate rows directly, every read releases rows - as it goes, relation batches reuse one prepared target read, and - `insertMany()` no longer copies its rows. - -### Migrating from Base Repository - -The original `solophp/base-repository` package keeps its v3 API and version -history. Solo Repository uses composition instead of inheritance, moves reads -to `ReadQuery`, and makes write results and query state explicit. It does not -provide a compatibility adapter or replace the old Composer package. - -See the [migration guide](docs/guide/migration.md) for construction, criteria, -translations, relations, pagination, and transaction changes. +- Soft delete with `purge`/`purgeBy`, native upserts by a unique key, atomic + `insertMany`, and many-to-many `LinkSet` operations that skip a pair another + writer stored first. +- SQLite tests, MySQL 8.4/MariaDB 12.3/PostgreSQL 17 integration tests, and a + PHP/DBAL CI matrix. ### Requirements - PHP ^8.3 and Doctrine DBAL ^4.3, with the appropriate PDO driver. -- One integer or string primary key; relation keys reference primary keys. +- At most one primary key column, integer or string; relation keys reference + primary keys. - Application-managed FK/UNIQUE constraints and compatible key collations. -- Supported test matrix: SQLite, MySQL 8.4, MariaDB 12.3, PostgreSQL 17. Other DBAL - platforms are not included in this release's compatibility claim. +- Supported test matrix: SQLite, MySQL 8.4, MariaDB 12.3, PostgreSQL 17. Other + DBAL platforms are not included in this release's compatibility claim. diff --git a/LICENSE b/LICENSE index 8441e42..80b805a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2025 SoloPHP +Copyright (c) 2026 SoloPHP Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 57c3b92..e0c69d9 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,22 @@ # Solo Repository -Typed PHP repositories with consistent translation fallback and batch-loaded relations. +[![Latest Version on Packagist](https://img.shields.io/packagist/v/solophp/repository.svg)](https://packagist.org/packages/solophp/repository) +[![PHP Version](https://img.shields.io/badge/PHP-8.3%2B-8892BF.svg)](https://php.net/) +[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) -Map tables to your own objects, reuse query settings, and write data explicitly. +Typed PHP repositories on Doctrine DBAL. Map a table to your own objects, read through reusable queries, write explicitly, and get translations with one fallback rule and relations loaded in batches. -## Requirements and installation +## Installation -- PHP **8.3+** and Doctrine DBAL **^4.3**. -- A PDO driver for your database: `pdo_mysql` (MySQL and MariaDB), `pdo_pgsql`, or `pdo_sqlite`. -- Tested server versions: **MySQL 8.4**, **MariaDB 12.3** and **PostgreSQL 17**, plus SQLite. - Other DBAL platforms are not automatically supported. - -Install from the GitHub repository: - -```sh -composer config repositories.solophp-repository vcs https://github.com/SoloPHP/Repository.git -composer require 'solophp/repository:dev-main' +```bash +composer require solophp/repository ``` -## Quick start +Requires PHP 8.3+, Doctrine DBAL ^4.3 and the PDO driver of your database. Tested on MySQL 8.4, MariaDB 12.3, PostgreSQL 17 and SQLite. -The application owns its database schema. This SQLite example creates one in -memory so you can run it after installing the package: +## Example ```php -insertGetId(['sku' => 'CHAIR', 'price' => '49.90']); -$products->update($id, ['price' => '59.90']); // Affected rows; no hidden model read. - -$query = $products->read(); -$product = $query->find($id); // stdClass|null -$page = $query->findBy( - criteria: ['price >=' => '50.00'], - orderBy: ['price' => 'ASC', 'id' => 'ASC'], - limit: 20, - offset: 0, -); - -foreach ($query->iterateById(batchSize: 100) as $product) { - echo $product->sku . PHP_EOL; -} +$products->update($id, ['price' => '59.90']); + +$product = $products->read()->find($id); +$page = $products->read()->findBy(['price >=' => '50.00'], ['price' => 'ASC', 'id' => 'ASC'], limit: 20); ``` -`hydrate` receives DBAL-converted values and can construct your own immutable -model instead. `Mapping` defines every readable and writable field; unknown -fields are rejected. - -## What it provides - -- Reusable `ReadQuery` settings; `withLocale()`, `with()` and `withVisibility()` - 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 - insert-missing seeding through `translations()->seed()`. -- `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, 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 -across repositories, and cache invalidation belong to the application and DBAL. -There is no identity map, lazy loading, automatic cascade save, or change tracking. +`hydrate` receives values already converted by their DBAL types and may build an immutable model of your own. The columns of the mapping are the only fields a read or a write accepts. ## Documentation -- [Getting started](docs/guide/index.md) -- [Public API and contracts](docs/guide/api.md) -- [Migration from Base Repository v3](docs/guide/migration.md) -- [Detailed behavior and database tests](docs/guide/details.md) -- [Runnable catalog with translations and relations](examples/relations.php) -- [Changelog](CHANGELOG.md) and [release verification](RELEASING.md) -- [Base Repository v3 documentation](https://github.com/SoloPHP/Base-Repository/tree/v3.1.0/docs) - -## Development - -```sh -git clone https://github.com/SoloPHP/Repository.git -cd Repository -composer install -composer test -php examples/crud.php -php examples/translations.php -php examples/relations.php -php examples/migration.php -``` +**[Full Documentation](https://solophp.github.io/Repository/)** -`composer test:database` runs the separate MySQL/MariaDB/PostgreSQL suite and requires -`REPOSITORY_DATABASE_URL`. See the [Docker and CI instructions](docs/guide/details.md#проверка-на-mysql-mariadb-и-postgresql). -CI covers PHP 8.3 with the minimum DBAL 4.3 branch and PHP 8.3/8.5 with the latest -compatible DBAL release. +- [Getting Started](https://solophp.github.io/Repository/guide/) +- [Typed Repositories](https://solophp.github.io/Repository/guide/api#typed-repositories) +- [Mapping and Types](https://solophp.github.io/Repository/guide/api#mapping-and-types) +- [Read Queries](https://solophp.github.io/Repository/guide/api#repository-and-read-queries) +- [Criteria and Filter](https://solophp.github.io/Repository/guide/api#criteria-and-filter) +- [Translations](https://solophp.github.io/Repository/guide/api#translation-metadata-and-locale) +- [Relations](https://solophp.github.io/Repository/guide/api#relations-and-load) +- [Writes](https://solophp.github.io/Repository/guide/api#repository-writes) +- [Transactions and DBAL](https://solophp.github.io/Repository/guide/api#transactions-and-the-dbal-escape-hatch) +- [Behavior in Detail](https://solophp.github.io/Repository/guide/details) +- [Changelog](CHANGELOG.md) ## License -[MIT](LICENSE). +MIT. See [LICENSE](LICENSE). diff --git a/RELEASING.md b/RELEASING.md deleted file mode 100644 index a960282..0000000 --- a/RELEASING.md +++ /dev/null @@ -1,75 +0,0 @@ -# Preparing and publishing Solo Repository - -The first planned release is **1.0.0** of `solophp/repository`, with namespace -`Solo\Repository`. The standalone repository is -[SoloPHP/Repository](https://github.com/SoloPHP/Repository), with default branch -`main` and a fresh Git history. Source availability does not imply a tagged -release or publication on Packagist. - -Keep `SoloPHP/Base-Repository`, its remote, tags, and `solophp/base-repository` -package unchanged. Do not merge this new package identity into the old product's -release branch. The new product starts its own release history at 1.0.0. - -Composer derives stable versions from Git tags. Do not add a `version` field to -`composer.json`. The `dev-main` alias `1.0.x-dev` describes development on `main`; -it does not publish a version. The README installs this branch directly from -GitHub through a Composer VCS repository. - -## Verify the release candidate - -1. Review [public API](docs/guide/api.md), [migration guide](docs/guide/migration.md), - and [changelog](CHANGELOG.md) together. Keep method names, named arguments, - return types, fallback rules, and supported platforms consistent. -2. Run `composer validate --strict`, `composer test`, and the runnable examples: - `php examples/crud.php`, `php examples/translations.php`, - `php examples/relations.php`, and `php examples/migration.php`. - `examples/definitions.php` contains definitions used by the catalog demo. -3. Run `composer test:database` on MySQL, MariaDB and PostgreSQL using the - [integration instructions](docs/guide/details.md#проверка-на-mysql-mariadb-и-postgresql). - Before tagging, require the complete CI matrix for the candidate commit in - the new repository: PHP 8.3 / DBAL 4.3.*, PHP 8.3 / current compatible DBAL, - PHP 8.5 / current DBAL, each with SQLite, MySQL 8.4, MariaDB 12.3, and PostgreSQL 17. -4. With Node 24, run `npm ci`, `npm audit`, and `npm run build` in `docs/`. - The workflow validates pull requests and audits all dependencies. Pushes only - run checks. Deployment requires a manual Documentation workflow dispatch - with `deploy: true` on `main` in `SoloPHP/Repository`. -5. Inspect `git archive` or `composer archive`: runtime source, Composer metadata, - README, changelog, and license must be present; tests, examples, CI, Docker - files, and caches must be excluded. Install in a clean consumer with `--no-dev` - and run the README example. Verify the new namespace autoloads, and that the - old package is neither replaced nor provided by the new one. -6. Exercise one real consumer's catalog and export before the first stable tag. - Check pagination, translated filters, empty-string data, hydration types, - FK/UNIQUE constraints, and explicit transaction boundaries. The synthetic - integration suite does not replace migration of an application. - -## Documentation toolchain - -Use Node 24 to match CI; `docs/package.json` requires at least Node 22.12. -VitePress is pinned to **2.0.0-alpha.20**, a prerelease, because the stable 1.x -dependency ranges retain vulnerable Vite/esbuild versions. This uses the -[upstream VitePress 2 dependency graph](https://github.com/vuejs/vitepress/blob/v2.0.0-alpha.20/package.json) -without overrides. The exact pin makes future prerelease upgrades explicit. - -For an upgrade, update both `docs/package.json` and `docs/package-lock.json`, -then run a clean install, the full audit, and the build. Keep dev dependencies -in the audit: the documentation toolchain is declared in `devDependencies`. -Preview the generated site under `/Repository/` and check navigation, local -search, anchors, and the mobile menu after theme upgrades. These Node -dependencies are not included in the PHP package archive. - -## Publish only when explicitly requested - -1. Verify the candidate in this repository. Date the 1.0.0 changelog entry and - update installation and release-status text together. If real consumer - validation is pending, use an explicitly chosen prerelease instead. -2. Create and push the corresponding tag and GitHub release, register the new - Composer package on Packagist, and confirm the indexed name, version, and - source URL. Link the migration guide from the release notes. -3. For documentation publication, enable GitHub Pages in this repository, then - manually run the Documentation workflow on `main` with `deploy` enabled. - Pushes, pull requests, and default manual runs only build and audit the site. - The site base `/Repository/` assumes the new repository's GitHub Pages path. - -The initial source transfer creates no tags, releases, Packagist registration, -or Pages deployment. Each publication step above requires explicit approval. diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index be4cd8e..4a88f3c 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -21,8 +21,8 @@ export default defineConfig({ nav: [ { text: 'Guide', link: '/guide/' }, { text: 'API', link: '/guide/api' }, - { text: 'Migration', link: '/guide/migration' }, - { text: 'Details (RU)', link: '/guide/details' }, + { text: 'Details', link: '/guide/details' }, + { text: 'v1.0.0', link: 'https://github.com/SoloPHP/Repository/releases' }, ], sidebar: [ @@ -31,8 +31,7 @@ export default defineConfig({ items: [ { text: 'Getting started', link: '/guide/' }, { text: 'API reference', link: '/guide/api' }, - { text: 'Migration from Base Repository v3', link: '/guide/migration' }, - { text: 'Detailed guide (Russian)', link: '/guide/details' }, + { text: 'Behavior in detail', link: '/guide/details' }, ], }, ], @@ -43,7 +42,7 @@ export default defineConfig({ footer: { message: 'MIT licensed.', - copyright: `Copyright © 2025-${new Date().getFullYear()} SoloPHP`, + copyright: 'Copyright © 2026 SoloPHP', }, editLink: { diff --git a/docs/guide/api.md b/docs/guide/api.md index 4c0c714..ba79299 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -4,7 +4,7 @@ This reference describes Solo Repository 1.0: PHP 8.3+, Doctrine DBAL `^4.3`, an `Repository`, `Mapping` and `ReadQuery` use PHPDoc generics, where `T` is an object. `T` is covariant, so `Repository` is accepted where `Repository` is expected. Relation definitions are generic over their owner and target models, so static analysis checks every `assign` callback against the target mapping. The runtime checks that hydration and relation assignment return objects; it does not enforce their concrete class. `Mapping`, `ReadQuery`, the configuration objects and the write helpers are `final readonly`; `Repository` is `readonly` and may be extended into a [typed repository](#typed-repositories). Readonly configuration does not make the shared DBAL connection, returned models or objects captured by callbacks immutable. -The public API consists of the types and methods documented below. The `Internal` namespace and members marked `@internal` are implementation details without a semantic-versioning compatibility promise: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (obtain them from a `Repository`), the properties of `Filter`, and `Relations\Relation::resolve()`. The abstract `Relation` base is not an extension point: use the four supplied final definitions. `Repository` may be extended under the compatibility rules of [typed repositories](#typed-repositories). The legacy `BaseRepository`, `RepositoryInterface` and singular `Relation` namespace belong to the separate `solophp/base-repository` package; see the [migration guide](migration.md). +The public API consists of the types and methods documented below. The `Internal` namespace and members marked `@internal` are implementation details without a semantic-versioning compatibility promise: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (obtain them from a `Repository`), the properties of `Filter`, and `Relations\Relation::resolve()`. The abstract `Relation` base is not an extension point: use the four supplied final definitions. `Repository` may be extended under the compatibility rules of [typed repositories](#typed-repositories). ## A minimal repository diff --git a/docs/guide/details.md b/docs/guide/details.md index 5dc3720..63ef48a 100644 --- a/docs/guide/details.md +++ b/docs/guide/details.md @@ -1,10 +1,10 @@ -# Руководство Solo Repository +# Behavior in detail -Solo Repository предоставляет типизированное чтение, явную запись, переводы с единым fallback и пакетную загрузку связей. [Быстрый старт](index.md) показывает подключение, [публичный API](api.md) описывает контракты. Для приложения на `solophp/base-repository` v3 есть [руководство по миграции](migration.md). +Solo Repository provides typed reads, explicit writes, translations with one fallback rule and batch-loaded relations. [Getting started](index.md) shows the setup, and the [public API](api.md) describes the contracts. This page explains how the pieces behave and how the package is tested. -## Реализовано +## What is included -Доступны `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 в памяти: +`Mapping`, `Repository`, `ReadQuery`, `Filter::all/any/not/related`, `Visibility`, `Translations`, `TranslationStore`, four relation types, `Load` and `LinkSet`. Reads of models and projections, ordering by fields of `BelongsTo` targets, locking reads, count/exists, CRUD, atomic `insertMany`, native upserts by a unique key, soft delete, batched iteration by ID, translations with one fallback rule and batch loading of nested relations. The runnable examples `examples/crud.php`, `examples/translations.php` and `examples/relations.php` use in-memory SQLite: ```sh composer install @@ -15,73 +15,75 @@ vendor/bin/phpunit --testsuite Core composer test ``` -`Mapping` принимает `translations` и `relations`. `withLocale()`, `with()` и `withVisibility()` возвращают независимые настройки чтения. `translations()` и `links()` дают отдельный API записи. Сценарии каталога и экспорта входят в интеграционные тесты. +`Mapping` takes `translations` and `relations`. `withLocale()`, `with()` and `withVisibility()` return independent read settings. `translations()` and `links()` give a separate write API. Catalog and export scenarios are part of the integration tests. -Бюджет связанных параметров statement включает locale-параметры JOIN; keyset оставляет один из них для продолжения. По умолчанию это лимит платформы: 65 535 для PostgreSQL и MySQL/MariaDB, 32 766 для SQLite 3.32+, 900 для более старого SQLite и прочих платформ. Аргумент `parameterLimit` конструктора `Repository` задаёт другой положительный бюджет, например чтобы раньше отклонять большие IN-фильтры корня. Значение не должно превышать лимит сервера; повышать его стоит только на платформе, чей реальный лимит выше значения по умолчанию. Внутренние списки ключей (загрузка связей, `lockForUpdate()`, удаление в `LinkSet`) дополнительно ограничены 5 000 ключей на statement: более длинный IN-список может превысить память range optimizer MySQL и превратить поиск по индексу в полный скан. Создание репозиториев и запросов не открывает соединение: платформа определяется при построении первого statement. Имя таблицы пока простое, без schema-prefix. ID целочисленного PK принимается как int или каноническая десятичная строка: нечисловые значения и переполнение PHP integer для integer/smallint отклоняются. Это исключает превращение ошибочного ID в чужой числовой ключ. Значения критериев проверяются по типу поля по тому же принципу: integer-поле принимает int или каноническую десятичную строку; decimal — конечное число или десятичную строку без экспоненты; float — конечное число или числовую строку с конечным значением; boolean — `bool`, `0` или `1` (в том числе строкой); строковые поля — строку, целое или `Stringable`; enum — строку или `Stringable` (целое MySQL читает как номер элемента); `simple_array` — массив. Иначе драйвер молча превратил бы `'12x'` в 12, а MySQL — `'false'` в TRUE. Даты, интервалы и bcmath-числа проверяет сам DBAL; JSON, бинарные и пользовательские типы получают значение как есть. Проверяется форма значения, а не диапазон, точность или масштаб колонки: это остаётся ограничением базы. Например, SQLite хранит decimal как REAL, и слишком большое значение становится там бесконечностью. +The bound-parameter budget of a statement includes the locale parameters of its JOINs; keyset iteration keeps one of them for the continuation. By default it is the platform limit: 65,535 for PostgreSQL and MySQL/MariaDB, 32,766 for SQLite 3.32+, 900 for older SQLite and other platforms. The `parameterLimit` argument of the `Repository` constructor sets another positive budget, for example to reject large root IN filters earlier. The value must not exceed the server's limit; raise it only on a platform whose real limit is above the default. Internal key lists (relation loads, `lockForUpdate()`, deletes in `LinkSet`) are additionally capped at 5,000 keys per statement: a longer IN list can exceed the memory of MySQL's range optimizer and turn an index lookup into a full scan. Creating repositories and queries does not open a connection: the platform is detected when the first statement is built. A table name is a plain name, without a schema prefix. -Основной набор тестов использует SQLite. Отдельный набор `Database` выполняется на реальных MySQL 8.4, MariaDB 12.3 и PostgreSQL 17 с native PDO prepares. Он запускается отдельно от `composer test`: отсутствие URL, недоступная БД и пропущенные тесты считаются ошибками. +An ID of an integer primary key is accepted as an int or a canonical decimal string: non-numeric values and PHP integer overflow for integer/smallint are rejected, so a wrong ID cannot turn into someone else's numeric key. Criteria values are checked against the field type the same way: an integer field takes an int or a canonical decimal string; decimal a finite number or a decimal string without an exponent; float a finite number or a numeric string with a finite value; boolean `bool`, `0` or `1` (also as a string); string fields a string, an integer or a `Stringable`; enum a string or a `Stringable` (MySQL reads an integer as the element number); `simple_array` an array. Otherwise the driver would silently turn `'12x'` into 12, and MySQL `'false'` into TRUE. Dates, intervals and bcmath numbers are checked by DBAL itself; JSON, binary and custom types get the value as is. The form of a value is checked, not the range, precision or scale of the column: that stays a database constraint. SQLite, for example, stores decimal as REAL, and a value that is too large becomes infinity there. -Solo Repository превращает строки БД в обычные PHP-объекты, разрешает переводы с fallback и загружает связи пакетами. Doctrine DBAL остаётся SQL API. Пакет не отслеживает изменения объектов и не сохраняет граф автоматически. +The main test suite uses SQLite. A separate `Database` suite runs on real MySQL 8.4, MariaDB 12.3 and PostgreSQL 17 with native PDO prepares. It runs apart from `composer test`: a missing URL, an unreachable database and skipped tests count as failures. -## Проверка на MySQL, MariaDB и PostgreSQL +Solo Repository turns database rows into ordinary PHP objects, resolves translations with fallback and loads relations in batches. Doctrine DBAL stays the SQL API. The package does not track changes of objects and does not save object graphs automatically. -Общий набор из 39 тестов проверяет generated ID и CRUD, преобразование decimal/bool/date/JSON, soft delete и keyset, native upsert строк и PATCH upsert переводов, единый fallback, четыре типа связей, вложенные EXISTS и сортировку по путям `BelongsTo`. Блокирующее чтение проверяется второй сессией: какие строки держит блокировка и чем такое чтение отличается от снимка транзакции REPEATABLE READ на каждой СУБД. Вторая сессия также сохраняет пару между чтением и вставкой `attach()`: на уровне изоляции сервера и на REPEATABLE READ проверяется, где конфликт пропускается, а где транзакция отклоняется. Отдельные сценарии проверяют пакетные границы, запрос с максимальным для сервера числом параметров (65 535), сортировку коллекции из 905 элементов, освобождение предыдущей страницы, строковые ключи и native PostgreSQL UUID, rollback позднего пакета и продолжение внешней транзакции после savepoint. Схемы содержат настоящие FK и UNIQUE; тесты выполняют SQL на серверах без моков платформ. +## Testing on MySQL, MariaDB and PostgreSQL -`.github/workflows/tests.yml` сохраняет три задания основного SQLite-набора и запускает `Database` на каждой из трёх СУБД для тех же комбинаций: +The shared suite checks generated IDs and CRUD, decimal/bool/date/JSON conversion, soft delete and keyset iteration, native row upserts and PATCH upserts of translations, the single fallback rule, four relation types, nested EXISTS and ordering by `BelongsTo` paths. Locking reads are checked with a second session: which rows the lock holds and how such a read differs from the snapshot of a REPEATABLE READ transaction on each database. A second session also stores a pair between the read and the insert of `attach()`: at the server's isolation level and at REPEATABLE READ the suite checks where the conflict is skipped and where the transaction is refused. Separate scenarios check batch boundaries, a statement with the server's maximum number of parameters (65,535), ordering of a 905-item collection, release of the previous page, string keys and native PostgreSQL UUIDs, rollback of a late batch and continuation of an outer transaction after a savepoint. The schemas have real FK and UNIQUE constraints; the tests run SQL on the servers without platform mocks. -| PHP | Ограничение DBAL при установке | +`.github/workflows/tests.yml` keeps three jobs of the main SQLite suite and runs `Database` on each of the three databases for the same combinations: + +| PHP | DBAL constraint at install | |---|---| -| 8.3 | `4.3.*` — минимальная поддерживаемая ветка | -| 8.3 | `^4.3` — актуальная совместимая версия | -| 8.5 | `^4.3` — актуальная совместимая версия | +| 8.3 | `4.3.*`, the minimum supported branch | +| 8.3 | `^4.3`, the latest compatible release | +| 8.5 | `^4.3`, the latest compatible release | -Для своей тестовой БД нужен `REPOSITORY_DATABASE_URL` и соответствующее расширение `pdo_mysql` или `pdo_pgsql`. Поддерживаются URL `mysql://` (MySQL и MariaDB) и `postgresql://`; имя БД должно заканчиваться на `_test`. Набор создаёт и удаляет свои fixture-таблицы с префиксом `repo_`, поэтому ему нужна отдельная тестовая БД: +Your own test database needs `REPOSITORY_DATABASE_URL` and the matching `pdo_mysql` or `pdo_pgsql` extension. `mysql://` (MySQL and MariaDB) and `postgresql://` URLs are supported; the database name must end in `_test`. The suite creates and drops its own fixture tables with the `repo_` prefix, so it needs a dedicated test database: ```sh REPOSITORY_DATABASE_URL='mysql://repository:repository@127.0.0.1:3306/repository_test' composer test:database REPOSITORY_DATABASE_URL='postgresql://repository:repository@127.0.0.1:5432/repository_test' composer test:database ``` -Локально достаточно Docker с Compose v2. `compose.database.yml` создаёт проект `solo-repository-database`, MySQL 8.4, MariaDB 12.3, PostgreSQL 17 и PHP runner. Порты на хост не публикуются, данные всех БД находятся в tmpfs. Runner монтирует репозиторий только для чтения; зависимости устанавливаются отдельной командой до запуска тестов: +Locally, Docker with Compose v2 is enough. `compose.database.yml` creates the `solo-repository-database` project with MySQL 8.4, MariaDB 12.3, PostgreSQL 17 and a PHP runner. No ports are published to the host, and the data of all databases lives in tmpfs. The runner mounts the repository read-only; dependencies are installed by a separate command before the tests run: ```sh docker compose -f compose.database.yml build tests docker run --rm -v "$PWD":/workspace -w /workspace \ solo-repository-database-tests:local composer install --no-interaction --prefer-dist -# MySQL — URL по умолчанию. +# MySQL: the default URL. docker compose -f compose.database.yml run --rm tests -# MariaDB и PostgreSQL — тот же набор, другой URL. +# MariaDB and PostgreSQL: the same suite, another URL. REPOSITORY_DATABASE_URL='mysql://repository:repository@mariadb:3306/repository_test' \ docker compose -f compose.database.yml run --rm tests REPOSITORY_DATABASE_URL='postgresql://repository:repository@postgres:5432/repository_test' \ docker compose -f compose.database.yml run --rm tests -# Удалить контейнеры, сеть и временные данные. +# Remove the containers, the network and the temporary data. 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`. После такой проверки верните нужную версию зависимостей. +Compose waits for the health checks of all three databases. The runner's command is `php vendor/bin/phpunit -c phpunit.database.xml --do-not-cache-result`; connection errors are not turned into skips. Pass `PHP_VERSION=8.5` at build time to pick the PHP version. To check the minimum DBAL branch locally, run `composer update --with='doctrine/dbal:4.3.*'` in the same runner instead of `composer install`; this changes the local `composer.lock` and `vendor`, so restore the dependencies you need afterwards. -MySQL 8.4, MariaDB 12.3 и PostgreSQL 17 — проверяемые серверные платформы Solo Repository. MariaDB использует те же ветки кода, что и MySQL (generated ID, upsert строк и переводов); в блокирующем чтении у неё нет `FOR UPDATE OF`. Другие платформы не поддерживаются. +MySQL 8.4, MariaDB 12.3 and PostgreSQL 17 are the verified server platforms. MariaDB uses the same code paths as MySQL (generated IDs, upserts of rows and translations); its locking reads have no `FOR UPDATE OF`. Other platforms are not supported. -## Основные решения +## Design decisions -| Область | Решение | +| Area | Decision | |---|---| -| Основа | PHP ≥ 8.3, Doctrine DBAL 4.x с исходным минимумом 4.3. Без новых runtime-зависимостей | -| Модель | Любой объект; явная функция `hydrate(array): object`. Базовый `Entity` и reflection не нужны | -| Конфигурация | Один неизменяемый `Mapping`: таблица, типы колонок, ключ, mapper и необязательные возможности | -| Чтение | `Repository` создаёт независимый `ReadQuery`; `withLocale()` и `with()` сохраняются | -| Запись | Явные операции над данными; результат — affected rows либо явно запрошенный ID. Автоматического перечитывания модели нет | -| Переводы | Один resolver для значения в SELECT, фильтре и сортировке; fallback по каждому полю | -| Связи | Явные определения и функции присвоения; пакетная загрузка вместо запросов из объектов | -| Сложный SQL | Настоящий DBAL `QueryBuilder`: `ReadQuery::queryBuilder()` с критериями Mapping либо через уже имеющийся `Connection` | +| Foundation | PHP ≥ 8.3, Doctrine DBAL 4.x with 4.3 as the minimum. No other runtime dependencies | +| Model | Any object, built by an explicit `hydrate(array): object` function. No base `Entity`, no reflection | +| Configuration | One immutable `Mapping`: table, column types, key, hydrator and optional features | +| Reads | `Repository` creates an independent `ReadQuery`; `withLocale()` and `with()` settings are kept | +| Writes | Explicit operations on data; the result is affected rows or an explicitly requested ID. No automatic re-read of the model | +| Translations | One resolver for the value in SELECT, filters and sorting; fallback per field | +| Relations | Explicit definitions and assign functions; batch loading instead of queries from objects | +| Complex SQL | A real DBAL `QueryBuilder`: `ReadQuery::queryBuilder()` with the mapping's criteria, or the application's own `Connection` | -Не входят в 1.0: Unit of Work, identity map, lazy proxies, dirty tracking, каскадное сохранение графа, генерация схемы, query cache, event bus, advisory locks, собственный контейнер и отдельные Composer-пакеты. Приложение определяет бизнес-операции, транзакции между несколькими репозиториями и правила повторных попыток. +Not part of 1.0: unit of work, identity map, lazy proxies, dirty tracking, cascading graph saves, schema generation, query cache, event bus, advisory locks, a container of its own and separate Composer packages. The application defines business operations, transactions across several repositories and retry rules. -## Устройство +## Structure ```text Repository ── Mapping + Connection @@ -95,57 +97,57 @@ Repository ── Mapping + Connection └── links(name) → LinkSet ``` -Публичные типы: `Repository`, `Mapping`, `ReadQuery`, `Filter`, `Visibility`, `Load`, `Translations`, четыре определения связей, `TranslationStore` и `LinkSet`. Тип `T` задаётся PHPDoc generics для статического анализа и ковариантен; определения связей параметризованы владельцем и целью, поэтому анализатор проверяет `assign` по Mapping цели. Runtime проверяет, что mapper и assign возвращают объект. Namespace `Internal` и элементы с `@internal` не являются поддерживаемым API приложения: конструкторы `ReadQuery`, `LinkSet` и `TranslationStore` (их получают из `Repository`), свойства `Filter` и `Relation::resolve()`. +Public types: `Repository`, `Mapping`, `ReadQuery`, `Filter`, `Visibility`, `Load`, `Translations`, four relation definitions, `TranslationStore` and `LinkSet`. The type `T` is given by PHPDoc generics for static analysis and is covariant; relation definitions are generic over owner and target, so the analyser checks `assign` against the target's mapping. At runtime the package checks that the hydrator and `assign` return an object. The `Internal` namespace and members marked `@internal` are not a supported application API: the constructors of `ReadQuery`, `LinkSet` and `TranslationStore` (they come from `Repository`), the properties of `Filter` and `Relation::resolve()`. -Внутри достаточно небольших компонентов по ответственности: +Inside, a few small components each own one responsibility: -- `Database`: соединение плюс сведения о платформе (диалект, лимит параметров, экранирование), получаемые лениво. -- `ReadExecutor`: создаёт новый DBAL builder для каждого выполнения. -- `PredicateCompiler`: проверяет фильтры целиком, сворачивает константы в типизированное дерево условий и переводит его в выражения и параметры DBAL. -- `FieldResolver`: проверяет колонку и возвращает обычное либо локализованное SQL-выражение. -- `RowMapper`: применяет типы DBAL и вызывает пользовательский mapper. -- `RelationLoader`: группирует строки, пакетно получает связи и вызывает `assign`. -- `Repository`, `TranslationStore` и `LinkSet`: явные операции записи, включая узкие платформенные варианты upsert и получения generated ID. +- `Database`: the connection plus platform facts (dialect, parameter limit, quoting), resolved lazily. +- `ReadExecutor`: creates a new DBAL builder for every execution. +- `PredicateCompiler`: validates filters as a whole, folds constants into a typed tree of conditions and renders it into DBAL expressions and parameters. +- `FieldResolver`: checks a column and returns a plain or a localized SQL expression. +- `RowMapper`: applies DBAL types and calls the hydrator. +- `RelationLoader`: groups rows, loads relations in batches and calls `assign`. +- `Repository`, `TranslationStore` and `LinkSet`: explicit write operations, including the narrow platform variants of upserts and generated IDs. -У пакета нет собственного общего 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()` вызывает ошибку. +The package has no SQL AST of its own, no dialect engine and no public `select/from/join/groupBy/having` methods. For such queries the application uses DBAL directly. To keep the mapping's criteria in such SQL, `ReadQuery::queryBuilder($alias, $criteria)` returns a DBAL `QueryBuilder` with the table under the alias in FROM, the criteria and visibility in WHERE, and the translation JOINs the criteria need in the query's locale. It has no SELECT: the application adds it, along with joins, grouping and sorting. Add your own conditions with `andWhere()`, not `where()`: `where()` in DBAL replaces the whole WHERE clause, and the criteria and soft delete would silently disappear. The alias is a lowercase SQL identifier, so that unquoted references such as `s.product_id` match it on every platform; translation JOINs are named `_translation` and `_fallback`. Criteria values are bound as named parameters, so bind your own values with `createNamedParameter()` too. An `IN` list is one `ArrayParameterType` parameter that DBAL expands at execution, so run the builder's SQL through the builder itself or together with `getParameterTypes()`. Everything the application adds is plain DBAL: joined tables get no visibility or locale, and result rows are not converted by the mapping's types. A non-empty `with()` is an error. -## Mapping и модели +## Mapping and models -`Mapping` содержит `table`, `columns`, `hydrate`, `primaryKey = 'id'` (NULL для таблицы без одноколоночного ключа), `generatedId = true`, а также необязательные `translations`, `relations` и `softDeleteColumn`. +`Mapping` holds `table`, `columns`, `hydrate`, `primaryKey = 'id'` (NULL for a table without a single-column key), `generatedId = true`, and the optional `translations`, `relations` and `softDeleteColumn`. -`hydrate` может быть NULL у таблицы, которую читают только строками, например у таблицы связей без своей модели. Для неё работают `rows()`, агрегаты, `queryBuilder()`, связанные фильтры и запись, а `find()`, `findOneBy()`, `findBy()`, `iterateById()` и загрузка её как цели связи бросают `LogicException` до SQL. +`hydrate` may be NULL for a table that is read only as rows, such as a link table without a model of its own. `rows()`, aggregates, `queryBuilder()`, related filters and writes work for it, while `find()`, `findOneBy()`, `findBy()`, `iterateById()` and loading it as a relation target throw `LogicException` before SQL. -`columns` — ассоциативный массив `имя_колонки => DBAL type name`. Эти имена используются в фильтрах, сортировке, записи и строковых результатах. Это одновременно allowlist: неизвестное поле вызывает ошибку до SQL. CamelCase, приватные свойства и конструкторы остаются задачей mapper. SQL-идентификаторы проверяются и экранируются средствами DBAL; значения всегда передаются параметрами. +`columns` is an associative array of `column_name => DBAL type name`. These names are used in filters, sorting, writes and row results. It is also an allowlist: an unknown field is an error before SQL. camelCase, private properties and constructors stay the hydrator's job. SQL identifiers are validated and quoted by DBAL; values are always bound as parameters. -Поддерживается один первичный ключ `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 у такой таблицы нет, а вставляемая строка содержит хотя бы одну колонку. +One `int|string` primary key is supported, or none. `primaryKey: null` describes a table without a single-column key, for example with a composite key: its rows are read, inserted and changed by criteria (`findBy`, `rows`, `count`, aggregates, `queryBuilder`, `insert`, `insertMany`, `updateBy`, `deleteBy`, `purgeBy`). Operations by ID (`find`, `insertGetId`, `update`, `delete`, `restore`, `purge`, `lockForUpdate`) throw `LogicException`, and `iterateById` throws `InvalidArgumentException`, all before SQL. Such a table has no generated ID, and an inserted row has at least one column. -Без первичного ключа нет переводов, а из связей возможен только `BelongsTo`: `HasOne`, `HasMany` и `BelongsToMany` находят владельца по его ключу. Такую таблицу могут загружать `HasOne` и `HasMany`, но не `BelongsTo` и `BelongsToMany`, которые ссылаются на ключ цели. `Filter::related` по её `BelongsTo` работает с любым типом ключа, а загрузка требует целочисленного ключа цели: строковые ключи сравниваются по collation базы в SQL через первичный ключ владельца. Адресация строки по составному ключу и связи по альтернативным уникальным ключам остаются за границами 1.0. Mapper получает все объявленные основные и переведённые колонки, а не `SELECT *`. +Without a primary key there are no translations, and the only possible relation is `BelongsTo`: `HasOne`, `HasMany` and `BelongsToMany` find their owner by its key. `HasOne` and `HasMany` can load such a table, but `BelongsTo` and `BelongsToMany` cannot, since they reference the target's key. `Filter::related` through its `BelongsTo` works with any key type, while loading needs an integer target key: string keys are compared in SQL by the database collation, through the owner's primary key. Addressing a row by a composite key and relations over alternative unique keys are outside 1.0. The hydrator gets every declared base and translated column, not `SELECT *`. -Заданный PK обязательно входит в `columns`; FK связи входит в `columns` соответствующей стороны. `generatedId: true` допустим только для совместимого целочисленного PK. Собственный Mapping проверяется сразу, требования к ленивой целевой стороне — при первом разрешении связи. +A given primary key must be part of `columns`; a relation's foreign key is part of the `columns` of its side. `generatedId: true` is allowed only for a compatible integer primary key. A mapping is validated at once; the requirements on a lazy target side are checked when the relation is first resolved. -После чтения типы преобразуются через DBAL перед вызовом `hydrate`. Например, `decimal` остаётся строкой, а `datetime_immutable` становится `DateTimeImmutable`. На запись и в сравнения DBAL получает имя типа и выполняет преобразование один раз. Список `IN` после проверки каждого элемента преобразуется типом поля в значения БД и связывается одним параметром-списком DBAL, который DBAL разворачивает при выполнении; тип без списочного связывания, например boolean, связывает каждый элемент отдельно. В бюджет параметров список входит каждым значением. Пользовательские типы регистрируются в DBAL; второй реестр codecs не создаётся. Типы, требующие специальных SQL-обёрток, в первый контракт не входят. +After a read, values are converted by DBAL before `hydrate` is called. `decimal`, for example, stays a string, and `datetime_immutable` becomes a `DateTimeImmutable`. For writes and comparisons, DBAL gets the type name and converts the value once. An `IN` list, after each element is checked, is converted by the field type into database values and bound as one DBAL list parameter, which DBAL expands at execution; a type without a list binding, such as boolean, binds each element separately. Every value of a list counts toward the parameter budget. Custom types are registered in DBAL; there is no second registry of codecs. Types that need special SQL wrappers are not part of the first contract. -Для загрузки связей ключи сохраняются из **преобразованных строк**, до `hydrate`. Loader не читает `$model->id` или `$model->category_id`. Типы связанных ключей должны быть совместимы. Для строковых ключей FK и соответствующий PK должны использовать одинаковые правила сравнения (collation). Фабрика `target` возвращает Mapping цели и вызывается отложенно, что допускает циклическую конфигурацию; отдельный registry не нужен. Связанные строки читаются через соединение репозитория владельца. +For relation loads, keys are taken from the **converted rows**, before `hydrate`. The loader does not read `$model->id` or `$model->category_id`. Related key types must be compatible. For string keys, the foreign key and its primary key must use the same comparison rules (collation). The `target` factory returns the target's mapping and is called lazily, which allows cyclic configuration without a separate registry. Related rows are read through the owner repository's connection. -## Публичное чтение +## Reads -У `Repository` три точки входа в чтение: +`Repository` has three entry points for reads: ```php -read(): ReadQuery; // настройки по умолчанию +read(): ReadQuery; // default settings withLocale(string $locale, ?string $fallback = null): ReadQuery; with(array $relations): ReadQuery; // list ``` -Последние две — короткие формы `read()->withLocale(...)` и `read()->with(...)`. Обычное чтение выглядит как `$products->read()->find($id)`. Бизнес-методы приложения живут в сервисе, который владеет репозиторием, или в типизированном наследнике `Repository`: `readonly`-класс задаёт маппинг в своём конструкторе, контейнер внедряет его по типу, а статический анализ берёт модель из `@extends Repository`. Публичные методы `Repository` final — наследник добавляет свои методы, но не меняет унаследованные чтения и записи. +The last two are short forms of `read()->withLocale(...)` and `read()->with(...)`. A plain read looks like `$products->read()->find($id)`. The application's business methods live in a service that owns the repository, or in a typed subclass of `Repository`: a `readonly` class fixes the mapping in its constructor, a container injects it by type, and static analysis takes the model from `@extends Repository`. The public methods of `Repository` are final: a subclass adds methods of its own but does not change the inherited reads and writes. -Контракт `ReadQuery`: +The `ReadQuery` contract: ```php withLocale(string $locale, ?string $fallback = null): self; with(array $relations): self; // list withVisibility(Visibility $visibility): self; -forUpdate(): self; // блокирующее чтение +forUpdate(): self; // locking read find(int|string $id): ?object; // T|null findOneBy(array|Filter $criteria, array $orderBy = []): ?object; @@ -157,8 +159,8 @@ findBy( ): array; // list exists(array|Filter $criteria = []): bool; count(array|Filter $criteria = []): int; -sum(string $field, array|Filter $criteria = []): mixed; // 0 своего типа, если строк нет -min(string $field, array|Filter $criteria = []): mixed; // NULL, если строк нет +sum(string $field, array|Filter $criteria = []): mixed; // zero of its type when no rows match +min(string $field, array|Filter $criteria = []): mixed; // NULL when no rows match max(string $field, array|Filter $criteria = []): mixed; avg(string $field, array|Filter $criteria = []): ?float; rows( @@ -172,33 +174,33 @@ iterateById(array|Filter $criteria = [], int $batchSize = 500): iterable; queryBuilder(string $alias, array|Filter $criteria = []): QueryBuilder; ``` -Каждый `with*` возвращает новый объект. Terminal-методы не сбрасывают настройки: запрос можно повторять и независимо разветвлять. `with()` заменяет весь список загрузок, `with([])` очищает его. DBAL builder никогда не хранится как разделяемое изменяемое состояние. +Every `with*` returns a new object. Terminal methods do not reset the settings: a query can be repeated and branched independently. `with()` replaces the whole list of loads, and `with([])` clears it. A DBAL builder is never kept as shared mutable state. -`find` и `findOneBy` ограничивают SQL одной строкой. `exists` запрашивает константу с LIMIT 1. `count` считает корневые записи; загрузки `with()` на эти две операции не влияют. Ни один из этих методов не делает дополнительный COUNT для пагинации. +`find` and `findOneBy` limit the SQL to one row. `exists` selects a constant with LIMIT 1. `count` counts root rows; `with()` loads do not affect these two operations. None of these methods runs an extra COUNT for pagination. -`sum`, `min`, `max` и `avg` агрегируют одно читаемое поле (в том числе переводимое — с locale запроса) по тем же строкам, что считает `count`: те же критерии, relation predicates и видимость. Итог для отфильтрованного списка совпадает с его фильтром. `sum`, `min` и `max` преобразуют результат DBAL-типом поля: сумма decimal — точная строка, `max('created_at')` — `DateTimeImmutable`. Без подходящих строк `sum` возвращает ноль типа поля, остальные — NULL. `sum` и `avg` принимают только поля smallint, integer, bigint, decimal, float и smallfloat; другие поля отклоняются до SQL. Агрегаты по нескольким таблицам строятся через DBAL. +`sum`, `min`, `max` and `avg` aggregate one readable field (a translated one too, in the query's locale) over the same rows `count` counts: the same criteria, relation predicates and visibility. The total of a filtered list matches its filter. `sum`, `min` and `max` convert the result by the field's DBAL type: the sum of a decimal is an exact string, `max('created_at')` is a `DateTimeImmutable`. Without matching rows `sum` returns the zero of the field's type and the others return NULL. `sum` and `avg` take only smallint, integer, bigint, decimal, float and smallfloat fields; other fields are rejected before SQL. Aggregates over several tables are built with DBAL. -`rows` возвращает только запрошенные, преобразованные по DBAL типам колонки. Он не создаёт частично заполненные модели. Непустой `with()` для `rows` вызывает ошибку, а не молча игнорируется; можно использовать отдельную ветку запроса с `with([])`. +`rows` returns only the requested columns, converted by their DBAL types. It does not create partially filled models. A non-empty `with()` with `rows` is an error rather than being silently ignored; use a separate branch of the query with `with([])`. -Без `orderBy` порядок не определён. Для стабильной страницы приложение добавляет уникальный ключ в конец сортировки. Отрицательные limit/offset и неизвестные направления сортировки отклоняются; `limit: 0` возвращает пустой список. Коллекции `findBy()` материализуются полностью в пределах указанного limit. +Without `orderBy` the order is undefined. For a stable page, the application ends the ordering with a unique key. Negative limits and offsets and unknown sort directions are rejected; `limit: 0` returns an empty list. `findBy()` collections are materialized in full within the given 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` принимают те же пути, от маппинга цели. +An `orderBy` key of `findBy`, `findOneBy` and `rows` can be a path through `BelongsTo` relations to a field of the target: `['category.name' => 'ASC']`, `['category.parent.name' => 'DESC']`. Each target of a path is LEFT JOINed by its primary key once per statement, over the rows a load of the same relation in this read sees: the active ones, unless the read loads the relation with another visibility. A list that shows soft-deleted categories through `with([new Load('category', visibility: Visibility::All)])` is therefore also sorted by their names; only the load's visibility is taken, not its criteria. A row with an empty, dangling or invisible reference sorts as a row with NULL in that field, and the database decides where NULL goes (first in ascending order on MySQL, MariaDB and SQLite, last on PostgreSQL). A translated target field is read in the query's locale and fallback, which the target inherits as a relation load does. Paths through `HasOne`, `HasMany` and `BelongsToMany` could yield several rows and are rejected before SQL. The default order of a to-many relation and the order of a `Load` take the same paths, from the target's mapping. -`forUpdate()` даёт то же чтение блокирующим: `find`, `findOneBy`, `findBy`, `rows`, `exists` и каждый пакет `iterateById` выполняют `SELECT ... FOR UPDATE` и держат прочитанные строки до конца транзакции; вне транзакции они бросают `LogicException`. Обычное чтение в транзакции REPEATABLE READ отвечает из её снимка, а блокирующее никогда не возвращает устаревшую версию строки: MySQL читает последнюю зафиксированную, PostgreSQL и MariaDB (с `innodb_snapshot_isolation`, по умолчанию начиная с 11.6) отклоняют строку, изменённую после снимка, ошибкой сериализации — транзакцию нужно начать заново. Блокируются строки таблицы самого чтения: PostgreSQL и MySQL начиная с 8.0.1 (это определяется по версии сервера) получают `FOR UPDATE OF`, а MariaDB и MySQL 5.7, где его нет, блокируют и присоединённые строки переводов и сортировки. Загрузки связей читаются без блокировок. Агрегаты и `queryBuilder()` блокирующего чтения бросают `LogicException`. В SQLite строковых блокировок нет, выполняется обычный SELECT. Строки блокируются в том порядке, в каком их читает БД; транзакции, которые блокируют пересекающиеся наборы строк, читают их в порядке ключа или сначала берут `lockForUpdate()`. MySQL и MariaDB блокируют каждую строку, прочитанную ради ответа, поэтому при сортировке, которую не обслуживает индекс (например, по пути связи), чтение с limit блокирует все подходящие строки, а не только страницу. +`forUpdate()` makes the same read a locking one: `find`, `findOneBy`, `findBy`, `rows`, `exists` and each batch of `iterateById` run `SELECT ... FOR UPDATE` and hold the rows they read until the transaction ends; outside a transaction they throw `LogicException`. A plain read in a REPEATABLE READ transaction answers from its snapshot, while a locking read never returns an older version of a row: MySQL reads the latest committed one, and PostgreSQL and MariaDB (with `innodb_snapshot_isolation`, the default since 11.6) refuse a row changed after the snapshot with a serialization failure, and the transaction has to start over. The rows of the read's own table are locked: PostgreSQL and MySQL 8.0.1 or later (told by the server version) get `FOR UPDATE OF`, while MariaDB and MySQL 5.7, which lack it, also lock the joined rows of translations and sorting. Relation loads read without locks. Aggregates and `queryBuilder()` of a locking read throw `LogicException`. SQLite has no row locks and runs a plain SELECT. Rows are locked in the order the database reads them; transactions that lock overlapping sets of rows read them in key order or take `lockForUpdate()` first. MySQL and MariaDB lock every row they read to answer, so with an ordering no index serves (by a relation path, for example) a read with a limit locks all matching rows, not only the page. -## Фильтры без второго QueryBuilder +## Filters without a second QueryBuilder -Обычный массив — AND по полям: +A plain array is an AND over fields: ```php ['status' => 'active', 'price >=' => '50.00', 'id IN' => [1, 2, 3]] ``` -Поддерживаются операторы `=`, `!=`, `>`, `>=`, `<`, `<=`, `IN`, `NOT IN`, `LIKE`, `NOT LIKE`; отсутствие суффикса означает `=`. `= null` и `!= null` превращаются в IS NULL и IS NOT NULL. NULL с прочими операторами, NULL внутри IN и массив без явного IN отклоняются. `IN []` означает false, `NOT IN []` — true. LIKE использует SQL wildcard-семантику; регистр, collation и порядок NULL зависят от БД. +The operators are `=`, `!=`, `>`, `>=`, `<`, `<=`, `IN`, `NOT IN`, `LIKE` and `NOT LIKE`; no suffix means `=`. `= null` and `!= null` become IS NULL and IS NOT NULL. NULL with other operators, NULL inside IN and an array without an explicit IN are rejected. `IN []` is false and `NOT IN []` is true. LIKE uses SQL wildcard semantics; case, collation and NULL order depend on the database. -Ключ задаёт и поле, и оператор, поэтому ключи критериев строятся только из фиксированных строк в коде, а не из параметров запроса и других входных данных. Кто управляет ключом, тот выбирает оператор: `filter[price >=]=0` превратит равенство в сравнение. Если пользователь выбирает поля фильтра, сопоставьте каждое разрешённое имя с фиксированным ключом. +The key carries both the field and the operator, so criteria keys are built only from fixed strings in code, never from request parameters or other input. Whoever controls a key chooses the 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. -Четыре конструктора `Filter` нужны для группировки и отношений: +The four `Filter` constructors group conditions and express relations: ```php Filter::all(array|Filter ...$parts): Filter; @@ -211,68 +213,68 @@ Filter::related( ): Filter; ``` -`all` и `any` требуют хотя бы один аргумент. Пустой массив означает true. Логические группы сохраняются буквально; простые константы нормализуются. NOT следует SQL three-valued logic: например, `NOT(price > 10)` не включает NULL-цены автоматически. +`all` and `any` need at least one argument. An empty array means true. Logical groups are kept as written; simple constants are normalized. NOT follows SQL three-valued logic: `NOT(price > 10)`, for example, does not include NULL prices automatically. -`related('tags', ['color' => 'red', 'size' => 'large'])` означает **одну** связанную строку с обоими признаками и компилируется в EXISTS. Два отдельных `related('tags', ...)` в `all` допускают две разные строки. `not(related(...))` — NOT EXISTS. OR внутри related остаётся OR. Корневые записи не размножаются от совпавших связей. +`related('tags', ['color' => 'red', 'size' => 'large'])` means **one** related row with both properties and compiles to EXISTS. Two separate `related('tags', ...)` inside `all` allow two different rows. `not(related(...))` is NOT EXISTS. OR inside related stays OR. Root rows are not multiplied by matching relations. -Имена `tags.slug`, SQL-фрагменты, скрытые scope-ключи и неизвестные поля не принимаются. Вложенные связи выражаются вложенными `related`, а не неоднозначным разбором точки. У каждого EXISTS собственные alias и параметры. Сортировка по коллекции не поддерживается: её агрегат и JOIN задаются через DBAL. +Names such as `tags.slug`, SQL fragments, hidden scope keys and unknown fields are not accepted. Nested relations are expressed by nested `related`, not by ambiguous dot parsing. Each EXISTS has its own alias and parameters. Ordering by a collection is not supported: its aggregate and JOIN are written with DBAL. -Произвольный корневой фильтр с большим IN не разбивается на несколько запросов: это изменило бы семантику OR, сортировки и limit. Превышение бюджета параметров даёт явную ошибку; иной способ передать большой набор задаётся через DBAL. Автоматическое разбиение относится только к внутренним пакетам loader и bulk insert. +An arbitrary root filter with a large IN is not split into several queries: that would change the semantics of OR, ordering and limits. Exceeding the parameter budget is an explicit error; another way to pass a large set is written with DBAL. Automatic splitting applies only to the loader's internal batches and to bulk inserts. -## Переводы +## Translations -`Translations` задаёт `table`, `foreignKey`, `columns`, необязательный `defaultLocale` и `localeColumn = 'locale'`. В первом релизе переводимые поля — nullable string/text; их имена не пересекаются с основными колонками. Нужен UNIQUE `(foreignKey, localeColumn)` и внешний ключ на основную таблицу. Для переносимого PATCH upsert эта пара должна быть единственным возможным конфликтом уникальности при вставке переводимых данных; дополнительные UNIQUE по переводимым полям требуют отдельной операции приложения. Это ограничение учитывает поведение [MySQL ON DUPLICATE KEY](https://dev.mysql.com/doc/refman/8.4/en/insert-on-duplicate.html). +`Translations` sets `table`, `foreignKey`, `columns`, an optional `defaultLocale` and `localeColumn = 'locale'`. Translated fields are nullable string/text, and their names do not overlap with the base columns. A UNIQUE `(foreignKey, localeColumn)` and a foreign key to the base table are required. For a portable PATCH upsert, this pair must be the only possible unique conflict when translated data is inserted; additional UNIQUE constraints on translated fields need a separate operation of the application. This restriction follows the behavior of [MySQL ON DUPLICATE KEY](https://dev.mysql.com/doc/refman/8.4/en/insert-on-duplicate.html). -UNIQUE должен обеспечивать одну строку на владельца и locale с теми же правилами сравнения ID, что и PK владельца. Например, для строкового PK с `COLLATE NOCASE` в SQLite колонка translation FK тоже требует `COLLATE NOCASE`: бинарный UNIQUE позволил бы два перевода для `Owner` и `owner`, хотя это один владелец. Согласованные типы, collation и ограничения задаются миграциями приложения, без автоматической интроспекции схемы в репозитории. +The UNIQUE constraint must allow one row per owner and locale with the same ID comparison rules as the owner's primary key. For a string primary key with `COLLATE NOCASE` in SQLite, for example, the translation foreign key also needs `COLLATE NOCASE`: a binary UNIQUE would allow two translations for `Owner` and `owner`, although they are one owner. Matching types, collations and constraints are set by the application's migrations, without automatic schema introspection in the repository. -Служебные `foreignKey` и `localeColumn` не входят в переводимые `columns` и недоступны в patch. +The technical `foreignKey` and `localeColumn` are not part of the translated `columns` and are not available in a patch. -Обычное чтение использует `defaultLocale` без fallback. Без `defaultLocale` чтение, которое не называет locale, не делает translation JOIN: переводимые поля приходят NULL, а условия, сортировки и агрегаты по ним бросают `LogicException`, пока чтение не вызовет `withLocale()`. `withLocale('uk', fallback: 'en')` явно выбирает пару. Неявного глобального языка, цепочки fallback и fallback к колонке основной таблицы нет. Пустая locale отклоняется; совпадающие primary/fallback сворачиваются в один язык. +A plain read uses `defaultLocale` without fallback. Without `defaultLocale`, a read that names no locale makes no translation JOIN: translated fields come back NULL, and conditions, sorting and aggregates on them throw `LogicException` until the read calls `withLocale()`. `withLocale('uk', fallback: 'en')` chooses the pair explicitly. There is no implicit global language, no fallback chain and no fallback to a base-table column. An empty locale is rejected; equal primary and fallback locales collapse into one language. -| Значение для `uk` | Значение для `en` | Результат с fallback `en` | +| Value for `uk` | Value for `en` | Result with fallback `en` | |---|---|---| -| Нет строки | `"Chair"` | `"Chair"` | +| No row | `"Chair"` | `"Chair"` | | NULL | `"Chair"` | `"Chair"` | | `""` | `"Chair"` | `""` | | `"0"` | `"Chair"` | `"0"` | | `"Стілець"` | `"Chair"` | `"Стілець"` | -| NULL | Нет строки | NULL | +| NULL | No row | NULL | -Таким образом, fallback выражается `COALESCE(primary.field, fallback.field)`. Для каждого поля выбор независим. Без fallback отсутствующая строка/NULL дают NULL. Mapper должен допускать это значение либо применять явно выбранное приложением правило. +Fallback is thus `COALESCE(primary.field, fallback.field)`, chosen independently for each field. Without fallback a missing row or NULL gives NULL. The hydrator must accept that value or apply a rule the application chose explicitly. -Один `FieldResolver` применяется к проекции, WHERE, ORDER BY и условиям внутри связей. Фильтр по `name` проверяет именно то значение с fallback, которое будет показано. Это намеренное отличие от v3, где fallback выборки и условия могли расходиться. +One `FieldResolver` serves the projection, WHERE, ORDER BY and conditions inside relations. A filter on `name` checks exactly the value with fallback that will be shown. -Эффективная пара языков корневого чтения наследуется связями и relation predicates. Если у корня нет ни `withLocale()`, ни `defaultLocale`, в каждой ветви первая переводимая сущность с `defaultLocale` применяет его, далее он наследуется; переводимые сущности выше неё читают NULL в переводимых полях. Для одного языка всего графа достаточно задать `withLocale()` у корня, даже если он сам не переводится. Переопределения языка отдельной загрузки в 1.0 нет. +The effective language pair of the root read is inherited by relations and relation predicates. When the root has neither `withLocale()` nor `defaultLocale`, in each branch the first translated entity with a `defaultLocale` applies it, and it is inherited from there; translated entities above it read NULL in their translated fields. For one language across the whole graph, set `withLocale()` on the root, even if the root itself is not translated. A per-load language override is not part of 1.0. -При чтении модели из переводимого репозитория с `defaultLocale` этот язык означает JOIN по умолчанию. `rows`, `count` и `exists` добавляют translation JOIN только когда их поля/фильтры этого требуют. Нелокализованные физические строки можно читать напрямую через DBAL; отдельный `withoutLocale()` не нужен. +When a model is read from a translated repository with `defaultLocale`, that language means a JOIN by default. `rows`, `count` and `exists` add a translation JOIN only when their fields or filters need it. Unlocalized physical rows can be read directly through DBAL; there is no separate `withoutLocale()`. -`TranslationStore` отделяет редактирование от отображения: +`TranslationStore` separates editing from display: ```php -get(int|string $id, string $locale): ?array; // собственные поля, без fallback -all(int|string $id): array; // все локали владельца, по возрастанию +get(int|string $id, string $locale): ?array; // own fields, without fallback +all(int|string $id): array; // every locale of the owner, ascending save(int|string $id, string $locale, array $patch): void; -seed(int|string $id, array $locales, array $values): int; // вставленные строки +seed(int|string $id, array $locales, array $values): int; // rows inserted delete(int|string $id, string $locale): int; ``` -`save` — атомарный upsert **только переданных полей**. Значения patch принимаются как string или NULL. Пропущенное поле не изменяется, NULL включает fallback при чтении, `""` сохраняет пустой перевод. При создании строки неприсланные переводимые поля получают значение по умолчанию колонки; у колонки без DEFAULT это NULL, и при чтении сработает fallback. Пустой patch — no-op после проверки ID и locale. Переведённые поля в обычном `insert/update` и критериях записи отклоняются. Операции store используют физический ID, включая soft-deleted владельца; правила админского редактирования задаёт приложение. +`save` is an atomic upsert of **only the given fields**. Patch values are strings or NULL. An omitted field is not changed, NULL enables fallback on read, and `""` stores an empty translation. When the row is created, translated fields that were not sent get the column default; for a column without a DEFAULT that is NULL, and fallback applies on read. An empty patch is a no-op after the ID and the locale are checked. Translated fields in a plain `insert/update` and in write criteria are rejected. Store operations use the physical ID, including a soft-deleted owner; the rules of admin editing are the application's. -Сохранение выполняет один native upsert: `ON CONFLICT` на SQLite/PostgreSQL или `ON DUPLICATE KEY UPDATE` на MySQL/MariaDB. Оно участвует в транзакции переданного DBAL connection; ошибки FK и ограничений не подавляются. Для других платформ непустой `save` вызывает ошибку до выполнения SQL. При отсутствии `Mapping.translations` вызов `Repository::translations()` тоже даёт явную ошибку. +Saving runs one native upsert: `ON CONFLICT` on SQLite/PostgreSQL or `ON DUPLICATE KEY UPDATE` on MySQL/MariaDB. It takes part in the transaction of the given DBAL connection; FK and constraint errors are not suppressed. On other platforms a non-empty `save` fails before SQL. Without `Mapping.translations`, `Repository::translations()` is an explicit error too. -`seed` создаёт перевод для каждой locale, у которой его ещё нет, — например, для всех активных языков новой сущности — и возвращает число вставленных строк. Существующие строки не меняются, поэтому повторный seed безопасен. Значения подчиняются правилам `save`, неприсланные поля новой строки получают значение по умолчанию колонки. Пропускается только конфликт по паре `(foreignKey, localeColumn)`: `ON CONFLICT ... DO NOTHING` на PostgreSQL/SQLite и no-op `ON DUPLICATE KEY UPDATE` на MySQL/MariaDB, без `INSERT IGNORE`. Ошибки FK и прочих ограничений по-прежнему пробрасываются. +`seed` creates a translation for each locale that does not have one yet, for example for all active languages of a new entity, and returns the number of inserted rows. Existing rows are not changed, so repeating a seed is safe. Values follow the rules of `save`, and fields not sent get the column default in a new row. Only a conflict on the `(foreignKey, localeColumn)` pair is skipped: `ON CONFLICT ... DO NOTHING` on PostgreSQL/SQLite and a no-op `ON DUPLICATE KEY UPDATE` on MySQL/MariaDB, without `INSERT IGNORE`. FK and other constraint errors still propagate. -`get` возвращает все объявленные переводимые поля с DBAL conversion. NULL вместо массива означает отсутствие строки; существующая строка со всеми NULL возвращает массив. `all` возвращает те же поля для каждой сохранённой локали владельца, ключи — локали по возрастанию; без переводов — пустой массив. +`get` returns every declared translated field, converted by DBAL. NULL instead of an array means there is no row; an existing row with all NULLs returns an array. `all` returns the same fields for each stored locale of the owner, keyed by locale in ascending order; without translations it is an empty array. -## Связи +## Relations -Определения `BelongsTo`, `HasOne`, `HasMany`, `BelongsToMany` содержат отложенный `target: Closure(): Mapping` и `assign: Closure(entity, related): entity`. Фабрика `target` вызывается один раз, при первом использовании, и её Mapping запоминается для маппинга-владельца. `assign` можно не указывать у связи, по которой только фильтруют или которой пользуются через `links()`; загрузка такой связи бросает `LogicException` до SQL. В PHPDoc это `callable(TOwner, ?TTarget): TOwner` для to-one и `callable(TOwner, list): TOwner` для to-many. `assign` возвращает исходный объект после setter либо новую immutable-модель. Для to-one аргумент — объект или NULL, для to-many — список, включая пустой. +The `BelongsTo`, `HasOne`, `HasMany` and `BelongsToMany` definitions hold a lazy `target: Closure(): Mapping` and `assign: Closure(entity, related): entity`. The `target` factory is called once, on first use, and its mapping is remembered for the owner mapping. `assign` can be left out of a relation that is only filtered by or used through `links()`; loading such a relation throws `LogicException` before SQL. In PHPDoc it is `callable(TOwner, ?TTarget): TOwner` for to-one and `callable(TOwner, list): TOwner` for to-many. `assign` returns the original object after a setter, or a new immutable model. For to-one the argument is an object or NULL, for to-many a list, possibly empty. -Описания связей Solo Repository находятся в namespace `Solo\Repository\Relations` (во множественном числе). Namespace `Solo\BaseRepository\Relation` относится к прежнему пакету `solophp/base-repository`. +Relation definitions live in the `Solo\Repository\Relations` namespace (plural). -У `BelongsTo` `foreignKey` находится у владельца; у `HasOne/HasMany` — у целевой таблицы. В обоих случаях ссылка ведёт на primary key. У `BelongsToMany` задаются `pivotTable`, `foreignPivotKey`, `relatedPivotKey`; UNIQUE по паре ключей и оба FK обязательны. Pivot с дополнительными атрибутами моделируется отдельным репозиторием. +For `BelongsTo` the `foreignKey` is on the owner; for `HasOne/HasMany` it is on the target table. In both cases the reference points to a primary key. `BelongsToMany` takes `pivotTable`, `foreignPivotKey` and `relatedPivotKey`; a UNIQUE on the key pair and both foreign keys are required. A pivot with additional attributes is modelled as a separate repository. -`HasMany` и `BelongsToMany` принимают необязательный `orderBy` — порядок коллекции по умолчанию для каждой загрузки (например, изображения по `position`). `Load` с собственным непустым `orderBy` его заменяет. +`HasMany` and `BelongsToMany` accept an optional `orderBy`, the default order of the collection for every load (images by `position`, for example). A `Load` with its own non-empty `orderBy` replaces it. ```php $query = $query->with([ @@ -281,37 +283,37 @@ $query = $query->with([ ]); ``` -`Load(name, criteria = [], orderBy = [], visibility = Visibility::Active)` — настройки конкретной связи. `with(['category.parent'])` означает конечный путь загрузки, а не рекурсивный обход графа. Конфликтующие описания одного пути и неизвестные связи вызывают ошибку. Условие Load ограничивает загружаемую коллекцию; оно **не фильтрует владельцев**. Для отбора владельцев используется `Filter::related`, и его условия не меняют содержимое `with()` автоматически. +`Load(name, criteria = [], orderBy = [], visibility = Visibility::Active)` holds the settings of one relation. `with(['category.parent'])` means a finite load path, not a recursive walk of the graph. Conflicting descriptions of one path and unknown relations are errors. A Load condition limits the loaded collection; it **does not filter owners**. Owners are selected with `Filter::related`, and its conditions do not change the content of `with()` automatically. -`Load` также принимает полный путь, например `Load('category.parent', ...)`. Строки создают структуру пути; явный Load задаёт настройки конкретного ребра. Поэтому `with([new Load('category', visibility: Visibility::All), 'category.parent'])` включает удалённую category, но её parent остаётся Active. Различающиеся явные настройки одного точного пути считаются конфликтом. +`Load` also takes a full path, such as `Load('category.parent', ...)`. Strings create the structure of a path; an explicit Load sets the settings of one edge. So `with([new Load('category', visibility: Visibility::All), 'category.parent'])` includes a deleted category, but its parent stays Active. Different explicit settings for the same exact path are a conflict. -Loader выполняет один запрос для to-one/has-many и два для many-to-many: pivot, затем связанные модели. Это бюджет на путь и пакет ключей, а не обещание двух запросов при любом объёме. Большие IN разбиваются с учётом бюджета параметров и уже связанных параметров. Translation JOIN не добавляет отдельного round-trip. +The loader runs one query for to-one and has-many relations and two for many-to-many: the pivot, then the related models. That is the budget per path and per key batch, not a promise of two queries at any volume. Large IN lists are split with the parameter budget and already bound parameters in mind. A translation JOIN adds no separate round trip. -Целочисленные ключи сравниваются по значению: цель `BelongsTo` выбирается по уникальным FK, гидрируется один раз и передаётся всем владельцам одним объектом; `HasOne/HasMany` выбираются по `fk IN (...)` без JOIN владельцев. Строковые ключи сопоставляются в SQL через JOIN с таблицей владельца, чтобы равенство следовало collation БД; каждая отличающаяся цель всё равно гидрируется один раз. +Integer keys are compared by value: a `BelongsTo` target is selected by the unique foreign keys, hydrated once and passed to all owners as one object; `HasOne/HasMany` are selected by `fk IN (...)` without joining the owners. String keys are matched in SQL by a JOIN with the owner table, so equality follows the database collation; each distinct target is still hydrated once. -Единица пакета many-to-many — владельцы. Target SELECT ограничивается EXISTS по pivot и пакету owner IDs, а не списком всех target IDs. Все targets одного владельца сортируются в одном SQL-запросе; loader обходит этот результат в порядке БД и распределяет по pivot. Конкатенация независимо отсортированных target-чанков или PHP-сортировка вместо collation БД не используются. +The batch unit of many-to-many is the owners. The target SELECT is limited by an EXISTS over the pivot and the batch of owner IDs, not by a list of all target IDs. All targets of one owner are sorted in one SQL query; the loader walks that result in database order and distributes it through the pivot. Concatenating independently sorted target chunks, or sorting in PHP instead of by the database collation, is not used. -Отбор/limit владельцев выполняется до загрузки коллекций. Результаты связываются по typed row keys. Непустой `Load.orderBy` задаёт порядок элементов каждой коллекции; без него порядок не гарантируется. `HasOne` требует уникальности внешнего ключа в целевой таблице; несколько совпадений — ошибка данных. `limit per parent`, lazy loading, cross-connection связи и автоматические каскады исключены из 1.0. +Owners are selected and limited before collections are loaded. Results are matched by typed row keys. A non-empty `Load.orderBy` sets the order of each collection's items; without it the order is not guaranteed. `HasOne` requires the foreign key to be unique in the target table; several matches are a data error. A limit per parent, lazy loading, cross-connection relations and automatic cascades are not part of 1.0. -Незагруженные связи остаются в состоянии, заданном mapper. Загруженная to-one без видимой цели присваивается как NULL. Наличие одной PHP-инстанции для одной строки между запросами не гарантируется. +Relations that were not loaded stay as the hydrator left them. A loaded to-one without a visible target is assigned as NULL. One PHP instance per row across queries is not guaranteed. ## Soft delete -`softDeleteColumn` должна присутствовать в `Mapping.columns` с nullable datetime-типом. Чтение по умолчанию добавляет IS NULL. `Visibility::All` снимает ограничение, `Visibility::Deleted` добавляет IS NOT NULL; при отсутствии soft delete `Active/All` эквивалентны, а `Deleted` — ошибка конфигурации запроса. +`softDeleteColumn` must be part of `Mapping.columns` with a nullable datetime type. Reads add IS NULL by default. `Visibility::All` removes the restriction and `Visibility::Deleted` adds IS NOT NULL; without soft delete `Active/All` are equivalent, and `Deleted` is a query configuration error. -`withVisibility()` меняет только корень. Связи и relation predicates по умолчанию используют `Active`; `Load.visibility` и `Filter::related(..., visibility: ...)` переопределяют это явно. Translation JOIN не имеет собственного soft delete. +`withVisibility()` changes only the root. Relations and relation predicates use `Active` by default; `Load.visibility` and `Filter::related(..., visibility: ...)` override it explicitly. A translation JOIN has no soft delete of its own. -Условие видимости добавляется снаружи пользовательской группы: `visible AND (criteria)`. Указание `deleted_at` в критериях не отключает его. Поэтому `not(related('tags', []))` означает отсутствие **видимых** тегов. +The visibility condition is added outside the user's group: `visible AND (criteria)`. Naming `deleted_at` in the criteria does not turn it off. That is why `not(related('tags', []))` means the absence of **visible** tags. -`update/updateBy` изменяют только активные строки; изменение колонки soft delete через patch запрещено. `delete/deleteBy` ставят UTC timestamp только активным строкам; повторное удаление возвращает 0 и сохраняет прежний timestamp. Без soft delete эти методы удаляют физически. `restore(id)` очищает timestamp только у удалённой строки и требует настройки soft delete. `purge(id)` и `purgeBy(criteria)` физически удаляют строки независимо от видимости; пустой критерий `purgeBy` отклоняется, как у `deleteBy`. Очистка переводов/pivot при физическом удалении определяется FK и миграциями приложения. +`update/updateBy` change only active rows; changing the soft-delete column through a patch is forbidden. `delete/deleteBy` set a UTC timestamp on active rows only; deleting again returns 0 and keeps the earlier timestamp. Without soft delete these methods delete physically. `restore(id)` clears the timestamp of a deleted row only and requires soft delete to be configured. `purge(id)` and `purgeBy(criteria)` delete rows physically regardless of visibility; an empty `purgeBy` criterion is rejected, as for `deleteBy`. Cleanup of translations and pivots on physical deletion is defined by the application's FKs and migrations. -## Запись и транзакции +## Writes and transactions -Контракт записи `Repository`: +The write contract of `Repository`: ```php insert(array $data): int; // affected rows -insertGetId(array $data): int|string; // ID, не affected rows +insertGetId(array $data): int|string; // the ID, not 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; @@ -321,82 +323,59 @@ deleteBy(array|Filter $criteria): int; restore(int|string $id): int; purge(int|string $id): int; purgeBy(array|Filter $criteria): int; -lockForUpdate(int|string|array $ids): void; // только внутри транзакции +lockForUpdate(int|string|array $ids): void; // inside a transaction only translations(): TranslationStore; -links(string $relation): LinkSet; // только BelongsToMany +links(string $relation): LinkSet; // BelongsToMany only ``` -`insert` и `insertGetId` каждый выполняют вставку: вызывать их последовательно для одной записи нельзя. При `generatedId: false` ID обязателен. При `generatedId: true` разрешён переданный ID либо генерация integer identity/sequence. UUID, генерируемые на стороне БД, не входят в этот контракт; UUID приложения передаётся явно. - -Явный ID допустим, только если его разрешает схема БД. Пакет не добавляет override для GENERATED ALWAYS и не синхронизирует sequence после ручной вставки. - -Для MySQL при `generatedId: true` явный нулевой ID отклоняется: без NO_AUTO_VALUE_ON_ZERO сервер может заменить его новым ключом. Для генерации ключа ID нужно опустить. +`insert` and `insertGetId` each perform an insert: do not call both for one record. With `generatedId: false` the ID is required. With `generatedId: true` a given ID is allowed, or an integer identity/sequence generates one. UUIDs generated by the database are not part of this contract; an application UUID is passed explicitly. -`insertGetId` использует переданный ID либо проверенную стратегию платформы и возвращает ключ после преобразования по его типу Mapping. PostgreSQL получает ключ через INSERT RETURNING, MySQL/SQLite — через предусмотренное драйвером получение ID. Возможный служебный обмен с БД для ID не считается перечитыванием модели; обещания «всегда один SQL» здесь нет. +An explicit ID is allowed only where the database schema allows it. The package adds no override for GENERATED ALWAYS and does not resynchronize a sequence after a manual insert. -Patch не меняет пропущенные поля; NULL записывает SQL NULL. Записываемые значения до SQL проверяются по типу колонки по тем же правилам, что и значения критериев: `update($id, ['quantity' => 'abc'])` выбрасывает исключение, а не записывает 0. Primary key изменять нельзя. Пустой patch возвращает 0 без SQL. Для `updateBy/deleteBy` разрешены только основные колонки и логические группы; relation/translation predicates отклоняются, чтобы не обещать переносимый UPDATE/DELETE с JOIN. +On MySQL with `generatedId: true` an explicit zero ID is rejected: without NO_AUTO_VALUE_ON_ZERO the server may replace it with a new key. To have a key generated, leave the ID out. -Пустой критерий или критерий, свёрнутый простыми правилами к true, для массовой записи отклоняется до применения soft-delete условия. Это защита от пустого фильтра, а не доказательство безопасности любого логического выражения. Намеренное изменение всей таблицы выражается прямо через DBAL. +`insertGetId` uses the given ID or the platform's verified strategy and returns the key converted by its mapping type. PostgreSQL gets the key through INSERT RETURNING, MySQL and SQLite through the driver's last-insert-ID support. A possible extra round trip for the ID is not a re-read of the model; there is no promise of "always one SQL statement" here. -`insertMany` принимает строки с одним набором полей; порядок ключей неважен. Различающиеся наборы отклоняются до первой записи. Пустой список возвращает 0. Чанки учитывают лимит параметров; вся операция атомарна: пакет, который помещается в один statement, выполняется этим statement без транзакции, а разбитый — в одной транзакции/savepoint. Как и неудачный `insert`, такой пакет, упавший внутри транзакции вызывающего на PostgreSQL, обрывает эту транзакцию; к своему savepoint откатывается только разбитый пакет. Возвращаемый affected count зависит от драйвера: 0 от UPDATE не доказывает отсутствие записи. +A patch does not change omitted fields; NULL writes SQL NULL. Values are checked against the column type before SQL, by the same rules as criteria values: `update($id, ['quantity' => 'abc'])` throws instead of writing 0. The primary key cannot be changed. An empty patch returns 0 without SQL. `updateBy/deleteBy` accept only base columns and logical groups; relation and translation predicates are rejected, so that no portable UPDATE/DELETE with JOINs is promised. -`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 на разных платформах считаются по-разному, поэтому метод ничего не возвращает: строку перечитывают по ключу. +An empty criterion, or one that simple rules fold to true, is rejected for bulk writes before the soft-delete condition is added. This guards against an empty filter; it does not prove any logical expression safe. Changing a whole table on purpose is written directly with DBAL. -`lockForUpdate(ids)` блокирует физические строки с этими PK до конца текущей транзакции через `SELECT ... FOR UPDATE`; вне транзакции вызов отклоняется. ID нормализуются и дедуплицируются, строки блокируются в порядке ключа (так конкурирующие транзакции не взаимоблокируются). Большие наборы делятся на statement по 5 000 ключей; целочисленные ключи сортируются до разбиения, поэтому порядок сохраняется и между statement, а строковые ключи следуют collation базы внутри каждого statement. В SQLite строковых блокировок нет, выполняется обычный SELECT. Межпроцессные advisory locks («одна критическая секция на заказ») остаются в приложении. +`insertMany` takes rows with one set of fields; key order does not matter. Different sets are rejected before the first write. An empty list returns 0. Chunks respect the parameter limit, and the operation is atomic: a batch that fits one statement runs as that statement without a transaction, and a split batch runs in one transaction or savepoint. Like a failed `insert`, such a batch that fails inside the caller's transaction on PostgreSQL aborts that transaction; only a split batch rolls back to its own savepoint. The returned affected count depends on the driver: 0 from an UPDATE does not prove that no row exists. -Несколько операций объединяются стандартным `$db->transactional(...)` на общем Connection. Одиночный CRUD, upsert и `insertMany` в один statement не создают дополнительную транзакцию. Разбитый на несколько statement `insertMany` и операции `LinkSet` используют транзакцию/вложенный savepoint DBAL и пробрасывают ошибки. Автоматические retries отсутствуют. +`upsert(key, data, onInsert)` 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. A new row gets `key + data + onInsert`; an existing one updates only the `data` columns, and the key and other columns stay as they were. `onInsert` holds what only a new row needs: an explicit ID, a creation time. With an empty `data` an existing row is not changed. The key is non-empty, has no NULL and names the columns of one unique index or the primary key: PostgreSQL and SQLite use it as the conflict target and reject a key without such an index, while MySQL and MariaDB update the row on a conflict with any unique index of the table and insert another row when no index covers the key. Each column appears in the three arrays once; `data` does not change the primary key, and none of them holds the soft-delete column. A new row is checked as in `insert`, so with `generatedId: false` the ID goes into `key` or `onInsert`. The row of the key is updated even when it is soft-deleted, and stays deleted; an explicit `restore` brings it back. Platforms count the affected rows of an upsert differently, so the method returns nothing: read the row back by its key. -`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 пустого списка ничего не делают. +`lockForUpdate(ids)` locks the physical rows with these primary keys until the end of the current transaction with `SELECT ... FOR UPDATE`; outside a transaction the call is rejected. IDs are normalized and deduplicated, and rows are locked in key order, so competing transactions do not deadlock each other. Large sets are split into statements of 5,000 keys; integer keys are sorted before splitting, so the order holds across statements, while string keys follow the database collation within each statement. SQLite has no row locks and runs a plain SELECT. Cross-process advisory locks ("one critical section per order") stay in the application. -Синхронизация читает все физические pivot-строки владельца, включая ссылки на скрытые soft-delete цели. Фильтры отображения не превращаются в фильтры записи. Для строковых ID LinkSet дополнительно читает канонические ключи через SQL, чтобы attach/detach/sync учитывали collation БД и разные написания одного ID. Ошибки FK не скрываются. Пара, которую другой писатель сохранил после того, как операция прочитала набор, пропускается, а не становится ошибкой unique: INSERT идёт с `ON CONFLICT (foreignPivotKey, relatedPivotKey) DO NOTHING` в PostgreSQL и SQLite, поэтому им нужен обязательный UNIQUE пары, и с `ON DUPLICATE KEY UPDATE` в MySQL и MariaDB, где такой парой считается конфликт по любому уникальному индексу pivot. Транзакция гарантирует rollback частичного изменения, но не сериализует конкурентные sync/attach. Параллельные attach одной пары проходят в MySQL и в PostgreSQL на READ COMMITTED. Транзакцию, чей снимок старше чужого коммита, MariaDB со snapshot isolation (по умолчанию с 11.6) отклоняет ошибкой 1020, а PostgreSQL на REPEATABLE READ и SERIALIZABLE — ошибкой сериализации; два sync одного набора по-прежнему могут перемежаться. Если несколько процессов должны прийти к одному набору, приложение берёт блокировку владельца (`lockForUpdate()` первым действием транзакции) или иную стратегию конкурентной записи в общей транзакции. +Several operations are combined with DBAL's standard `$db->transactional(...)` on the shared connection. A single CRUD call, an upsert and an `insertMany` that fits one statement open no extra transaction. An `insertMany` split into several statements and `LinkSet` operations use a DBAL transaction or nested savepoint and propagate errors. There are no automatic retries. -## Большие выборки и сложный SQL +`LinkSet` provides `attach(id, ids): void`, `detach(id, ids): void` and `sync(id, ids): void`. Input IDs are normalized by the type of the target's primary key and deduplicated; their order is not kept. Attaching an existing link and detaching a missing one are no-ops; `sync` sets the exact set, and `sync(id, [])` clears it. Attaching or detaching an empty list does nothing. -`iterateById` выполняет keyset batching: `id > lastId`, `ORDER BY id ASC`, `LIMIT batchSize`. Он требует одного неизменяемого ключа DBAL integer/bigint, не принимает другую сортировку и не использует OFFSET/предварительный COUNT. Размер пакета должен быть положительным. +A sync reads every physical pivot row of the owner, including references to hidden soft-deleted targets. Display filters do not become write filters. For string IDs, LinkSet also reads the canonical keys through SQL, so that attach, detach and sync follow the database collation and different spellings of one ID. FK errors are not hidden. A pair that another writer stored after the operation read the set is skipped instead of becoming a unique-key error: the INSERT carries `ON CONFLICT (foreignPivotKey, relatedPivotKey) DO NOTHING` on PostgreSQL and SQLite, which therefore need the required UNIQUE on the pair, and `ON DUPLICATE KEY UPDATE` on MySQL and MariaDB, where a conflict with any unique index of the pivot counts as that pair. The transaction guarantees a rollback of a partial change but does not serialize concurrent syncs and attaches. Concurrent attaches of one pair succeed on MySQL and on PostgreSQL in READ COMMITTED. A transaction whose snapshot is older than the other writer's commit is refused by MariaDB with snapshot isolation (the default since 11.6) with error 1020, and by PostgreSQL in REPEATABLE READ and SERIALIZABLE with a serialization failure; two syncs of one set can still interleave. When several processes must arrive at one set, the application takes the owner's lock (`lockForUpdate()` as the transaction's first statement) or another strategy for concurrent writes in a shared transaction. -Фильтры, locale, visibility и includes одинаковы для каждого пакета. Память занята текущими владельцами **и их связанными строками**; неограниченный fan-out может быть большим. Завершённые DBAL results освобождаются, история объектов не хранится. Удержание моделей самим потребителем не ограничивается библиотекой. +## Large reads and complex SQL -Это не серверный cursor и не snapshot при конкурентных изменениях. Для согласованного экспорта приложение выбирает транзакцию/изоляцию своей БД. Для произвольного порядка, составного cursor, сырых потоковых строк и отчётов используется DBAL. +`iterateById` batches by keyset: `id > lastId`, `ORDER BY id ASC`, `LIMIT batchSize`. It needs one immutable DBAL integer/bigint key, takes no other ordering and uses neither OFFSET nor a preliminary COUNT. The batch size must be positive. -У `ReadQuery` нет `toDbal()` в первом релизе: изменение экспортированного builder создало бы второй контракт для alias, проекций и применения политик. Сложный запрос строится на уже инжектированном Connection и может использовать ту же функцию mapper. Soft delete, переводы, type conversion и связи в таком запросе задаются явно. +Filters, locale, visibility and includes are the same for every batch. Memory holds the current owners **and their related rows**; an unbounded fan-out can be large. Finished DBAL results are released, and no history of objects is kept. What the consumer itself keeps is not limited by the library. -## Платформы и ошибки +This is not a server-side cursor and not a snapshot under concurrent changes. For a consistent export the application chooses the transaction and isolation of its database. For an arbitrary order, a composite cursor, raw streamed rows and reports, use DBAL. -Проверяемая матрица — PostgreSQL 17 (`pdo_pgsql`), MySQL 8.4 и MariaDB 12.3 (`pdo_mysql`) и SQLite (`pdo_sqlite`). CI проверяет минимальную ветку DBAL 4.3 и актуальную совместимую версию. MariaDB обрабатывается как MySQL; SQL Server и прочие платформы не объявляются совместимыми автоматически по наличию DBAL-драйвера; совместимость с более старыми серверными версиями здесь не заявляется. +`ReadQuery` has no `toDbal()`: changing an exported builder would create a second contract for aliases, projections and policies. A complex query is built on the injected connection and may reuse the same hydrator. Soft delete, translations, type conversion and relations are set explicitly in such a query. -SQL builder, экранирование, параметры, типы и транзакции делегируются DBAL. Узкие операции, для которых нет нужного общего API, проверяют платформу явно: generated ID и PATCH upsert переводов. Нет ветки «всё неизвестное считаем PostgreSQL» и общего INSERT IGNORE, скрывающего сторонние нарушения ограничений. +## Platforms and errors -Ошибки определения Mapping и неподдерживаемые параметры запроса должны выявляться до SQL насколько это возможно; ленивые связи проверяются при первом разрешении. DBAL-ошибки исполнения сохраняются с причиной. Некорректные результаты mapper/assign — ошибки контракта, а не пропущенные модели. +The verified matrix is PostgreSQL 17 (`pdo_pgsql`), MySQL 8.4 and MariaDB 12.3 (`pdo_mysql`) and SQLite (`pdo_sqlite`). CI checks the minimum DBAL 4.3 branch and the latest compatible release. MariaDB is handled as MySQL; SQL Server and other platforms are not declared compatible just because DBAL has a driver for them, and compatibility with older server versions is not claimed. -## Переход с v3 - -Полная последовательность перехода, изменения схемы и примеры «до/после» находятся в [руководстве по миграции](migration.md). В Solo Repository нет `BaseRepository`, `RepositoryInterface`, старых relation DTO и сервисов v3. Документация v3 остаётся в [репозитории прежнего пакета](https://github.com/SoloPHP/Base-Repository/tree/v3.1.0/docs). - -| V3 | Solo Repository | -|---|---| -| Наследование и protected-настройки | `new Repository($db, new Mapping(...))` или типизированный наследник, который задаёт маппинг в своём конструкторе; публичные методы `Repository` final | -| Статический метод mapper по имени | Типизированный callable; `Model::fromArray(...)` адаптируется к преобразованным DBAL значениям | -| Изменяемые/одноразовые `withLocale`, `with` | Независимый повторно используемый `ReadQuery` | -| `find/findBy` на репозитории | `read()->find/findBy`, либо сразу `withLocale/with` | -| `create/update` возвращают модель | `insertGetId/update`, затем явное чтение при необходимости | -| Нет locale — нет translation JOIN | Настроенный `defaultLocale` для обычного чтения; без него нет JOIN, переводимые поля NULL | -| Пустая строка вызывает fallback | Пустая строка — перевод; только NULL/нет строки вызывают fallback | -| Fallback в выводе отличается от фильтра | Одинаковый resolver для вывода, фильтра и сортировки | -| `relation.field` и scope-ключи в массиве | `Filter::related` и обычные функции, возвращающие критерии | -| Связь через публичное свойство repo и имя setter | Lazy callable репозитория и `assign(entity, related): entity` | -| Неявное поведение `deleted_at` в критериях | `Visibility`; отдельные правила видимости связей | -| Произвольные наборы полей в `insertMany` | Один набор полей на вызов | -| `sum/avg/min/max`, `lockForUpdate` | `ReadQuery::sum/avg/min/max`, `Repository::lockForUpdate` | -| Transaction и advisory lock wrappers | DBAL и код приложения | +The SQL builder, quoting, parameters, types and transactions are delegated to DBAL. Narrow operations without a suitable common API check the platform explicitly: generated IDs and upserts. There is no "treat everything unknown as PostgreSQL" branch and no general INSERT IGNORE that would hide unrelated constraint violations. -Автоматический compatibility layer в ядро не включается. До миграции данных нужно решить, какие старые `""` должны стать NULL для сохранения fallback. Обязательны аудит уникальности переводов/pivot/has-one, совпадения типов ключей и ожиданий mapper. Например, mapper, который сам создаёт дату из строки, теперь получает `DateTimeImmutable`; набор доступных колонок определяется Mapping. +Errors in mapping definitions and unsupported query parameters are detected before SQL as far as possible; lazy relations are checked when first resolved. DBAL execution errors keep their cause. Invalid results of a hydrator or `assign` are contract errors, not skipped models. -## Проверяемое поведение +## Verified behavior -Интеграционные сценарии проверяют каталог с category/tags, переводы, page limit, атомарную запись и обход по ID. Проверяются независимость locale/includes, same-row/OR/NOT EXISTS, soft delete, проекции, NULL/пустые переводы, typed keys, разбиение пакетов, rollback и `assign`, возвращающий immutable-модель. +Integration scenarios check a catalog with categories and tags, translations, page limits, atomic writes and iteration by ID. They check the independence of locale and includes, same-row/OR/NOT EXISTS predicates, soft delete, projections, NULL and empty translations, typed keys, batch splitting, rollback and an `assign` that returns an immutable model. -Для каталога с category + tags в пределах одного пакета проверяется 4 SELECT: владельцы, category, pivot, tags. Для UPDATE по ID — один UPDATE без SELECT. При переходе keyset на следующую страницу тесты проверяют освобождение объектов завершённого пакета. Производительность в миллисекундах зависит от данных, платформы и схемы и не является обещанием преимущества перед ORM. +For a catalog with category and tags within one batch, the tests check 4 SELECTs: owners, category, pivot, tags. For an UPDATE by ID, one UPDATE without a SELECT. When keyset iteration moves to the next page, the tests check that the objects of the finished batch are released. Performance in milliseconds depends on data, platform and schema and is not a promise of an advantage over an ORM. -## Основа DBAL +## Built on DBAL -Дизайн опирается на существующие API DBAL: [QueryBuilder](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/query-builder.html), [параметры и получение данных](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/data-retrieval-and-manipulation.html), [типы](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/types.html), [транзакции](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/transactions.html). При реализации проверяются минимальная поддерживаемая и текущая версии DBAL 4.x. +The design builds on existing DBAL APIs: [QueryBuilder](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/query-builder.html), [parameters and data retrieval](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/data-retrieval-and-manipulation.html), [types](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/types.html) and [transactions](https://www.doctrine-project.org/projects/doctrine-dbal/en/4.3/reference/transactions.html). The minimum supported and the current DBAL 4.x releases are both checked. diff --git a/docs/guide/index.md b/docs/guide/index.md index a70082a..9214b4e 100644 --- a/docs/guide/index.md +++ b/docs/guide/index.md @@ -10,11 +10,8 @@ Models can be mutable or immutable. PHP 8.3+, Doctrine DBAL ^4.3, and the matching PDO driver are required. The test matrix covers SQLite, MySQL 8.4, MariaDB 12.3, and PostgreSQL 17. -Install from the GitHub repository: - ```sh -composer config repositories.solophp-repository vcs https://github.com/SoloPHP/Repository.git -composer require 'solophp/repository:dev-main' +composer require solophp/repository ``` ## Map an existing table @@ -107,6 +104,4 @@ relation types, visibility, and transaction behavior. In the source checkout, ## Further reading - [Public API and constraints](api.md) -- [Migration from Base Repository v3](migration.md) -- [Detailed behavior and database test commands (Russian)](details.md) -- [Base Repository v3 documentation](https://github.com/SoloPHP/Base-Repository/tree/v3.1.0/docs) +- [Behavior in detail and database tests](details.md) diff --git a/docs/guide/migration.md b/docs/guide/migration.md deleted file mode 100644 index 9737500..0000000 --- a/docs/guide/migration.md +++ /dev/null @@ -1,522 +0,0 @@ -# Migrating from Base Repository v3 - -This guide moves an application from **`solophp/base-repository` v3** to -**`solophp/repository` 1.0**. Solo Repository is a separate package with the -`Solo\Repository` namespace. - -The new package uses composition and does not contain `BaseRepository`, -`RepositoryInterface`, or the old singular `Relation` namespace. `Repository` -does not implement the old interface. The -[v3 documentation](https://github.com/SoloPHP/Base-Repository/tree/v3.1.0/docs) -remains with the original product. - -The migration changes repository construction, query state, criteria, and write -results. Keep the existing schema initially, audit the constraints below, and -migrate one workflow at a time. The source checkout's `examples/migration.php` -runs a catalog query, translates and updates a product, replaces its tags in a -transaction, verifies rollback, and exports the result: - -```sh -composer install -php examples/migration.php -``` - -## 1. Dependencies and installation - -Solo Repository requires PHP `^8.3` and Doctrine DBAL `^4.3`. Update the -application's PHP runtime, PDO driver, and dependency constraints together. -Check other Doctrine dependencies when upgrading DBAL. - -Add the new package using the [installation instructions](index.md#install). -If Composer reports a conflict with an existing dependency, review its constraint -and use `--with-all-dependencies` when updating the related packages. - -Keep `solophp/base-repository:^3.0` installed while migrating its callers. The -namespaces are independent; the new package neither `replace`s nor `provide`s -the old one. Once no code uses the old API, remove its dependency: - -```sh -composer remove solophp/base-repository -``` - -Change imports for new code to `Solo\Repository`. This is **not** a namespace-only -migration from v3: construction and behavior also change as described below. - -The integration matrix covers MySQL 8.4, MariaDB 12.3 and PostgreSQL 17, alongside SQLite. -Other DBAL platforms are outside that matrix. See the -[database test instructions](details.md#проверка-на-mysql-mariadb-и-postgresql). - -## 2. Replace inheritance with composition - -V3 configured behavior on a `BaseRepository` subclass, usually hydrating through `Product::fromArray()`: - -```php -// Base Repository v3 -use Doctrine\DBAL\Connection; -use Solo\BaseRepository\BaseRepository; - -final class ProductRepository extends BaseRepository -{ - protected ?string $deletedAtColumn = 'deleted_at'; - - public function __construct(Connection $db) - { - parent::__construct($db, Product::class, 'products'); - } -} -``` - -Construct a Solo Repository `Repository` from the application's DBAL `Connection` and a `Mapping`, or extend it into a [typed repository](api.md#typed-repositories) whose constructor fixes the mapping. Its public methods are final: a subclass adds methods of its own, it does not override reads or writes. Inject the same connection separately wherever the application needs SQL or transactions. - -```php -use Doctrine\DBAL\Types\Types; -use Solo\Repository\Mapping; -use Solo\Repository\Repository; -use Solo\Repository\Translations; - -final class Product -{ - public ?object $category = null; - /** @var list */ - public array $tags = []; - - public function __construct( - public readonly int $id, - public readonly string $sku, - public readonly string $price, - public readonly ?string $name, - public readonly ?DateTimeImmutable $deletedAt, - ) { - } -} - -$products = new Repository($db, new Mapping( - table: 'products', - columns: [ - 'id' => Types::INTEGER, - 'category_id' => Types::INTEGER, - 'sku' => Types::STRING, - 'price' => Types::DECIMAL, - 'status' => Types::STRING, - 'deleted_at' => Types::DATETIME_IMMUTABLE, - ], - hydrate: static fn(array $row): Product => new Product( - id: $row['id'], - sku: $row['sku'], - price: $row['price'], - name: $row['name'], - deletedAt: $row['deleted_at'], - ), - softDeleteColumn: 'deleted_at', - translations: new Translations( - table: 'product_translations', - foreignKey: 'product_id', - columns: ['name' => Types::STRING, 'description' => Types::TEXT], - defaultLocale: 'en', - ), -)); -``` - -The application's schema must match this mapping. `Mapping` does not create tables or discover columns. `columns` is an explicit allowlist keyed by **database column names**; those names also appear in criteria, patches and projected rows. Table names are plain identifiers, without a schema prefix. The primary key defaults to `id`, must be mapped and must be a single integer, string, ASCII string or GUID key. A table with a composite key, such as stock keyed by product and store, maps with `primaryKey: null`. Address its rows with criteria, as in `updateBy(['product_id' => 1, 'store_id' => 2], $patch)`: operations by ID require a primary key. - -Before `hydrate` runs, DBAL converts every selected mapped field: `decimal` remains a string, `boolean` becomes a PHP boolean, JSON is decoded and `datetime_immutable` becomes `DateTimeImmutable`. Preserve NULL in nullable fields. Update old mappers that call `json_decode()` or construct dates from raw strings; they now receive converted values. You can reuse `Product::fromArray(...)` as the callback if it already accepts these types. The mapper need not expose database IDs or foreign keys as public model properties. - -For application-assigned IDs, replace `$autoIncrement = false` with `generatedId: false` and supply the ID on every insert. Use `Types::GUID` or `Types::STRING` for UUIDs as appropriate for the schema; DB-generated UUIDs are outside the generated-ID contract. Integer IDs accept integers or canonical decimal strings, not arbitrary text, leading-zero strings or overflowing smallint/integer PHP values. String IDs such as `'01'` retain their spelling. An explicit identity ID still has to be legal in the database schema; Solo Repository does not override `GENERATED ALWAYS` or repair sequences after manual inserts. - -That ID validation applies to separate ID arguments and explicit primary keys in insert data. Criteria values are checked against their field type as well: `findBy(['id' => $input])` throws for input such as `'12x'` instead of letting the driver turn it into 12. Validate external filter input in the application when it needs its own error response. - -## 3. Move reads to an immutable ReadQuery - -| V3 | Solo Repository | -|---|---| -| `$repo->find($id)` | `$repo->read()->find($id)` | -| `$repo->findOneBy($criteria)` | `$repo->read()->findOneBy($criteria)` | -| `$repo->findAll()` | `$repo->read()->findBy()` | -| `$repo->findBy($criteria, $order)` | `$repo->read()->findBy($criteria, $order)` | -| `$repo->count($criteria)` / `exists($criteria)` | `$repo->read()->count($criteria)` / `exists($criteria)` | -| `withLocale()/with()` modify the next read | Their return value is an independent, reusable `ReadQuery` | - -`withLocale()` and `with()` are also entry points on `Repository`. **Capture their return value**: calling `$products->withLocale('uk');` and then starting a separate `$products->read()` does not configure the latter. - -```php -$default = $products->read(); -$uk = $default->withLocale('uk', fallback: 'en'); -$catalog = $uk->with(['category', 'tags']); // Requires the relations below. - -$first = $catalog->find(1); -$again = $catalog->find(1); // Same locale/includes; settings are not consumed. -$english = $default->find(1); // Still uses the mapping's default locale. -``` - -Every `with*` returns a new query. `with([...])` replaces the complete loading list; it does not append to an earlier list. `with([])` removes eager loads from that query branch. - -### Convert page numbers to offsets - -V3's fourth argument was a **one-based page number**. Solo Repository's fourth argument is a **zero-based row offset**. A positional call can still type-check while selecting the wrong page. - -```php -// V3: page 3, 20 rows per page. -$oldProducts->findBy(['status' => 'active'], ['id' => 'ASC'], 20, 3); - -// Solo Repository: the equivalent page starts after 40 rows. -$page = 3; -$perPage = 20; -$items = $products->read()->findBy( - ['status' => 'active'], - orderBy: ['id' => 'ASC'], - limit: $perPage, - offset: ($page - 1) * $perPage, -); -``` - -Validate page/per-page values in the application. Negative limit/offset is rejected; `limit: 0` returns an empty list. Pass `[]` rather than `null` for omitted sorting. Without `orderBy`, order is unspecified; append the unique PK to nonunique sort fields when paginating. Count totals explicitly only when the UI needs them. - -### Missing records and projections - -Both packages’ `find()/findOneBy()` return NULL when no visible row matches. Solo Repository has no `findOrFail()`; keep that policy in the application: - -```php -$product = $products->read()->find($id) - ?? throw new RuntimeException('Product not found.'); -``` - -Use `rows()` for partial results, rather than hydrating an incomplete model: - -```php -$rows = $products->withLocale('uk', 'en')->rows( - ['id', 'sku', 'name'], - ['status' => 'active'], - ['id' => 'ASC'], -); -``` - -Projected values are still converted through DBAL. `rows()` rejects nonempty eager loads; use `$catalog->with([])->rows(...)`. `count()/exists()` do not load relations, even on a query with `with()`. - -## 4. Rewrite criteria explicitly - -The array shorthand is still an AND of fields, but operators now belong in the **key**. Old nested operator arrays and automatic IN lists are rejected. Because the key now carries the operator, build keys only from fixed strings, never from request input, and map user-selected filters to fixed keys through an allowlist; see [Criteria and Filter](api.md#criteria-and-filter). - -| V3 criterion | Solo Repository criterion | -|---|---| -| `['status' => 'active']` | Unchanged | -| `['price' => ['>=' => '10.00']]` | `['price >=' => '10.00']` | -| `['status' => ['<>' => 'draft']]` | `['status !=' => 'draft']` | -| `['id' => [1, 2]]` | `['id IN' => [1, 2]]` | -| `['id' => ['NOT IN' => [1, 2]]]` | `['id NOT IN' => [1, 2]]` | -| `['name' => ['LIKE' => '%chair%']]` | `['name LIKE' => '%chair%']` | -| `['category_id' => ['!=' => null]]` | `['category_id !=' => null]` | -| `['price' => ['BETWEEN' => ['10.00', '20.00']]]` | `['price >=' => '10.00', 'price <=' => '20.00']` | -| `['OR' => [['status' => 'active'], ['sku' => 'special']]]` | `Filter::any(['status' => 'active'], ['sku' => 'special'])` | - -The full operator set is `=`, `!=`, `>`, `>=`, `<`, `<=`, `IN`, `NOT IN`, `LIKE` and `NOT LIKE`. Equality may omit `=`. BETWEEN's replacement above preserves inclusive boundaries. For mapped datetime fields, supply the corresponding PHP date objects so DBAL performs conversion. - -`IN/NOT IN` require an array, including for one value. NULL inside IN and nested arrays are rejected. `['id IN' => []]` is false; `['id NOT IN' => []]` is true. NULL is accepted only with `=` or `!=`, producing `IS NULL` or `IS NOT NULL`. LIKE keeps SQL wildcard behavior; parameter binding does not escape `%` or `_` into literal characters. - -Use `Filter::all(...)`, `Filter::any(...)` and `Filter::not(...)` for groups. `all/any` require at least one argument; `[]` itself is true. NOT follows SQL NULL logic: `Filter::not(['price >' => '10.00'])` does not include NULL prices unless you explicitly add that alternative. - -A statement has a budget of bound parameters, including translation and related-filter parameters: the platform limit by default (65,535 on PostgreSQL and MySQL/MariaDB, 32,766 on SQLite 3.32+, otherwise 900), or `parameterLimit` passed to the `Repository` constructor. A larger root IN filter is rejected rather than split into queries that could change OR, ordering or pagination semantics. Automatic chunking is limited to internal loading and bulk-writing operations; their internal key lists also stop at 5,000 keys per statement. - -### Replace named scopes with application functions - -There is no `scopes()` hook or virtual criterion key. Translate validated user input into criteria before calling the repository: - -```php -use Solo\Repository\Filter; - -function catalogCriteria(?string $minimumPrice, ?string $tagSlug): array|Filter -{ - return Filter::all( - ['status' => 'active'], - $minimumPrice === null ? [] : ['price >=' => $minimumPrice], - $tagSlug === null ? [] : Filter::related('tags', ['slug' => $tagSlug]), - ); -} - -$items = $products->withLocale('uk', 'en')->findBy( - catalogCriteria('10.00', 'sale'), - ['id' => 'ASC'], -); -``` - -An unrecognized scope key now fails as an unknown mapped column. Validate input names and values at the application boundary instead of passing an arbitrary request payload as criteria. - -### Replace relation dot notation with related() - -```php -// V3 -$oldProducts->findBy(['tags.slug' => 'sale', 'tags.enabled' => true]); - -// Solo Repository: a single related row must satisfy both conditions. -$products->read()->findBy(Filter::related('tags', [ - 'slug' => 'sale', - 'enabled' => true, -])); - -// Two separate EXISTS predicates may match different related rows. -$products->read()->findBy(Filter::all( - Filter::related('tags', ['slug' => 'sale']), - Filter::related('tags', ['slug' => 'new']), -)); - -// V3 !tags.slug => 'sale' becomes NOT EXISTS. -$products->read()->findBy(Filter::not( - Filter::related('tags', ['slug' => 'sale']), -)); - -// Nested filtering is explicit, if category also maps a parent relation. -$products->read()->findBy(Filter::related( - 'category', - Filter::related('parent', ['name' => 'Furniture']), -)); -``` - -`Filter::related('tags', Filter::any(...))` keeps OR inside one related-row predicate. Dotted fields and raw SQL are not accepted as criteria. Relation filters select owners without multiplying them; they do not restrict the collection loaded by `with()`. Their target visibility defaults to `Active` independently of root visibility. - -`updateBy()/deleteBy()` accept only base-table fields and logical groups. Translated fields and `Filter::related` are read-only predicates. Move complex UPDATE/DELETE statements to DBAL with explicit scope and transaction semantics. An empty criterion, or a criterion normalized to true, is rejected for these writes, even on soft-deletable mappings. A false criterion affects zero rows. This guard is not a proof that every nonempty predicate is selective. - -## 5. Adapt writes and return values - -| V3 call | Solo Repository replacement and result | -|---|---| -| `create($data): object` | `insertGetId($data): int|string`; read explicitly if needed | -| `insert($data): int` | `insert($data): int`, affected rows | -| `update($id, $patch): object` | `update($id, $patch): int`, affected rows | -| `updateBy()/delete()/deleteBy()/restore()` | Affected rows; apply Solo Repository's visibility and criteria rules | -| `forceDelete($id)` | `purge($id)` | -| `forceDeleteBy($criteria)` | `purgeBy($criteria)`, physical regardless of visibility | - -`insert()` and `insertGetId()` each perform an INSERT. Choose one; do not call both for the same row. Generated IDs use the platform's supported mechanism. For MySQL generated integer keys, omit the ID instead of passing zero. - -```php -$id = $products->insertGetId([ - 'sku' => 'CHAIR-1', - 'price' => '29.90', - 'status' => 'active', -]); -$products->translations()->save($id, 'en', ['name' => 'Chair']); -$affected = $products->update($id, ['price' => '31.50']); -$product = $products->withLocale('uk', 'en')->find($id); -``` - -Wrap related writes in a transaction when they must succeed together; the example above shows individual operations only. Unlike v3 `create()/update()`, Solo Repository does not reread the model or throw a not-found exception after writing. An UPDATE result of zero can mean a missing/inactive row or an unchanged value, depending on the driver. Do not treat it as a portable not-found test. - -Patches leave omitted fields unchanged; explicit NULL writes NULL. Unknown fields, translated fields, PK changes and soft-delete-column changes are rejected by `update()/updateBy()`. Use dedicated operations for translations and visibility. An empty patch is a no-op after validation. - -`insertMany($rows, batchSize: 500)` requires every row to contain the same set of columns; key order may differ. V3 grouped heterogeneous rows automatically. Split them into homogeneous calls in an outer transaction if you need that workflow. Solo Repository validates the batch first, chunks by the parameter budget and rolls back all its chunks on failure; it returns affected rows, not IDs or models. - -## 6. Migrate translations and stored data - -Replace `$translationConfig['fields']` with typed `Translations::columns`. With a `defaultLocale`, a read that names no locale resolves that locale without fallback, so a former `$repo->find($id)` without locale no longer means “no translation JOIN”. Without one, such a read joins no translations, as in v3, but its translated fields come back NULL, and conditions, sorts and aggregates on them throw until the read calls `withLocale()`. - -`withLocale('uk', fallback: 'en')` overrides the default. The named parameter is now `fallback`, not v3's `fallbackLocale`. Passing no fallback does not implicitly reuse the mapping's default language. - -| Primary-locale field | Fallback field | Solo Repository resolved value | -|---|---|---| -| No translation row | `'Chair'` | `'Chair'` | -| NULL | `'Chair'` | `'Chair'` | -| `''` | `'Chair'` | `''` | -| `'0'` | `'Chair'` | `'0'` | -| NULL | Missing/NULL | NULL | - -**V3 treated an empty string as missing when fallback was enabled; Solo Repository preserves it.** Before switching reads, decide which historical empty strings mean “untranslated” and migrate those values to NULL. Keep intentional empty values as empty strings. Do this per field with application knowledge, not a blind conversion of every empty value. - -The same resolved expression is used in SELECT, WHERE and ORDER BY, including related filters. A fallback name can therefore now satisfy a filter even when the primary translation is missing. Compare existing catalog search and sorting expectations, not just rendered text. - -There is no `withoutLocale()`. Start a fresh default read to use `defaultLocale`, request only base fields with `read()->rows(['id', 'sku'])`, or use DBAL for direct physical-table access. Base-only projections/counts do not need translation JOINs unless criteria/order require translated fields. - -### Audit translation constraints first - -- A translation FK must reference the owner's PK, with matching ID type and comparison/collation rules. -- Require UNIQUE `(foreignKey, localeColumn)` and non-NULL owner/locale keys. It must identify exactly one translation per logical owner and locale. -- Translation columns must be nullable string/text fields and must not overlap base mapped fields. The service FK and locale column are not translated fields. -- Apart from a separate generated surrogate PK, no additional unique constraint may produce a conflict for the supplied translation data. MySQL's upsert cannot target only the owner/locale unique constraint. -- Confirm how deleting an owner should handle translations through FK actions. - -For example, find duplicate pairs before creating or correcting the unique constraint: - -```sql -SELECT product_id, locale, COUNT(*) -FROM product_translations -GROUP BY product_id, locale -HAVING COUNT(*) > 1; -``` - -Also audit string-key collation: a binary translation FK could allow `Owner` and `owner` as separate unique pairs while a case-insensitive owner PK treats them as one owner. The repository does not introspect or repair these schema invariants. - -### Use TranslationStore for explicit patches - -```php -$translations = $products->translations(); -$translations->save($id, 'uk', ['name' => 'Стілець']); -$translations->save($id, 'uk', ['description' => null]); -$ownTranslation = $translations->get($id, 'uk'); // All translated fields, no fallback. -$everyLocale = $translations->all($id); // ['en' => [...], 'uk' => [...]] -$deletedRows = $translations->delete($id, 'uk'); // Only this owner/locale. -``` - -`save()` is one atomic native upsert and returns void. Existing omitted fields remain unchanged. On a new row, omitted translated fields take the column default, which is NULL for a column without one. Values must be string or NULL; unknown/protected fields are rejected rather than silently ignored. An empty patch validates ID/locale and performs no SQL. `get()` returns NULL only when the row is missing; an existing all-NULL translation returns an array. - -`seedTranslations($id, $locales, $values)` becomes `$translations->seed($id, $locales, $values)`. It inserts a row for every locale that has none and leaves existing rows unchanged, so it is safe to repeat; it returns the number of inserted rows. As with `save()`, omitted translated fields of a new row take their column defaults, and only a conflict on the `(foreignKey, localeColumn)` pair is skipped: `INSERT IGNORE` is not used, so FK and other constraint errors still propagate. Do not replace seeding with a loop of `save()`: it would overwrite existing translations. - -## 7. Replace relation definitions and setters - -V3 relation definitions use `Solo\BaseRepository\Relation`, repository property names and setter names. Solo Repository definitions are in **`Solo\Repository\Relations`**, plural, and use callbacks: - -```php -use Solo\Repository\Relations\BelongsTo; -use Solo\Repository\Relations\BelongsToMany; - -// Add these entries to the relations argument of the products Mapping. -$relations = [ - 'category' => new BelongsTo( - target: static fn(): Mapping => $categories, - foreignKey: 'category_id', - assign: static function (Product $product, ?object $category): Product { - $product->category = $category; - return $product; - }, - ), - 'tags' => new BelongsToMany( - target: static fn(): Mapping => $tags, - pivotTable: 'product_tags', // V3 called this constructor argument "pivot". - foreignPivotKey: 'product_id', - relatedPivotKey: 'tag_id', - assign: static function (Product $product, array $tags): Product { - $product->tags = $tags; - return $product; - }, - ), -]; -``` - -`$categories` and `$tags` are the `Mapping` objects of the target tables; their own repositories are needed only for writing them. Pass `relations: $relations` when constructing the products mapping. Related rows are read through the products repository's connection, so a read replica or a transaction applies to the whole graph. Lazy target callbacks support cyclic configuration and are checked when the relation is resolved. - -`assign` must return the owner object, either the mutated object or a new immutable copy. A legacy void setter needs a wrapper that calls the setter **and returns the owner**. To-one callbacks receive an object or NULL; to-many callbacks receive a list, including an empty list. A relation used only for filtering (`Filter::related()`) or pivot writes (`links()`) may omit `assign`; loading it then throws before SQL. - -`BelongsTo` uses an FK on the owner. `HasOne/HasMany` use an FK on the target; `HasOne` requires that FK to be unique. `BelongsToMany` requires UNIQUE on its pivot pair and both foreign keys. Audit compatible types and matching PK/FK collations, including translations. Alternative-key/composite-key relations, cross-connection graphs and pivot attributes are outside 1.0; model a pivot with business fields as a separate repository. - -V3 relation-level ordering becomes the `orderBy` argument of `HasMany` and `BelongsToMany`; it orders every load of that collection unless a `Load` sets its own order. Move constraints to `Load`: - -```php -use Solo\Repository\Load; - -$items = $products->withLocale('uk', 'en')->with([ - 'category', - new Load('tags', criteria: ['enabled' => true], orderBy: ['name' => 'ASC']), -])->findBy(Filter::related('tags', ['slug' => 'sale'])); -``` - -The related filter selects owners that have a visible sale tag. The Load returns all visible enabled tags for those owners; it does not implicitly repeat the sale predicate. Nested eager loading still uses finite paths such as `with(['category.parent'])`. Dots are supported in loading paths, not in filter field names. Per-parent limits and per-relation locale overrides are not provided. - -The effective locale/fallback pair flows to loaded relations and related filters. With no explicit pair, the root mapping's default is inherited. If the root has no translations, the first translated mapping on each branch supplies its default; explicitly set the root locale when the whole graph must use one language. - -Loading is batched by owner keys; it does not access relations lazily from models. Many-to-many loading uses pivot and target queries per owner batch. The same database row is not guaranteed to have a single shared PHP object across queries. - -## 8. Make soft-delete visibility explicit - -Replace v3's `['deleted_at' => '*']` sentinel and visibility-by-criterion conventions: - -```php -use Solo\Repository\Visibility; - -$all = $products->read()->withVisibility(Visibility::All)->findBy(); -$deleted = $products->read()->withVisibility(Visibility::Deleted)->findBy(); - -$withDeletedTags = $products->with([ - new Load('tags', visibility: Visibility::All), -])->find($id); - -$hasDeletedTags = $products->read()->findBy(Filter::related( - 'tags', - visibility: Visibility::Deleted, -)); -``` - -`Active` is the default. Root `withVisibility()` does not change relation visibility. Visibility is applied outside user OR groups; mentioning `deleted_at` in criteria does not disable it. Without a soft-delete mapping, `Active/All` are equivalent and `Deleted` is rejected. - -`update()/updateBy()` only modify active rows. Soft `delete()/deleteBy()` set a UTC timestamp on active rows; repeating a delete returns zero without replacing the timestamp. `restore($id)` only affects deleted rows and requires soft delete configuration. `purge($id)` deletes physically regardless of visibility. Without soft delete, `delete` is already physical. Configure FK actions or explicit application cleanup for dependent translations and pivots. - -## 9. Move pivot writes and transactions to explicit services - -| V3 | Solo Repository | -|---|---| -| `attach('tags', $id, $ids)` | `links('tags')->attach($id, $ids)` | -| `detach('tags', $id, $ids)` | `links('tags')->detach($id, $ids)` | -| `detach('tags', $id)` or `detach('tags', $id, [])` | `links('tags')->sync($id, [])` | -| `sync('tags', $id, $ids)` | `links('tags')->sync($id, $ids)` | - -**An empty detach list is a no-op**, as is an empty attach list. Only `sync($id, [])` means “remove all links”. IDs are converted by the target PK type and deduplicated; their input order is not persisted. - -LinkSet membership is physical: hidden/deleted targets still count, and hidden owners can be edited. A filtered UI collection is not automatically the complete physical set. Calling sync with only that collection's visible IDs would remove omitted hidden memberships; choose that policy deliberately. - -Use the injected connection to combine base patches, translation patches and pivot replacement: - -```php -$db->transactional(function () use ($products, $id): void { - $products->update($id, ['sku' => 'CHAIR-UPDATED']); - $products->translations()->save($id, 'uk', ['name' => 'Оновлений стілець']); - $products->links('tags')->sync($id, [2, 3]); -}); -``` - -All repositories and write services must share that connection. CRUD uses the current transaction without adding one. `insertMany` split into several statements and nonempty LinkSet operations use DBAL transactions/nested savepoints; translation save is a single native upsert that participates in the caller's transaction. Database errors, including FK and unique violations, propagate; the one exception is a LinkSet pair that another writer stored after the operation read the set, which the INSERT skips. Catch exceptions outside the transaction boundary when the entire workflow must roll back. - -Atomic rollback does not serialize concurrent sync/attach calls or provide automatic retries. Concurrent attaches of one pair no longer fail on the pivot key on MySQL and on PostgreSQL in READ COMMITTED, but MariaDB with snapshot isolation and PostgreSQL above READ COMMITTED refuse a transaction whose snapshot is older than the other writer's commit. If concurrent writers must agree on a final tag set, apply the application's locking/versioning policy in the transaction. Physical string-key operations may read canonical IDs to respect database collation; do not assume that LinkSet is a write-only operation. Missing/orphan targets are not an orphan-cleanup feature; enforce the required FKs. - -## 10. Replace repository wrappers with application code and DBAL - -The following v3 extension points have no equivalent in Solo Repository: - -| V3 feature | Migration | -|---|---| -| `RepositoryInterface` / subclassing `BaseRepository` | Extend `Repository` into a typed repository with a fixed mapping, or own an instance; its public methods are final. Define an application interface if needed | -| `getConnection()` and protected `queryBuilder()` | Inject `Connection` into the application component | -| Protected `table()` with `applyCriteria()` | `read()->queryBuilder($alias, $criteria)`; add the SELECT, joins and `andWhere()` conditions to the returned DBAL builder | -| `beginTransaction()/commit()/rollBack()/withTransaction()/inTransaction()` | Use DBAL `Connection` transaction methods | -| `lockForUpdate($ids)` | `Repository::lockForUpdate($ids)` inside a transaction | -| `withLock($key, $callback)` and `LockTimeoutException` | Application-owned advisory lock (`GET_LOCK`, `pg_advisory_lock`) on the same connection | -| `sum()/avg()/min()/max()` | `ReadQuery::sum()/avg()/min()/max()` with the same criteria, locale and visibility | -| `aggregate()` overrides on a joined `table()` | `read()->queryBuilder()` with the joins and the aggregate SELECT | -| `afterWrite()` | Explicit application invalidation/events at the intended transaction boundary | -| `scopes()` | Application functions returning criteria | -| Reflection/static mapper convention | Explicit `hydrate` callback in `Mapping` | - -Aggregates over one mapped table keep the criteria of the list they summarize: - -```php -$query = $products->read(); -$page = $query->findBy($criteria, ['id' => 'ASC'], limit: 20); -$total = $query->sum('price', $criteria); // converted by the field type: a string for decimals -$latest = $query->max('created_at', $criteria); // DateTimeImmutable|null -``` - -Aggregates over joined tables are DBAL SQL. Start from `queryBuilder()` to keep the list's criteria, soft delete and locale for the mapped table: - -```php -$query = $stocks->read()->queryBuilder('s', $criteria); -$total = $query - ->select('SUM(s.stock * b.price)') - ->innerJoin('s', 'batches', 'b', 'b.product_id = s.product_id') - ->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. 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. - -For exports, use `iterateById($criteria, batchSize: 500)` with an integer PK instead of paging a growing OFFSET. It loads ascending IDs in bounded batches and releases each consumed page. It is not a snapshot, does not support another ordering, and cannot bound memory if the consumer retains every model or a single owner has an enormous relation collection. Use database-specific export SQL for other requirements. - -## 11. Verify a migrated consumer - -Run the `examples/migration.php` smoke example, then test the consumer's actual behavior: - -1. Compare stable paginated IDs and NULL/missing-record handling, including callers that used the old positional page argument. -2. Check all mapped types and old hydration conversions; verify patches preserve omitted fields. -3. Compare localized rendering, filtering and sorting for missing, NULL and empty translations. -4. Audit FK/unique/collation invariants before enabling nested eager loads and relation predicates. -5. Verify owner selection separately from collection loading, root/target visibility and physical sync semantics. -6. Cause a late FK/unique error after earlier writes; verify the entire intended transaction rolls back. -7. Check query counts on a realistic catalog and memory behavior on a realistic export. -8. Replace advisory locks, retry policies and invalidation hooks explicitly before switching traffic. - -Use the project's [SQLite and live database suites](details.md#проверка-на-mysql-mariadb-и-postgresql) for library checks. They complement consumer tests; they do not infer your domain's visibility, transaction or concurrency policies. diff --git a/docs/index.md b/docs/index.md index 76f1c93..15f1c71 100644 --- a/docs/index.md +++ b/docs/index.md @@ -15,9 +15,6 @@ hero: - theme: alt text: API reference link: /guide/api - - theme: alt - text: Migrate from Base Repository - link: /guide/migration features: - icon: 🧩 @@ -94,11 +91,8 @@ translations, relations, visibility, and transaction contracts. PHP **8.3+**, Doctrine DBAL **^4.3**, and the matching PDO driver are required. The integration matrix covers SQLite, MySQL 8.4, MariaDB 12.3, and PostgreSQL 17. -Install from the GitHub repository: - ```sh -composer config repositories.solophp-repository vcs https://github.com/SoloPHP/Repository.git -composer require 'solophp/repository:dev-main' +composer require solophp/repository ``` Continue with the [getting-started guide](./guide/index.md). diff --git a/docs/package-lock.json b/docs/package-lock.json index 5f8c866..fce496c 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -1,12 +1,12 @@ { "name": "solo-repository-docs", - "version": "1.0.0-dev", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "solo-repository-docs", - "version": "1.0.0-dev", + "version": "1.0.0", "devDependencies": { "vitepress": "2.0.0-alpha.20" }, diff --git a/docs/package.json b/docs/package.json index 2ea2a79..ced7b14 100644 --- a/docs/package.json +++ b/docs/package.json @@ -1,6 +1,6 @@ { "name": "solo-repository-docs", - "version": "1.0.0-dev", + "version": "1.0.0", "private": true, "type": "module", "description": "Documentation for Solo Repository", diff --git a/examples/migration.php b/examples/migration.php deleted file mode 100644 index 67d0ecd..0000000 --- a/examples/migration.php +++ /dev/null @@ -1,275 +0,0 @@ - */ - public array $tags = []; - - public function __construct( - public readonly int $id, - public readonly string $sku, - public readonly string $price, - public readonly ?string $name, - public readonly ?string $description, - public readonly ?DateTimeImmutable $deletedAt, - ) { - } -} - -function expect(bool $condition, string $message): void -{ - if (!$condition) { - throw new RuntimeException($message); - } -} - -$logger = new class extends AbstractLogger { - public int $selects = 0; - - public function log($level, string|Stringable $message, array $context = []): void - { - if (isset($context['sql']) && str_starts_with($context['sql'], 'SELECT ')) { - ++$this->selects; - } - } -}; -$configuration = new Configuration(); -$configuration->setMiddlewares([new Middleware($logger)]); -$db = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration); -$db->executeStatement('PRAGMA foreign_keys = ON'); - -// Schema remains the application's responsibility. All relation keys have FKs. -$schema = [ - 'CREATE TABLE categories (id INTEGER PRIMARY KEY, deleted_at DATETIME)', - 'CREATE TABLE category_translations (category_id INTEGER NOT NULL REFERENCES categories(id), ' - . 'locale TEXT NOT NULL, name TEXT, UNIQUE(category_id, locale))', - 'CREATE TABLE tags (id INTEGER PRIMARY KEY, slug TEXT NOT NULL UNIQUE, ' - . 'enabled BOOLEAN NOT NULL, deleted_at DATETIME)', - 'CREATE TABLE tag_translations (tag_id INTEGER NOT NULL REFERENCES tags(id), ' - . 'locale TEXT NOT NULL, name TEXT, UNIQUE(tag_id, locale))', - 'CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, ' - . 'category_id INTEGER REFERENCES categories(id), sku TEXT NOT NULL UNIQUE, ' - . 'price DECIMAL(10, 2) NOT NULL, status TEXT NOT NULL, deleted_at DATETIME)', - 'CREATE TABLE product_translations (product_id INTEGER NOT NULL REFERENCES products(id) ON DELETE CASCADE, ' - . 'locale TEXT NOT NULL, name TEXT, description TEXT, UNIQUE(product_id, locale))', - 'CREATE TABLE product_tags (product_id INTEGER NOT NULL REFERENCES products(id) ON DELETE CASCADE, ' - . 'tag_id INTEGER NOT NULL REFERENCES tags(id), PRIMARY KEY(product_id, tag_id))', -]; -foreach ($schema as $sql) { - $db->executeStatement($sql); -} - -$categoryMapping = new Mapping( - table: 'categories', - columns: ['id' => Types::INTEGER, 'deleted_at' => Types::DATETIME_IMMUTABLE], - hydrate: static fn(array $row): object => (object) $row, - generatedId: false, - softDeleteColumn: 'deleted_at', - translations: new Translations('category_translations', 'category_id', ['name' => Types::STRING], 'en'), -); -$tagMapping = new Mapping( - table: 'tags', - columns: [ - 'id' => Types::INTEGER, - 'slug' => Types::STRING, - 'enabled' => Types::BOOLEAN, - 'deleted_at' => Types::DATETIME_IMMUTABLE, - ], - hydrate: static fn(array $row): object => (object) $row, - generatedId: false, - softDeleteColumn: 'deleted_at', - translations: new Translations('tag_translations', 'tag_id', ['name' => Types::STRING], 'en'), -); -$categories = new Repository($db, $categoryMapping); -$tags = new Repository($db, $tagMapping); -$products = new Repository($db, new Mapping( - table: 'products', - columns: [ - 'id' => Types::INTEGER, - 'category_id' => Types::INTEGER, - 'sku' => Types::STRING, - 'price' => Types::DECIMAL, - 'status' => Types::STRING, - 'deleted_at' => Types::DATETIME_IMMUTABLE, - ], - hydrate: static fn(array $row): Product => new Product( - $row['id'], - $row['sku'], - $row['price'], - $row['name'], - $row['description'], - $row['deleted_at'], - ), - softDeleteColumn: 'deleted_at', - translations: new Translations( - 'product_translations', - 'product_id', - ['name' => Types::STRING, 'description' => Types::TEXT], - 'en', - ), - relations: [ - 'category' => new BelongsTo( - static fn(): Mapping => $categoryMapping, - 'category_id', - static function (Product $product, ?object $category): Product { - $product->category = $category; - return $product; - }, - ), - 'tags' => new BelongsToMany( - static fn(): Mapping => $tagMapping, - 'product_tags', - 'product_id', - 'tag_id', - static function (Product $product, array $tags): Product { - $product->tags = $tags; - return $product; - }, - ), - ], -)); - -$categories->insert(['id' => 1]); -$categories->translations()->save(1, 'en', ['name' => 'Furniture']); -foreach ([[1, 'sale', 'Sale'], [2, 'new', 'New'], [3, 'hidden', 'Hidden']] as [$tagId, $slug, $name]) { - $tags->insert(['id' => $tagId, 'slug' => $slug, 'enabled' => true]); - $tags->translations()->save($tagId, 'en', ['name' => $name]); -} -$tags->delete(3); - -// V3 create() + seedTranslations() + attach(): make the whole creation atomic. -$id = $db->transactional(function () use ($products): int|string { - $id = $products->insertGetId([ - 'category_id' => 1, 'sku' => 'CHAIR-1', 'price' => '29.90', 'status' => 'active', - ]); - $products->translations()->save($id, 'en', ['name' => 'Chair', 'description' => 'English description']); - $products->translations()->save($id, 'uk', ['name' => null, 'description' => '']); - $products->links('tags')->attach($id, [1, 2, 3]); - return $id; -}); -$secondId = $products->insertGetId([ - 'category_id' => 1, 'sku' => 'DESK-1', 'price' => '39.90', 'status' => 'active', -]); -$products->translations()->save($secondId, 'en', ['name' => 'Desk']); -$thirdId = $products->insertGetId([ - 'category_id' => 1, 'sku' => 'LAMP-1', 'price' => '19.90', 'status' => 'active', -]); -$products->translations()->save($thirdId, 'en', ['name' => 'Lamp']); - -// The read settings are reusable and do not mutate the default query. -$default = $products->read(); -$uk = $default->withLocale('uk', fallback: 'en'); -expect($default->find($id)?->name === 'Chair', 'The default locale must remain English.'); -expect($default->withLocale('uk')->find($id)?->name === null, 'Fallback must be explicit.'); -expect($uk->find($id)?->name === 'Chair', 'NULL must use the fallback.'); -expect($uk->find($id)?->description === '', 'An empty translation must stay empty.'); - -$criteria = Filter::all( - ['status' => 'active', 'price >=' => '20.00', 'price <=' => '40.00'], - Filter::related('tags', ['slug' => 'sale', 'enabled' => true]), - ['name' => 'Chair'], -); -$catalog = $uk->with([ - 'category', - new Load('tags', criteria: ['enabled' => true], orderBy: ['name' => 'ASC']), -]); -$logger->selects = 0; -$items = $catalog->findBy($criteria, ['id' => 'ASC'], limit: 20, offset: 0); -expect(count($items) === 1 && $items[0]->id === $id, 'The catalog must match the resolved name and one sale tag.'); -expect($logger->selects === 4, 'The catalog must use owner, category, pivot and target SELECTs.'); -expect($items[0]->category?->name === 'Furniture', 'Loaded relations must inherit fallback.'); -expect(array_column($items[0]->tags, 'name') === ['New', 'Sale'], 'The hidden tag must not be loaded.'); - -// V3 page 2 / perPage 1 becomes offset 1 / limit 1. -$page = 2; -$perPage = 1; -$pageRows = $default->rows(['id'], orderBy: ['id' => 'ASC'], limit: $perPage, offset: ($page - 1) * $perPage); -expect($pageRows === [['id' => $secondId]], 'A page number must be converted to an offset.'); -expect($catalog->with([])->rows(['id'], $criteria) === [['id' => $id]], 'Projection must preserve criteria.'); - -// Writes return counts/IDs, so reread deliberately when the caller needs a model. -$db->transactional(function () use ($products, $id): void { - expect($products->update($id, ['sku' => 'CHAIR-UPDATED']) === 1, 'The base patch must affect one row.'); - $products->translations()->save($id, 'uk', ['name' => 'Оновлений стілець']); - $products->links('tags')->sync($id, [2, 3]); -}); -$physicalIds = static fn(): array => array_map('intval', $db->fetchFirstColumn( - 'SELECT tag_id FROM product_tags WHERE product_id = ? ORDER BY tag_id', - [$id], - [Types::INTEGER], -)); -expect($physicalIds() === [2, 3], 'Sync must retain the explicitly requested hidden membership.'); -expect($items[0]->sku === 'CHAIR-1', 'A previously hydrated model is not automatically updated.'); -expect($uk->find($id)?->sku === 'CHAIR-UPDATED', 'Reread must show the committed base patch.'); -$products->links('tags')->detach($id, []); -expect($physicalIds() === [2, 3], 'An empty detach list must do nothing.'); - -// A late FK failure must roll back base, translation and pivot writes together. -try { - $db->transactional(function () use ($products, $id): void { - $products->update($id, ['sku' => 'MUST-ROLL-BACK']); - $products->translations()->save($id, 'uk', ['name' => 'Must roll back']); - $products->links('tags')->sync($id, [1, 999999]); - }); - throw new RuntimeException('The missing tag must cause an FK exception.'); -} catch (ForeignKeyConstraintViolationException) { - expect(!$db->isTransactionActive(), 'The failed outer transaction must have ended.'); -} -expect($uk->find($id)?->sku === 'CHAIR-UPDATED', 'The base patch must roll back.'); -expect($uk->find($id)?->name === 'Оновлений стілець', 'The translation patch must roll back.'); -expect($physicalIds() === [2, 3], 'The complete physical tag set must roll back.'); -$products->links('tags')->sync($id, []); -expect($physicalIds() === [], 'sync(id, []) clears all physical memberships.'); -$products->links('tags')->attach($id, [2]); - -// Visibility no longer uses a criterion sentinel such as deleted_at => '*'. -expect($products->delete($thirdId) === 1, 'Soft delete must affect the active row.'); -expect($products->delete($thirdId) === 0, 'Repeating soft delete must be a no-op.'); -expect($default->find($thirdId) === null, 'Deleted rows must be hidden by default.'); -expect($default->withVisibility(Visibility::Deleted)->find($thirdId) !== null, 'Deleted visibility must expose it.'); -expect($products->restore($thirdId) === 1, 'Restore must make the row active again.'); -expect($products->purge($thirdId) === 1, 'Purge must delete physically, including configured FK cascades.'); -expect($default->find($thirdId) === null, 'A missing record must return NULL.'); -expect($products->update($thirdId, ['sku' => 'missing']) === 0, 'Update must return an affected count.'); - -// Export consumes pages rather than accumulating model objects. -$export = []; -foreach ($uk->with(['tags'])->iterateById(['status' => 'active'], batchSize: 1) as $product) { - $export[] = ['id' => $product->id, 'name' => $product->name, 'tags' => count($product->tags)]; -} -expect(array_column($export, 'id') === [$id, $secondId], 'Keyset export must visit active owners in ID order.'); -expect($export[0]['tags'] === 1, 'Export relations must reflect the final committed tag set.'); - -echo json_encode([ - 'migration' => 'ok', - 'catalog_selects' => 4, - 'rollback_verified' => true, - 'export' => $export, -], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE) . PHP_EOL; -$db->close();