Skip to main content

common_function/scalars/
matches.rs

1// Copyright 2023 Greptime Team
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::collections::HashMap;
16use std::fmt;
17use std::sync::Arc;
18
19use common_query::error::{InvalidFuncArgsSnafu, Result};
20use datafusion::arrow::array::{Array, ArrayRef, AsArray, BooleanArray};
21use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeIterator, TreeNodeRecursion};
22use datafusion::common::{DFSchema, Result as DfResult};
23use datafusion::execution::SessionStateBuilder;
24use datafusion::logical_expr::{self, ColumnarValue, Expr, Volatility};
25use datafusion::physical_planner::{DefaultPhysicalPlanner, PhysicalPlanner};
26use datafusion_common::{DataFusionError, ScalarValue};
27use datafusion_expr::physical_planning_context::PhysicalPlanningContext;
28use datafusion_expr::{ScalarFunctionArgs, Signature};
29use datatypes::arrow::array::RecordBatch;
30use datatypes::arrow::datatypes::{DataType, Field};
31use snafu::{OptionExt, ensure};
32
33use crate::function::{Function, extract_args};
34use crate::function_registry::FunctionRegistry;
35
36/// `matches` for full text search.
37///
38/// Usage: matches(`<col>`, `<pattern>`) -> boolean
39#[derive(Clone, Debug)]
40pub struct MatchesFunction {
41    signature: Signature,
42}
43
44impl MatchesFunction {
45    pub fn register(registry: &FunctionRegistry) {
46        registry.register_scalar(MatchesFunction::default());
47    }
48}
49
50impl Default for MatchesFunction {
51    fn default() -> Self {
52        Self {
53            signature: Signature::string(2, Volatility::Immutable),
54        }
55    }
56}
57
58impl fmt::Display for MatchesFunction {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        write!(f, "MATCHES")
61    }
62}
63
64impl Function for MatchesFunction {
65    fn name(&self) -> &str {
66        "matches"
67    }
68
69    fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
70        Ok(DataType::Boolean)
71    }
72
73    fn signature(&self) -> &Signature {
74        &self.signature
75    }
76
77    // TODO: read case-sensitive config
78    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> DfResult<ColumnarValue> {
79        let [data_column, patterns] = extract_args(self.name(), &args)?;
80
81        if data_column.is_empty() {
82            return Ok(ColumnarValue::Array(Arc::new(BooleanArray::from(
83                Vec::<bool>::with_capacity(0),
84            ))));
85        }
86
87        // Safety: both length and type are checked before
88        let pattern = match patterns.data_type() {
89            DataType::Utf8View => patterns.as_string_view().value(0),
90            DataType::Utf8 => patterns.as_string::<i32>().value(0),
91            DataType::LargeUtf8 => patterns.as_string::<i64>().value(0),
92            t => {
93                return Err(DataFusionError::Execution(format!(
94                    "unsupported datatype {t}"
95                )));
96            }
97        };
98        self.eval(data_column, pattern)
99    }
100}
101
102impl MatchesFunction {
103    fn eval(&self, data_array: ArrayRef, pattern: &str) -> DfResult<ColumnarValue> {
104        let data_type = data_array.data_type();
105        if !data_type.is_string() {
106            return Err(DataFusionError::Execution(format!(
107                "unsupported datatype {data_type}"
108            )));
109        }
110        let col_name = "data";
111        let parser_context = ParserContext::default();
112        let raw_ast = parser_context.parse_pattern(pattern)?;
113        let ast = raw_ast.transform_ast()?;
114
115        let like_expr = ast.into_like_expr(col_name, data_type);
116        let input_schema = Self::input_schema(data_type);
117        let session_state = SessionStateBuilder::new().with_default_features().build();
118        let planner = DefaultPhysicalPlanner::default();
119        let physical_expr = planner.create_physical_expr(
120            &like_expr,
121            &input_schema,
122            &session_state,
123            &PhysicalPlanningContext::default(),
124        )?;
125
126        let arrow_schema = Arc::new(input_schema.as_arrow().clone());
127        let input_record_batch = RecordBatch::try_new(arrow_schema, vec![data_array])?;
128
129        let num_rows = input_record_batch.num_rows();
130        let result = physical_expr.evaluate(&input_record_batch)?;
131        let result_array = result.into_array(num_rows)?;
132
133        Ok(ColumnarValue::Array(Arc::new(result_array)))
134    }
135
136    fn input_schema(data_type: &DataType) -> DFSchema {
137        DFSchema::from_unqualified_fields(
138            [Arc::new(Field::new("data", data_type.clone(), true))].into(),
139            HashMap::new(),
140        )
141        .unwrap()
142    }
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
146enum PatternAst {
147    // Distinguish this with `Group` for simplicity
148    /// A leaf node that matches a column with `pattern`
149    Literal { op: UnaryOp, pattern: String },
150    /// Flattened binary chains
151    Binary {
152        op: BinaryOp,
153        children: Vec<PatternAst>,
154    },
155    /// A sub-tree enclosed by parenthesis
156    Group { op: UnaryOp, child: Box<PatternAst> },
157}
158
159#[derive(Debug, Copy, Clone, PartialEq, Eq)]
160enum UnaryOp {
161    Must,
162    Optional,
163    Negative,
164}
165
166#[derive(Debug, Copy, Clone, PartialEq, Eq)]
167enum BinaryOp {
168    And,
169    Or,
170}
171
172impl PatternAst {
173    fn into_like_expr(self, column: &str, data_type: &DataType) -> Expr {
174        match self {
175            PatternAst::Literal { op, pattern } => {
176                let expr = Self::convert_literal(column, &pattern, data_type);
177                match op {
178                    UnaryOp::Must => expr,
179                    UnaryOp::Optional => expr,
180                    UnaryOp::Negative => logical_expr::not(expr),
181                }
182            }
183            PatternAst::Binary { op, children } => {
184                if children.is_empty() {
185                    return logical_expr::lit(true);
186                }
187                let exprs = children
188                    .into_iter()
189                    .map(|child| child.into_like_expr(column, data_type));
190                // safety: children is not empty
191                match op {
192                    BinaryOp::And => exprs.reduce(Expr::and).unwrap(),
193                    BinaryOp::Or => exprs.reduce(Expr::or).unwrap(),
194                }
195            }
196            PatternAst::Group { op, child } => {
197                let child = child.into_like_expr(column, data_type);
198                match op {
199                    UnaryOp::Must => child,
200                    UnaryOp::Optional => child,
201                    UnaryOp::Negative => logical_expr::not(child),
202                }
203            }
204        }
205    }
206
207    fn convert_literal(column: &str, pattern: &str, data_type: &DataType) -> Expr {
208        let pattern = Some(format!("%{}%", crate::utils::escape_like_pattern(pattern)));
209        let pattern = match data_type {
210            DataType::Utf8View => ScalarValue::Utf8View(pattern),
211            DataType::LargeUtf8 => ScalarValue::LargeUtf8(pattern),
212            _ => ScalarValue::Utf8(pattern),
213        };
214        logical_expr::col(column).like(Expr::Literal(pattern, None))
215    }
216
217    /// Transform this AST with preset rules to make it correct.
218    fn transform_ast(self) -> Result<Self> {
219        self.transform_up(Self::collapse_binary_branch_fn)
220            .map(|data| data.data)?
221            .transform_up(Self::eliminate_optional_fn)
222            .map(|data| data.data)?
223            .transform_down(Self::eliminate_single_child_fn)
224            .map(|data| data.data)
225            .map_err(Into::into)
226    }
227
228    /// Collapse binary branch with the same operator. I.e., this transformer
229    /// changes the binary-tree AST into a multiple branching AST.
230    ///
231    /// This function is expected to be called in a bottom-up manner as
232    /// it won't recursion.
233    fn collapse_binary_branch_fn(self) -> DfResult<Transformed<Self>> {
234        let PatternAst::Binary {
235            op: parent_op,
236            children,
237        } = self
238        else {
239            return Ok(Transformed::no(self));
240        };
241
242        let mut collapsed = vec![];
243        let mut remains = vec![];
244
245        for child in children {
246            match child {
247                PatternAst::Literal { .. } | PatternAst::Group { .. } => {
248                    collapsed.push(child);
249                }
250                PatternAst::Binary { op, children } => {
251                    // no need to recursion because this function is expected to be called
252                    // in a bottom-up manner
253                    if op == parent_op {
254                        collapsed.extend(children);
255                    } else {
256                        remains.push(PatternAst::Binary { op, children });
257                    }
258                }
259            }
260        }
261
262        if collapsed.is_empty() {
263            Ok(Transformed::no(PatternAst::Binary {
264                op: parent_op,
265                children: remains,
266            }))
267        } else {
268            collapsed.extend(remains);
269            Ok(Transformed::yes(PatternAst::Binary {
270                op: parent_op,
271                children: collapsed,
272            }))
273        }
274    }
275
276    /// Eliminate optional pattern. An optional pattern can always be
277    /// omitted or transformed into a must pattern follows the following rules:
278    /// - If there is only one pattern and it's optional, change it to must
279    /// - If there is any must pattern, remove all other optional patterns
280    fn eliminate_optional_fn(self) -> DfResult<Transformed<Self>> {
281        let PatternAst::Binary {
282            op: parent_op,
283            children,
284        } = self
285        else {
286            return Ok(Transformed::no(self));
287        };
288
289        if parent_op == BinaryOp::Or {
290            let mut must_list = vec![];
291            let mut must_not_list = vec![];
292            let mut optional_list = vec![];
293            let mut compound_list = vec![];
294
295            for child in children {
296                match child {
297                    PatternAst::Literal { op, .. } | PatternAst::Group { op, .. } => match op {
298                        UnaryOp::Must => must_list.push(child),
299                        UnaryOp::Optional => optional_list.push(child),
300                        UnaryOp::Negative => must_not_list.push(child),
301                    },
302                    PatternAst::Binary { .. } => {
303                        compound_list.push(child);
304                    }
305                }
306            }
307
308            // Eliminate optional list if there is MUST.
309            if !must_list.is_empty() {
310                optional_list.clear();
311            }
312
313            let children_this_level = optional_list.into_iter().chain(compound_list).collect();
314            let new_node = if !must_list.is_empty() || !must_not_list.is_empty() {
315                let new_children = must_list
316                    .into_iter()
317                    .chain(must_not_list)
318                    .chain(Some(PatternAst::Binary {
319                        op: BinaryOp::Or,
320                        children: children_this_level,
321                    }))
322                    .collect();
323                PatternAst::Binary {
324                    op: BinaryOp::And,
325                    children: new_children,
326                }
327            } else {
328                PatternAst::Binary {
329                    op: BinaryOp::Or,
330                    children: children_this_level,
331                }
332            };
333
334            return Ok(Transformed::yes(new_node));
335        }
336
337        Ok(Transformed::no(PatternAst::Binary {
338            op: parent_op,
339            children,
340        }))
341    }
342
343    /// Eliminate single child [`PatternAst::Binary`] node. If a binary node has only one child, it can be
344    /// replaced by its only child.
345    ///
346    /// This function prefers to be applied in a top-down manner. But it's not required.
347    fn eliminate_single_child_fn(self) -> DfResult<Transformed<Self>> {
348        let PatternAst::Binary { op, mut children } = self else {
349            return Ok(Transformed::no(self));
350        };
351
352        // remove empty grand children
353        children.retain(|child| match child {
354            PatternAst::Binary {
355                children: grand_children,
356                ..
357            } => !grand_children.is_empty(),
358            PatternAst::Literal { .. } | PatternAst::Group { .. } => true,
359        });
360
361        if children.len() == 1 {
362            Ok(Transformed::yes(children.into_iter().next().unwrap()))
363        } else {
364            Ok(Transformed::no(PatternAst::Binary { op, children }))
365        }
366    }
367}
368
369impl TreeNode for PatternAst {
370    fn apply_children<'n, F: FnMut(&'n Self) -> DfResult<TreeNodeRecursion>>(
371        &'n self,
372        mut f: F,
373    ) -> DfResult<TreeNodeRecursion> {
374        match self {
375            PatternAst::Literal { .. } => Ok(TreeNodeRecursion::Continue),
376            PatternAst::Binary { op: _, children } => {
377                for child in children {
378                    if TreeNodeRecursion::Stop == f(child)? {
379                        return Ok(TreeNodeRecursion::Stop);
380                    }
381                }
382                Ok(TreeNodeRecursion::Continue)
383            }
384            PatternAst::Group { op: _, child } => f(child),
385        }
386    }
387
388    fn map_children<F: FnMut(Self) -> DfResult<Transformed<Self>>>(
389        self,
390        mut f: F,
391    ) -> DfResult<Transformed<Self>> {
392        match self {
393            PatternAst::Literal { .. } => Ok(Transformed::no(self)),
394            PatternAst::Binary { op, children } => children
395                .into_iter()
396                .map_until_stop_and_collect(&mut f)?
397                .map_data(|new_children| {
398                    Ok(PatternAst::Binary {
399                        op,
400                        children: new_children,
401                    })
402                }),
403            PatternAst::Group { op, child } => f(*child)?.map_data(|new_child| {
404                Ok(PatternAst::Group {
405                    op,
406                    child: Box::new(new_child),
407                })
408            }),
409        }
410    }
411}
412
413#[derive(Default)]
414struct ParserContext {
415    stack: Vec<PatternAst>,
416}
417
418impl ParserContext {
419    pub fn parse_pattern(mut self, pattern: &str) -> Result<PatternAst> {
420        let tokenizer = Tokenizer::default();
421        let raw_tokens = tokenizer.tokenize(pattern)?;
422        let raw_tokens = Self::accomplish_optional_unary_op(raw_tokens)?;
423        let mut tokens = Self::to_rpn(raw_tokens)?;
424
425        while !tokens.is_empty() {
426            self.parse_one_impl(&mut tokens)?;
427        }
428
429        ensure!(
430            !self.stack.is_empty(),
431            InvalidFuncArgsSnafu {
432                err_msg: "Empty pattern",
433            }
434        );
435
436        // conjoin them together
437        if self.stack.len() == 1 {
438            Ok(self.stack.pop().unwrap())
439        } else {
440            Ok(PatternAst::Binary {
441                op: BinaryOp::Or,
442                children: self.stack,
443            })
444        }
445    }
446
447    /// Add [`Token::Optional`] for all bare [`Token::Phase`] and [`Token::Or`]
448    /// for all adjacent [`Token::Phase`]s.
449    ///
450    /// This function also does some checks by the way. Like if two unary ops are
451    /// adjacent.
452    fn accomplish_optional_unary_op(raw_tokens: Vec<Token>) -> Result<Vec<Token>> {
453        let mut is_prev_unary_op = false;
454        // The first one doesn't need binary op
455        let mut is_binary_op_before = true;
456        let mut is_unary_op_before = false;
457        let mut new_tokens = Vec::with_capacity(raw_tokens.len());
458        for token in raw_tokens {
459            // fill `Token::Or`
460            if !is_binary_op_before
461                && matches!(
462                    token,
463                    Token::Phase(_)
464                        | Token::OpenParen
465                        | Token::Must
466                        | Token::Optional
467                        | Token::Negative
468                )
469            {
470                is_binary_op_before = true;
471                new_tokens.push(Token::Or);
472            }
473            if matches!(
474                token,
475                Token::OpenParen // treat open paren as begin of new group
476                | Token::And | Token::Or
477            ) {
478                is_binary_op_before = true;
479            } else if matches!(token, Token::Phase(_) | Token::CloseParen) {
480                // need binary op next time
481                is_binary_op_before = false;
482            }
483
484            // fill `Token::Optional`
485            if !is_prev_unary_op && matches!(token, Token::Phase(_) | Token::OpenParen) {
486                new_tokens.push(Token::Optional);
487            } else {
488                is_prev_unary_op = matches!(token, Token::Must | Token::Negative);
489            }
490
491            // check if unary ops are adjacent by the way
492            if matches!(token, Token::Must | Token::Optional | Token::Negative) {
493                if is_unary_op_before {
494                    return InvalidFuncArgsSnafu {
495                        err_msg: "Invalid pattern, unary operators should not be adjacent",
496                    }
497                    .fail();
498                }
499                is_unary_op_before = true;
500            } else {
501                is_unary_op_before = false;
502            }
503
504            new_tokens.push(token);
505        }
506
507        Ok(new_tokens)
508    }
509
510    /// Convert infix token stream to RPN
511    fn to_rpn(mut raw_tokens: Vec<Token>) -> Result<Vec<Token>> {
512        let mut operator_stack = vec![];
513        let mut result = vec![];
514        raw_tokens.reverse();
515
516        while let Some(token) = raw_tokens.pop() {
517            match token {
518                Token::Phase(_) => result.push(token),
519                Token::Must | Token::Negative | Token::Optional => {
520                    operator_stack.push(token);
521                }
522                Token::OpenParen => operator_stack.push(token),
523                Token::And | Token::Or => {
524                    // - Or has lower priority than And
525                    // - Binary op have lower priority than unary op
526                    while let Some(stack_top) = operator_stack.last()
527                        && ((*stack_top == Token::And && token == Token::Or)
528                            || matches!(
529                                *stack_top,
530                                Token::Must | Token::Optional | Token::Negative
531                            ))
532                    {
533                        result.push(operator_stack.pop().unwrap());
534                    }
535                    operator_stack.push(token);
536                }
537                Token::CloseParen => {
538                    let mut is_open_paren_found = false;
539                    while let Some(op) = operator_stack.pop() {
540                        if op == Token::OpenParen {
541                            is_open_paren_found = true;
542                            break;
543                        }
544                        result.push(op);
545                    }
546                    if !is_open_paren_found {
547                        return InvalidFuncArgsSnafu {
548                            err_msg: "Unmatched close parentheses",
549                        }
550                        .fail();
551                    }
552                }
553            }
554        }
555
556        while let Some(operator) = operator_stack.pop() {
557            if operator == Token::OpenParen {
558                return InvalidFuncArgsSnafu {
559                    err_msg: "Unmatched parentheses",
560                }
561                .fail();
562            }
563            result.push(operator);
564        }
565
566        Ok(result)
567    }
568
569    fn parse_one_impl(&mut self, tokens: &mut Vec<Token>) -> Result<()> {
570        if let Some(token) = tokens.pop() {
571            match token {
572                Token::Must => {
573                    if self.stack.is_empty() {
574                        self.parse_one_impl(tokens)?;
575                    }
576                    let phase_or_group = self.stack.pop().context(InvalidFuncArgsSnafu {
577                        err_msg: "Invalid pattern, \"+\" operator should have one operand",
578                    })?;
579                    match phase_or_group {
580                        PatternAst::Literal { op: _, pattern } => {
581                            self.stack.push(PatternAst::Literal {
582                                op: UnaryOp::Must,
583                                pattern,
584                            });
585                        }
586                        PatternAst::Binary { .. } | PatternAst::Group { .. } => {
587                            self.stack.push(PatternAst::Group {
588                                op: UnaryOp::Must,
589                                child: Box::new(phase_or_group),
590                            })
591                        }
592                    }
593                    return Ok(());
594                }
595                Token::Negative => {
596                    if self.stack.is_empty() {
597                        self.parse_one_impl(tokens)?;
598                    }
599                    let phase_or_group = self.stack.pop().context(InvalidFuncArgsSnafu {
600                        err_msg: "Invalid pattern, \"-\" operator should have one operand",
601                    })?;
602                    match phase_or_group {
603                        PatternAst::Literal { op: _, pattern } => {
604                            self.stack.push(PatternAst::Literal {
605                                op: UnaryOp::Negative,
606                                pattern,
607                            });
608                        }
609                        PatternAst::Binary { .. } | PatternAst::Group { .. } => {
610                            self.stack.push(PatternAst::Group {
611                                op: UnaryOp::Negative,
612                                child: Box::new(phase_or_group),
613                            })
614                        }
615                    }
616                    return Ok(());
617                }
618                Token::Optional => {
619                    if self.stack.is_empty() {
620                        self.parse_one_impl(tokens)?;
621                    }
622                    let phase_or_group = self.stack.pop().context(InvalidFuncArgsSnafu {
623                        err_msg:
624                            "Invalid pattern, OPTIONAL(space) operator should have one operand",
625                    })?;
626                    match phase_or_group {
627                        PatternAst::Literal { op: _, pattern } => {
628                            self.stack.push(PatternAst::Literal {
629                                op: UnaryOp::Optional,
630                                pattern,
631                            });
632                        }
633                        PatternAst::Binary { .. } | PatternAst::Group { .. } => {
634                            self.stack.push(PatternAst::Group {
635                                op: UnaryOp::Optional,
636                                child: Box::new(phase_or_group),
637                            })
638                        }
639                    }
640                    return Ok(());
641                }
642                Token::Phase(pattern) => {
643                    self.stack.push(PatternAst::Literal {
644                        // Op here is a placeholder
645                        op: UnaryOp::Optional,
646                        pattern,
647                    })
648                }
649                Token::And => {
650                    if self.stack.is_empty() {
651                        self.parse_one_impl(tokens)?;
652                    };
653                    let rhs = self.stack.pop().context(InvalidFuncArgsSnafu {
654                        err_msg: "Invalid pattern, \"AND\" operator should have two operands",
655                    })?;
656                    if self.stack.is_empty() {
657                        self.parse_one_impl(tokens)?
658                    };
659                    let lhs = self.stack.pop().context(InvalidFuncArgsSnafu {
660                        err_msg: "Invalid pattern, \"AND\" operator should have two operands",
661                    })?;
662                    self.stack.push(PatternAst::Binary {
663                        op: BinaryOp::And,
664                        children: vec![lhs, rhs],
665                    });
666                    return Ok(());
667                }
668                Token::Or => {
669                    if self.stack.is_empty() {
670                        self.parse_one_impl(tokens)?
671                    };
672                    let rhs = self.stack.pop().context(InvalidFuncArgsSnafu {
673                        err_msg: "Invalid pattern, \"OR\" operator should have two operands",
674                    })?;
675                    if self.stack.is_empty() {
676                        self.parse_one_impl(tokens)?
677                    };
678                    let lhs = self.stack.pop().context(InvalidFuncArgsSnafu {
679                        err_msg: "Invalid pattern, \"OR\" operator should have two operands",
680                    })?;
681                    self.stack.push(PatternAst::Binary {
682                        op: BinaryOp::Or,
683                        children: vec![lhs, rhs],
684                    });
685                    return Ok(());
686                }
687                Token::OpenParen | Token::CloseParen => {
688                    return InvalidFuncArgsSnafu {
689                        err_msg: "Unexpected parentheses",
690                    }
691                    .fail();
692                }
693            }
694        }
695
696        Ok(())
697    }
698}
699
700#[derive(Clone, Debug, PartialEq, Eq)]
701enum Token {
702    /// "+"
703    Must,
704    /// "-"
705    Negative,
706    /// "AND"
707    And,
708    /// "OR"
709    Or,
710    /// "("
711    OpenParen,
712    /// ")"
713    CloseParen,
714    /// Any other phases
715    Phase(String),
716
717    /// This is not a token from user input, but a placeholder for internal use.
718    /// It's used to accomplish the unary operator class with Must and Negative.
719    /// In user provided pattern, optional is expressed by a bare phase or group
720    /// (simply nothing or writespace).
721    Optional,
722}
723
724#[derive(Default)]
725struct Tokenizer {
726    cursor: usize,
727}
728
729impl Tokenizer {
730    pub fn tokenize(mut self, pattern: &str) -> Result<Vec<Token>> {
731        let mut tokens = vec![];
732        let char_len = pattern.chars().count();
733        while self.cursor < char_len {
734            // TODO: collect pattern into Vec<char> if this tokenizer is bottleneck in the future
735            let c = pattern.chars().nth(self.cursor).unwrap();
736            match c {
737                '+' => tokens.push(Token::Must),
738                '-' => tokens.push(Token::Negative),
739                '(' => tokens.push(Token::OpenParen),
740                ')' => tokens.push(Token::CloseParen),
741                ' ' => {
742                    if let Some(last_token) = tokens.last() {
743                        match last_token {
744                            Token::Must | Token::Negative => {
745                                return InvalidFuncArgsSnafu {
746                                    err_msg: format!("Unexpected space after {:?}", last_token),
747                                }
748                                .fail();
749                            }
750                            _ => {}
751                        }
752                    }
753                }
754                '\"' => {
755                    self.step_next();
756                    let phase = self.consume_next_phase(true, pattern)?;
757                    tokens.push(Token::Phase(phase));
758                    // consume a writespace (or EOF) after quotes
759                    if let Some(ending_separator) = self.consume_next(pattern)
760                        && ending_separator != ' '
761                    {
762                        return InvalidFuncArgsSnafu {
763                            err_msg: "Expect a space after quotes ('\"')",
764                        }
765                        .fail();
766                    }
767                }
768                _ => {
769                    let phase = self.consume_next_phase(false, pattern)?;
770                    match phase.to_uppercase().as_str() {
771                        "AND" => tokens.push(Token::And),
772                        "OR" => tokens.push(Token::Or),
773                        _ => tokens.push(Token::Phase(phase)),
774                    }
775                }
776            }
777            self.cursor += 1;
778        }
779        Ok(tokens)
780    }
781
782    fn consume_next(&mut self, pattern: &str) -> Option<char> {
783        self.cursor += 1;
784        pattern.chars().nth(self.cursor)
785    }
786
787    fn step_next(&mut self) {
788        self.cursor += 1;
789    }
790
791    fn rewind_one(&mut self) {
792        self.cursor -= 1;
793    }
794
795    /// Current `cursor` points to the first character of the phase.
796    /// If the phase is enclosed by double quotes, consume the start quote before calling this.
797    fn consume_next_phase(&mut self, is_quoted: bool, pattern: &str) -> Result<String> {
798        let mut phase = String::new();
799        let mut is_quote_present = false;
800
801        let char_len = pattern.chars().count();
802        while self.cursor < char_len {
803            let mut c = pattern.chars().nth(self.cursor).unwrap();
804
805            match c {
806                '\"' => {
807                    is_quote_present = true;
808                    break;
809                }
810                ' ' if !is_quoted => {
811                    break;
812                }
813                '(' | ')' | '+' | '-' if !is_quoted => {
814                    self.rewind_one();
815                    break;
816                }
817                '\\' => {
818                    let Some(next) = self.consume_next(pattern) else {
819                        return InvalidFuncArgsSnafu {
820                            err_msg: "Unexpected end of pattern, expected a character after escape ('\\')",
821                        }.fail();
822                    };
823                    // it doesn't check whether the escaped character is valid or not
824                    c = next;
825                }
826                _ => {}
827            }
828
829            phase.push(c);
830            self.cursor += 1;
831        }
832
833        if is_quoted ^ is_quote_present {
834            return InvalidFuncArgsSnafu {
835                err_msg: "Unclosed quotes ('\"')",
836            }
837            .fail();
838        }
839
840        Ok(phase)
841    }
842}
843
844#[cfg(test)]
845mod test {
846    use datafusion::arrow::array::StringArray;
847    use datafusion_common::config::ConfigOptions;
848
849    use super::*;
850
851    #[test]
852    fn valid_matches_tokenizer() {
853        use Token::*;
854        let cases = [
855            (
856                "a +b -c",
857                vec![
858                    Phase("a".to_string()),
859                    Must,
860                    Phase("b".to_string()),
861                    Negative,
862                    Phase("c".to_string()),
863                ],
864            ),
865            (
866                "+a(b-c)",
867                vec![
868                    Must,
869                    Phase("a".to_string()),
870                    OpenParen,
871                    Phase("b".to_string()),
872                    Negative,
873                    Phase("c".to_string()),
874                    CloseParen,
875                ],
876            ),
877            (
878                r#"Barack Obama"#,
879                vec![Phase("Barack".to_string()), Phase("Obama".to_string())],
880            ),
881            (
882                r#"+apple +fruit"#,
883                vec![
884                    Must,
885                    Phase("apple".to_string()),
886                    Must,
887                    Phase("fruit".to_string()),
888                ],
889            ),
890            (
891                r#""He said \"hello\"""#,
892                vec![Phase("He said \"hello\"".to_string())],
893            ),
894            (
895                r#"a AND b OR c"#,
896                vec![
897                    Phase("a".to_string()),
898                    And,
899                    Phase("b".to_string()),
900                    Or,
901                    Phase("c".to_string()),
902                ],
903            ),
904            (
905                r#"中文 测试"#,
906                vec![Phase("中文".to_string()), Phase("测试".to_string())],
907            ),
908            (
909                r#"中文 AND 测试"#,
910                vec![Phase("中文".to_string()), And, Phase("测试".to_string())],
911            ),
912            (
913                r#"中文 +测试"#,
914                vec![Phase("中文".to_string()), Must, Phase("测试".to_string())],
915            ),
916            (
917                r#"中文 -测试"#,
918                vec![
919                    Phase("中文".to_string()),
920                    Negative,
921                    Phase("测试".to_string()),
922                ],
923            ),
924        ];
925
926        for (query, expected) in cases {
927            let tokenizer = Tokenizer::default();
928            let tokens = tokenizer.tokenize(query).unwrap();
929            assert_eq!(expected, tokens, "{query}");
930        }
931    }
932
933    #[test]
934    fn invalid_matches_tokenizer() {
935        let cases = [
936            (r#""He said "hello""#, "Expect a space after quotes"),
937            (r#""He said hello"#, "Unclosed quotes"),
938            (r#"a + b - c"#, "Unexpected space after"),
939            (r#"ab "c"def"#, "Expect a space after quotes"),
940        ];
941
942        for (query, expected) in cases {
943            let tokenizer = Tokenizer::default();
944            let result = tokenizer.tokenize(query);
945            assert!(result.is_err(), "{query}");
946            let actual_error = result.unwrap_err().to_string();
947            assert!(actual_error.contains(expected), "{query}, {actual_error}");
948        }
949    }
950
951    #[test]
952    fn valid_ast_transformer() {
953        let cases = [
954            (
955                "a AND b OR c",
956                PatternAst::Binary {
957                    op: BinaryOp::Or,
958                    children: vec![
959                        PatternAst::Literal {
960                            op: UnaryOp::Optional,
961                            pattern: "c".to_string(),
962                        },
963                        PatternAst::Binary {
964                            op: BinaryOp::And,
965                            children: vec![
966                                PatternAst::Literal {
967                                    op: UnaryOp::Optional,
968                                    pattern: "a".to_string(),
969                                },
970                                PatternAst::Literal {
971                                    op: UnaryOp::Optional,
972                                    pattern: "b".to_string(),
973                                },
974                            ],
975                        },
976                    ],
977                },
978            ),
979            (
980                "a -b",
981                PatternAst::Binary {
982                    op: BinaryOp::And,
983                    children: vec![
984                        PatternAst::Literal {
985                            op: UnaryOp::Negative,
986                            pattern: "b".to_string(),
987                        },
988                        PatternAst::Literal {
989                            op: UnaryOp::Optional,
990                            pattern: "a".to_string(),
991                        },
992                    ],
993                },
994            ),
995            (
996                "a +b",
997                PatternAst::Literal {
998                    op: UnaryOp::Must,
999                    pattern: "b".to_string(),
1000                },
1001            ),
1002            (
1003                "a b c d",
1004                PatternAst::Binary {
1005                    op: BinaryOp::Or,
1006                    children: vec![
1007                        PatternAst::Literal {
1008                            op: UnaryOp::Optional,
1009                            pattern: "a".to_string(),
1010                        },
1011                        PatternAst::Literal {
1012                            op: UnaryOp::Optional,
1013                            pattern: "b".to_string(),
1014                        },
1015                        PatternAst::Literal {
1016                            op: UnaryOp::Optional,
1017                            pattern: "c".to_string(),
1018                        },
1019                        PatternAst::Literal {
1020                            op: UnaryOp::Optional,
1021                            pattern: "d".to_string(),
1022                        },
1023                    ],
1024                },
1025            ),
1026            (
1027                "a b c AND d",
1028                PatternAst::Binary {
1029                    op: BinaryOp::Or,
1030                    children: vec![
1031                        PatternAst::Literal {
1032                            op: UnaryOp::Optional,
1033                            pattern: "a".to_string(),
1034                        },
1035                        PatternAst::Literal {
1036                            op: UnaryOp::Optional,
1037                            pattern: "b".to_string(),
1038                        },
1039                        PatternAst::Binary {
1040                            op: BinaryOp::And,
1041                            children: vec![
1042                                PatternAst::Literal {
1043                                    op: UnaryOp::Optional,
1044                                    pattern: "c".to_string(),
1045                                },
1046                                PatternAst::Literal {
1047                                    op: UnaryOp::Optional,
1048                                    pattern: "d".to_string(),
1049                                },
1050                            ],
1051                        },
1052                    ],
1053                },
1054            ),
1055            (
1056                r#"中文 测试"#,
1057                PatternAst::Binary {
1058                    op: BinaryOp::Or,
1059                    children: vec![
1060                        PatternAst::Literal {
1061                            op: UnaryOp::Optional,
1062                            pattern: "中文".to_string(),
1063                        },
1064                        PatternAst::Literal {
1065                            op: UnaryOp::Optional,
1066                            pattern: "测试".to_string(),
1067                        },
1068                    ],
1069                },
1070            ),
1071            (
1072                r#"中文 AND 测试"#,
1073                PatternAst::Binary {
1074                    op: BinaryOp::And,
1075                    children: vec![
1076                        PatternAst::Literal {
1077                            op: UnaryOp::Optional,
1078                            pattern: "中文".to_string(),
1079                        },
1080                        PatternAst::Literal {
1081                            op: UnaryOp::Optional,
1082                            pattern: "测试".to_string(),
1083                        },
1084                    ],
1085                },
1086            ),
1087            (
1088                r#"中文 +测试"#,
1089                PatternAst::Literal {
1090                    op: UnaryOp::Must,
1091                    pattern: "测试".to_string(),
1092                },
1093            ),
1094            (
1095                r#"中文 -测试"#,
1096                PatternAst::Binary {
1097                    op: BinaryOp::And,
1098                    children: vec![
1099                        PatternAst::Literal {
1100                            op: UnaryOp::Negative,
1101                            pattern: "测试".to_string(),
1102                        },
1103                        PatternAst::Literal {
1104                            op: UnaryOp::Optional,
1105                            pattern: "中文".to_string(),
1106                        },
1107                    ],
1108                },
1109            ),
1110        ];
1111
1112        for (query, expected) in cases {
1113            let parser = ParserContext { stack: vec![] };
1114            let ast = parser.parse_pattern(query).unwrap();
1115            let ast = ast.transform_ast().unwrap();
1116            assert_eq!(expected, ast, "{query}");
1117        }
1118    }
1119
1120    #[test]
1121    fn invalid_ast() {
1122        let cases = [
1123            (r#"a b (c"#, "Unmatched parentheses"),
1124            (r#"a b) c"#, "Unmatched close parentheses"),
1125            (r#"a +-b"#, "unary operators should not be adjacent"),
1126        ];
1127
1128        for (query, expected) in cases {
1129            let result: Result<()> = (|| {
1130                let parser = ParserContext { stack: vec![] };
1131                let ast = parser.parse_pattern(query)?;
1132                let _ast = ast.transform_ast()?;
1133                Ok(())
1134            })();
1135
1136            assert!(result.is_err(), "{query}");
1137            let actual_error = result.unwrap_err().to_string();
1138            assert!(actual_error.contains(expected), "{query}, {actual_error}");
1139        }
1140    }
1141
1142    #[test]
1143    fn valid_matches_parser() {
1144        let cases = [
1145            (
1146                "a AND b OR c",
1147                PatternAst::Binary {
1148                    op: BinaryOp::Or,
1149                    children: vec![
1150                        PatternAst::Binary {
1151                            op: BinaryOp::And,
1152                            children: vec![
1153                                PatternAst::Literal {
1154                                    op: UnaryOp::Optional,
1155                                    pattern: "a".to_string(),
1156                                },
1157                                PatternAst::Literal {
1158                                    op: UnaryOp::Optional,
1159                                    pattern: "b".to_string(),
1160                                },
1161                            ],
1162                        },
1163                        PatternAst::Literal {
1164                            op: UnaryOp::Optional,
1165                            pattern: "c".to_string(),
1166                        },
1167                    ],
1168                },
1169            ),
1170            (
1171                "(a AND b) OR c",
1172                PatternAst::Binary {
1173                    op: BinaryOp::Or,
1174                    children: vec![
1175                        PatternAst::Group {
1176                            op: UnaryOp::Optional,
1177                            child: Box::new(PatternAst::Binary {
1178                                op: BinaryOp::And,
1179                                children: vec![
1180                                    PatternAst::Literal {
1181                                        op: UnaryOp::Optional,
1182                                        pattern: "a".to_string(),
1183                                    },
1184                                    PatternAst::Literal {
1185                                        op: UnaryOp::Optional,
1186                                        pattern: "b".to_string(),
1187                                    },
1188                                ],
1189                            }),
1190                        },
1191                        PatternAst::Literal {
1192                            op: UnaryOp::Optional,
1193                            pattern: "c".to_string(),
1194                        },
1195                    ],
1196                },
1197            ),
1198            (
1199                "a AND (b OR c)",
1200                PatternAst::Binary {
1201                    op: BinaryOp::And,
1202                    children: vec![
1203                        PatternAst::Literal {
1204                            op: UnaryOp::Optional,
1205                            pattern: "a".to_string(),
1206                        },
1207                        PatternAst::Group {
1208                            op: UnaryOp::Optional,
1209                            child: Box::new(PatternAst::Binary {
1210                                op: BinaryOp::Or,
1211                                children: vec![
1212                                    PatternAst::Literal {
1213                                        op: UnaryOp::Optional,
1214                                        pattern: "b".to_string(),
1215                                    },
1216                                    PatternAst::Literal {
1217                                        op: UnaryOp::Optional,
1218                                        pattern: "c".to_string(),
1219                                    },
1220                                ],
1221                            }),
1222                        },
1223                    ],
1224                },
1225            ),
1226            (
1227                "a +b -c",
1228                PatternAst::Binary {
1229                    op: BinaryOp::Or,
1230                    children: vec![
1231                        PatternAst::Literal {
1232                            op: UnaryOp::Optional,
1233                            pattern: "a".to_string(),
1234                        },
1235                        PatternAst::Binary {
1236                            op: BinaryOp::Or,
1237                            children: vec![
1238                                PatternAst::Literal {
1239                                    op: UnaryOp::Must,
1240                                    pattern: "b".to_string(),
1241                                },
1242                                PatternAst::Literal {
1243                                    op: UnaryOp::Negative,
1244                                    pattern: "c".to_string(),
1245                                },
1246                            ],
1247                        },
1248                    ],
1249                },
1250            ),
1251            (
1252                "(+a +b) c",
1253                PatternAst::Binary {
1254                    op: BinaryOp::Or,
1255                    children: vec![
1256                        PatternAst::Group {
1257                            op: UnaryOp::Optional,
1258                            child: Box::new(PatternAst::Binary {
1259                                op: BinaryOp::Or,
1260                                children: vec![
1261                                    PatternAst::Literal {
1262                                        op: UnaryOp::Must,
1263                                        pattern: "a".to_string(),
1264                                    },
1265                                    PatternAst::Literal {
1266                                        op: UnaryOp::Must,
1267                                        pattern: "b".to_string(),
1268                                    },
1269                                ],
1270                            }),
1271                        },
1272                        PatternAst::Literal {
1273                            op: UnaryOp::Optional,
1274                            pattern: "c".to_string(),
1275                        },
1276                    ],
1277                },
1278            ),
1279            (
1280                "\"AND\" AnD \"OR\"",
1281                PatternAst::Binary {
1282                    op: BinaryOp::And,
1283                    children: vec![
1284                        PatternAst::Literal {
1285                            op: UnaryOp::Optional,
1286                            pattern: "AND".to_string(),
1287                        },
1288                        PatternAst::Literal {
1289                            op: UnaryOp::Optional,
1290                            pattern: "OR".to_string(),
1291                        },
1292                    ],
1293                },
1294            ),
1295        ];
1296
1297        for (query, expected) in cases {
1298            let parser = ParserContext { stack: vec![] };
1299            let ast = parser.parse_pattern(query).unwrap();
1300            assert_eq!(expected, ast, "{query}");
1301        }
1302    }
1303
1304    #[test]
1305    fn evaluate_matches_string_layouts() {
1306        let input: ArrayRef = Arc::new(StringArray::from(vec![
1307            Some("error timeout"),
1308            Some("healthy"),
1309            None,
1310        ]));
1311        let function = MatchesFunction::default();
1312        for data_type in [DataType::Utf8, DataType::LargeUtf8, DataType::Utf8View] {
1313            let input = datatypes::arrow::compute::cast(&input, &data_type).unwrap();
1314            for (pattern, expected) in [
1315                ("error", vec![Some(true), Some(false), None]),
1316                ("error AND timeout", vec![Some(true), Some(false), None]),
1317                ("error OR healthy", vec![Some(true), Some(true), None]),
1318            ] {
1319                let expected: ArrayRef = Arc::new(BooleanArray::from(expected));
1320                let actual = function
1321                    .eval(input.clone(), pattern)
1322                    .unwrap()
1323                    .to_array(3)
1324                    .unwrap();
1325                assert_eq!(expected.as_ref(), actual.as_ref(), "{data_type}, {pattern}");
1326            }
1327        }
1328    }
1329
1330    #[test]
1331    fn evaluate_matches() {
1332        let input_data = vec![
1333            "The quick brown fox jumps over the lazy dog",
1334            "The             fox jumps over the lazy dog",
1335            "The quick brown     jumps over the lazy dog",
1336            "The quick brown fox       over the lazy dog",
1337            "The quick brown fox jumps      the lazy dog",
1338            "The quick brown fox jumps over          dog",
1339            "The quick brown fox jumps over the      dog",
1340        ];
1341        let col: ArrayRef = Arc::new(StringArray::from(input_data));
1342        let cases = [
1343            // basic cases
1344            ("quick", vec![true, false, true, true, true, true, true]),
1345            (
1346                "\"quick brown\"",
1347                vec![true, false, true, true, true, true, true],
1348            ),
1349            (
1350                "\"fox jumps\"",
1351                vec![true, true, false, false, true, true, true],
1352            ),
1353            (
1354                "fox OR lazy",
1355                vec![true, true, true, true, true, true, true],
1356            ),
1357            (
1358                "fox AND lazy",
1359                vec![true, true, false, true, true, false, false],
1360            ),
1361            (
1362                "-over -lazy",
1363                vec![false, false, false, false, false, false, false],
1364            ),
1365            (
1366                "-over AND -lazy",
1367                vec![false, false, false, false, false, false, false],
1368            ),
1369            // priority between AND & OR
1370            (
1371                "fox AND jumps OR over",
1372                vec![true, true, true, true, true, true, true],
1373            ),
1374            (
1375                "fox OR brown AND quick",
1376                vec![true, true, true, true, true, true, true],
1377            ),
1378            (
1379                "(fox OR brown) AND quick",
1380                vec![true, false, true, true, true, true, true],
1381            ),
1382            (
1383                "brown AND quick OR fox",
1384                vec![true, true, true, true, true, true, true],
1385            ),
1386            (
1387                "brown AND (quick OR fox)",
1388                vec![true, false, true, true, true, true, true],
1389            ),
1390            (
1391                "brown AND quick AND fox  OR  jumps AND over AND lazy",
1392                vec![true, true, true, true, true, true, true],
1393            ),
1394            // optional & must conversion
1395            (
1396                "quick brown fox +jumps",
1397                vec![true, true, true, false, true, true, true],
1398            ),
1399            (
1400                "fox +jumps -over",
1401                vec![false, false, false, false, true, false, false],
1402            ),
1403            (
1404                "fox AND +jumps AND -over",
1405                vec![false, false, false, false, true, false, false],
1406            ),
1407            // weird parentheses cases
1408            (
1409                "(+fox +jumps) over",
1410                vec![true, true, true, true, true, true, true],
1411            ),
1412            (
1413                "+(fox jumps) AND over",
1414                vec![true, true, true, true, false, true, true],
1415            ),
1416            (
1417                "over -(fox jumps)",
1418                vec![false, false, false, false, false, false, false],
1419            ),
1420            (
1421                "over -(fox AND jumps)",
1422                vec![false, false, true, true, false, false, false],
1423            ),
1424            (
1425                "over AND -(-(fox OR jumps))",
1426                vec![true, true, true, true, false, true, true],
1427            ),
1428        ];
1429
1430        let f = MatchesFunction::default();
1431        for (pattern, expected) in cases {
1432            let args = ScalarFunctionArgs {
1433                args: vec![
1434                    ColumnarValue::Array(col.clone()),
1435                    ColumnarValue::Scalar(ScalarValue::Utf8View(Some(pattern.to_string()))),
1436                ],
1437                arg_fields: vec![],
1438                number_rows: col.len(),
1439                return_field: Arc::new(Field::new("x", col.data_type().clone(), true)),
1440                config_options: Arc::new(ConfigOptions::new()),
1441            };
1442            let actual = f
1443                .invoke_with_args(args)
1444                .and_then(|x| x.to_array(col.len()))
1445                .unwrap();
1446            let expected: ArrayRef = Arc::new(BooleanArray::from(expected));
1447            assert_eq!(expected.as_ref(), actual.as_ref(), "{pattern}");
1448        }
1449    }
1450}