Skip to main content

uqa_sql/expr/regex/
split.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `regexp_split_to_table` and `regexp_split_to_array`: the text between the matches `PostgreSQL`'s `setup_regexp_matches` finds when it ignores degenerate matches.
8
9use super::{
10    argument_text, flag_text,
11    flags::ReFlags,
12    match_set::{MatchSet, Search},
13    plain, string, SingleResult,
14};
15use crate::error::{Result, SQLError};
16use uqa_core::{
17    memory::{Produced, ProductionControl, ProductionVec},
18    ArrayValue, Value,
19};
20
21/// The pieces of one split. Preparing the cursor finds every match; the cursor owns the input's code points and the match spans, so a caller can draw each piece under its own control.
22#[derive(Debug)]
23pub struct RegexSplit {
24    matches: MatchSet,
25    /// The piece returned next: the text before match `next`, or after the last match once `next` equals the match count.
26    next: usize,
27}
28
29impl RegexSplit {
30    /// Prepare `function(string, pattern [, flags])` for `regexp_split_to_table` or `regexp_split_to_array` under the call's input collation (`PostgreSQL`'s `inputcollid`, zero when indeterminate). A NULL argument yields no cursor, as both functions are strict.
31    ///
32    /// # Errors
33    ///
34    /// Reports `PostgreSQL`'s diagnostics for an invalid flag, the `g` flag, an invalid collation or pattern and a failed search, an exhausted allowance and cancellation.
35    pub fn new(
36        function: &'static str,
37        arguments: &[Value],
38        collation: u32,
39        control: &ProductionControl<'_>,
40    ) -> Result<Option<Self>> {
41        control.check()?;
42        if !(2..=3).contains(&arguments.len()) {
43            return Err(SQLError::TypeMismatch(format!(
44                "{function} takes 2 or 3 args"
45            )));
46        }
47        if arguments.iter().any(|value| matches!(value, Value::Null)) {
48            return Ok(None);
49        }
50        let input = argument_text(&arguments[0], control)?;
51        let pattern = argument_text(&arguments[1], control)?;
52        let flags = ReFlags::parse(&flag_text(arguments.get(2), control)?)?
53            .reject_global(SingleResult::named(function))?
54            .every_match();
55        let search = Search {
56            start: 0,
57            subexpressions: false,
58            ignore_degenerate: true,
59        };
60        let matches = MatchSet::find(&input, &pattern, flags, collation, search, control)?;
61        Ok(Some(Self { matches, next: 0 }))
62    }
63
64    /// The next piece, or `None` after the last one, `build_regexp_split_result`.
65    ///
66    /// # Errors
67    ///
68    /// Reports an exhausted allowance or cancellation. The cursor stays before the failed piece, and pieces already returned remain valid.
69    pub fn next_piece(
70        &mut self,
71        control: &ProductionControl<'_>,
72    ) -> Result<Option<Produced<Value>>> {
73        control.check()?;
74        let count = self.matches.len();
75        if self.next > count {
76            return Ok(None);
77        }
78        let start = if self.next == 0 {
79            Some(0)
80        } else {
81            self.matches.span(self.next - 1, 0).end()
82        };
83        let end = if self.next == count {
84            Some(self.matches.input_len())
85        } else {
86            self.matches.span(self.next, 0).start()
87        };
88        let (Some(start), Some(end)) = (start, end) else {
89            return Err(SQLError::Internal(
90                "a regular expression split lost a match boundary".into(),
91            ));
92        };
93        let piece = string(self.matches.slice(start..end, control)?, control)?;
94        self.next += 1;
95        Ok(Some(piece))
96    }
97}
98
99/// `regexp_split_to_array`: every piece of the split as one `text[]` value, or NULL for a NULL argument. The cursor's code points and spans are released before the array is returned.
100pub(super) fn array(
101    args: &[Value],
102    collation: u32,
103    control: &ProductionControl<'_>,
104) -> Result<Produced<Value>> {
105    let Some(mut split) = RegexSplit::new("regexp_split_to_array", args, collation, control)?
106    else {
107        return plain(Value::Null, control);
108    };
109    let mut pieces = ProductionVec::new(*control);
110    while let Some(piece) = split.next_piece(control)? {
111        pieces.push_produced(piece)?;
112    }
113    drop(split);
114    let array = ArrayValue::try_new_with_control(pieces.finish()?, control)?
115        .ok_or_else(|| SQLError::TypeMismatch("invalid regexp_split_to_array result".into()))?;
116    let (array, memory) = array.into_parts();
117    control
118        .finish(Value::Array(array), memory)
119        .map_err(Into::into)
120}