packages/ztd-query-core/src/Rewrite/SqlTransformer.php
1<?php
2
3declare(strict_types=1);
4
5namespace ZtdQuery\Rewrite;
6
7use ZtdQuery\Platform\ValueRenderer;
8use ZtdQuery\Schema\ColumnDeclaration;
9use ZtdQuery\Schema\Key\IdentityGenerationStrategy;
10use ZtdQuery\Schema\Key\PartialUniqueIndex;
11use ZtdQuery\Schema\Partition\TablePartitioning;
12use ZtdQuery\Schema\TableDefinition;
13
14/**
15 * Rewrites a statement so that it reads the shadow instead of the database.
16 *
17 * A transformer holds nothing: everything it needs about a table is handed to
18 * it, so the same transformer can rewrite one statement against one shadow and
19 * the next against another.
20 *
21 * A shadow row's values are whatever the driver handed back, which is wider
22 * than what a row holds once it has been read: a driver may answer a large
23 * column as an open stream, or an object that says how it spells itself.
24 *
25 * @phpstan-import-type Row from TableDefinition
26 * @phpstan-import-type RenderableValue from ValueRenderer
27 *
28 * @phpstan-type ShadowView array{viewSql: string}
29 * @phpstan-type ShadowRows array{
30 * rows: array<int, array<string, mixed>>,
31 * columns: array<int, string>,
32 * columnTypes: array<string, ColumnDeclaration>,
33 * primaryKeys?: array<int, string>,
34 * candidateKeys?: array<string, array<int, string>>,
35 * partialUniqueIndexes?: array<string, PartialUniqueIndex>,
36 * columnDefaults?: array<string, string>,
37 * identityStrategies?: array<string, IdentityGenerationStrategy>,
38 * generatedExpressions?: array<string, string>,
39 * partitioning?: TablePartitioning|null,
40 * sourceSql?: string,
41 * storageTable?: string
42 * }
43 * @phpstan-type ShadowTable ShadowView|ShadowRows
44 * @phpstan-type ShadowTables array<string, ShadowTable>
45 */
46interface SqlTransformer
47{
48 /**
49 * Rewrites a statement so that it reads these tables' shadow rows.
50 *
51 * A table given as a view is rewritten to the statement that defines it;
52 * a table given as rows is rewritten to those rows written out.
53 *
54 * @param string $sql The statement, as it was written
55 * @param ShadowTables $tables Table name => what the shadow holds for it
56 *
57 * @return string The statement, rewritten to read the shadow
58 */
59 public function transform(string $sql, array $tables): string;
60}
61