packages/sql-semantics-mysql/src/Statement/Table/ParseGeneratedColumn.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Table;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11use SqlSemantics\Platform\MySql\Model\Statement\Statement;
12
13/**
14 * The internal statement PARSE_GCOL_EXPR(expr) of MySQL 5.7, which the server uses to read a stored generated column expression.
15 *
16 * Rule: MYSQL-PARSE-GCOL-EXPR-001. The grammar of 5.7 reaches it from SQL
17 * text because PARSE_GCOL_EXPR is a keyword of its lexer; the server only
18 * accepts it while it opens a table definition. Outside one, no table is
19 * visible: the expression is derived at a position that sees no relation, so
20 * a column name in it is a missing column.
21 * Source: sql/sql_yacc.yy and sql/table.cc (`unpack_gcol_info`) of MySQL 5.7,
22 * https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html. Status: Implemented.
23 *
24 * @visibility public
25 * @example Reading the expression
26 *     $statement = (new \SqlSemantics\Platform\MySql\Semantics('mysql-5.7.44'))->analyze('PARSE_GCOL_EXPR(1 + 2)');
27 *     $statement->statement instanceof \SqlSemantics\Platform\MySql\Statement\Table\ParseGeneratedColumn // => true
28 */
29final class ParseGeneratedColumn implements Statement
30{
31    use Snapshot;
32
33    /**
34     * @param Scalar $expression The generated column expression
35     */
36    public function __construct(public readonly Scalar $expression)
37    {
38    }
39
40    /**
41     * Derives the expression at a position that sees no relation.
42     */
43    public function deriveStatement(Derivation $derivation): void
44    {
45        $derivation->scalar($this->expression, $derivation->environment());
46    }
47
48    /**
49     * Writes the statement.
50     */
51    public function render(Output $out): void
52    {
53        $out->keyword('PARSE_GCOL_EXPR')->glue()->symbol('(')->node($this->expression)->symbol(')');
54    }
55}
56