Skip to content

Commit 16b2895

Browse files
committed
Add REGEXP_INSTR() UDF
Implement MySQL REGEXP_INSTR(expr, pattern [, pos [, occurrence [, return_option [, match_type]]]]) with 1-based character positions and start-or-end result selection. Evaluate anchors and lookbehind against the region beginning at pos, matching MySQL semantics. Validate return_option before nullable pattern and flag arguments, and reject positions beyond the subject. Cover validation precedence, multibyte results, occurrence clamping, region-relative anchors and lookbehind, and return-option errors.
1 parent 3d14282 commit 16b2895

2 files changed

Lines changed: 165 additions & 0 deletions

File tree

‎packages/mysql-on-sqlite/src/sqlite/class-wp-sqlite-pdo-user-defined-functions.php‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ public static function register_for( $pdo ): self {
6767
'regexp_like' => 'regexp_like',
6868
'regexp_replace' => 'regexp_replace',
6969
'regexp_substr' => 'regexp_substr',
70+
'regexp_instr' => 'regexp_instr',
7071
'field' => 'field',
7172
'log' => 'log',
7273
'least' => 'least',
@@ -103,6 +104,7 @@ public static function register_for( $pdo ): self {
103104
'regexp_like' => array( 2, 3 ),
104105
'regexp_replace' => array( 3, 4, 5, 6 ),
105106
'regexp_substr' => array( 2, 3, 4, 5 ),
107+
'regexp_instr' => array( 2, 3, 4, 5, 6 ),
106108
);
107109

108110
/** @var string|null Last validated regex pattern. */
@@ -760,6 +762,65 @@ public function regexp_substr( $expr, $pattern, $pos = 1, $occurrence = 1, $matc
760762
return $match[0][0];
761763
}
762764

765+
/**
766+
* Method to emulate MySQL REGEXP_INSTR() function.
767+
*
768+
* Values of `occurrence` less than 1 are clamped to 1, matching MySQL.
769+
* `pos` greater than char_count is rejected (unlike SUBSTR and REPLACE).
770+
* Like MySQL, `pos` is not checked for an empty subject, where a match is
771+
* reported at `pos`.
772+
*
773+
* @param string|null $expr Subject string.
774+
* @param string|null $pattern Regex pattern.
775+
* @param int|float|string|null $pos 1-based character position to start matching.
776+
* @param int|float|string|null $occurrence Which match to locate (1-based; <= 0 clamps to 1).
777+
* @param int|float|string|null $return_option 0 = start of match (default), 1 = one past end.
778+
* @param string|null $match_type MySQL match_type flags.
779+
*
780+
* @throws Exception If the pattern is invalid, pos is out of range, or
781+
* return_option is not 0 or 1.
782+
* @return int|null 1-based character position, 0 if no match, NULL on NULL input.
783+
*/
784+
public function regexp_instr( $expr, $pattern, $pos = 1, $occurrence = 1, $return_option = 0, $match_type = '' ) {
785+
if (
786+
null === $expr || null === $pattern || null === $pos
787+
|| null === $occurrence || null === $return_option || null === $match_type
788+
) {
789+
return null;
790+
}
791+
$ret = (int) $return_option;
792+
if ( 0 !== $ret && 1 !== $ret ) {
793+
throw new Exception( 'Incorrect arguments to regexp_instr: return_option must be 1 or 0.' );
794+
}
795+
$compiled = $this->regexp_compile( $pattern, $match_type );
796+
797+
$expr = (string) $expr;
798+
$position = (int) $pos;
799+
800+
// MySQL clamps occurrence <= 0 to 1.
801+
$n = max( 1, (int) $occurrence );
802+
803+
$byte_start = '' === $expr ? 0 : $this->regexp_char_to_byte_offset( $expr, $position );
804+
$region = substr( $expr, $byte_start );
805+
806+
$match = $this->regexp_find_nth_match( $compiled, $pattern, $region, 0, $n );
807+
if ( null === $match ) {
808+
return 0;
809+
}
810+
if ( '' === $expr ) {
811+
return $position;
812+
}
813+
814+
list( $matched_text, $matched_byte_offset ) = $match[0];
815+
$target_byte = $byte_start + $matched_byte_offset;
816+
if ( 1 === $ret ) {
817+
$target_byte += strlen( $matched_text );
818+
}
819+
820+
// Every byte except a UTF-8 continuation byte starts a character.
821+
return $target_byte - preg_match_all( '/[\x80-\xBF]/', substr( $expr, 0, $target_byte ) ) + 1;
822+
}
823+
763824
/**
764825
* Method to emulate MySQL FIELD() function.
765826
*

‎packages/mysql-on-sqlite/tests/WP_MySQL_On_SQLite_Tests.php‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,110 @@ public function testRegexpSubstrNumericSubject() {
736736
$this->assertSame( '2', $this->last_result[0]->r );
737737
}
738738

739+
/**
740+
* @dataProvider regexpInstrCases
741+
*/
742+
public function testRegexpInstr( $sql, $expected ) {
743+
$this->assertQuery( "SELECT $sql AS r" );
744+
$this->assertSame( $expected, $this->last_result[0]->r );
745+
}
746+
747+
public static function regexpInstrCases() {
748+
return array(
749+
'basic' => array( "REGEXP_INSTR('dog cat dog', 'dog')", '1' ),
750+
'no match' => array( "REGEXP_INSTR('abc', 'xyz')", '0' ),
751+
'second match' => array( "REGEXP_INSTR('dog cat dog', 'dog', 1, 2)", '9' ),
752+
'pos skips first match' => array( "REGEXP_INSTR('dog cat dog', 'dog', 5)", '9' ),
753+
'return_option=1 (end)' => array( "REGEXP_INSTR('dog cat dog', 'dog', 1, 1, 1)", '4' ),
754+
'match_type c miss' => array( "REGEXP_INSTR('DOG', 'dog', 1, 1, 0, 'c')", '0' ),
755+
'multibyte position' => array( "REGEXP_INSTR('café123', '[0-9]+')", '5' ),
756+
'null expr' => array( "REGEXP_INSTR(NULL, 'abc')", null ),
757+
'null pattern' => array( "REGEXP_INSTR('abc', NULL)", null ),
758+
// A NULL match_type returns NULL before the pattern and pos are checked.
759+
'null match_type first' => array( "REGEXP_INSTR('abc', '(abc', 0, 1, 0, NULL)", null ),
760+
// NULL arguments return NULL before pos is checked.
761+
'null expr, pos 0' => array( "REGEXP_INSTR(NULL, 'a', 0)", null ),
762+
'null expr, pos -1' => array( "REGEXP_INSTR(NULL, 'a', -1)", null ),
763+
'null expr, pos 5' => array( "REGEXP_INSTR(NULL, 'a', 5)", null ),
764+
'null pattern, pos 0' => array( "REGEXP_INSTR('abc', NULL, 0)", null ),
765+
'null occurrence, pos 0' => array( "REGEXP_INSTR('abc', 'a', 0, NULL)", null ),
766+
);
767+
}
768+
769+
/**
770+
* @dataProvider regexpInstrErrors
771+
*/
772+
public function testRegexpInstrErrors( $sql, $message ) {
773+
$this->assertQueryError( "SELECT $sql", $message );
774+
}
775+
776+
public static function regexpInstrErrors() {
777+
$return_option = 'Incorrect arguments to regexp_instr: return_option must be 1 or 0.';
778+
return array(
779+
'invalid pattern' => array( "REGEXP_INSTR('abc', '(abc')", 'Invalid regular expression: (abc.' ),
780+
'invalid flag' => array( "REGEXP_INSTR('abc', 'a', 1, 1, 0, 'x')", 'Invalid match_type flag: x.' ),
781+
'pos zero' => array( "REGEXP_INSTR('abc', 'a', 0)", 'Index out of bounds in regular expression search.' ),
782+
'pos far past end' => array( "REGEXP_INSTR('abc', 'a', 10)", 'Index out of bounds in regular expression search.' ),
783+
'invalid return_option' => array( "REGEXP_INSTR('abc', 'a', 1, 1, 2)", $return_option ),
784+
'extra argument' => array(
785+
"REGEXP_INSTR('abc', 'a', 1, 1, 0, 'c', 'extra')",
786+
'SQLSTATE[HY000]: General error: 1 wrong number of arguments to function REGEXP_INSTR()',
787+
),
788+
);
789+
}
790+
791+
public function testRegexpInstrEmptySubjectSkipsPosCheck() {
792+
// MySQL does not check pos for an empty subject and reports a match at pos.
793+
$cases = array(
794+
"'a', 2" => '0',
795+
"'^', 5" => '5',
796+
"'^', -3" => '-3',
797+
);
798+
foreach ( $cases as $args => $expected ) {
799+
$this->assertQuery( "SELECT REGEXP_INSTR('', $args) AS r" );
800+
$this->assertSame( $expected, $this->last_result[0]->r, $args );
801+
}
802+
803+
$this->assertQueryError(
804+
"SELECT REGEXP_INSTR('', '(', 2)",
805+
'Invalid regular expression: (.'
806+
);
807+
}
808+
809+
public function testRegexpInstrOccurrenceClampedToOne() {
810+
// MySQL clamps occurrence <= 0 to 1.
811+
$this->assertQuery( "SELECT REGEXP_INSTR('abcabc', 'b', 1, 0) AS r" );
812+
$this->assertSame( '2', $this->last_result[0]->r );
813+
$this->assertQuery( "SELECT REGEXP_INSTR('abcabc', 'b', 1, -5) AS r" );
814+
$this->assertSame( '2', $this->last_result[0]->r );
815+
}
816+
817+
public function testRegexpInstrStraddlingMatch() {
818+
// A match that starts before pos is not returned; the next match at or
819+
// after pos is returned instead.
820+
$this->assertQuery( "SELECT REGEXP_INSTR('abc123def', '[0-9]+', 5) AS r" );
821+
$this->assertSame( '5', $this->last_result[0]->r );
822+
}
823+
824+
public function testRegexpInstrMultibyteReturnOptionEnd() {
825+
// Multibyte match ('é' is 2 bytes) with return_option=1 (one past end).
826+
// 'aéb' char positions: a=1, é=2, b=3. 'é' matches at char 2, end char position = 3.
827+
$this->assertQuery( "SELECT REGEXP_INSTR('aéb', 'é', 1, 1, 1) AS r" );
828+
$this->assertSame( '3', $this->last_result[0]->r );
829+
}
830+
831+
public function testRegexpInstrPatternIsRelativeToPos() {
832+
$this->assertQuery( "SELECT REGEXP_INSTR('abc', '^b', 2) AS r" );
833+
$this->assertSame( '2', $this->last_result[0]->r );
834+
$this->assertQuery( "SELECT REGEXP_INSTR('ab', '(?<=a)b', 2) AS r" );
835+
$this->assertSame( '0', $this->last_result[0]->r );
836+
}
837+
838+
public function testRegexpInstrNumericSubject() {
839+
$this->assertQuery( "SELECT REGEXP_INSTR(123, '2') AS r" );
840+
$this->assertSame( '2', $this->last_result[0]->r );
841+
}
842+
739843
public function testInsertDateNow() {
740844
$this->assertQuery(
741845
"INSERT INTO _dates (option_name, option_value) VALUES ('first', now());"

0 commit comments

Comments
 (0)