Skip to content
Closed
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
54 changes: 0 additions & 54 deletions analyzer-baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -282,60 +282,6 @@ code = "missing-return-type"
message = "Function `__unset` is missing a return type hint."
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "class-must-be-final"
message = 'Class `PhpDb\Sql\Platform\Platform` should be declared `final`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "mixed-array-assignment"
message = "Unsafe array assignment on type `mixed`."
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "mixed-return-statement"
message = 'Could not infer a precise return type for function `PhpDb\Sql\Platform\Platform::getDecorators`. Saw type `mixed`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "non-existent-method"
message = 'Method `getSqlString` does not exist on type `PhpDb\Sql\Platform\PlatformDecoratorInterface`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "non-existent-method"
message = 'Method `getSqlString` does not exist on type `PhpDb\Sql\PreparableSqlInterface`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "non-existent-method"
message = 'Method `prepareStatement` does not exist on type `PhpDb\Sql\Platform\PlatformDecoratorInterface`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "non-existent-method"
message = 'Method `prepareStatement` does not exist on type `PhpDb\Sql\SqlInterface`.'
count = 1

[[issues]]
file = "src/Sql/Platform/Platform.php"
code = "possibly-undefined-string-array-index"
message = "Possibly undefined array key `string` accessed on `array<array-key, mixed>`."
count = 1

[[issues]]
file = "src/Sql/Platform/PlatformDecoratorInterface.php"
code = "missing-api-or-internal"
message = 'Interface `PhpDb\Sql\Platform\PlatformDecoratorInterface` is missing an `@api` or `@internal` annotation.'
count = 1

[[issues]]
file = "src/Sql/Select.php"
code = "missing-return-type"
Expand Down
77 changes: 77 additions & 0 deletions docs/book/sql/platform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Platforms and Decorators

Rendering a statement for a driver is split across two objects, and both are
called a platform:

| | Contract | Responsibility | Supplied by |
|---|---|---|---|
| Adapter platform | `PhpDb\Adapter\Platform\PlatformInterface` | quoting identifiers and values | the driver package (`Mysql\AdapterPlatform`, or `Sqlite\AdapterPlatform`), or `Adapter\Platform\Sql92` for standard SQL |
| SQL platform | `PhpDb\Sql\Platform\PlatformDecoratorInterface` | rendering `Sql` objects, decorating the statements a dialect writes differently | the driver package, or `Sql\Platform\Platform` for standard SQL |

The adapter platform only knows syntax. The SQL platform knows the language: it
takes a `Select`, `Insert`, `CreateTable` and so on and turns it into a string.

## One platform per adapter

`Sql` takes its SQL platform from the adapter it was constructed with:

```php
$sql = new Sql($adapter); // $adapter->getPlatform()->getSqlPlatformDecorator()
$select = $sql->select('users')->where(['active' => 1]);
```

Nothing is resolved while rendering. The dialect is fixed when the adapter is
built, so a statement is always rendered for the platform it will run on. Two
drivers in one process mean two adapters and two `Sql` instances, each with its
own platform, which is what a cross-platform migration needs.

## Decorators

A platform registers a decorator for each subject type whose rendering differs
from standard SQL:

```php
final class Platform extends AbstractPlatform
{
public function __construct()
{
$this->setTypeDecorator(Select::class, new SelectDecorator());
$this->setTypeDecorator(CreateTable::class, new CreateTableDecorator());
}
}
```

A decorator must implement the type it is registered for. `setTypeDecorator()`
rejects anything else with `Sql\Exception\RuntimeException::DECORATOR_WRONG_TYPE`,
because a decorator that cannot render the subject it is registered for would
otherwise fail later, at the point of use.

Lookup goes through `decoratorFor()`:

```php
$decorator = $platform->decoratorFor($subject); // bound to $subject, or null

return ($decorator ?? $subject)->getSqlString();
```

A `null` result means this dialect writes the statement as standard SQL, so the
subject renders itself. That is the common case: a platform holds only the
differences for its dialect, and standard SQL needs none.

## Writing a driver package

A driver package is complete when it provides all of the following and needs no
change to `phpdb`:

