Skip to main content

uqa_sql/semantics/sets/
placement.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Where a set-returning call may appear, and the diagnostics `PostgreSQL` reports for one that may not.
8
9use crate::SQLError;
10
11const LATERAL_HINT: &str =
12    "You might be able to move the set-returning function into a LATERAL FROM item.";
13
14/// The kind of expression under analysis, as `PostgreSQL`'s `check_srf_call_placement` distinguishes them by `ParseExprKind`.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum SetPlacement {
17    /// A target list entry or a clause processed like one: GROUP BY, ORDER BY, DISTINCT ON, a window's PARTITION BY and ORDER BY, and the single row of `INSERT ... VALUES` or of a MERGE INSERT action. A set-returning call there expands the rows.
18    Expanding,
19    /// An argument of a function in FROM, which may not itself contain a set-returning call.
20    FromFunction,
21    JoinCondition,
22    Where,
23    Having,
24    Filter,
25    /// A window frame offset.
26    WindowFrame,
27    /// An UPDATE source or target, including `ON CONFLICT DO UPDATE SET` and a MERGE UPDATE action.
28    Update,
29    Limit,
30    Offset,
31    Returning,
32    /// A row of a multiple-row `VALUES` list, or of `VALUES` used as a query or in FROM.
33    Values,
34    MergeWhen,
35    /// An `ON CONFLICT` inference expression.
36    IndexExpression,
37    /// An `ON CONFLICT` inference predicate.
38    IndexPredicate,
39    ExecuteParameter,
40    TriggerWhen,
41    CallArgument,
42}
43
44impl SetPlacement {
45    /// Admit a set-returning call in this kind of expression; `nested` reports whether the call's own arguments contain one.
46    pub fn admit(self, nested: bool) -> Result<(), SQLError> {
47        let context = match self {
48            Self::Expanding => return Ok(()),
49            Self::FromFunction if nested => return Err(top_level_from()),
50            Self::FromFunction => return Ok(()),
51            Self::JoinCondition => "JOIN conditions",
52            Self::Where => "WHERE",
53            Self::Having => "HAVING",
54            Self::Filter => "FILTER",
55            Self::WindowFrame => "window definitions",
56            Self::Update => "UPDATE",
57            Self::Limit => "LIMIT",
58            Self::Offset => "OFFSET",
59            Self::Returning => "RETURNING",
60            Self::Values => "VALUES",
61            Self::MergeWhen => "MERGE WHEN conditions",
62            Self::IndexExpression => "index expressions",
63            Self::IndexPredicate => "index predicates",
64            Self::ExecuteParameter => "EXECUTE parameters",
65            Self::TriggerWhen => "trigger WHEN conditions",
66            Self::CallArgument => "CALL arguments",
67        };
68        Err(feature_not_supported(format!(
69            "set-returning functions are not allowed in {context}"
70        )))
71    }
72}
73
74/// A set-returning call nested in a function in FROM.
75pub fn top_level_from() -> SQLError {
76    feature_not_supported("set-returning functions must appear at top level of FROM".into())
77}
78
79/// A construct that evaluates its inputs conditionally or once per group or window, and so cannot contain a set-returning call: `CASE` and `COALESCE`, and the arguments of an aggregate or window function call.
80pub fn conditional_set_error(message: &str) -> SQLError {
81    SQLError::Diagnostic {
82        sqlstate: "0A000".into(),
83        message: message.into(),
84        detail: None,
85        hint: Some(LATERAL_HINT.into()),
86    }
87}
88
89/// A set-valued operand of a construct that requires a single value, as `coerce_to_boolean` reports it.
90pub fn set_argument_error(construct: &str) -> SQLError {
91    datatype_mismatch(format!("argument of {construct} must not return a set"))
92}
93
94/// A row comparison, or the comparison of a subquery test expression, whose operator returns a set.
95pub fn row_comparison_set_error() -> SQLError {
96    datatype_mismatch("row comparison operator must not return a set".into())
97}
98
99/// A set-returning call reached an expression evaluated for one value, as `PostgreSQL`'s executor reports it when it initializes such an expression.
100pub fn set_valued_call_error() -> SQLError {
101    feature_not_supported("set-valued function called in context that cannot accept a set".into())
102}
103
104fn feature_not_supported(message: String) -> SQLError {
105    SQLError::Routine {
106        sqlstate: "0A000".into(),
107        message,
108    }
109}
110
111fn datatype_mismatch(message: String) -> SQLError {
112    SQLError::Routine {
113        sqlstate: "42804".into(),
114        message,
115    }
116}