diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index f75758c..9ed110d 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -146,6 +146,16 @@ classes: use the classes directly. All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace. +### A mapper function given as a class name is created once + +`FieldMapping` created a mapper function given as a class name (`withSelectFunction(StandardMapper::class)`, +the default of every field) for **each value**: on reading, for every field of every row. It is now created +once per `FieldMapping`, at its first use, and reused for every row and query, as a function given as an +instance already was. Each `with*Function()` replaces it. + +Only a custom mapper class that keeps state between calls of `processedValue()` is affected: make it +stateless (it gets the value, the instance and the executor in each call). + ### Observer scope: global → per executor - Observers now fire for writes flowing through the `DatabaseExecutor` instance(s) of the repository where they were registered. Two repositories over different executors no longer @@ -183,6 +193,24 @@ All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace. - The protected property `Query::$limitEnd` that stores it is renamed to `Query::$limitQuantity`. Subclasses of `Query` reading or writing `$this->limitEnd` must use `$this->limitQuantity` +## Performance + +Reading entities (`get()`, `getByQuery()`, `getByFilter()`, `ActiveRecord`) is about 5x faster than at the +start of 7.0 development: 20,000 entities with `getByQuery()`, MySQL ~152 ms -> ~29 ms, SQLite ~147 ms -> +~32 ms (PHP 8.5, Xdebug off). From this library: + +- `MapFromDbToInstanceHandler` fills each entity itself (byjg/anydataset-db `EntityHydratorInterface`): + the property, the field mapping (`selectFunction`) and how the entity takes each column + (byjg/serializer `ObjectCopy::writerFor()`) are resolved once per query, and each row is one loop, with + the same result as before (pinned by `MapFromDbToInstanceHandlerTest`). +- The mapper functions given as a class name are created once (see Breaking Changes). +- `getByQuery()` with several mappers (a join) builds the entities of each mapper with the mapping resolved once + per query (the new `Mapper::entityHydrator()`), instead of for each row; `Mapper::getEntity()` uses the same + hydrator. Same result as before (pinned by `MapFromDbToInstanceHandlerTest::testGetEntityBuildsAsBefore`). + +The rest comes from byjg/anydataset-db and byjg/serializer 7.0 (entity defaults read once per query, +`ObjectCopy` direct array copy and write resolution cached per class). + ## Bug Fixes - `Repository::getByFilter()` paging (and `ActiveRecord::all()`, which uses it) returned the wrong rows past the @@ -205,6 +233,7 @@ All of them are in the `ByJG\MicroOrm\MapperFunctions` namespace. | `Repository` subclass overriding `insert()`/`update()` | Update to the new `OrmSqlStatement` signatures | | `match` over `ObserverEvent` | Add the `SoftDelete` arm | | `->limit(start: $s, end: $n)` (named argument) | `->limit(start: $s, limit: $n)` | +| Custom mapper function class that keeps state per call | Make it stateless: it is created once per `FieldMapping` | ## Requirements diff --git a/docs/controlling-the-data.md b/docs/controlling-the-data.md index 0f4b8f1..0f93e4a 100644 --- a/docs/controlling-the-data.md +++ b/docs/controlling-the-data.md @@ -66,12 +66,19 @@ The `withUpdateFunction`, `withInsertFunction`, and `withSelectFunction` methods Unlike earlier versions, **you cannot pass a closure or callable directly**. You must create a class implementing `MapperFunctionInterface`. +:::note One instance, reused +A class name is created once per `FieldMapping` and reused for every row and query: keep a mapper function +stateless. See [Keep a mapper function stateless](mapper-functions.md#keep-a-mapper-function-stateless). +::: + ## Arguments passed to the processedValue method The `processedValue` method in your custom mapper class will receive three arguments: -- `$value`: The value of the field in the entity class -- `$instance`: The instance of the entity class +- `$value`: The value of the field +- `$instance`: for an update or insert function, the instance of the entity class being saved (`null` when a + primary key is converted for a lookup, as in `get()`); for a select function, the row read: an array of the + columns, merged over the properties of a new entity - `$executor`: The instance of the DatabaseExecutor. You can use it to query the database or convert the value to the database format. diff --git a/docs/mapper-functions.md b/docs/mapper-functions.md index 1ed2bce..13dd56c 100644 --- a/docs/mapper-functions.md +++ b/docs/mapper-functions.md @@ -141,7 +141,9 @@ class MyCustomMapper implements MapperFunctionInterface The `processedValue` method receives: - `$value`: The current value of the field -- `$instance`: The entity instance being processed +- `$instance`: for an update or insert function, the entity instance being saved (`null` when a primary key is + converted for a lookup, as in `get()`); for a select function, the row read: an array of the columns, merged + over the properties of a new entity - `$executor`: The database executor that allows query the database or provides database-specific functions You can then use your custom mapper function just like the built-in ones: @@ -151,6 +153,27 @@ You can then use your custom mapper function just like the built-in ones: protected $myField; ``` +### Keep a mapper function stateless + +A mapper function given as a class name (`MyCustomMapper::class`) is created **once** per field mapping, at its +first use, and that instance is reused for every row, every save and every query, as an instance you pass +(`new MyCustomMapper()`) is. Do not keep state between calls of `processedValue()` (a counter, the previous +value, a cache of the entity): everything a call needs comes in its arguments. + +```php +// Wrong: the second row sees the first row's value +class RunningTotalMapper implements MapperFunctionInterface +{ + private int $total = 0; + + public function processedValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed + { + $this->total += (int)$value; + return $this->total; + } +} +``` + ## How Mapper Functions Work - **Select**: When data is retrieved from the database, the `selectFunction` is applied to transform the value before diff --git a/docs/using-mapper-object.md b/docs/using-mapper-object.md index b561632..0620d15 100644 --- a/docs/using-mapper-object.md +++ b/docs/using-mapper-object.md @@ -254,6 +254,30 @@ $mapper->addFieldMapping( ); ``` +### Building entities from rows + +The `Repository` builds the entities of its queries for you. To build them from values you already have (a raw +query, an import, a test), use the mapper: the field names are mapped to the properties, and the select functions +are applied, as when the repository reads them. + +```php +getEntity(['id' => 10, 'name' => 'Joao', 'createdate' => '2020-01-01']); + +// Many rows of one query: entityHydrator() resolves the mapping once, then builds each entity +$hydrate = $mapper->entityHydrator(); +$users = []; +foreach ($executor->getIterator('SELECT * FROM users') as $row) { + $users[] = $hydrate($row->toArray()); +} +``` + +`getEntity()` resolves the mapping on each call; for many rows, `entityHydrator()` is several times faster. The +properties without a value in the row take the values of a new entity, read once per hydrator (see +[Entity Mapping](https://github.com/byjg/php-anydataset-db/blob/master/docs/entity.md#property-mapping)). +`getByQuery()` with several mappers (a join) uses one hydrator per mapper. + ## Summary | Feature | Attributes | Mapper Objects | diff --git a/src/FieldMapping.php b/src/FieldMapping.php index c1e51a3..7d93ce8 100644 --- a/src/FieldMapping.php +++ b/src/FieldMapping.php @@ -40,6 +40,13 @@ class FieldMapping */ private string $fieldAlias; + /** + * The instance of each function given as a class name, created once (at its first use) instead of for each value + * + * @var array + */ + private array $functionInstances = []; + private bool $syncWithDb = true; private ?string $parentTable = null; @@ -83,6 +90,7 @@ public function withUpdateFunction(MapperFunctionInterface|string $updateFunctio } $this->updateFunction = $updateFunction; + unset($this->functionInstances['update']); return $this; } @@ -93,6 +101,7 @@ public function withSelectFunction(MapperFunctionInterface|string $selectFunctio } $this->selectFunction = $selectFunction; + unset($this->functionInstances['select']); return $this; } @@ -103,6 +112,7 @@ public function withInsertFunction(MapperFunctionInterface|string $insertFunctio } $this->insertFunction = $insertFunction; + unset($this->functionInstances['insert']); return $this; } @@ -165,30 +175,37 @@ public function getFieldAlias(): ?string return $this->fieldAlias; } - public function getSelectFunctionValue(mixed $value, mixed $instance): mixed + /** + * The function itself, or the instance of its class name, created once and reused for every value + */ + private function functionInstance(string $kind, MapperFunctionInterface|string $function): MapperFunctionInterface { - $function = $this->selectFunction; - if (is_string($function)) { - $function = new $function(); + if (!is_string($function)) { + return $function; + } + if (!isset($this->functionInstances[$kind])) { + /** @var MapperFunctionInterface $instance */ + $instance = new $function(); + $this->functionInstances[$kind] = $instance; } + return $this->functionInstances[$kind]; + } + + public function getSelectFunctionValue(mixed $value, mixed $instance): mixed + { + $function = $this->functionInstance('select', $this->selectFunction); return $function->processedValue($value, $instance, null); } public function getUpdateFunctionValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed { - $function = $this->updateFunction; - if (is_string($function)) { - $function = new $function(); - } + $function = $this->functionInstance('update', $this->updateFunction); return $function->processedValue($value, $instance, $executor); } public function getInsertFunctionValue(mixed $value, mixed $instance, ?DatabaseExecutor $executor = null): mixed { - $function = $this->insertFunction; - if (is_string($function)) { - $function = new $function(); - } + $function = $this->functionInstance('insert', $this->insertFunction); return $function->processedValue($value, $instance, $executor); } diff --git a/src/Mapper.php b/src/Mapper.php index 77adbde..8259c3d 100644 --- a/src/Mapper.php +++ b/src/Mapper.php @@ -12,8 +12,8 @@ use ByJG\MicroOrm\Interface\MapperFunctionInterface; use ByJG\MicroOrm\Literal\LiteralInterface; use ByJG\MicroOrm\PropertyHandler\MapFromDbToInstanceHandler; -use ByJG\Serializer\ObjectCopy; use ByJG\Serializer\Serialize; +use Closure; use ReflectionAttribute; use ReflectionClass; use ReflectionException; @@ -229,20 +229,28 @@ public function getEntityClass(): string */ public function getEntity(array $fieldValues = []): object { - $class = $this->entity; - $instance = new $class(); - - // The command below is to get all properties of the class. - // This will allow processing all properties, even if they are not in the $fieldValues array. - // Particularly useful for processing the selectFunction. - $fieldValues = array_merge(Serialize::from($instance)->withStopAtFirstLevel()->toArray(), $fieldValues); - ObjectCopy::copy($fieldValues, $instance, new MapFromDbToInstanceHandler($this)); - - if (is_array($instance)) { - $instance = (object)$instance; - } + return ($this->entityHydrator())($fieldValues); + } - return $instance; + /** + * A function that builds an entity of this mapper from the values of a row (field names), with the mapping + * resolved once for all the rows it builds: the properties of a new entity are read once (at the first level, + * so the properties without a value in the row are processed too, e.g. by a selectFunction), and a + * MapFromDbToInstanceHandler fills each entity. For the rows of one query, such as a join of several mappers. + * + * @return Closure(array): object + */ + public function entityHydrator(): Closure + { + $class = $this->entity; + $handler = new MapFromDbToInstanceHandler($this); + $defaults = Serialize::from(new $class())->withStopAtFirstLevel()->toArray(); + + return static function (array $fieldValues) use ($class, $handler, $defaults): object { + $instance = new $class(); + $handler->hydrate($fieldValues, $instance, $defaults); + return $instance; + }; } public function getQuery(): Query diff --git a/src/PropertyHandler/MapFromDbToInstanceHandler.php b/src/PropertyHandler/MapFromDbToInstanceHandler.php index 1f05fa6..ffec281 100644 --- a/src/PropertyHandler/MapFromDbToInstanceHandler.php +++ b/src/PropertyHandler/MapFromDbToInstanceHandler.php @@ -2,19 +2,96 @@ namespace ByJG\MicroOrm\PropertyHandler; +use BackedEnum; +use ByJG\AnyDataset\Db\Interfaces\EntityHydratorInterface; use ByJG\MicroOrm\FieldMapping; use ByJG\MicroOrm\Mapper; +use ByJG\Serializer\ObjectCopy; use ByJG\Serializer\PropertyHandler\PropertyHandlerInterface; use Override; +use stdClass; -class MapFromDbToInstanceHandler implements PropertyHandlerInterface +/** + * Maps the columns of a row to the properties of the entity of a Mapper (property names, selectFunction). + * + * As a property handler, ObjectCopy calls it for each value. As an entity hydrator, it fills each entity itself + * with the same result: how each column is written is resolved once per query, and each row is one loop. + */ +class MapFromDbToInstanceHandler implements PropertyHandlerInterface, EntityHydratorInterface { protected ?FieldMapping $fieldMap = null; + + /** + * The property name and the field mapping of each field name, resolved once (the handler lives for a query) + * + * @var array + */ + private array $fields = []; + + /** + * How each column is written, resolved once (the handler lives for a query): the property name, the field + * mapping, and ObjectCopy::writerFor() of the entity class + * + * @var array|null}|false}> + */ + private array $plan = []; + public function __construct(private Mapper $mapper) { } + /** + * The same values as ObjectCopy::copy(array_merge($defaults, $row), $entity, $this): for each key in that + * order, the property name (mapName()), the selectFunction (transformValue()), then the setter or the public + * property of the entity, as ObjectCopy writes it (a backed enum member takes the enum). + */ + #[Override] + public function hydrate(array $row, object $entity, array $defaults): void + { + $source = array_merge($defaults, $row); + $className = get_class($entity); + $isStdClass = $entity instanceof stdClass; + + foreach ($source as $key => $value) { + $key = (string)$key; + if (!isset($this->plan[$key])) { + $propertyName = $this->mapName($key); + $this->plan[$key] = [ + $propertyName, + $this->fieldMap, + $isStdClass ? false : ObjectCopy::writerFor($className, $propertyName), + ]; + } + [$propertyName, $fieldMap, $writer] = $this->plan[$key]; + + if ($value instanceof BackedEnum) { + $value = $value->value; + } + if ($fieldMap !== null) { + $value = $fieldMap->getSelectFunctionValue($value, $source) ?? $value; + } + + if ($writer === false) { + // stdClass takes any name; another class, a property the instance has (dynamic or magic) + if ($isStdClass || isset($entity->{$propertyName})) { + $entity->{$propertyName} = $value; + } + continue; + } + + [$member, $isSetter, $enum] = $writer; + if ($enum !== null && (is_int($value) || is_string($value))) { + $value = $enum::from($value); + } + if ($isSetter) { + $entity->{$member}($value); + continue; + } + $entity->{$member} = $value; + } + } + #[Override] /** * Note: @@ -26,8 +103,12 @@ public function __construct(private Mapper $mapper) */ public function mapName(string $property): string { - $propertyName = $this->mapper->getPropertyName($property); - $this->fieldMap = $this->mapper->getFieldMap($propertyName); + if (!isset($this->fields[$property])) { + $propertyName = $this->mapper->getPropertyName($property); + $fieldMap = $this->mapper->getFieldMap($propertyName); + $this->fields[$property] = [$propertyName, $fieldMap instanceof FieldMapping ? $fieldMap : null]; + } + [$propertyName, $this->fieldMap] = $this->fields[$property]; return $propertyName; } diff --git a/src/Repository.php b/src/Repository.php index b1142c9..b8cb043 100644 --- a/src/Repository.php +++ b/src/Repository.php @@ -35,6 +35,7 @@ use ByJG\Serializer\Serialize; use ByJG\XmlUtil\Exception\FileException; use ByJG\XmlUtil\Exception\XmlUtilException; +use Closure; use Exception; use ReflectionException; use stdClass; @@ -570,14 +571,12 @@ public function getByQuery(QueryBuilderInterface $query, array $mapper = [], ?Ca } $iterator = $this->getExecutor()->getIterator($sqlBuild); - // Manually map each row to multiple entities + // Map each row to the entity of each mapper, with the mapping of each resolved once for the query + $hydrators = array_map(fn(Mapper $item) => $item->entityHydrator(), $mapper); $result = []; foreach ($iterator as $row) { - $collection = []; - foreach ($mapper as $item) { - $instance = $item->getEntity($row->toArray()); - $collection[] = $instance; - } + $values = $row->toArray(); + $collection = array_map(fn(Closure $hydrate) => $hydrate($values), $hydrators); $result[] = count($collection) === 1 ? $collection[0] : $collection; } diff --git a/tests/MapFromDbToInstanceHandlerTest.php b/tests/MapFromDbToInstanceHandlerTest.php new file mode 100644 index 0000000..5d6c328 --- /dev/null +++ b/tests/MapFromDbToInstanceHandlerTest.php @@ -0,0 +1,113 @@ +addFieldMapping(FieldMapping::create('value')->withFieldName('property')); + $info->addFieldMapping(FieldMapping::create('registrationId')->withFieldName('registration_id')); + + $selectFunction = new Mapper(Users::class, 'users', 'Id'); + $selectFunction->addFieldMapping(FieldMapping::create('name')->withSelectFunction(CountingMapper::class)); + + return [ + 'setters, protected properties' => [ + new Mapper(Users::class, 'users', 'Id'), + [['id' => '1', 'name' => 'Joao', 'createdate' => '2020-01-01'], ['id' => '2', 'name' => null, 'createdate' => '']], + ], + 'column mapped to another property, a column without property' => [ + $info, + [['id' => '1', 'iduser' => '3', 'property' => '10.5', 'registration_id' => 'r1', 'created_at' => 'x']], + ], + 'selectFunction' => [ + $selectFunction, + [['id' => '1', 'name' => 'Joao', 'createdate' => '2020-01-01'], ['id' => '2', 'name' => 'Maria', 'createdate' => '2021-01-01']], + ], + 'backed enum property, typed public properties' => [ + new Mapper(Order::class), + [['id' => '1', 'status' => 'PAID'], ['id' => '2', 'status' => null], ['id' => '3', 'status' => OrderStatus::Pending]], + ], + 'stdClass' => [ + new Mapper(stdClass::class, 'anything', 'id'), + [['id' => '1', 'name' => 'Joao'], ['id' => '2', 'other' => '']], + ], + ]; + } + + #[DataProvider('hydrateProvider')] + public function testHydrateFillsAsObjectCopyWithTheHandler(Mapper $mapper, array $rows): void + { + $class = $mapper->getEntityClass(); + // As GenericDbIterator reads them: at the first level + $defaults = Serialize::from(new $class())->withStopAtFirstLevel()->toArray(); + // One handler per query, for each path + $hydrator = new MapFromDbToInstanceHandler($mapper); + $handler = new MapFromDbToInstanceHandler($mapper); + + foreach ($rows as $i => $row) { + $hydrated = new $class(); + $hydrator->hydrate($row, $hydrated, $defaults); + + $copied = new $class(); + ObjectCopy::copy(array_merge($defaults, $row), $copied, $handler); + + $this->assertEquals((array)$copied, (array)$hydrated, "Row $i"); + } + } + + /** + * Mapper::getEntity() built each entity as ObjectCopy::copy() of the row merged over the properties of the + * entity, with the handler; it now uses the hydrator, with the same result + */ + #[DataProvider('hydrateProvider')] + public function testGetEntityBuildsAsBefore(Mapper $mapper, array $rows): void + { + $hydrate = $mapper->entityHydrator(); + + foreach ($rows as $i => $row) { + $class = $mapper->getEntityClass(); + $before = new $class(); + ObjectCopy::copy( + array_merge(Serialize::from($before)->withStopAtFirstLevel()->toArray(), $row), + $before, + new MapFromDbToInstanceHandler($mapper) + ); + + $this->assertEquals((array)$before, (array)$mapper->getEntity($row), "getEntity, row $i"); + $this->assertEquals((array)$before, (array)$hydrate($row), "entityHydrator, row $i"); + } + } + + public function testHydrateUsesTheSelectFunctionAndTheMapping(): void + { + $mapper = new Mapper(Info::class, 'info', 'id'); + $mapper->addFieldMapping(FieldMapping::create('value')->withFieldName('property')->withSelectFunction(CountingMapper::class)); + + $info = new Info(); + (new MapFromDbToInstanceHandler($mapper))->hydrate(['id' => '7', 'property' => '10.5'], $info, []); + + $this->assertEquals('7', $info->getId()); + $this->assertEquals('mapped:10.5', $info->getValue()); + } +} diff --git a/tests/MapperFunctionsTest.php b/tests/MapperFunctionsTest.php index 58fd29a..6caed21 100644 --- a/tests/MapperFunctionsTest.php +++ b/tests/MapperFunctionsTest.php @@ -4,6 +4,7 @@ use ByJG\AnyDataset\Db\DatabaseExecutor; use ByJG\AnyDataset\Db\Interfaces\SqlDialectInterface; +use ByJG\MicroOrm\FieldMapping; use ByJG\MicroOrm\Literal\HexUuidLiteral; use ByJG\MicroOrm\Literal\Literal; use ByJG\MicroOrm\Literal\LiteralInterface; @@ -14,9 +15,44 @@ use ByJG\MicroOrm\MapperFunctions\StandardMapper; use PHPUnit\Framework\TestCase; use stdClass; +use Tests\Model\CountingMapper; class MapperFunctionsTest extends TestCase { + // A function given as a class name is created once and reused for every value + + public function testFunctionClassNameIsCreatedOnceAndReused() + { + CountingMapper::$instances = 0; + $fieldMapping = FieldMapping::create('name') + ->withSelectFunction(CountingMapper::class) + ->withUpdateFunction(CountingMapper::class) + ->withInsertFunction(CountingMapper::class); + + $this->assertEquals('mapped:a', $fieldMapping->getSelectFunctionValue('a', null)); + $this->assertEquals('mapped:b', $fieldMapping->getSelectFunctionValue('b', null)); + $this->assertEquals('mapped:c', $fieldMapping->getUpdateFunctionValue('c', null)); + $this->assertEquals('mapped:d', $fieldMapping->getUpdateFunctionValue('d', null)); + $this->assertEquals('mapped:e', $fieldMapping->getInsertFunctionValue('e', null)); + $this->assertEquals('mapped:f', $fieldMapping->getInsertFunctionValue('f', null)); + + // One for each function (select, update, insert), not one for each value + $this->assertEquals(3, CountingMapper::$instances); + $this->assertEquals(CountingMapper::class, $fieldMapping->getSelectFunction()); + } + + public function testFunctionReplacedIsUsed() + { + $fieldMapping = FieldMapping::create('name')->withSelectFunction(CountingMapper::class); + $this->assertEquals('mapped:a', $fieldMapping->getSelectFunctionValue('a', null)); + + $fieldMapping->withSelectFunction(StandardMapper::class); + $this->assertEquals('b', $fieldMapping->getSelectFunctionValue('b', null)); + + $fieldMapping->withSelectFunction(new CountingMapper()); + $this->assertEquals('mapped:c', $fieldMapping->getSelectFunctionValue('c', null)); + } + // StandardMapper Tests public function testStandardMapperWithNonEmptyValue() diff --git a/tests/Model/CountingMapper.php b/tests/Model/CountingMapper.php new file mode 100644 index 0000000..82666e5 --- /dev/null +++ b/tests/Model/CountingMapper.php @@ -0,0 +1,25 @@ +