- a `ConfigProvider` registering the driver, connection, statement, result,
platform and metadata services;
- a `Driver` implementation;
- a `Connection` implementation;
- an `AdapterPlatform` for naming, identifier quoting and value quoting;
- optionally, a `Sql\Platform` carrying the decorators for its dialect;
- optionally, driver features for capabilities that SQL cannot express, chosen by
the driver rather than named by the abstraction.

Keep dialect knowledge in the package that owns the dialect. Core must not name a
driver class, and `PlatformInterface::getName()` is for labels only, never for
dispatch.
21 changes: 21 additions & 0 deletions mago.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@ php-version = "8.3.0"
paths = ["src", "test"]
includes = ["vendor"]

[guard]
excludes = ["vendor", "test"]

[guard.perimeter]
layering-reason = """
The Adapter layer is the abstraction; the Sql layer is built on it. The only thing the
Adapter layer may take from PhpDb\\Sql\\Platform is the decorator contract it returns from
PlatformInterface::getSqlPlatformDecorator(). Everything else in that namespace renders Sql
objects and belongs to the Sql layer.
"""

[[guard.perimeter.restrictions]]
dependency = "PhpDb\\Sql\\Platform\\AbstractPlatform"
deny-from = ["PhpDb\\Adapter"]
reason = "Only PlatformDecoratorInterface crosses from Sql\\Platform into the Adapter layer; the platform classes that render Sql objects do not."

[[guard.perimeter.restrictions]]
dependency = "PhpDb\\Adapter\\Platform\\AbstractPlatform"
deny-from = ["PhpDb\\Sql"]
reason = "The Sql layer depends on the Adapter platform contract, not on an implementation base class."

[formatter]
parentheses-around-new-in-member-access = true

Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ nav:
- Where and Having: sql/where-having.md
- Examples: sql/examples.md
- Advanced Usage: sql/advanced.md
- Platforms and Decorators: sql/platform.md
- "DDL Abstraction":
- Introduction: sql-ddl/intro.md
- Columns: sql-ddl/columns.md
Expand Down
8 changes: 4 additions & 4 deletions src/Sql/Exception/RuntimeException.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@

