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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 2 additions & 8 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
147 changes: 18 additions & 129 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
Expand All @@ -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<Model>`. 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.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -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
Expand Down
112 changes: 27 additions & 85 deletions README.md
Original file line number Diff line number Diff line change
@@ -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
<?php

require 'vendor/autoload.php';

use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Types\Types;
use Solo\Repository\Mapping;
Expand All @@ -48,77 +37,30 @@ $products = new Repository($db, new Mapping(
));

$id = $products->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).
Loading
Loading