packages/sql-semantics-mysql/src/Statement/Dml/Problem/ValueCountMismatch.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Dml\Problem;
6
7use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
8use SqlSemantics\Platform\MySql\Model\Statement\Fact\Diagnostic;
9use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
10
11/**
12 * A row of an INSERT or REPLACE with another number of values than the columns it writes.
13 *
14 * The row number counts from 1 for a row of VALUES; a query source has no row number.
15 * Source: https://dev.mysql.com/doc/refman/8.4/en/insert.html,
16 * https://dev.mysql.com/doc/mysql-errors/8.4/en/server-error-reference.html (ER_WRONG_VALUE_COUNT_ON_ROW,
17 * ER_WRONG_VALUE_COUNT).
18 *
19 * @visibility public
20 * @example Reading a row with too many values
21 *     (new \SqlSemantics\Platform\MySql\Semantics())->analyze('INSERT INTO t (a) VALUES (1), (2, 3)') // throws \SqlSemantics\Platform\MySql\Model\Diagnostic\SemanticException: Column count doesn't match value count at row 2
22 */
23final class ValueCountMismatch implements Diagnostic
24{
25    use Snapshot;
26
27    /**
28     * @param int $expected The number of columns written
29     * @param int $actual The number of values of the row
30     * @param int|null $row The row number counted from 1, or null for the rows of a query
31     */
32    public function __construct(public readonly int $expected, public readonly int $actual, public readonly ?int $row = null)
33    {
34        Check::input($row === null || $row > 0, 'Rows are counted from 1.');
35    }
36
37    /**
38     * Describes the problem in the words of the server.
39     */
40    public function message(): string
41    {
42        return $this->row === null ? "Column count doesn't match value count" : "Column count doesn't match value count at row " . $this->row;
43    }
44}
45