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
26 changes: 17 additions & 9 deletions src/ORM/Parser/Typecast.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,11 @@ final class Typecast implements CastableInterface, UncastableInterface
/** @var array<non-empty-string, \Closure(mixed): mixed> */
private array $uncasters = [];

/** @var array<non-empty-string, 'int'|'bool'|'float'> 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<non-empty-string, 'int'|'bool'|'float'|\Closure(mixed): mixed>
*/
private array $plain = [];

/**
Expand All @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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<non-empty-string, 'int'|'bool'|'float'>|null
* @return array<non-empty-string, 'int'|'bool'|'float'|\Closure(mixed): mixed>|null
*/
public function plainRules(): ?array
{
Expand Down
5 changes: 5 additions & 0 deletions src/ORM/Schema.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
100 changes: 79 additions & 21 deletions src/ORM/Select.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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'] === [];
}

/**
Expand Down Expand Up @@ -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();

Expand All @@ -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();
Expand Down Expand Up @@ -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<TEntity>|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 => $_) {
Expand Down Expand Up @@ -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'] === []
Expand Down
23 changes: 19 additions & 4 deletions src/ORM/Service/Implementation/EntityFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -336,7 +351,7 @@ private function compileRowMaker(string $role, array $columns, ?string $groupBy,
// $nodes the heap node of each result.
$maker = eval(<<<PHP
declare(strict_types=1);
return static function (iterable \$rows, ?array &\$fresh = null, ?array &\$nodes = null, ?array &\$groups = null, ?array \$only = null) use (\$heap, \$make, \$prototype, \$relMap, \$nodePrototype): array {
return static function (iterable \$rows, ?array &\$fresh = null, ?array &\$nodes = null, ?array &\$groups = null, ?array \$only = null) use (\$heap, \$make, \$prototype, \$relMap, \$nodePrototype, \$casters): array {
\$result = [];
{$seenInit} \$storage = \$heap->loadedStorage();
\$index = &\$heap->loadedIndex({$roleKey});
Expand Down
4 changes: 4 additions & 0 deletions src/ORM/Transaction/DirectInsert.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'] !== []) {
Expand Down
21 changes: 20 additions & 1 deletion src/ORM/Transaction/UnitOfWork.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
Loading