risingwave_frontend/expr/
pure.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use expr_node::Type;
16use risingwave_pb::expr::expr_node;
17
18use super::{ExprImpl, ExprVisitor};
19use crate::expr::FunctionCall;
20
21#[derive(Default)]
22pub(crate) struct ImpureAnalyzer {
23    pub(crate) impure: bool,
24}
25
26impl ExprVisitor for ImpureAnalyzer {
27    fn visit_user_defined_function(&mut self, _func_call: &super::UserDefinedFunction) {
28        self.impure = true;
29    }
30
31    fn visit_now(&mut self, _: &super::Now) {
32        self.impure = true;
33    }
34
35    fn visit_function_call(&mut self, func_call: &super::FunctionCall) {
36        match func_call.func_type() {
37            Type::Unspecified => unreachable!(),
38            Type::Add
39            | Type::Subtract
40            | Type::Multiply
41            | Type::Divide
42            | Type::Modulus
43            | Type::Equal
44            | Type::NotEqual
45            | Type::LessThan
46            | Type::LessThanOrEqual
47            | Type::GreaterThan
48            | Type::GreaterThanOrEqual
49            | Type::And
50            | Type::Or
51            | Type::Not
52            | Type::In
53            | Type::Some
54            | Type::All
55            | Type::BitwiseAnd
56            | Type::BitwiseOr
57            | Type::BitwiseXor
58            | Type::BitwiseNot
59            | Type::BitwiseShiftLeft
60            | Type::BitwiseShiftRight
61            | Type::Extract
62            | Type::DatePart
63            | Type::TumbleStart
64            | Type::SecToTimestamptz
65            | Type::AtTimeZone
66            | Type::DateTrunc
67            | Type::MakeDate
68            | Type::MakeTime
69            | Type::MakeTimestamp
70            | Type::CharToTimestamptz
71            | Type::CharToDate
72            | Type::CastWithTimeZone
73            | Type::AddWithTimeZone
74            | Type::SubtractWithTimeZone
75            | Type::Cast
76            | Type::Substr
77            | Type::Length
78            | Type::Like
79            | Type::ILike
80            | Type::SimilarToEscape
81            | Type::Upper
82            | Type::Lower
83            | Type::Trim
84            | Type::Replace
85            | Type::Position
86            | Type::Ltrim
87            | Type::Rtrim
88            | Type::Case
89            | Type::ConstantLookup
90            | Type::RoundDigit
91            | Type::Round
92            | Type::Ascii
93            | Type::Translate
94            | Type::Coalesce
95            | Type::ConcatWs
96            | Type::ConcatWsVariadic
97            | Type::Abs
98            | Type::SplitPart
99            | Type::Ceil
100            | Type::Floor
101            | Type::Trunc
102            | Type::ToChar
103            | Type::Md5
104            | Type::CharLength
105            | Type::Repeat
106            | Type::ConcatOp
107            | Type::Concat
108            | Type::ConcatVariadic
109            | Type::BoolOut
110            | Type::OctetLength
111            | Type::BitLength
112            | Type::Overlay
113            | Type::RegexpMatch
114            | Type::RegexpReplace
115            | Type::RegexpCount
116            | Type::RegexpSplitToArray
117            | Type::RegexpEq
118            | Type::Pow
119            | Type::Exp
120            | Type::Ln
121            | Type::Log10
122            | Type::Chr
123            | Type::StartsWith
124            | Type::Initcap
125            | Type::Lpad
126            | Type::Rpad
127            | Type::Reverse
128            | Type::Strpos
129            | Type::ToAscii
130            | Type::ToHex
131            | Type::QuoteIdent
132            | Type::Sin
133            | Type::Cos
134            | Type::Tan
135            | Type::Cot
136            | Type::Asin
137            | Type::Acos
138            | Type::Acosd
139            | Type::Atan
140            | Type::Atan2
141            | Type::Atand
142            | Type::Atan2d
143            | Type::Sqrt
144            | Type::Cbrt
145            | Type::Sign
146            | Type::Scale
147            | Type::MinScale
148            | Type::TrimScale
149            | Type::Left
150            | Type::Right
151            | Type::Degrees
152            | Type::Radians
153            | Type::IsTrue
154            | Type::IsNotTrue
155            | Type::IsFalse
156            | Type::IsNotFalse
157            | Type::IsNull
158            | Type::IsNotNull
159            | Type::IsDistinctFrom
160            | Type::IsNotDistinctFrom
161            | Type::Neg
162            | Type::Field
163            | Type::Array
164            | Type::ArrayAccess
165            | Type::ArrayRangeAccess
166            | Type::Row
167            | Type::ArrayToString
168            | Type::ArrayCat
169            | Type::ArrayMax
170            | Type::ArraySum
171            | Type::ArraySort
172            | Type::ArrayAppend
173            | Type::ArrayPrepend
174            | Type::FormatType
175            | Type::ArrayDistinct
176            | Type::ArrayMin
177            | Type::ArrayDims
178            | Type::ArrayLength
179            | Type::Cardinality
180            | Type::TrimArray
181            | Type::ArrayRemove
182            | Type::ArrayReplace
183            | Type::ArrayPosition
184            | Type::ArrayContains
185            | Type::ArrayContained
186            | Type::HexToInt256
187            | Type::JsonbConcat
188            | Type::JsonbAccess
189            | Type::JsonbAccessStr
190            | Type::JsonbExtractPath
191            | Type::JsonbExtractPathVariadic
192            | Type::JsonbExtractPathText
193            | Type::JsonbExtractPathTextVariadic
194            | Type::JsonbTypeof
195            | Type::JsonbArrayLength
196            | Type::JsonbObject
197            | Type::JsonbPretty
198            | Type::JsonbDeletePath
199            | Type::JsonbContains
200            | Type::JsonbContained
201            | Type::JsonbExists
202            | Type::JsonbExistsAny
203            | Type::JsonbExistsAll
204            | Type::JsonbStripNulls
205            | Type::JsonbBuildArray
206            | Type::JsonbBuildArrayVariadic
207            | Type::JsonbBuildObject
208            | Type::JsonbPopulateRecord
209            | Type::JsonbToRecord
210            | Type::JsonbBuildObjectVariadic
211            | Type::JsonbPathExists
212            | Type::JsonbPathMatch
213            | Type::JsonbPathQueryArray
214            | Type::JsonbPathQueryFirst
215            | Type::JsonbSet
216            | Type::JsonbPopulateMap
217            | Type::IsJson
218            | Type::ToJsonb
219            | Type::Sind
220            | Type::Cosd
221            | Type::Cotd
222            | Type::Asind
223            | Type::Sinh
224            | Type::Cosh
225            | Type::Coth
226            | Type::Tanh
227            | Type::Atanh
228            | Type::Asinh
229            | Type::Acosh
230            | Type::Decode
231            | Type::Encode
232            | Type::Sha1
233            | Type::Sha224
234            | Type::Sha256
235            | Type::Sha384
236            | Type::Sha512
237            | Type::Hmac
238            | Type::SecureCompare
239            | Type::Decrypt
240            | Type::Encrypt
241            | Type::Tand
242            | Type::ArrayPositions
243            | Type::StringToArray
244            | Type::Format
245            | Type::FormatVariadic
246            | Type::PgwireSend
247            | Type::PgwireRecv
248            | Type::ArrayTransform
249            | Type::Greatest
250            | Type::Least
251            | Type::ConvertFrom
252            | Type::ConvertTo
253            | Type::IcebergTransform
254            | Type::InetNtoa
255            | Type::InetAton
256            | Type::QuoteLiteral
257            | Type::QuoteNullable
258            | Type::MapFromEntries
259            | Type::MapAccess
260            | Type::MapKeys
261            | Type::MapValues
262            | Type::MapEntries
263            | Type::MapFromKeyValues
264            | Type::MapCat
265            | Type::MapContains
266            | Type::MapDelete
267            | Type::MapInsert
268            | Type::MapLength
269            | Type::VnodeUser
270            | Type::RwEpochToTs
271            | Type::CheckNotNull =>
272            // expression output is deterministic(same result for the same input)
273            {
274                func_call
275                    .inputs()
276                    .iter()
277                    .for_each(|expr| self.visit_expr(expr));
278            }
279            // expression output is not deterministic
280            Type::Vnode // obtain vnode count from the context
281            | Type::TestPaidTier
282            | Type::License
283            | Type::Proctime
284            | Type::PgSleep
285            | Type::PgSleepFor
286            | Type::PgSleepUntil
287            | Type::CastRegclass
288            | Type::PgGetIndexdef
289            | Type::ColDescription
290            | Type::PgGetViewdef
291            | Type::PgGetUserbyid
292            | Type::PgIndexesSize
293            | Type::PgRelationSize
294            | Type::PgGetSerialSequence
295            | Type::PgIndexColumnHasProperty
296            | Type::HasTablePrivilege
297            | Type::HasAnyColumnPrivilege
298            | Type::HasSchemaPrivilege
299            | Type::MakeTimestamptz
300            | Type::PgIsInRecovery
301            | Type::RwRecoveryStatus
302            | Type::PgTableIsVisible
303            | Type::HasFunctionPrivilege => self.impure = true,
304        }
305    }
306}
307
308pub fn is_pure(expr: &ExprImpl) -> bool {
309    !is_impure(expr)
310}
311
312pub fn is_impure(expr: &ExprImpl) -> bool {
313    let mut a = ImpureAnalyzer::default();
314    a.visit_expr(expr);
315    a.impure
316}
317
318pub fn is_impure_func_call(func_call: &FunctionCall) -> bool {
319    let mut a = ImpureAnalyzer::default();
320    a.visit_function_call(func_call);
321    a.impure
322}
323
324#[cfg(test)]
325mod tests {
326    use risingwave_common::types::DataType;
327    use risingwave_pb::expr::expr_node::Type;
328
329    use crate::expr::{ExprImpl, FunctionCall, InputRef, is_impure, is_pure};
330
331    fn expect_pure(expr: &ExprImpl) {
332        assert!(is_pure(expr));
333        assert!(!is_impure(expr));
334    }
335
336    fn expect_impure(expr: &ExprImpl) {
337        assert!(!is_pure(expr));
338        assert!(is_impure(expr));
339    }
340
341    #[test]
342    fn test_pure_funcs() {
343        let e: ExprImpl = FunctionCall::new(
344            Type::Add,
345            vec![
346                InputRef::new(0, DataType::Int16).into(),
347                InputRef::new(0, DataType::Int16).into(),
348            ],
349        )
350        .unwrap()
351        .into();
352        expect_pure(&e);
353
354        let e: ExprImpl = FunctionCall::new(
355            Type::GreaterThan,
356            vec![
357                InputRef::new(0, DataType::Timestamptz).into(),
358                FunctionCall::new(Type::Proctime, vec![]).unwrap().into(),
359            ],
360        )
361        .unwrap()
362        .into();
363        expect_impure(&e);
364    }
365}