Fix SUBSTRING with a non-positive start position - #2521
Open
spokodev wants to merge 1 commit into
Open
Conversation
SUBSTRING/SUBSTR/MID compiled 'SUBSTRING(str, pos, len)' to
str.substr(pos - 1, len). When pos was 0 or negative, pos - 1 became a
negative index and JavaScript's substr() counts that from the end of the
string, so 'SUBSTRING("abcdef", 0, 3)' returned 'f' and
'SUBSTRING("abcdef", -1, 3)' returned 'ef'.
Follow MySQL semantics instead: a start of 0 yields an empty string, and
a negative start counts from the end (clamped to empty when it reaches
past the beginning). Positive start positions are unchanged.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
SUBSTRING/SUBSTR/MIDcompileSUBSTRING(str, pos, len)tostr.substr(pos - 1, len). Whenposis0or negative,pos - 1becomes a negative index, and JavaScript'sString.prototype.substr()counts a negative start from the end of the string. The result is neither correct nor consistent with any SQL dialect:So a computed start position that lands on
0or goes negative silently returns wrong characters.Fix
Follow MySQL semantics (verified against MySQL 8), which alasql already matches for positive positions:
= 0yields an empty string;SUBSTRING('abcdef', -2)->'ef'), clamped to an empty string when it reaches past the beginning (SUBSTRING('abcdef', -7)->'');SUBSTRING('abcdef', 0, 3)'f'''SUBSTRING('abcdef', -1, 3)'ef''f'SUBSTRING('abcdef', -2, 3)'def''ef'SUBSTRING('abcdef', -2)'def''ef'SUBSTRING('abcdef', -7, 3)'bcd'''SUBSTRING('abcdef', 2, 3)'bcd''bcd'Test
Added
test/test-substring-negative-start.js.yarn testpasses (2193 tests).