packages/sql-semantics-postgres/src/Rules/Table/Command/Policies.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Rules\Table\Command;
6
7use SqlSemantics\Platform\PostgreSql\Model\Construction\Derivation;
8use SqlSemantics\Platform\PostgreSql\Model\Rendering\Output;
9use SqlSemantics\Platform\PostgreSql\Model\Statement\Declaration\RelationKind;
10use SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\QualifiedName;
11use SqlSemantics\Platform\PostgreSql\Model\Statement\Relation;
12use SqlSemantics\Platform\PostgreSql\Model\Statement\Scalar;
13use SqlSemantics\Platform\PostgreSql\Rules\Table\Conditions;
14use SqlSemantics\Platform\PostgreSql\Rules\Table\RelationKinds;
15use SqlSemantics\Platform\PostgreSql\Rules\Table\Targets;
16use SqlSemantics\Platform\PostgreSql\Statement\Name\RoleSpec;
17use SqlSemantics\Platform\PostgreSql\Statement\Table\Problem\KindRule;
18
19/**
20 * Derives and writes row security policies.
21 *
22 * Rule: PG-POLICY-001. The table is resolved (PG-TABLE-TARGET-001) and is
23 * the relation fact of the statement; a relation declared as another kind
24 * than a table is reported (`"%s" is not a table`, PG-RELATION-KIND-001). The USING and WITH CHECK expressions
25 * are conditions (PG-TABLE-CONDITION-001) where the table is the only visible
26 * relation ("expressions ... can refer to columns of the table"). Source: https://www.postgresql.org/docs/17/sql-createpolicy.html.
27 * Status: Implemented.
28 *
29 * @visibility SqlSemantics\Platform\PostgreSql
30 */
31final class Policies
32{
33 /**
34 * Resolves the table and derives the conditions.
35 */
36 public function derive(Relation $policy, QualifiedName $table, ?Scalar $using, ?Scalar $check, Derivation $derivation): void
37 {
38 $targets = new Targets();
39 $fact = $derivation->target($policy, $targets->resolve($derivation, $table));
40 $kinds = new RelationKinds();
41 $kinds->require($derivation, $kinds->of($fact), $table->name, [RelationKind::BaseTable], KindRule::NotTable);
42 $scope = $targets->scope($derivation, $policy, $table, $fact->shape, $targets->implicit($fact));
43 foreach ([$using, $check] as $condition) {
44 if ($condition !== null) {
45 (new Conditions())->derive($derivation, $condition, $scope, 'POLICY');
46 }
47 }
48 }
49
50 /**
51 * Writes TO, USING and WITH CHECK, each when given.
52 *
53 * @param list<RoleSpec> $roles
54 */
55 public function write(Output $out, array $roles, ?Scalar $using, ?Scalar $check): void
56 {
57 if ($roles !== []) {
58 $out->keyword('TO')->list($roles);
59 }
60 if ($using !== null) {
61 $out->keyword('USING')->symbol('(')->node($using)->symbol(')');
62 }
63 if ($check !== null) {
64 $out->keyword('WITH', 'CHECK')->symbol('(')->node($check)->symbol(')');
65 }
66 }
67}
68