packages/sql-semantics-postgres/src/Rules/Manipulation/AssignmentCasts.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Manipulation;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Statement\Shape\OutputSlot;
9use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\Known;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Type\TypeFact;
11use SqlSemantics\Platform\PostgreSql\Rules\Expression\Typing\Categories;
12use SqlSemantics\Platform\PostgreSql\Statement\Manipulation\Problem\ManipulationMisuse;
13use SqlSemantics\Platform\PostgreSql\Statement\Manipulation\Problem\ManipulationMisuseRule;
14use SqlSemantics\Platform\PostgreSql\Statement\Type\Descriptor\Builtin;
15
16/**
17 * Checks that a value assigned to a column converts to the column's type in assignment context.
18 *
19 * Rule: PG-ASSIGNMENT-CAST-001. A value converts when its type is the
20 * column type, converts implicitly (PG-TYPE-CATEGORY-001), when both are
21 * numeric types, when the column is of a string type (automatic I/O
22 * conversion to string types is an assignment cast), or along one of the
23 * listed `pg_cast` entries of context `a`. A string constant or NULL
24 * (pseudo-type `unknown`) converts to any type. Only a pair of types that
25 * both belong to the covered catalog types and that none of these allow is
26 * reported; any other pair (domains, arrays, user types, `money`, `oid`,
27 * `xml`, a value whose type depends on missing declarations) is accepted.
28 * Termination: constant work.
29 * Source: https://www.postgresql.org/docs/17/typeconv-query.html, https://www.postgresql.org/docs/17/sql-createcast.html,
30 * https://www.postgresql.org/docs/17/catalog-pg-cast.html. Status: Implemented.
31 *
32 * @visibility SqlSemantics\Platform\PostgreSql
33 */
34final class AssignmentCasts
35{
36    /**
37     * The catalog types whose assignment casts the rule lists completely.
38     */
39    private const COVERED = [
40        'int2', 'int4', 'int8', 'numeric', 'float4', 'float8', 'bool', 'text', 'varchar', 'bpchar', 'name',
41        'date', 'time', 'timetz', 'timestamp', 'timestamptz', 'interval', 'bytea', 'uuid', 'json', 'jsonb', 'inet', 'cidr', 'bit', 'varbit',
42    ];
43
44    /**
45     * The assignment casts between covered types that are not implicit, by source type.
46     */
47    private const ASSIGNMENT = [
48        'timestamp' => ['date', 'time'],
49        'timestamptz' => ['date', 'time', 'timestamp', 'timetz'],
50        'interval' => ['time'],
51        'timetz' => ['time'],
52        'json' => ['jsonb'],
53        'jsonb' => ['json'],
54        'inet' => ['cidr'],
55    ];
56
57    /**
58     * Tells whether a value of one catalog type is certainly not assignable to a column of another.
59     */
60    public function refused(Builtin $value, Builtin $column): bool
61    {
62        $categories = new Categories();
63        if (!in_array($value->value, self::COVERED, true) || !in_array($column->value, self::COVERED, true)) {
64            return false;
65        }
66
67        return !$categories->implicit($value, $column)
68            && !($categories->numeric($value) && $categories->numeric($column))
69            && !$categories->textual($column)
70            && !in_array($column->value, self::ASSIGNMENT[$value->value] ?? [], true);
71    }
72
73    /**
74     * Reports a value that the column it is assigned to cannot take.
75     */
76    public function check(OutputSlot $column, TypeFact $value, Derivation $derivation): void
77    {
78        $categories = new Categories();
79        $from = $categories->builtin($value);
80        $to = $categories->builtin($column->type);
81        if ($from === null || $to === null || $from === Builtin::Unknown || !$value instanceof Known || !$column->type instanceof Known || !$this->refused($from, $to)) {
82            return;
83        }
84        $derivation->report(new ManipulationMisuse(ManipulationMisuseRule::AssignmentType, $column->name->value ?? '', $column->type->descriptor->name(), $value->descriptor->name()));
85    }
86}
87