packages/sql-semantics-mysql/src/Statement/Dml/Insert/InsertQuery.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Dml\Insert;
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\Query;
12use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
13use SqlSemantics\Platform\MySql\Model\Statement\Statement;
14use SqlSemantics\Platform\MySql\Rules\Dml\InsertFacts;
15use SqlSemantics\Platform\MySql\Statement\Dml\Assignment;
16
17/**
18 * INSERT or REPLACE of the rows of a query (SELECT, TABLE, VALUES or a set operation), with the optional ON DUPLICATE KEY UPDATE.
19 *
20 * Rule: MYSQL-INSERT-QUERY-001. The facts follow MYSQL-INSERT-001 with the
21 * query as the source.
22 * Source: https://dev.mysql.com/doc/refman/8.4/en/insert-select.html. Status: Implemented.
23 *
24 * @visibility public
25 * @example Reading the source of an INSERT ... SELECT
26 * $insert = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('INSERT INTO t (a) SELECT b FROM u');
27 * [$insert->statement->source instanceof \SqlSemantics\Platform\MySql\Statement\Query\Select, $insert->toString()] // => [true, 'INSERT INTO t (a) SELECT b FROM u']
28 */
29final class InsertQuery implements Statement
30{
31 use Snapshot;
32
33 /**
34 * @var list<Assignment> The assignments of ON DUPLICATE KEY UPDATE in written order
35 */
36 public readonly array $onDuplicate;
37
38 /**
39 * @param InsertInto $into The head: verb, modifiers, table and column list
40 * @param Query $source The query whose rows are written
41 * @param list<Assignment> $onDuplicate The assignments of ON DUPLICATE KEY UPDATE
42 * @throws InvalidConstruction When REPLACE has ON DUPLICATE KEY UPDATE
43 */
44 public function __construct(public readonly InsertInto $into, public readonly Query $source, array $onDuplicate = [])
45 {
46 $this->onDuplicate = Check::listOf($onDuplicate, Assignment::class, 'ON DUPLICATE KEY UPDATE holds assignments.');
47 Check::input(!$into->replace || $this->onDuplicate === [], 'REPLACE has no ON DUPLICATE KEY UPDATE.');
48 }
49
50 /**
51 * Derives the written table, the columns, the query and the assignments; the statement returns no rows.
52 */
53 public function deriveStatement(Derivation $derivation): void
54 {
55 (new InsertFacts())->query($this, $derivation, $derivation->environment());
56 }
57
58 /**
59 * Writes the statement.
60 */
61 public function render(Output $out): void
62 {
63 $out->node($this->into)->node($this->source);
64 if ($this->onDuplicate !== []) {
65 $out->keyword('ON', 'DUPLICATE', 'KEY', 'UPDATE')->list($this->onDuplicate);
66 }
67 }
68}
69