class RuntimeException extends Exception\RuntimeException
{
final public const string DECORATOR_NOT_IMPLEMENTING =
final public const string DECORATOR_WRONG_TYPE =
'The decorator %s does not implement %s,'
. ' thus %s cannot be delegated to it';
. ' so it cannot be registered for that type';

final public const string REPLACEMENT_MISMATCH =
'The number of replacements in the expression'
Expand Down Expand Up @@ -42,9 +42,9 @@ class RuntimeException extends Exception\RuntimeException
'%s renders its expression string and does not accept'
. ' a specification override; use setExpression() instead';

public static function forDecoratorNotImplementing(string $decorator, string $interface, string $method): self
public static function forDecoratorWrongType(string $decorator, string $type): self
{
return new self(sprintf(self::DECORATOR_NOT_IMPLEMENTING, $decorator, $interface, $method));
return new self(sprintf(self::DECORATOR_WRONG_TYPE, $decorator, $type));
}

public static function forReplacementMismatch(): self
Expand Down
106 changes: 48 additions & 58 deletions src/Sql/Platform/AbstractPlatform.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,42 @@
use PhpDb\Sql\PreparableSqlInterface;
use PhpDb\Sql\SqlInterface;

/**
* Renders Sql objects for a single dialect.
*
* A decorator is registered for each subject type whose rendering differs from standard
* SQL. A subject with no registered decorator renders itself, so a platform holds only
* the differences for the dialect it belongs to.
*/
class AbstractPlatform implements PlatformDecoratorInterface, PreparableSqlInterface, SqlInterface
{
protected SqlInterface|PreparableSqlInterface|null $subject = null;

/**
* Decorators keyed by the subject type they decorate; Platform nests them under a platform name first
*
* @var array<string, PlatformDecoratorInterface|array<string, PlatformDecoratorInterface>>
*/
/** @var array<class-string, PlatformDecoratorInterface> */
protected array $decorators = [];

/**
* @return array<string, PlatformDecoratorInterface>
* The decorator registered for this subject, bound to it, or null when it renders itself.
*/
public function decoratorFor(PreparableSqlInterface|SqlInterface $subject): ?PlatformDecoratorInterface
{
foreach ($this->decorators as $type => $decorator) {
/** @phpstan-ignore-next-line instanceof with a string class name is valid */
if (! $subject instanceof $type) {
continue;
}

$decorator->setSubject($subject);

return $decorator;
}

return null;
}

/** @return array<class-string, PlatformDecoratorInterface> */
public function getDecorators(): array
{
/** @var array<string, PlatformDecoratorInterface> */
return $this->decorators;
}

Expand All @@ -40,33 +59,17 @@ public function getDecorators(): array
#[Override]
public function getSqlString(?PlatformInterface $adapterPlatform = null): string
{
if (! $this->subject instanceof SqlInterface) {
$subject = $this->subject;
if (! $subject instanceof SqlInterface) {
throw Exception\RuntimeException::forSubjectNotImplementing(SqlInterface::class, 'getSqlString()');
}

return $this->requireDecoratorImplementing(
$this->getTypeDecorator($this->subject),
SqlInterface::class,
'getSqlString()',
)->getSqlString($adapterPlatform);
}

public function getTypeDecorator(
PreparableSqlInterface|SqlInterface $subject,
): PlatformDecoratorInterface|PreparableSqlInterface|SqlInterface {
/** @var array<string, PlatformDecoratorInterface> $decorators */
$decorators = $this->decorators;
foreach ($decorators as $type => $decorator) {
/** @phpstan-ignore-next-line instanceof with string class name is valid */
if (! $subject instanceof $type) {
continue;
}

$decorator->setSubject($subject);
return $decorator;
$renderer = $this->decoratorFor($subject);
if (! $renderer instanceof SqlInterface) {
$renderer = $subject;
}

return $subject;
return $renderer->getSqlString($adapterPlatform);
}

/**
Expand All @@ -77,55 +80,42 @@ public function prepareStatement(
AdapterInterface $adapter,
StatementContainerInterface $statementContainer,
): StatementContainerInterface {
if (! $this->subject instanceof PreparableSqlInterface) {
$subject = $this->subject;
if (! $subject instanceof PreparableSqlInterface) {
throw Exception\RuntimeException::forSubjectNotImplementing(
PreparableSqlInterface::class,
'prepareStatement()',
);
}

$this->requireDecoratorImplementing(
$this->getTypeDecorator($this->subject),
PreparableSqlInterface::class,
'prepareStatement()',
)->prepareStatement($adapter, $statementContainer);
$renderer = $this->decoratorFor($subject);
if (! $renderer instanceof PreparableSqlInterface) {
$renderer = $subject;
}

return $statementContainer;
return $renderer->prepareStatement($adapter, $statementContainer);
}

/**
* {@inheritDoc}
*/
/** {@inheritDoc} */
#[Override]
public function setSubject($subject): static
public function setSubject(SqlInterface|PreparableSqlInterface|null $subject): static
{
$this->subject = $subject;

return $this;
}

public function setTypeDecorator(string $type, PlatformDecoratorInterface $decorator): void
{
$this->decorators[$type] = $decorator;
}

/**
* Narrows the resolved decorator to the interface whose method is about to be delegated to it
* @param class-string $type The Sql type this decorator renders.
*
* @template T of PreparableSqlInterface|SqlInterface
* @param class-string<T> $interface
* @return T
* @throws Exception\RuntimeException
* @throws Exception\RuntimeException When the decorator does not implement the type it is registered for.
*/
final protected function requireDecoratorImplementing(
PlatformDecoratorInterface|PreparableSqlInterface|SqlInterface $decorator,
string $interface,
string $method,
): PreparableSqlInterface|SqlInterface {
if (! $decorator instanceof $interface) {
throw Exception\RuntimeException::forDecoratorNotImplementing($decorator::class, $interface, $method);
public function setTypeDecorator(string $type, PlatformDecoratorInterface $decorator): void
{
if (! $decorator instanceof $type) {
throw Exception\RuntimeException::forDecoratorWrongType($decorator::class, $type);
}

return $decorator;
$this->decorators[$type] = $decorator;
}
}
Loading
Loading