uqa_sql/expr/regex/
split.rs1use 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#[derive(Debug)]
23pub struct RegexSplit {
24 matches: MatchSet,
25 next: usize,
27}
28
29impl RegexSplit {
30 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 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
99pub(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}