Skip to content
Draft
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
18 changes: 9 additions & 9 deletions docs/book/sql-ddl/alter-drop.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,18 +305,18 @@ foreach ($tables as $tableName) {

### Current Status

A dialect renders DDL through its own statement class. `Sql` obtains those classes from the
adapter platform's statement factory, so `$sql->createTable()`, `$sql->alterTable()` and
`$sql->dropTable()` return the class the driver supplies. Where a driver has nothing to add, the
standard `PhpDb\Sql\Ddl\*` class is returned, which is what a directly constructed statement
renders with.
DDL statements are dialect-neutral. `$sql->createTable()`, `$sql->alterTable()` and
`$sql->dropTable()` return the standard `PhpDb\Sql\Ddl\*` classes, the same objects a directly
constructed statement gives you. When one is rendered, the adapter platform's dialect renders
each column definition, which is where a driver adds the column options its database accepts.

### What This Means

1. **Platform specialization lives in the driver's statement classes**, which subclass the
standard ones and override the render hooks they need
2. **DDL objects define the structure**; the dialect class decides how that structure is written
3. **Statements obtained from `$sql` carry the dialect**; a `new CreateTable()` does not
1. **Platform specialization lives in the driver's dialect**, which renders the column
definitions and clauses its database writes differently
2. **DDL objects define the structure**; the dialect decides how that structure is written
3. **Any DDL statement gets the dialect when it is rendered**, whether it came from `$sql` or
from `new CreateTable()`

### Platform-Agnostic Approach

Expand Down
24 changes: 14 additions & 10 deletions docs/book/sql/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,18 +248,22 @@ $sqlString = $sql->buildSqlString($select);
Note: Direct string building bypasses parameter binding.
Use with caution and never with user input.

```php title="Getting the Statement Factory"
$factory = $sql->getStatementFactory();
```
### Dialects

A statement is dialect-neutral. `$sql->select()` and `new Select()` build the same object, and
neither knows which database it will run against.

The dialect is applied when the statement is rendered. The adapter's platform says which clauses
its database renders differently from standard SQL, and those clauses are rendered by the driver.
Because that happens at render time, it reaches every statement the platform renders: one built
through `$sql`, one built with `new`, one changed by a TableGateway event listener, and any
subselect nested inside another statement.

The factory builds the statements this adapter renders. A driver whose dialect renders a
statement differently returns its own subclass from the matching factory method, so a statement
obtained from `$sql` carries the dialect from the moment it is created, including through
TableGateway events, RowGateway operations and subselects. The same applies to DDL through
`createTable()`, `alterTable()` and `dropTable()`.
```php title="The Same Statement Rendered for the Adapter's Database"
$select = (new Select('users'))->offset(20);

A statement built with `new Select()` renders with the standard SQL rules, because nothing has
told it which dialect it belongs to.
$sqlString = $sql->buildSqlString($select);
```

## TableIdentifier

Expand Down
15 changes: 6 additions & 9 deletions src/Adapter/Platform/PlatformInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,18 @@

namespace PhpDb\Adapter\Platform;

use PhpDb\Sql\Platform\StatementFactoryInterface;
use PhpDb\Sql\Dialect\DialectInterface;

/**
* @api
*/
interface PlatformInterface
{
/**
* Get what this platform renders differently from standard SQL
*/
public function getDialect(): DialectInterface;

/**
* Get identifier separator
*/
Expand All @@ -31,14 +36,6 @@ public function getQuoteIdentifierSymbol(): string;
*/
public function getQuoteValueSymbol(): string;

/**
* Get the statement factory for this platform's dialect
*
* Returns a PhpDb\Sql\Platform\* instance
* PhpDb\Sql\Platform\AbstractPlatform implements this interface
*/
public function getStatementFactory(): StatementFactoryInterface;

/**
* Quote identifier
*/
Expand Down
14 changes: 8 additions & 6 deletions src/Adapter/Platform/Sql92.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use Override;
use PhpDb\Adapter\Exception;
use PhpDb\Sql\Platform\Platform;
use PhpDb\Sql\Platform\StatementFactoryInterface;
use PhpDb\Sql\Dialect\DialectInterface;
use PhpDb\Sql\Dialect\StandardDialect;

/**
* Standard SQL conformance platform.
Expand All @@ -23,22 +23,24 @@ class Sql92 extends AbstractPlatform
{
final public const string PLATFORM_NAME = 'SQL92';

private ?DialectInterface $dialect = null;

/**
* {@inheritDoc}
*/
#[Override]
public function getName(): string
public function getDialect(): DialectInterface
{
return self::PLATFORM_NAME;
return $this->dialect ??= new StandardDialect();
}

/**
* {@inheritDoc}
*/
#[Override]
public function getStatementFactory(): StatementFactoryInterface
public function getName(): string
{
return new Platform();
return self::PLATFORM_NAME;
}

/**
Expand Down
106 changes: 97 additions & 9 deletions src/Sql/AbstractSql.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace PhpDb\Sql;

use Closure;
use Override;
use PhpDb\Adapter\Driver\DriverInterface;
use PhpDb\Adapter\ParameterContainer;
Expand All @@ -14,6 +15,7 @@
use PhpDb\Sql\Argument\Select as SelectArgument;
use PhpDb\Sql\Argument\Value;
use PhpDb\Sql\Argument\Values;
use PhpDb\Sql\Dialect\RenderContext;
use Stringable;

use function array_key_exists;
Expand Down Expand Up @@ -70,6 +72,55 @@ abstract class AbstractSql implements SqlInterface
/** @var array<string, int> */
protected array $instanceParameterIndex = [];

/**
* Shared by every render context, so building a context creates no closure of its own
*
* @var (Closure(self, ExpressionInterface, PlatformInterface, ?DriverInterface, ?ParameterContainer, ?string): string)|null
*/
private static ?Closure $expressionRenderer = null;

/** @var (Closure(self, Select, PlatformInterface, ?DriverInterface, ?ParameterContainer): string)|null */
private static ?Closure $subselectRenderer = null;

/**
* Lets a render context reach a statement's expression rendering
*
* @throws Exception\RuntimeException
*
* @mago-expect lint:excessive-parameter-list
*/
private static function renderExpressionOf(
self $statement,
ExpressionInterface $expression,
PlatformInterface $platform,
?DriverInterface $driver,
?ParameterContainer $parameterContainer,
?string $namedParameterPrefix,
): string {
return $statement->processExpression(
$expression,
$platform,
$driver,
$parameterContainer,
$namedParameterPrefix,
);
}

/**
* Lets a render context reach a statement's subselect rendering
*
* @throws Exception\RuntimeException
*/
private static function renderSubselectOf(
self $statement,
Select $subselect,
PlatformInterface $platform,
?DriverInterface $driver,
?ParameterContainer $parameterContainer,
): string {
return $statement->processSubSelect($subselect, $platform, $driver, $parameterContainer);
}

/**
* {@inheritDoc}
*
Expand All @@ -86,6 +137,9 @@ public function getSqlString(PlatformInterface $adapterPlatform): string
/**
* Dispatches each specification to its process{Name}() hook, so the method name is built at runtime
*
* A clause the platform's dialect renders itself goes to the dialect's renderer first, which
* may hand it back to be rendered as standard SQL.
*
* @throws Exception\RuntimeException
*
* @mago-expect analysis:string-member-selector
Expand All @@ -95,11 +149,31 @@ protected function buildSqlString(
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
): string {
$this->prepareSpecifications();
$renderers = $platform->getDialect()->clauseRenderers($this);
$context = null;

$sqls = [];

foreach ($this->specifications as $name => $specification) {
$renderer = $renderers[$name] ?? null;

if (null !== $renderer) {
$rendered = $renderer instanceof Stringable ? (string) $renderer : null;

if (! $renderer instanceof Stringable) {
$context ??= $this->createRenderContext($platform, $driver, $parameterContainer);
$rendered = $renderer->renderClause($this, $context);
}

if (null !== $rendered) {
if ('' !== $rendered) {
$sqls[$name] = $rendered;
}

continue;
}
}

/** @var SqlParameters|string|null $result */
$result = $this->{"process{$name}"}(
$platform,
Expand All @@ -120,6 +194,28 @@ protected function buildSqlString(
return rtrim(implode(' ', $sqls), characters: "\n ,");
}

/**
* The context a dialect renderer works through while this statement is being rendered
*/
final protected function createRenderContext(
PlatformInterface $platform,
?DriverInterface $driver = null,
?ParameterContainer $parameterContainer = null,
): RenderContext {
self::$expressionRenderer ??= self::renderExpressionOf(...);
self::$subselectRenderer ??= self::renderSubselectOf(...);

return new RenderContext(
$platform,
$driver,
$parameterContainer,
$this->processInfo['paramPrefix'],
$this,
self::$expressionRenderer,
self::$subselectRenderer,
);
}

/**
* @param Specification $specifications
* @param SqlParameters $parameters
Expand Down Expand Up @@ -200,14 +296,6 @@ protected function formatSpecification(string $name, string ...$values): string
return str_replace($placeholders, $values, $specification);
}

/**
* Adjust the specification table before the render hooks run.
*
* A dialect subclass overrides this where a clause is rendered with a different
* specification from the standard SQL one.
*/
protected function prepareSpecifications(): void {}

/**
* @throws Exception\RuntimeException
*/
Expand Down
20 changes: 14 additions & 6 deletions src/Sql/Ddl/AlterTable.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

use function array_key_exists;
use function array_map;
use function array_values;
use function is_bool;
use function is_int;
use function strtoupper;
Expand All @@ -33,6 +34,8 @@
*/
class AlterTable extends AbstractSql
{
use ColumnDefinitionTrait;

final public const string ADD_COLUMNS = 'addColumns';

final public const string ADD_CONSTRAINTS = 'addConstraints';
Expand Down Expand Up @@ -219,7 +222,9 @@ public function setTable(string|TableIdentifier $name): static
*/
protected function processAddColumns(PlatformInterface $adapterPlatform): array
{
return [$this->processExpressionList($this->addColumns, $adapterPlatform)];
return [
array_values($this->processColumnDefinitions($this->addColumns, self::ADD_COLUMNS, $adapterPlatform)),
];
}

/**
Expand All @@ -237,12 +242,15 @@ protected function processAddConstraints(PlatformInterface $adapterPlatform): ar
*/
protected function processChangeColumns(PlatformInterface $adapterPlatform): array
{
$definitions = $this->processColumnDefinitions(
$this->changeColumns,
self::CHANGE_COLUMNS,
$adapterPlatform,
);

$sqls = [];
foreach ($this->changeColumns as $name => $column) {
$sqls[] = [
$adapterPlatform->quoteIdentifier($name),
$this->processExpression($column, $adapterPlatform),
];
foreach ($definitions as $name => $definition) {
$sqls[] = [$adapterPlatform->quoteIdentifier($name), $definition];
}

return [$sqls];
Expand Down
51 changes: 51 additions & 0 deletions src/Sql/Ddl/ColumnDefinitionTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace PhpDb\Sql\Ddl;

use PhpDb\Adapter\Platform\PlatformInterface;
use PhpDb\Sql\AbstractSql;
use PhpDb\Sql\Exception\RuntimeException;

/**
* Renders column definitions, through the platform's dialect where it renders columns itself.
*
* @internal
*
* @require-extends AbstractSql
*/
trait ColumnDefinitionTrait
{
/**
* @template TKey of array-key
* @param array<TKey, Column\ColumnInterface> $columns
* @param string $clause The clause the columns belong to, by its statement constant.
* @return array<TKey, string> The column definitions, under the keys of the columns.
* @throws RuntimeException
*/
protected function processColumnDefinitions(array $columns, string $clause, PlatformInterface $platform): array
{
if ([] === $columns) {
return [];
}

$renderer = $platform->getDialect()->columnRenderer();
$context = null;

$sqls = [];
foreach ($columns as $key => $column) {
$standard = $this->processExpression($column, $platform);

if (null === $renderer) {
$sqls[$key] = $standard;
continue;
}

$context ??= $this->createRenderContext($platform);
$sqls[$key] = $renderer->renderColumn($column, $standard, $clause, $context);
}

return $sqls;
}
}
Loading
Loading