Optimize generate_username query #18061
Merged
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.
Followup/fix to #12745.
This PR uses a faster, and more accurate MySQL query for generating pseudo-sequential usernames.
While the query in #12745 selected an integer one greater than the maximum of all found integers, this query selects the first gap in the integer sequence. This is more accurate/reliable (because a single, random high-value integer won't cause all future pseudo-sequential numbers to be strictly greater), and it also turns out to be a faster query to boot.
Compare:
Previous PR query (super-long number, 4.29 sec):
Current PR query (shortest-available number, 2.58 sec):
This will fix the issue encountered in our UI tests because the previous query quickly encountered an integer-overrun issue, where the max value "999999[...etc...]" was selected, increased by 1 to "1000000[...etc...]", increasing its string length by 1. If the 999-etc string was already the maximum allowed username length, the newly-generated username would fail validation. The new query will only encounter this issue if all of the gaps in the sequence are also exhausted, which will be much less likely. I've also added a raise on this case, so we should be able to detect this error-condition more easily.