packages/sql-semantics-mysql/src/Statement/Dml/Load/LoadTable.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Dml\Load;
6
7use SqlSemantics\Platform\MySql\Model\Construction\Derivation;
8use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
9use SqlSemantics\Platform\MySql\Model\Diagnostic\InvalidConstruction;
10use SqlSemantics\Platform\MySql\Model\Rendering\Output;
11use SqlSemantics\Platform\MySql\Model\Statement\Node;
12use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\MySql\Model\Statement\Statement;
14use SqlSemantics\Platform\MySql\Rules\Dml\LoadFacts;
15use SqlSemantics\Platform\MySql\Statement\Dml\Assignment;
16use SqlSemantics\Platform\MySql\Statement\Dml\DuplicateHandling;
17use SqlSemantics\Platform\MySql\Statement\Dml\WriteTarget;
18use SqlSemantics\Platform\MySql\Statement\Literal\Numeral;
19use SqlSemantics\Platform\MySql\Statement\Literal\Text;
20use SqlSemantics\Platform\MySql\Statement\Name\CharsetName;
21use SqlSemantics\Platform\MySql\Statement\Name\ColumnUse;
22use SqlSemantics\Platform\MySql\Statement\Variable\UserVariable;
23
24/**
25 * LOAD DATA and LOAD XML: reads rows from a file into a table.
26 *
27 * Mirrors the server's `PT_load_table` with its `sql_exchange`. The facts
28 * follow MYSQL-LOAD-001. A clause written twice in the field or line
29 * options is kept twice.
30 * Source: https://dev.mysql.com/doc/refman/8.4/en/load-data.html, https://dev.mysql.com/doc/refman/8.4/en/load-xml.html.
31 *
32 * @visibility public
33 * @example Reading a LOAD DATA
34 *     $load = (new \SqlSemantics\Platform\MySql\Semantics())->analyze("LOAD DATA INFILE 'f' REPLACE INTO TABLE t FIELDS TERMINATED BY ',' IGNORE 1 LINES (a, @b) SET c = @b * 2");
35 *     [$load->statement->duplicates, count($load->statement->columns), $load->toString()] // => [\SqlSemantics\Platform\MySql\Statement\Dml\DuplicateHandling::Replace, 2, "LOAD DATA INFILE 'f' REPLACE INTO TABLE t COLUMNS TERMINATED BY ',' IGNORE 1 LINES (a, @b) SET c = @b * 2"]
36 */
37final class LoadTable implements Statement
38{
39    use Snapshot;
40
41    /**
42     * @var list<FieldOption> The FIELDS options in written order
43     */
44    public readonly array $fields;
45
46    /**
47     * @var list<LineOption> The LINES options in written order
48     */
49    public readonly array $lines;
50
51    /**
52     * @var list<ColumnUse|UserVariable> The columns and user variables the fields are read into, in written order; empty for every column
53     */
54    public readonly array $columns;
55
56    /**
57     * @var list<Assignment> The SET assignments in written order
58     */
59    public readonly array $assignments;
60
61    /**
62     * @param LoadFormat $format DATA or XML
63     * @param LoadLock|null $lock The scheduling modifier
64     * @param LoadInput $input What is read
65     * @param DuplicateHandling|null $duplicates What a row that duplicates a unique key does
66     * @param WriteTarget $table The table the rows are written to; it has no correlation name
67     * @param CharsetName|null $charset The character set of the file
68     * @param Text|null $compression The compression algorithm of the files (9.x bulk load)
69     * @param Text|null $rowTag The XML element of a row, `ROWS IDENTIFIED BY`
70     * @param list<FieldOption> $fields The FIELDS options
71     * @param list<LineOption> $lines The LINES options
72     * @param Numeral|null $ignored The number of lines or rows skipped at the start
73     * @param list<ColumnUse|UserVariable> $columns The columns and user variables the fields are read into
74     * @param list<Assignment> $assignments The SET assignments
75     * @param BulkOptions|null $bulk The options of a bulk load
76     * @throws InvalidConstruction When the table has a correlation name or a member of a list is of the wrong class
77     */
78    public function __construct(
79        public readonly LoadFormat $format,
80        public readonly ?LoadLock $lock,
81        public readonly LoadInput $input,
82        public readonly ?DuplicateHandling $duplicates,
83        public readonly WriteTarget $table,
84        public readonly ?CharsetName $charset = null,
85        public readonly ?Text $compression = null,
86        public readonly ?Text $rowTag = null,
87        array $fields = [],
88        array $lines = [],
89        public readonly ?Numeral $ignored = null,
90        array $columns = [],
91        array $assignments = [],
92        public readonly ?BulkOptions $bulk = null,
93    ) {
94        Check::input($table->alias === null, 'The table of LOAD has no correlation name.');
95        $this->fields = Check::listOf($fields, FieldOption::class, 'The FIELDS clause holds field options.');
96        $this->lines = Check::listOf($lines, LineOption::class, 'The LINES clause holds line options.');
97        $list = [];
98        foreach (Check::listOf($columns, Node::class, 'The column list of LOAD is an ordered list.') as $column) {
99            Check::input($column instanceof ColumnUse || $column instanceof UserVariable, 'LOAD reads fields into columns and user variables.');
100            $list[] = $column;
101        }
102        $this->columns = $list;
103        $this->assignments = Check::listOf($assignments, Assignment::class, 'The SET clause of LOAD holds assignments.');
104    }
105
106    /**
107     * Derives the table, the columns and the assignments; the statement returns no rows.
108     */
109    public function deriveStatement(Derivation $derivation): void
110    {
111        (new LoadFacts())->derive($this, $derivation);
112    }
113
114    /**
115     * Writes the statement.
116     */
117    public function render(Output $out): void
118    {
119        $out->keyword('LOAD', $this->format->value);
120        if ($this->lock !== null) {
121            $out->keyword($this->lock->value);
122        }
123        $out->node($this->input);
124        if ($this->duplicates !== null) {
125            $out->keyword($this->duplicates->value);
126        }
127        $out->keyword('INTO', 'TABLE')->node($this->table);
128        if ($this->charset !== null) {
129            $out->keyword('CHARSET')->node($this->charset);
130        }
131        if ($this->compression !== null) {
132            $out->keyword('COMPRESSION')->symbol('=')->node($this->compression);
133        }
134        if ($this->rowTag !== null) {
135            $out->keyword('ROWS', 'IDENTIFIED', 'BY')->node($this->rowTag);
136        }
137        if ($this->fields !== []) {
138            $out->keyword('COLUMNS');
139        }
140        foreach ($this->fields as $option) {
141            $out->node($option);
142        }
143        if ($this->lines !== []) {
144            $out->keyword('LINES');
145        }
146        foreach ($this->lines as $option) {
147            $out->node($option);
148        }
149        if ($this->ignored !== null) {
150            $out->keyword('IGNORE')->node($this->ignored)->keyword('LINES');
151        }
152        if ($this->columns !== []) {
153            $out->symbol('(')->list($this->columns)->symbol(')');
154        }
155        if ($this->assignments !== []) {
156            $out->keyword('SET')->list($this->assignments);
157        }
158        $out->node($this->bulk);
159    }
160}
161