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::DateBin
68            | Type::MakeDate
69            | Type::MakeTime
70            | Type::MakeTimestamp
71            | Type::CharToTimestamptz
72            | Type::CharToDate
73            | Type::CastWithTimeZone
74            | Type::AddWithTimeZone
75            | Type::SubtractWithTimeZone
76            | Type::Cast
77            | Type::Substr
78            | Type::Length
79            | Type::Like
80            | Type::ILike
81            | Type::SimilarToEscape
82            | Type::Upper
83            | Type::Lower
84            | Type::Trim
85            | Type::Replace
86            | Type::Position
87            | Type::Ltrim
88            | Type::Rtrim
89            | Type::Case
90            | Type::ConstantLookup
91            | Type::RoundDigit
92            | Type::Round
93            | Type::Ascii
94            | Type::Translate
95            | Type::Coalesce
96            | Type::ConcatWs
97            | Type::ConcatWsVariadic
98            | Type::Abs
99            | Type::SplitPart
100            | Type::Ceil
101            | Type::Floor
102            | Type::Trunc
103            | Type::ToChar
104            | Type::Md5
105            | Type::CharLength
106            | Type::Repeat
107            | Type::ConcatOp
108            | Type::ByteaConcatOp
109            | Type::Concat
110            | Type::ConcatVariadic
111            | Type::BoolOut
112            | Type::OctetLength
113            | Type::BitLength
114            | Type::Overlay
115            | Type::RegexpMatch
116            | Type::RegexpReplace
117            | Type::RegexpCount
118            | Type::RegexpSplitToArray
119            | Type::RegexpEq
120            | Type::Pow
121            | Type::Exp
122            | Type::Ln
123            | Type::Log10
124            | Type::Chr
125            | Type::StartsWith
126            | Type::Initcap
127            | Type::Lpad
128            | Type::Rpad
129            | Type::Reverse
130            | Type::Strpos
131            | Type::ToAscii
132            | Type::ToHex
133            | Type::QuoteIdent
134            | Type::Sin
135            | Type::Cos
136            | Type::Tan
137            | Type::Cot
138            | Type::Asin
139            | Type::Acos
140            | Type::Acosd
141            | Type::Atan
142            | Type::Atan2
143            | Type::Atand
144            | Type::Atan2d
145            | Type::Sqrt
146            | Type::Cbrt
147            | Type::Sign
148            | Type::Scale
149            | Type::MinScale
150            | Type::TrimScale
151            | Type::Left
152            | Type::Right
153            | Type::Degrees
154            | Type::Radians
155            | Type::IsTrue
156            | Type::IsNotTrue
157            | Type::IsFalse
158            | Type::IsNotFalse
159            | Type::IsNull
160            | Type::IsNotNull
161            | Type::IsDistinctFrom
162            | Type::IsNotDistinctFrom
163            | Type::Neg
164            | Type::Field
165            | Type::Array
166            | Type::ArrayAccess
167            | Type::ArrayRangeAccess
168            | Type::Row
169            | Type::ArrayToString
170            | Type::ArrayCat
171            | Type::ArrayMax
172            | Type::ArraySum
173            | Type::ArraySort
174            | Type::ArrayAppend
175            | Type::ArrayPrepend
176            | Type::FormatType
177            | Type::ArrayDistinct
178            | Type::ArrayMin
179            | Type::ArrayDims
180            | Type::ArrayLength
181            | Type::Cardinality
182            | Type::TrimArray
183            | Type::ArrayRemove
184            | Type::ArrayReplace
185            | Type::ArrayPosition
186            | Type::ArrayContains
187            | Type::ArrayContained
188            | Type::ArrayFlatten
189            | Type::HexToInt256
190            | Type::JsonbConcat
191            | Type::JsonbAccess
192            | Type::JsonbAccessStr
193            | Type::JsonbExtractPath
194            | Type::JsonbExtractPathVariadic
195            | Type::JsonbExtractPathText
196            | Type::JsonbExtractPathTextVariadic
197            | Type::JsonbTypeof
198            | Type::JsonbArrayLength
199            | Type::JsonbObject
200            | Type::JsonbPretty
201            | Type::JsonbDeletePath
202            | Type::JsonbContains
203            | Type::JsonbContained
204            | Type::JsonbExists
205            | Type::JsonbExistsAny
206            | Type::JsonbExistsAll
207            | Type::JsonbStripNulls
208            | Type::JsonbBuildArray
209            | Type::JsonbBuildArrayVariadic
210            | Type::JsonbBuildObject
211            | Type::JsonbPopulateRecord
212            | Type::JsonbToRecord
213            | Type::JsonbBuildObjectVariadic
214            | Type::JsonbPathExists
215            | Type::JsonbPathMatch
216            | Type::JsonbPathQueryArray
217            | Type::JsonbPathQueryFirst
218            | Type::JsonbSet
219            | Type::JsonbPopulateMap
220            | Type::IsJson
221            | Type::ToJsonb
222            | Type::Sind
223            | Type::Cosd
224            | Type::Cotd
225            | Type::Asind
226            | Type::Sinh
227            | Type::Cosh
228            | Type::Coth
229            | Type::Tanh
230            | Type::Atanh
231            | Type::Asinh
232            | Type::Acosh
233            | Type::Decode
234            | Type::Encode
235            | Type::Sha1
236            | Type::Sha224
237            | Type::Sha256
238            | Type::Sha384
239            | Type::Sha512
240            | Type::Hmac
241            | Type::SecureCompare
242            | Type::Decrypt
243            | Type::Encrypt
244            | Type::Tand
245            | Type::ArrayPositions
246            | Type::StringToArray
247            | Type::Format
248            | Type::FormatVariadic
249            | Type::PgwireSend
250            | Type::PgwireRecv
251            | Type::ArrayTransform
252            | Type::Greatest
253            | Type::Least
254            | Type::ConvertFrom
255            | Type::ConvertTo
256            | Type::IcebergTransform
257            | Type::InetNtoa
258            | Type::InetAton
259            | Type::QuoteLiteral
260            | Type::QuoteNullable
261            | Type::MapFromEntries
262            | Type::MapAccess
263            | Type::MapKeys
264            | Type::MapValues
265            | Type::MapEntries
266            | Type::MapFromKeyValues
267            | Type::MapCat
268            | Type::MapContains
269            | Type::MapDelete
270            | Type::MapFilter
271            | Type::MapInsert
272            | Type::MapLength
273            | Type::L2Distance
274            | Type::VnodeUser
275            | Type::RwEpochToTs
276            | Type::CheckNotNull
277            | Type::CompositeCast =>
278            // expression output is deterministic(same result for the same input)
279            {
280                func_call
281                    .inputs()
282                    .iter()
283                    .for_each(|expr| self.visit_expr(expr));
284            }
285            // expression output is not deterministic
286            Type::Vnode // obtain vnode count from the context
287            | Type::TestPaidTier
288            | Type::License
289            | Type::Proctime
290            | Type::PgSleep
291            | Type::PgSleepFor
292            | Type::PgSleepUntil
293            | Type::CastRegclass
294            | Type::PgGetIndexdef
295            | Type::ColDescription
296            | Type::PgGetViewdef
297            | Type::PgGetUserbyid
298            | Type::PgIndexesSize
299            | Type::PgRelationSize
300            | Type::PgGetSerialSequence
301            | Type::PgIndexColumnHasProperty
302            | Type::HasTablePrivilege
303            | Type::HasAnyColumnPrivilege
304            | Type::HasSchemaPrivilege
305            | Type::MakeTimestamptz
306            | Type::PgIsInRecovery
307            | Type::RwRecoveryStatus
308            | Type::PgTableIsVisible
309            | Type::HasFunctionPrivilege
310            | Type::OpenaiEmbedding
311            | Type::HasDatabasePrivilege => self.impure = true,
312        }
313    }
314}
315
316pub fn is_pure(expr: &ExprImpl) -> bool {
317    !is_impure(expr)
318}
319
320pub fn is_impure(expr: &ExprImpl) -> bool {
321    let mut a = ImpureAnalyzer::default();
322    a.visit_expr(expr);
323    a.impure
324}
325
326pub fn is_impure_func_call(func_call: &FunctionCall) -> bool {
327    let mut a = ImpureAnalyzer::default();
328    a.visit_function_call(func_call);
329    a.impure
330}
331
332#[cfg(test)]
333mod tests {
334    use risingwave_common::types::DataType;
335    use risingwave_pb::expr::expr_node::Type;
336
337    use crate::expr::{ExprImpl, FunctionCall, InputRef, is_impure, is_pure};
338
339    fn expect_pure(expr: &ExprImpl) {
340        assert!(is_pure(expr));
341        assert!(!is_impure(expr));
342    }
343
344    fn expect_impure(expr: &ExprImpl) {
345        assert!(!is_pure(expr));
346        assert!(is_impure(expr));
347    }
348
349    #[test]
350    fn test_pure_funcs() {
351        let e: ExprImpl = FunctionCall::new(
352            Type::Add,
353            vec![
354                InputRef::new(0, DataType::Int16).into(),
355                InputRef::new(0, DataType::Int16).into(),
356            ],
357        )
358        .unwrap()
359        .into();
360        expect_pure(&e);
361
362        let e: ExprImpl = FunctionCall::new(
363            Type::GreaterThan,
364            vec![
365                InputRef::new(0, DataType::Timestamptz).into(),
366                FunctionCall::new(Type::Proctime, vec![]).unwrap().into(),
367            ],
368        )
369        .unwrap()
370        .into();
371        expect_impure(&e);
372    }
373}