Skip to main content

risingwave_frontend/expr/
pure.rs

1// Copyright 2023 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 std::borrow::Cow;
16
17use expr_node::Type;
18use risingwave_pb::expr::expr_node;
19
20use super::{ExprImpl, ExprVisitor};
21use crate::expr::FunctionCall;
22
23#[derive(Default)]
24pub(crate) struct ImpureAnalyzer {
25    impure: Option<Cow<'static, str>>,
26}
27
28impl ImpureAnalyzer {
29    /// Returns `true` if the expression is impure.
30    ///
31    /// Only call this method after visiting the expression.
32    pub fn is_impure(&self) -> bool {
33        self.impure.is_some()
34    }
35
36    /// Returns the description of the impure expression if it is impure, for error reporting.
37    /// `None` if the expression is pure.
38    ///
39    /// Only call this method after visiting the expression.
40    pub fn impure_expr_desc(&self) -> Option<&str> {
41        self.impure.as_deref()
42    }
43}
44
45impl ExprVisitor for ImpureAnalyzer {
46    fn visit_function_call_with_lambda(&mut self, call: &super::FunctionCallWithLambda) {
47        self.visit_function_call(&call.to_full_function_call());
48    }
49
50    fn visit_user_defined_function(&mut self, func_call: &super::UserDefinedFunction) {
51        if func_call.catalog.is_immutable {
52            func_call.args.iter().for_each(|expr| self.visit_expr(expr));
53        } else {
54            let name = &func_call.catalog.name;
55            self.impure = Some(format!("user-defined function `{name}`").into());
56        }
57    }
58
59    fn visit_table_function(&mut self, func_call: &super::TableFunction) {
60        use crate::expr::table_function::TableFunctionType as Type;
61        let func_type = func_call.function_type;
62        match func_type {
63            Type::Unspecified => unreachable!(),
64
65            // deterministic
66            Type::GenerateSeries
67            | Type::Unnest
68            | Type::RegexpMatches
69            | Type::Range
70            | Type::GenerateSubscripts
71            | Type::PgExpandarray
72            | Type::JsonbArrayElements
73            | Type::JsonbArrayElementsText
74            | Type::JsonbEach
75            | Type::JsonbEachText
76            | Type::JsonbObjectKeys
77            | Type::JsonbPathQuery
78            | Type::JsonbPopulateRecordset
79            | Type::JsonbToRecordset => {
80                func_call.args.iter().for_each(|expr| self.visit_expr(expr));
81            }
82
83            // indeterministic
84            Type::FileScan
85            | Type::PostgresQuery
86            | Type::MysqlQuery
87            | Type::MssqlQuery
88            | Type::InternalBackfillProgress
89            | Type::InternalSourceBackfillProgress
90            | Type::InternalGetChannelDeltaStats
91            | Type::PgGetKeywords => {
92                self.impure = Some(func_type.as_str_name().into());
93            }
94            Type::UserDefined => {
95                let name = &func_call.user_defined.as_ref().unwrap().name;
96                self.impure = Some(format!("user-defined table function `{name}`").into());
97            }
98        }
99    }
100
101    fn visit_now(&mut self, _: &super::Now) {
102        self.impure = Some("NOW or PROCTIME".into());
103    }
104
105    fn visit_secret_ref(&mut self, secret_ref: &super::SecretRef) {
106        self.impure = Some(format!("secret reference `{}`", secret_ref.secret_name).into());
107    }
108
109    fn visit_function_call(&mut self, func_call: &super::FunctionCall) {
110        let func_type = func_call.func_type();
111        match func_type {
112            Type::Unspecified => unreachable!(),
113            #[expect(deprecated)]
114            Type::Add
115            | Type::Subtract
116            | Type::Multiply
117            | Type::Divide
118            | Type::Modulus
119            | Type::Equal
120            | Type::NotEqual
121            | Type::LessThan
122            | Type::LessThanOrEqual
123            | Type::GreaterThan
124            | Type::GreaterThanOrEqual
125            | Type::And
126            | Type::Or
127            | Type::Not
128            | Type::In
129            | Type::Some
130            | Type::All
131            | Type::BitwiseAnd
132            | Type::BitwiseOr
133            | Type::BitwiseXor
134            | Type::BitwiseNot
135            | Type::BitwiseShiftLeft
136            | Type::BitwiseShiftRight
137            | Type::Extract
138            | Type::DatePart
139            | Type::TumbleStart
140            | Type::SecToTimestamptz
141            | Type::AtTimeZone
142            | Type::DateTrunc
143            | Type::DateBin
144            | Type::MakeDate
145            | Type::MakeTime
146            | Type::MakeTimestamp
147            | Type::CharToTimestamptz
148            | Type::CharToDate
149            | Type::CastWithTimeZone
150            | Type::AddWithTimeZone
151            | Type::SubtractWithTimeZone
152            | Type::Cast
153            | Type::Substr
154            | Type::Length
155            | Type::Like
156            | Type::ILike
157            | Type::SimilarToEscape
158            | Type::Upper
159            | Type::Lower
160            | Type::Trim
161            | Type::Replace
162            | Type::Position
163            | Type::Ltrim
164            | Type::Rtrim
165            | Type::Case
166            | Type::ConstantLookup
167            | Type::RoundDigit
168            | Type::Round
169            | Type::Ascii
170            | Type::Translate
171            | Type::Coalesce
172            | Type::ConcatWs
173            | Type::ConcatWsVariadic
174            | Type::Abs
175            | Type::SplitPart
176            | Type::Ceil
177            | Type::Floor
178            | Type::Trunc
179            | Type::ToChar
180            | Type::Md5
181            | Type::CharLength
182            | Type::Repeat
183            | Type::ConcatOp
184            | Type::ByteaConcatOp
185            | Type::Concat
186            | Type::ConcatVariadic
187            | Type::BoolOut
188            | Type::OctetLength
189            | Type::BitLength
190            | Type::Overlay
191            | Type::RegexpMatch
192            | Type::RegexpReplace
193            | Type::RegexpCount
194            | Type::RegexpSplitToArray
195            | Type::RegexpEq
196            | Type::Pow
197            | Type::Exp
198            | Type::Ln
199            | Type::Log10
200            | Type::Chr
201            | Type::StartsWith
202            | Type::Initcap
203            | Type::Lpad
204            | Type::Rpad
205            | Type::Reverse
206            | Type::Strpos
207            | Type::ToAscii
208            | Type::ToHex
209            | Type::QuoteIdent
210            | Type::Sin
211            | Type::Cos
212            | Type::Tan
213            | Type::Cot
214            | Type::Asin
215            | Type::Acos
216            | Type::Acosd
217            | Type::Atan
218            | Type::Atan2
219            | Type::Atand
220            | Type::Atan2d
221            | Type::Sqrt
222            | Type::Cbrt
223            | Type::Sign
224            | Type::Scale
225            | Type::MinScale
226            | Type::TrimScale
227            | Type::Gamma
228            | Type::Lgamma
229            | Type::Left
230            | Type::Right
231            | Type::Degrees
232            | Type::Radians
233            | Type::IsTrue
234            | Type::IsNotTrue
235            | Type::IsFalse
236            | Type::IsNotFalse
237            | Type::IsNull
238            | Type::IsNotNull
239            | Type::IsDistinctFrom
240            | Type::IsNotDistinctFrom
241            | Type::Neg
242            | Type::Field
243            | Type::Array
244            | Type::ArrayAccess
245            | Type::ArrayRangeAccess
246            | Type::Row
247            | Type::ArrayToString
248            | Type::ArrayCat
249            | Type::ArrayMax
250            | Type::ArraySum
251            | Type::ArraySort
252            | Type::ArrayAppend
253            | Type::ArrayReverse
254            | Type::ArrayPrepend
255            | Type::FormatType
256            | Type::ArrayDistinct
257            | Type::ArrayMin
258            | Type::ArrayDims
259            | Type::ArrayLength
260            | Type::Cardinality
261            | Type::TrimArray
262            | Type::ArrayRemove
263            | Type::ArrayReplace
264            | Type::ArrayPosition
265            | Type::ArrayContains
266            | Type::ArrayContained
267            | Type::ArrayOverlaps
268            | Type::ArrayFlatten
269            | Type::HexToInt256
270            | Type::JsonbConcat
271            | Type::JsonbAccess
272            | Type::JsonbAccessStr
273            | Type::JsonbExtractPath
274            | Type::JsonbExtractPathVariadic
275            | Type::JsonbExtractPathText
276            | Type::JsonbExtractPathTextVariadic
277            | Type::JsonbTypeof
278            | Type::JsonbArrayLength
279            | Type::JsonbObject
280            | Type::JsonbPretty
281            | Type::JsonbDeletePath
282            | Type::JsonbContains
283            | Type::JsonbContained
284            | Type::JsonbExists
285            | Type::JsonbExistsAny
286            | Type::JsonbExistsAll
287            | Type::JsonbStripNulls
288            | Type::JsonbBuildArray
289            | Type::JsonbBuildArrayVariadic
290            | Type::JsonbBuildObject
291            | Type::JsonbPopulateRecord
292            | Type::JsonbToArray
293            | Type::JsonbToRecord
294            | Type::JsonbBuildObjectVariadic
295            | Type::JsonbPathExists
296            | Type::JsonbPathMatch
297            | Type::JsonbPathQueryArray
298            | Type::JsonbPathQueryFirst
299            | Type::JsonbSet
300            | Type::JsonbPopulateMap
301            | Type::IsJson
302            | Type::ToJsonb
303            | Type::ToVariant
304            | Type::VariantGet
305            | Type::TryVariantGet
306            | Type::VariantTypeof
307            | Type::Sind
308            | Type::Cosd
309            | Type::Cotd
310            | Type::Asind
311            | Type::Sinh
312            | Type::Cosh
313            | Type::Coth
314            | Type::Tanh
315            | Type::Atanh
316            | Type::Asinh
317            | Type::Acosh
318            | Type::Decode
319            | Type::Encode
320            | Type::GetBit
321            | Type::GetByte
322            | Type::SetBit
323            | Type::SetByte
324            | Type::BitCount
325            | Type::Sha1
326            | Type::Sha224
327            | Type::Sha256
328            | Type::Sha384
329            | Type::Sha512
330            | Type::Crc32
331            | Type::Crc32c
332            | Type::Hmac
333            | Type::SecureCompare
334            | Type::Decrypt
335            | Type::Encrypt
336            | Type::Tand
337            | Type::ArrayPositions
338            | Type::StringToArray
339            | Type::Format
340            | Type::FormatVariadic
341            | Type::PgwireSend
342            | Type::PgwireRecv
343            | Type::ArrayTransform
344            | Type::Greatest
345            | Type::Least
346            | Type::ConvertFrom
347            | Type::ConvertTo
348            | Type::IcebergTransform
349            | Type::InetNtoa
350            | Type::InetAton
351            | Type::QuoteLiteral
352            | Type::QuoteNullable
353            | Type::MapFromEntries
354            | Type::MapAccess
355            | Type::MapKeys
356            | Type::MapValues
357            | Type::MapEntries
358            | Type::MapFromKeyValues
359            | Type::MapCat
360            | Type::MapContains
361            | Type::MapDelete
362            | Type::MapFilter
363            | Type::MapInsert
364            | Type::MapLength
365            | Type::L2Distance
366            | Type::CosineDistance
367            | Type::L1Distance
368            | Type::InnerProduct
369            | Type::VecConcat
370            | Type::L2Norm
371            | Type::L2Normalize
372            | Type::Subvector
373            // TODO: `rw_vnode` is more like STABLE instead of IMMUTABLE, because even its result is
374            // deterministic, it needs to read the total vnode count from the context, which means that
375            // it cannot be evaluated during constant folding. We have to treat it pure here so it can be used
376            // internally without materialization.
377            | Type::Vnode
378            | Type::VnodeUser
379            | Type::RwEpochToTs
380            | Type::CheckNotNull
381            | Type::CompositeCast =>
382            // expression output is deterministic(same result for the same input)
383            {
384                func_call
385                    .inputs()
386                    .iter()
387                    .for_each(|expr| self.visit_expr(expr));
388            }
389            // expression output is not deterministic
390            Type::TestFeature
391            | Type::License
392            | Type::Proctime
393            | Type::PgSleep
394            | Type::PgSleepFor
395            | Type::PgSleepUntil
396            | Type::CastRegclass
397            | Type::PgGetIndexdef
398            | Type::ColDescription
399            | Type::PgGetViewdef
400            | Type::PgGetUserbyid
401            | Type::PgIndexesSize
402            | Type::PgRelationSize
403            | Type::PgGetSerialSequence
404            | Type::PgIndexColumnHasProperty
405            | Type::HasTablePrivilege
406            | Type::HasAnyColumnPrivilege
407            | Type::HasSchemaPrivilege
408            | Type::MakeTimestamptz
409            | Type::PgIsInRecovery
410            | Type::RwRecoveryStatus
411            | Type::RwWarmup
412            | Type::RwClusterId
413            | Type::RwFragmentVnodes
414            | Type::RwActorVnodes
415            | Type::PgTableIsVisible
416            | Type::HasFunctionPrivilege
417            | Type::OpenaiEmbedding
418            | Type::AiDecide
419            | Type::HasDatabasePrivilege
420            | Type::Random
421            | Type::ClockTimestamp
422            | Type::GenRandomUuid => self.impure = Some(func_type.as_str_name().into()),
423        }
424    }
425}
426
427/// Returns whether every function in the expression always produces the same result for the same
428/// inputs, so that the expression can be re-evaluated or moved by the optimizer.
429///
430/// - Built-in scalar and table functions are pure when they are deterministic, as classified by
431///   [`ImpureAnalyzer`]. `NOW`, `PROCTIME` and secret references are impure.
432/// - User-defined scalar functions are pure when they are declared `IMMUTABLE`. The planner
433///   trusts the declaration; it cannot verify the implementation. User-defined table functions
434///   are always impure.
435///
436/// A pure expression may still have its evaluated results materialized on retract streams: a UDF
437/// keeps materialization unless it sets `unsafe_skip_materializing_exprs`. Whether an expression
438/// needs materialization is decided by [`needs_materialization`].
439pub fn is_pure(expr: &ExprImpl) -> bool {
440    !is_impure(expr)
441}
442
443/// The inverse of [`is_pure`].
444pub fn is_impure(expr: &ExprImpl) -> bool {
445    let mut a = ImpureAnalyzer::default();
446    a.visit_expr(expr);
447    a.is_impure()
448}
449
450pub fn is_impure_func_call(func_call: &FunctionCall) -> bool {
451    let mut a = ImpureAnalyzer::default();
452    a.visit_function_call(func_call);
453    a.is_impure()
454}
455
456/// Returns the description of the impure expression if it is impure, for error reporting.
457/// `None` if the expression is pure.
458pub fn impure_expr_desc(expr: &ExprImpl) -> Option<String> {
459    let mut a = ImpureAnalyzer::default();
460    a.visit_expr(expr);
461    a.impure_expr_desc().map(|s| s.to_owned())
462}
463
464/// Finds UDFs that keep their evaluated results materialized on retract streams, that is, UDFs
465/// without `unsafe_skip_materializing_exprs`.
466#[derive(Default)]
467struct MaterializationAnalyzer {
468    needs_materialization: bool,
469}
470
471impl ExprVisitor for MaterializationAnalyzer {
472    fn visit_user_defined_function(&mut self, func_call: &super::UserDefinedFunction) {
473        self.needs_materialization |= !func_call.catalog.unsafe_skip_materializing_exprs;
474        func_call.args.iter().for_each(|expr| self.visit_expr(expr));
475    }
476}
477
478/// Returns whether a streaming project on a retract stream must materialize the evaluated results
479/// of the expression: when the expression is impure, or when it calls a UDF without
480/// `unsafe_skip_materializing_exprs`.
481pub fn needs_materialization(expr: &ExprImpl) -> bool {
482    if is_impure(expr) {
483        return true;
484    }
485    let mut a = MaterializationAnalyzer::default();
486    a.visit_expr(expr);
487    a.needs_materialization
488}
489
490#[cfg(test)]
491mod tests {
492    use risingwave_common::types::DataType;
493    use risingwave_pb::expr::expr_node::Type;
494
495    use crate::expr::{ExprImpl, FunctionCall, InputRef, is_impure, is_pure};
496
497    fn expect_pure(expr: &ExprImpl) {
498        assert!(is_pure(expr));
499        assert!(!is_impure(expr));
500    }
501
502    fn expect_impure(expr: &ExprImpl) {
503        assert!(!is_pure(expr));
504        assert!(is_impure(expr));
505    }
506
507    #[test]
508    fn test_pure_funcs() {
509        let e: ExprImpl = FunctionCall::new(
510            Type::Add,
511            vec![
512                InputRef::new(0, DataType::Int16).into(),
513                InputRef::new(0, DataType::Int16).into(),
514            ],
515        )
516        .unwrap()
517        .into();
518        expect_pure(&e);
519
520        let e: ExprImpl = FunctionCall::new(
521            Type::GreaterThan,
522            vec![
523                InputRef::new(0, DataType::Timestamptz).into(),
524                FunctionCall::new(Type::Proctime, vec![]).unwrap().into(),
525            ],
526        )
527        .unwrap()
528        .into();
529        expect_impure(&e);
530    }
531}