Skip to main content

uqa_sql/expr/regex/
matches.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! `regexp_matches`: one capture array per match.
8
9use super::{
10    argument_text, flag_text,
11    flags::ReFlags,
12    match_set::{MatchSet, Search},
13};
14use crate::error::{Result, SQLError};
15use uqa_core::{
16    memory::{Produced, ProductionControl},
17    Value,
18};
19
20/// The rows of one `regexp_matches` call. Like `PostgreSQL`'s first call, preparing the cursor finds every match; the cursor owns the input's code points and the match spans, so a caller can draw each row under its own control.
21#[derive(Debug)]
22pub struct RegexMatches {
23    matches: MatchSet,
24    next: usize,
25}
26
27impl RegexMatches {
28    /// Prepare `regexp_matches(string, pattern [, flags])` under the call's input collation (`PostgreSQL`'s `inputcollid`, zero when indeterminate). A NULL argument yields no cursor: the strict set-returning function returns no rows.
29    ///
30    /// # Errors
31    ///
32    /// Reports `PostgreSQL`'s diagnostics for an invalid flag, collation or pattern and for a failed search, an exhausted allowance and cancellation.
33    pub fn new(
34        arguments: &[Value],
35        collation: u32,
36        control: &ProductionControl<'_>,
37    ) -> Result<Option<Self>> {
38        control.check()?;
39        if !(2..=3).contains(&arguments.len()) {
40            return Err(SQLError::TypeMismatch(
41                "regexp_matches takes 2 or 3 args".into(),
42            ));
43        }
44        if arguments.iter().any(|value| matches!(value, Value::Null)) {
45            return Ok(None);
46        }
47        let input = argument_text(&arguments[0], control)?;
48        let pattern = argument_text(&arguments[1], control)?;
49        let flags = ReFlags::parse(&flag_text(arguments.get(2), control)?)?;
50        let search = Search {
51            start: 0,
52            subexpressions: true,
53            ignore_degenerate: false,
54        };
55        let matches = MatchSet::find(&input, &pattern, flags, collation, search, control)?;
56        Ok(Some(Self { matches, next: 0 }))
57    }
58
59    /// The capture array of the next match, or `None` after the last one.
60    ///
61    /// # Errors
62    ///
63    /// Reports an exhausted allowance or cancellation. The cursor stays at the failed match, and rows already returned remain valid.
64    pub fn next_row(&mut self, control: &ProductionControl<'_>) -> Result<Option<Produced<Value>>> {
65        control.check()?;
66        if self.next >= self.matches.len() {
67            return Ok(None);
68        }
69        let row = self.matches.row(self.next, control)?;
70        self.next += 1;
71        Ok(Some(row))
72    }
73}