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