risingwave_frontend/optimizer/plan_expr_visitor/
strong.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 fixedbitset::FixedBitSet;
16
17use crate::expr::{ExprImpl, ExprType, FunctionCall, InputRef};
18
19/// This utilities are with the same definition in calcite.
20/// Utilities for strong predicates.
21/// A predicate is strong (or null-rejecting) with regards to selected subset of inputs
22/// if it is UNKNOWN if all inputs in selected subset are UNKNOWN.
23/// By the way, UNKNOWN is just the boolean form of NULL.
24///
25/// Examples:
26///
27/// UNKNOWN is strong in `[]` (definitely null)
28///
29/// `c = 1` is strong in `[c]` (definitely null if and only if c is null)
30///
31/// `c IS NULL` is not strong (always returns TRUE or FALSE, nevernull)
32///
33/// `p1 AND p2` is strong in `[p1, p2]` (definitely null if either p1 is null or p2 is null)
34///
35/// `p1 OR p2` is strong if p1 and p2 are strong
36
37#[derive(Default)]
38pub struct Strong {
39    null_columns: FixedBitSet,
40}
41
42impl Strong {
43    fn new(null_columns: FixedBitSet) -> Self {
44        Self { null_columns }
45    }
46
47    /// Returns whether the analyzed expression will *definitely* return null if
48    /// all of a given set of input columns are null.
49    /// Note: we could not assume any null-related property for the input expression if `is_null` returns false
50    pub fn is_null(expr: &ExprImpl, null_columns: FixedBitSet) -> bool {
51        let strong = Strong::new(null_columns);
52        strong.is_null_visit(expr)
53    }
54
55    fn is_input_ref_null(&self, input_ref: &InputRef) -> bool {
56        self.null_columns.contains(input_ref.index())
57    }
58
59    fn is_null_visit(&self, expr: &ExprImpl) -> bool {
60        match expr {
61            ExprImpl::InputRef(input_ref) => self.is_input_ref_null(input_ref),
62            ExprImpl::Literal(literal) => literal.get_data().is_none(),
63            ExprImpl::FunctionCall(func_call) => self.is_null_function_call(func_call),
64            ExprImpl::FunctionCallWithLambda(_) => false,
65            ExprImpl::AggCall(_) => false,
66            ExprImpl::Subquery(_) => false,
67            ExprImpl::CorrelatedInputRef(_) => false,
68            ExprImpl::TableFunction(_) => false,
69            ExprImpl::WindowFunction(_) => false,
70            ExprImpl::UserDefinedFunction(_) => false,
71            ExprImpl::Parameter(_) => false,
72            ExprImpl::Now(_) => false,
73        }
74    }
75
76    fn is_null_function_call(&self, func_call: &FunctionCall) -> bool {
77        match func_call.func_type() {
78            // NOT NULL: This kind of expression is never null. No need to look at its arguments, if it has any.
79            ExprType::IsNull
80            | ExprType::IsNotNull
81            | ExprType::IsDistinctFrom
82            | ExprType::IsNotDistinctFrom
83            | ExprType::IsTrue
84            | ExprType::QuoteNullable
85            | ExprType::IsNotTrue
86            | ExprType::IsFalse
87            | ExprType::IsNotFalse
88            | ExprType::CheckNotNull => false,
89            // ANY: This kind of expression is null if and only if at least one of its arguments is null.
90            ExprType::Not
91            | ExprType::Equal
92            | ExprType::NotEqual
93            | ExprType::LessThan
94            | ExprType::LessThanOrEqual
95            | ExprType::GreaterThan
96            | ExprType::GreaterThanOrEqual
97            | ExprType::Like
98            | ExprType::Add
99            | ExprType::AddWithTimeZone
100            | ExprType::Subtract
101            | ExprType::Multiply
102            | ExprType::Modulus
103            | ExprType::Divide
104            | ExprType::Cast
105            | ExprType::Trim
106            | ExprType::Ltrim
107            | ExprType::Rtrim
108            | ExprType::Ceil
109            | ExprType::Floor
110            | ExprType::Extract
111            | ExprType::L2Distance
112            | ExprType::CosineDistance
113            | ExprType::L1Distance
114            | ExprType::InnerProduct
115            | ExprType::VecConcat
116            | ExprType::L2Norm
117            | ExprType::L2Normalize
118            | ExprType::Subvector
119            | ExprType::Greatest
120            | ExprType::Least => self.any_null(func_call),
121            // ALL: This kind of expression is null if and only if all of its arguments are null.
122            ExprType::And | ExprType::Or | ExprType::Coalesce => self.all_null(func_call),
123            // TODO: Function like case when is important but current its structure is complicated, so we need to implement it later if necessary.
124            // Assume that any other expressions cannot be simplified.
125            ExprType::In
126            | ExprType::Some
127            | ExprType::All
128            | ExprType::BitwiseAnd
129            | ExprType::BitwiseOr
130            | ExprType::BitwiseXor
131            | ExprType::BitwiseNot
132            | ExprType::BitwiseShiftLeft
133            | ExprType::BitwiseShiftRight
134            | ExprType::DatePart
135            | ExprType::TumbleStart
136            | ExprType::MakeDate
137            | ExprType::MakeTime
138            | ExprType::MakeTimestamp
139            | ExprType::SecToTimestamptz
140            | ExprType::AtTimeZone
141            | ExprType::DateTrunc
142            | ExprType::DateBin
143            | ExprType::CharToTimestamptz
144            | ExprType::CharToDate
145            | ExprType::CastWithTimeZone
146            | ExprType::SubtractWithTimeZone
147            | ExprType::MakeTimestamptz
148            | ExprType::Substr
149            | ExprType::Length
150            | ExprType::ILike
151            | ExprType::SimilarToEscape
152            | ExprType::Upper
153            | ExprType::Lower
154            | ExprType::Replace
155            | ExprType::Position
156            | ExprType::Case
157            | ExprType::ConstantLookup
158            | ExprType::RoundDigit
159            | ExprType::Round
160            | ExprType::Ascii
161            | ExprType::Translate
162            | ExprType::Concat
163            | ExprType::ConcatVariadic
164            | ExprType::ConcatWs
165            | ExprType::ConcatWsVariadic
166            | ExprType::Abs
167            | ExprType::SplitPart
168            | ExprType::ToChar
169            | ExprType::Md5
170            | ExprType::CharLength
171            | ExprType::Repeat
172            | ExprType::ConcatOp
173            | ExprType::ByteaConcatOp
174            | ExprType::BoolOut
175            | ExprType::OctetLength
176            | ExprType::BitLength
177            | ExprType::Overlay
178            | ExprType::RegexpMatch
179            | ExprType::RegexpReplace
180            | ExprType::RegexpCount
181            | ExprType::RegexpSplitToArray
182            | ExprType::RegexpEq
183            | ExprType::Pow
184            | ExprType::Exp
185            | ExprType::Chr
186            | ExprType::StartsWith
187            | ExprType::Initcap
188            | ExprType::Lpad
189            | ExprType::Rpad
190            | ExprType::Reverse
191            | ExprType::Strpos
192            | ExprType::ToAscii
193            | ExprType::ToHex
194            | ExprType::QuoteIdent
195            | ExprType::QuoteLiteral
196            | ExprType::Sin
197            | ExprType::Cos
198            | ExprType::Tan
199            | ExprType::Cot
200            | ExprType::Asin
201            | ExprType::Acos
202            | ExprType::Acosd
203            | ExprType::Atan
204            | ExprType::Atan2
205            | ExprType::Atand
206            | ExprType::Atan2d
207            | ExprType::Sind
208            | ExprType::Cosd
209            | ExprType::Cotd
210            | ExprType::Tand
211            | ExprType::Asind
212            | ExprType::Sqrt
213            | ExprType::Degrees
214            | ExprType::Radians
215            | ExprType::Cosh
216            | ExprType::Tanh
217            | ExprType::Coth
218            | ExprType::Asinh
219            | ExprType::Acosh
220            | ExprType::Atanh
221            | ExprType::Sinh
222            | ExprType::Trunc
223            | ExprType::Ln
224            | ExprType::Log10
225            | ExprType::Cbrt
226            | ExprType::Sign
227            | ExprType::Scale
228            | ExprType::MinScale
229            | ExprType::TrimScale
230            | ExprType::Encode
231            | ExprType::Decode
232            | ExprType::Sha1
233            | ExprType::Sha224
234            | ExprType::Sha256
235            | ExprType::Sha384
236            | ExprType::Sha512
237            | ExprType::GetBit
238            | ExprType::GetByte
239            | ExprType::SetBit
240            | ExprType::SetByte
241            | ExprType::BitCount
242            | ExprType::Hmac
243            | ExprType::SecureCompare
244            | ExprType::Left
245            | ExprType::Right
246            | ExprType::Format
247            | ExprType::FormatVariadic
248            | ExprType::PgwireSend
249            | ExprType::PgwireRecv
250            | ExprType::ConvertFrom
251            | ExprType::ConvertTo
252            | ExprType::Decrypt
253            | ExprType::Encrypt
254            | ExprType::Neg
255            | ExprType::Field
256            | ExprType::Array
257            | ExprType::ArrayAccess
258            | ExprType::Row
259            | ExprType::ArrayToString
260            | ExprType::ArrayRangeAccess
261            | ExprType::ArrayCat
262            | ExprType::ArrayAppend
263            | ExprType::ArrayPrepend
264            | ExprType::FormatType
265            | ExprType::ArrayDistinct
266            | ExprType::ArrayLength
267            | ExprType::Cardinality
268            | ExprType::ArrayRemove
269            | ExprType::ArrayPositions
270            | ExprType::TrimArray
271            | ExprType::StringToArray
272            | ExprType::ArrayPosition
273            | ExprType::ArrayReplace
274            | ExprType::ArrayDims
275            | ExprType::ArrayTransform
276            | ExprType::ArrayMin
277            | ExprType::ArrayMax
278            | ExprType::ArraySum
279            | ExprType::ArraySort
280            | ExprType::ArrayContains
281            | ExprType::ArrayContained
282            | ExprType::ArrayFlatten
283            | ExprType::HexToInt256
284            | ExprType::JsonbAccess
285            | ExprType::JsonbAccessStr
286            | ExprType::JsonbExtractPath
287            | ExprType::JsonbExtractPathVariadic
288            | ExprType::JsonbExtractPathText
289            | ExprType::JsonbExtractPathTextVariadic
290            | ExprType::JsonbTypeof
291            | ExprType::JsonbArrayLength
292            | ExprType::IsJson
293            | ExprType::JsonbConcat
294            | ExprType::JsonbObject
295            | ExprType::JsonbPretty
296            | ExprType::JsonbContains
297            | ExprType::JsonbContained
298            | ExprType::JsonbExists
299            | ExprType::JsonbExistsAny
300            | ExprType::JsonbExistsAll
301            | ExprType::JsonbDeletePath
302            | ExprType::JsonbStripNulls
303            | ExprType::ToJsonb
304            | ExprType::JsonbBuildArray
305            | ExprType::JsonbBuildArrayVariadic
306            | ExprType::JsonbBuildObject
307            | ExprType::JsonbBuildObjectVariadic
308            | ExprType::JsonbPathExists
309            | ExprType::JsonbPathMatch
310            | ExprType::JsonbPathQueryArray
311            | ExprType::JsonbPathQueryFirst
312            | ExprType::JsonbPopulateRecord
313            | ExprType::JsonbToArray
314            | ExprType::JsonbToRecord
315            | ExprType::JsonbSet
316            | ExprType::JsonbPopulateMap
317            | ExprType::MapFromEntries
318            | ExprType::MapAccess
319            | ExprType::MapKeys
320            | ExprType::MapValues
321            | ExprType::MapEntries
322            | ExprType::MapFromKeyValues
323            | ExprType::MapCat
324            | ExprType::MapContains
325            | ExprType::MapDelete
326            | ExprType::MapFilter
327            | ExprType::MapInsert
328            | ExprType::MapLength
329            | ExprType::Vnode
330            | ExprType::VnodeUser
331            | ExprType::TestFeature
332            | ExprType::License
333            | ExprType::Proctime
334            | ExprType::PgSleep
335            | ExprType::PgSleepFor
336            | ExprType::PgSleepUntil
337            | ExprType::CastRegclass
338            | ExprType::PgGetIndexdef
339            | ExprType::ColDescription
340            | ExprType::PgGetViewdef
341            | ExprType::PgGetUserbyid
342            | ExprType::PgIndexesSize
343            | ExprType::PgRelationSize
344            | ExprType::PgGetSerialSequence
345            | ExprType::PgIndexColumnHasProperty
346            | ExprType::PgIsInRecovery
347            | ExprType::PgTableIsVisible
348            | ExprType::RwRecoveryStatus
349            | ExprType::IcebergTransform
350            | ExprType::HasTablePrivilege
351            | ExprType::HasFunctionPrivilege
352            | ExprType::HasAnyColumnPrivilege
353            | ExprType::HasSchemaPrivilege
354            | ExprType::InetAton
355            | ExprType::InetNtoa
356            | ExprType::CompositeCast
357            | ExprType::RwEpochToTs
358            | ExprType::OpenaiEmbedding
359            | ExprType::HasDatabasePrivilege
360            | ExprType::Random => false,
361            ExprType::Unspecified => unreachable!(),
362        }
363    }
364
365    fn any_null(&self, func_call: &FunctionCall) -> bool {
366        func_call
367            .inputs()
368            .iter()
369            .any(|expr| self.is_null_visit(expr))
370    }
371
372    fn all_null(&self, func_call: &FunctionCall) -> bool {
373        func_call
374            .inputs()
375            .iter()
376            .all(|expr| self.is_null_visit(expr))
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use risingwave_common::types::DataType;
383
384    use super::*;
385    use crate::expr::ExprImpl::Literal;
386
387    #[test]
388    fn test_literal() {
389        let null_columns = FixedBitSet::with_capacity(1);
390        let expr = Literal(crate::expr::Literal::new(None, DataType::Varchar).into());
391        assert!(Strong::is_null(&expr, null_columns.clone()));
392
393        let expr = Literal(
394            crate::expr::Literal::new(Some("test".to_owned().into()), DataType::Varchar).into(),
395        );
396        assert!(!Strong::is_null(&expr, null_columns));
397    }
398
399    #[test]
400    fn test_input_ref1() {
401        let null_columns = FixedBitSet::with_capacity(2);
402        let expr = InputRef::new(0, DataType::Varchar).into();
403        assert!(!Strong::is_null(&expr, null_columns.clone()));
404
405        let expr = InputRef::new(1, DataType::Varchar).into();
406        assert!(!Strong::is_null(&expr, null_columns));
407    }
408
409    #[test]
410    fn test_input_ref2() {
411        let mut null_columns = FixedBitSet::with_capacity(2);
412        null_columns.insert(0);
413        null_columns.insert(1);
414        let expr = InputRef::new(0, DataType::Varchar).into();
415        assert!(Strong::is_null(&expr, null_columns.clone()));
416
417        let expr = InputRef::new(1, DataType::Varchar).into();
418        assert!(Strong::is_null(&expr, null_columns));
419    }
420
421    #[test]
422    fn test_c1_equal_1_or_c2_is_null() {
423        let mut null_columns = FixedBitSet::with_capacity(2);
424        null_columns.insert(0);
425        let expr = FunctionCall::new_unchecked(
426            ExprType::Or,
427            vec![
428                FunctionCall::new_unchecked(
429                    ExprType::Equal,
430                    vec![
431                        InputRef::new(0, DataType::Int64).into(),
432                        Literal(crate::expr::Literal::new(Some(1.into()), DataType::Int32).into()),
433                    ],
434                    DataType::Boolean,
435                )
436                .into(),
437                FunctionCall::new_unchecked(
438                    ExprType::IsNull,
439                    vec![InputRef::new(1, DataType::Int64).into()],
440                    DataType::Boolean,
441                )
442                .into(),
443            ],
444            DataType::Boolean,
445        )
446        .into();
447        assert!(!Strong::is_null(&expr, null_columns));
448    }
449
450    #[test]
451    fn test_divide() {
452        let mut null_columns = FixedBitSet::with_capacity(2);
453        null_columns.insert(0);
454        null_columns.insert(1);
455        let expr = FunctionCall::new_unchecked(
456            ExprType::Divide,
457            vec![
458                InputRef::new(0, DataType::Decimal).into(),
459                InputRef::new(1, DataType::Decimal).into(),
460            ],
461            DataType::Varchar,
462        )
463        .into();
464        assert!(Strong::is_null(&expr, null_columns));
465    }
466
467    /// generate a test case for (0.8 * sum / count) where sum is null and count is not null
468    #[test]
469    fn test_multiply_divide() {
470        let mut null_columns = FixedBitSet::with_capacity(2);
471        null_columns.insert(0);
472        let expr = FunctionCall::new_unchecked(
473            ExprType::Multiply,
474            vec![
475                Literal(crate::expr::Literal::new(Some(0.8f64.into()), DataType::Float64).into()),
476                FunctionCall::new_unchecked(
477                    ExprType::Divide,
478                    vec![
479                        InputRef::new(0, DataType::Decimal).into(),
480                        InputRef::new(1, DataType::Decimal).into(),
481                    ],
482                    DataType::Decimal,
483                )
484                .into(),
485            ],
486            DataType::Decimal,
487        )
488        .into();
489        assert!(Strong::is_null(&expr, null_columns));
490    }
491
492    /// generate test cases for is not null
493    macro_rules! gen_test {
494        ($func:ident, $expr:expr, $expected:expr) => {
495            #[test]
496            fn $func() {
497                let null_columns = FixedBitSet::with_capacity(2);
498                let expr = $expr;
499                assert_eq!(Strong::is_null(&expr, null_columns), $expected);
500            }
501        };
502    }
503
504    gen_test!(
505        test_is_not_null,
506        FunctionCall::new_unchecked(
507            ExprType::IsNotNull,
508            vec![InputRef::new(0, DataType::Varchar).into()],
509            DataType::Varchar
510        )
511        .into(),
512        false
513    );
514    gen_test!(
515        test_is_null,
516        FunctionCall::new_unchecked(
517            ExprType::IsNull,
518            vec![InputRef::new(0, DataType::Varchar).into()],
519            DataType::Varchar
520        )
521        .into(),
522        false
523    );
524    gen_test!(
525        test_is_distinct_from,
526        FunctionCall::new_unchecked(
527            ExprType::IsDistinctFrom,
528            vec![
529                InputRef::new(0, DataType::Varchar).into(),
530                InputRef::new(1, DataType::Varchar).into()
531            ],
532            DataType::Varchar
533        )
534        .into(),
535        false
536    );
537    gen_test!(
538        test_is_not_distinct_from,
539        FunctionCall::new_unchecked(
540            ExprType::IsNotDistinctFrom,
541            vec![
542                InputRef::new(0, DataType::Varchar).into(),
543                InputRef::new(1, DataType::Varchar).into()
544            ],
545            DataType::Varchar
546        )
547        .into(),
548        false
549    );
550    gen_test!(
551        test_is_true,
552        FunctionCall::new_unchecked(
553            ExprType::IsTrue,
554            vec![InputRef::new(0, DataType::Varchar).into()],
555            DataType::Varchar
556        )
557        .into(),
558        false
559    );
560    gen_test!(
561        test_is_not_true,
562        FunctionCall::new_unchecked(
563            ExprType::IsNotTrue,
564            vec![InputRef::new(0, DataType::Varchar).into()],
565            DataType::Varchar
566        )
567        .into(),
568        false
569    );
570    gen_test!(
571        test_is_false,
572        FunctionCall::new_unchecked(
573            ExprType::IsFalse,
574            vec![InputRef::new(0, DataType::Varchar).into()],
575            DataType::Varchar
576        )
577        .into(),
578        false
579    );
580}