diff --git a/src/ORM/Parser/Typecast.php b/src/ORM/Parser/Typecast.php index 825dd82..2e3ef63 100644 --- a/src/ORM/Parser/Typecast.php +++ b/src/ORM/Parser/Typecast.php @@ -49,7 +49,11 @@ final class Typecast implements CastableInterface, UncastableInterface /** @var array */ private array $uncasters = []; - /** @var array Rules that are a plain PHP cast. */ + /** + * Rules that compiled makers can inline: a plain PHP cast, or the caster of a datetime. + * + * @var array + */ private array $plain = []; /** @@ -67,11 +71,6 @@ public function setRules(array $rules): array foreach ($rules as $key => $rule) { // Static rules if (\in_array($rule, self::RULES, true)) { - if ($rule === 'int' || $rule === 'bool' || $rule === 'float') { - $this->plain[$key] = $rule; - } else { - unset($this->plain[$key]); - } $this->casters[$key] = match ($rule) { 'int' => static fn(mixed $value): int => (int) $value, 'bool' => static fn(mixed $value): bool => (bool) $value, @@ -90,6 +89,15 @@ public function setRules(array $rules): array ), }; + if ($rule === 'int' || $rule === 'bool' || $rule === 'float') { + $this->plain[$key] = $rule; + } elseif ($rule === 'datetime') { + // Database timestamps always parse: the maker calls the caster directly. + $this->plain[$key] = $this->casters[$key]; + } else { + unset($this->plain[$key]); + } + if ($rule === 'json') { $this->uncasters[$key] = static fn(mixed $value): string => \json_encode( $value, @@ -158,12 +166,12 @@ public function setRules(array $rules): array } /** - * The rules as plain casts (`int`, `bool`, `float`) when every rule is one, - * so callers can compile them; null otherwise. + * The rules as plain casts (`int`, `bool`, `float`) or datetime casters when every + * rule is one, so callers can compile them; null otherwise. * * @internal * - * @return array|null + * @return array|null */ public function plainRules(): ?array { diff --git a/src/ORM/Schema.php b/src/ORM/Schema.php index 9a6525c..3512e1c 100644 --- a/src/ORM/Schema.php +++ b/src/ORM/Schema.php @@ -184,6 +184,11 @@ private function normalize(array $schema): array } unset($item[self::ROLE]); + // A one-column key compiled as a list is the same key; the string form keeps the + // single-key fast paths (compiled row makers, direct inserts and updates) available. + if (\is_array($item[self::PRIMARY_KEY] ?? null) && \count($item[self::PRIMARY_KEY]) === 1) { + $item[self::PRIMARY_KEY] = \reset($item[self::PRIMARY_KEY]); + } $result[$role] = $item; } diff --git a/src/ORM/Select.php b/src/ORM/Select.php index 880931c..165d444 100644 --- a/src/ORM/Select.php +++ b/src/ORM/Select.php @@ -186,6 +186,15 @@ public function buildQuery(): SelectQuery */ public function wherePK(string|int|array|object ...$ids): self { + if (!$this->customized && \count($ids) === 1) { + $id = \reset($ids); + // One scalar key on a single-column primary key is a plain where(): recorded, so + // fetchOne() and fetchAll() can run the cached statement of the shape. + $pk = (\is_int($id) || \is_string($id)) ? ($this->deferred[0] ?? $this->loader)->getPrimaryFields() : []; + if (\count($pk) === 1) { + return $this->where(\reset($pk), $id); + } + } $this->customized = true; $pk = $this->loader->getPrimaryFields(); @@ -607,20 +616,39 @@ public function orWhereJsonLength(string $path, int $length, string $operator = /** * Attention, column will be quoted by driver! * - * @param non-empty-string|null $column When column is null DISTINCT(PK) will be generated. + * @param non-empty-string|null $column When column is null DISTINCT(PK) will be generated, or COUNT(*) + * when the query has no join, grouping or DISTINCT that could repeat a primary key. */ public function count(?string $column = null): int { + $query = $this->buildQuery(); if ($column === null) { $pk = (array) $this->loader->getPK(); - $column = \count($pk) > 1 + $column = \count($pk) > 1 || self::rowsAreUnique($query) ? '*' : \sprintf('DISTINCT(%s)', \reset($pk)); } - return (int) $this->builder->withQuery( - $this->buildQuery(), - )->count($column); + return (int) $this->builder->withQuery($query)->count($column); + } + + /** + * Every row of a single-table query without joins, grouping or set operations is a distinct + * entity, so COUNT(*) equals COUNT(DISTINCT pk) and skips the sort or hash of the primary keys. + */ + private static function rowsAreUnique(SelectQuery $query): bool + { + $tokens = $query->getTokens(); + + return \count($tokens['from']) === 1 + && \is_string(\reset($tokens['from'])) + && $tokens['join'] === [] + && $tokens['distinct'] === false + && $tokens['groupBy'] === [] + && $tokens['having'] === [] + && $tokens['union'] === [] + && $tokens['intersect'] === [] + && $tokens['except'] === []; } /** @@ -983,6 +1011,13 @@ public function fetchByPrimaryKeyPlan(array $plan, int|string $id): ?object */ public function fetchOne(?array $query = null): ?object { + if (!$this->customized && ($query === null || $query === [])) { + // Same entity as below through the cached statement and row maker of the shape. + $rows = (clone $this)->limit(1)->fetchShape(); + if ($rows !== null) { + return $rows[0] ?? null; + } + } $select = (clone $this)->where($query)->limit(1); $data = $select->loadData(); @@ -1001,22 +1036,9 @@ public function fetchOne(?array $query = null): ?object */ public function fetchAll(): iterable { - if (!$this->customized) { - $plan = $this->shapes[$this->shape] ?? null; - if ($plan === null && \count($this->shapes) < 1024) { - $plan = $this->shapes[$this->shape] = $this->shapePlan(); - } - if ($plan) { - [$driver, $sql, $values, $slots, $maker] = $plan; - foreach ($slots as $i => $index) { - $values[$index] = new Parameter($this->shapeValues[$i]); - } - $statement = $driver->query($sql, $values); - $rows = $statement->fetchAll(StatementInterface::FETCH_NUM); - $statement->close(); - - return $maker($rows); - } + $entities = $this->fetchShape(); + if ($entities !== null) { + return $entities; } $maker = $this->rowMaker(); @@ -1139,12 +1161,47 @@ private function applyRecorded(): void $this->recorded = []; } + /** + * Runs the cached statement of the recorded shape; null when the select was customized + * or its shape can't be cached. + * + * @return list|null + */ + private function fetchShape(): ?array + { + if ($this->customized) { + return null; + } + $plan = $this->shapes[$this->shape] ?? null; + if ($plan === null && \count($this->shapes) < 1024) { + $plan = $this->shapes[$this->shape] = $this->shapePlan(); + } + if (!$plan) { + return null; + } + [$driver, $sql, $values, $slots, $maker] = $plan; + foreach ($slots as $i => $index) { + $values[$index] = new Parameter($this->shapeValues[$i]); + } + $statement = $driver->query($sql, $values); + $rows = $statement->fetchAll(StatementInterface::FETCH_NUM); + $statement->close(); + + return $maker($rows); + } + /** * Compiles the recorded shape once with sentinel values and finds where each * value lands in the statement parameters. False when the shape can't be cached. */ private function shapePlan(): array|false { + // A scope adds its own values (a tenant, a soft-delete flag) when the query is built; + // a cached statement would keep the first ones. + $role = ($this->deferred[0] ?? $this->loader)->getTarget(); + if ($this->schema->define($role, SchemaInterface::SCOPE) !== null) { + return false; + } $copy = clone $this; $sentinels = []; foreach ($copy->shapeValues as $i => $_) { @@ -1318,6 +1375,7 @@ private static function readsWholeTable(SelectQuery $query): bool $tokens = $query->getTokens(); return \count($tokens['from']) === 1 + && \is_string(\reset($tokens['from'])) && $tokens['join'] === [] && $tokens['where'] === [] && $tokens['having'] === [] diff --git a/src/ORM/Service/Implementation/EntityFactory.php b/src/ORM/Service/Implementation/EntityFactory.php index 0771a97..35f0605 100644 --- a/src/ORM/Service/Implementation/EntityFactory.php +++ b/src/ORM/Service/Implementation/EntityFactory.php @@ -166,6 +166,8 @@ private function makerPlan(string $role, array $fields, bool $loaded = false): ? || $rRole !== $role || $this->schema->define($role, SchemaInterface::PARENT) !== null || ($this->schema->define($role, SchemaInterface::CHILDREN) ?? []) !== [] + // Joined-table subclasses: a row may belong to a subclass the maker doesn't build. + || $this->schema->getInheritedRoles($role) !== [] || \count(\array_unique($fields)) !== \count($fields) || !\in_array($pk, $fields, true) ) { @@ -215,11 +217,17 @@ private function compileDataMaker(string $role): ?\Closure } $items = []; + $casters = []; foreach (\array_intersect_key($rules, \array_flip($fields)) as $field => $rule) { $key = \var_export($field, true); + if ($rule instanceof \Closure) { + $casters[$field] = $rule; + $items[] = "\$d[{$key}] === null or \$d[{$key}] = \$casters[{$key}](\$d[{$key}]);"; + continue; + } $items[] = "\$d[{$key}] === null or \$d[{$key}] = ({$rule}) \$d[{$key}];"; } - $cast = eval("declare(strict_types=1);\nreturn static function (array \$d): array {\n" . \implode("\n", $items) . "\nreturn \$d;\n};"); + $cast = eval("declare(strict_types=1);\nreturn static function (array \$d) use (\$casters): array {\n" . \implode("\n", $items) . "\nreturn \$d;\n};"); $flip = \array_fill_keys($fields, true); $count = \count($fields); $heap = $this->heap; @@ -267,10 +275,17 @@ private function compileRowMaker(string $role, array $columns, ?string $groupBy, // Typecast compiled into the array literal: null stays null, as in Typecast::cast(). $items = []; + $casters = []; foreach ($columns as $i => $field) { $key = \var_export($field, true); - $items[] = isset($rules[$field]) - ? "{$key} => \$row[{$i}] === null ? null : ({$rules[$field]}) \$row[{$i}]" + $rule = $rules[$field] ?? null; + if ($rule instanceof \Closure) { + $casters[$field] = $rule; + $items[] = "{$key} => \$row[{$i}] === null ? null : \$casters[{$key}](\$row[{$i}])"; + continue; + } + $items[] = $rule !== null + ? "{$key} => \$row[{$i}] === null ? null : ({$rule}) \$row[{$i}]" : "{$key} => \$row[{$i}]"; } $build = \implode(', ', $items); @@ -336,7 +351,7 @@ private function compileRowMaker(string $role, array $columns, ?string $groupBy, // $nodes the heap node of each result. $maker = eval(<<loadedStorage(); \$index = &\$heap->loadedIndex({$roleKey}); diff --git a/src/ORM/Transaction/DirectInsert.php b/src/ORM/Transaction/DirectInsert.php index 5c6559c..b5d22f7 100644 --- a/src/ORM/Transaction/DirectInsert.php +++ b/src/ORM/Transaction/DirectInsert.php @@ -50,6 +50,10 @@ public function plan(object $entity, bool $cascade, array $persisted, array &$cl return null; } $fields = $root['mapper']->fetchFields($entity); + if ($fields === []) { + // Nothing to write: the command generator decides between an empty insert and no write. + return null; + } $slaves = []; if ($cascade && $root['slaves'] !== []) { diff --git a/src/ORM/Transaction/UnitOfWork.php b/src/ORM/Transaction/UnitOfWork.php index fa9c534..dcb65e1 100644 --- a/src/ORM/Transaction/UnitOfWork.php +++ b/src/ORM/Transaction/UnitOfWork.php @@ -310,8 +310,14 @@ private function describeDirect(string $role): ?array private function runDirect(array $plan): StateInterface { $drivers = []; - $begin = static function (DatabaseInterface $db) use (&$drivers): void { + // A lone statement is atomic by itself: outside a transaction it runs in autocommit + // and saves the BEGIN and COMMIT round trips. + $single = self::singleStatement($plan); + $begin = static function (DatabaseInterface $db) use (&$drivers, $single): void { $driver = $db->getDriver(); + if ($single && $driver->getTransactionLevel() === 0) { + return; + } if (!\in_array($driver, $drivers, true)) { $driver->beginTransaction(); $drivers[] = $driver; @@ -369,6 +375,19 @@ private function runDirect(array $plan): StateInterface return $this; } + /** + * Whether the direct plan writes exactly one row: one update, or one insert without children. + */ + private static function singleStatement(array $plan): bool + { + if (\count($plan) !== 1) { + return false; + } + [$insert, $op] = \reset($plan); + + return !$insert || $op[3] === []; + } + private function runCommand(?CommandInterface $command): void { if ($command === null) {