packages/sql-semantics-sqlite/src/Model/Resolution/Environment.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Model\Resolution;
6
7use SqlSemantics\Platform\Sqlite\Model\Contract\AnalysisContext;
8use SqlSemantics\Platform\Sqlite\Model\Statement\Identifier\Name;
9use SqlSemantics\Platform\Sqlite\Model\Statement\Shape\Field;
10
11/**
12 * What names mean at one position of a statement.
13 *
14 * An environment is derived from the clause position and the relation
15 * structure: the occurrences visible there, the enclosing query positions, the
16 * common tables in scope and the output aliases the position may use. It is a
17 * working value of one derivation and is not part of the published model.
18 *
19 * @visibility SqlSemantics
20 */
21final class Environment
22{
23 /**
24 * @param AnalysisContext $context The declaration context
25 * @param Environment|null $outer The position of the enclosing query that lookups continue in
26 * @param list<VisibleRelation> $relations The relation occurrences visible at this position
27 * @param list<CommonBinding> $commonTables The common tables introduced at this level; later bindings shadow earlier ones
28 * @param list<Field> $aliases The output fields this position may refer to by alias
29 */
30 public function __construct(
31 public readonly AnalysisContext $context,
32 public readonly ?Environment $outer = null,
33 public readonly array $relations = [],
34 public readonly array $commonTables = [],
35 public readonly array $aliases = [],
36 ) {
37 }
38
39 /**
40 * Finds the nearest common table with a name.
41 */
42 public function commonTable(Name $name): ?CommonBinding
43 {
44 for ($scope = $this; $scope !== null; $scope = $scope->outer) {
45 for ($index = count($scope->commonTables) - 1; $index >= 0; $index--) {
46 if ($this->context->relationNames->equal($scope->commonTables[$index]->name->value, $name->value)) {
47 return $scope->commonTables[$index];
48 }
49 }
50 }
51
52 return null;
53 }
54
55 /**
56 * Finds the output fields of this position an alias names.
57 *
58 * @return list<Field>
59 */
60 public function aliased(Name $name): array
61 {
62 $fields = [];
63 foreach ($this->aliases as $field) {
64 if ($field->name !== null && $this->context->columnNames->equal($field->name->value, $name->value)) {
65 $fields[] = $field;
66 }
67 }
68
69 return $fields;
70 }
71}
72