Skip to content

fix: make shorten method to properly work with camelCase_aliases - #11283

Merged
gioboa merged 6 commits into
typeorm:masterfrom
OSA413:try-fix-9544
Jan 20, 2026
Merged

gioboa merged 6 commits into
typeorm:masterfrom
OSA413:try-fix-9544

Conversation

@OSA413

@OSA413 OSA413 commented Feb 11, 2025

Copy link
Copy Markdown
Collaborator

Fixes #9544

Description of change

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

@mguida22 mguida22 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't completely address the issue in #9544, since shorten can still produce identical outputs for different inputs.

For example

// these differ by visualFrameAsset vs virtualFrameAsset
shorten("SupplierStockInTransit__supplierStock__productVariant_customFields_visualFrameAsset")
shorten("SupplierStockInTransit__supplierStock__productVariant_customFields_virtualFrameAsset")

// and shorten produces the same result
"SuStInTr__suSt__prVacuFiviFrAs"

To fully address the issue aliases probably need some kind of hash of their contents. I wonder how other ORMs handle this?

This PR might still be an improvement since it handles camel case aliases better than before.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to cfcdd94

CategorySuggestion                                                                                                                                    Impact
General
Handle uppercase letters after underscores

Modify the regex to handle underscores followed by either lowercase or uppercase
letters.

src/util/StringUtils.ts [98-100]

 .replace(/([a-z\xE0-\xFF])([A-Z\xC0-\xDF])/g, "$1 $2")
-.replace(/(_)([a-z])/g, " $2")
+.replace(/(_)([a-zA-Z])/g, " $2")
 .split(" ")
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the new regex only handles underscores followed by lowercase letters, and proposes a fix to handle uppercase letters as well, which improves the robustness of the function.

Low
  • More

Previous suggestions

Suggestions up to commit 7becb71
CategorySuggestion                                                                                                                                    Impact
General
Handle uppercase letters after underscores

Modify the regex to handle both lowercase and uppercase letters after an
underscore to correctly split strings like snake_Case.

src/util/StringUtils.ts [99]

-.replace(/(_)([a-z])/g, " $2")
+.replace(/(_)([a-zA-Z])/g, " $2")
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a flaw in the new regex which only handles lowercase characters after an underscore, and the proposed fix makes the function more robust by handling uppercase characters as well.

Medium
Use forEach instead of map

Replace .map() with .forEach() when iterating to create test cases, as the
returned array is unused and forEach better conveys the intent of performing
side effects.

test/github-issues/9544/issue-9544.test.ts [20-25]

-testCases.map((testCase, i) => {
+testCases.forEach((testCase, i) => {
     it(`should produce correct results for camel case aliases, case #${i + 1}`, () => {
         const { input, expected } = testCase
         expect(shorten(input)).to.equal(expected)
     })
 })
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly points out that forEach is more idiomatic than map for iteration with side-effects, which improves code readability and adherence to best practices.

Low
Suggestions up to commit 19fff0b
CategorySuggestion                                                                                                                                    Impact
General
Handle uppercase letters after underscores

Modify the regex to handle both lowercase and uppercase letters following an
underscore by changing [a-z] to [a-zA-Z].

src/util/StringUtils.ts [99]

-.replace(/(_)([a-z])/g, " $2")
+.replace(/(_)([a-zA-Z])/g, " $2")
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the regex only handles lowercase letters after an underscore and proposes a fix to handle uppercase letters as well, making the function more robust for edge cases not covered by the tests.

Low
Suggestions up to commit de792a2
CategorySuggestion                                                                                                                                    Impact
General
Handle uppercase letters after underscores

Modify the regex to handle both lowercase and uppercase letters after an
underscore by changing [a-z] to [a-zA-Z].

src/util/StringUtils.ts [99]

-.replace(/(_)([a-z])/g, " $2")
+.replace(/(_)([a-zA-Z])/g, " $2")
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the new regex only handles lowercase letters after an underscore, and proposes a fix to handle uppercase letters as well, which makes the function more robust for mixed-case identifiers.

Medium
Suggestions up to commit 855e6c2
CategorySuggestion                                                                                                                                    Impact
General
Handle uppercase letters after underscores

Modify the regex to handle uppercase letters following an underscore. Change
([a-z]) to ([a-zA-Z]) to correctly process strings like _CustomFields.

src/util/StringUtils.ts [95]

-.replace(/(_)([a-z])/g, " $2")
+.replace(/(_)([a-zA-Z])/g, " $2")
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the regex only handles underscores followed by lowercase letters, and proposing to include uppercase letters makes the function more robust for mixed snake_case and PascalCase strings.

Low
Use forEach for side effects

Replace map() with forEach() for iterating over test cases. The map() function
is being used for its side effect of creating tests, but its return value is
discarded, making forEach() a more appropriate choice.

test/github-issues/9544/issue-9544.ts [21-26]

-testCases.map((testCase, i) => {
+testCases.forEach((testCase, i) => {
     it(`should produce correct results for camel case aliases, case #${i+1}`, () => {
         const {input, expected} = testCase;
         expect(shorten(input)).to.equal(expected);
     })
 })
Suggestion importance[1-10]: 4

__

Why: The suggestion is correct; using forEach is more idiomatic for iterations with side-effects where the returned array from map is unused. This is a code style and best practice improvement.

Low

@pkg-pr-new

pkg-pr-new Bot commented Dec 1, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11283
    

commit: cfcdd94

@coveralls

coveralls commented Dec 1, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.957% (+26.4%) from 54.508%
when pulling 7becb71 on OSA413:try-fix-9544
into d233daa on typeorm:master.

@gioboa gioboa changed the title fix: Make shorten method to properly work with camelCase_aliases fix: make shorten method to properly work with camelCase_aliases Jan 19, 2026

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM @OSA413 👏

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 7becb71

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Incomplete underscore splitting regex pattern 🐞 Bug ✓ Correctness
Description
• The new regex .replace(/(_)([a-z])/g, " $2") only matches lowercase letters after underscores,
  failing to handle uppercase letters
• This creates inconsistent behavior: product_variant splits correctly but product_Variant does
  not
• The function already handles camelCase transitions (lowercase to uppercase) via the first regex,
  so underscores should split regardless of the following letter's case
• This bug is masked by test cases that only use lowercase letters after underscores
Code

src/util/StringUtils.ts[99]

+            .replace(/(_)([a-z])/g, " $2")
Evidence
The regex pattern only matches lowercase [a-z] after underscores. The existing camelCase regex on
line 98 handles lowercase-to-uppercase transitions, demonstrating the function should handle both
cases. The test file only validates lowercase scenarios, missing the uppercase edge case. If an
input like 'productVariant_CustomFields' is processed, the underscore before 'CustomFields' won't be
treated as a word boundary, causing incorrect abbreviation.

src/util/StringUtils.ts[98-99]
test/github-issues/9544/issue-9544.test.ts[7-17]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

# Issue Description
The new regex pattern for handling underscores in the `shorten` function only matches lowercase letters after underscores, creating inconsistent behavior when uppercase letters follow underscores.

# Issue Context
The `shorten` function abbreviates long identifiers by splitting them into terms. It already handles camelCase transitions (e.g., `productVariant` → `product Variant`) using a regex that matches lowercase-to-uppercase transitions. The new regex was added to also split on underscores, but it only handles lowercase letters after the underscore.

# Fix Focus Areas
- src/util/StringUtils.ts[99-99]
- test/github-issues/9544/issue-9544.test.ts[5-18] (add test case with uppercase after underscore)

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

2. Test added to github-issues, not functional 📘 Rule violation ✓ Correctness
Description
• The fix for issue #9544 adds tests only to test/github-issues/9544/ directory without adding or
  updating tests in test/functional/ or test/unit/util/string-utils.test.ts.
• Per compliance rule 3, issue fixes should preferably add or update tests in the functional test
  suite rather than only adding per-issue tests.
• The shorten function is a utility function that already has related tests in other locations
  (test/unit/util/string-utils.test.ts exists for other StringUtils functions), making it a good
  candidate for functional/unit testing.
Code

test/github-issues/9544/issue-9544.test.ts[R1-34]

+import { expect } from "chai"
+import { shorten } from "../../../src/util/StringUtils"
+
+describe("github issues > #9544 shorten long camel case alias correctly", () => {
+    const testCases = [
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_tryonFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFitrFrAs",
+        },
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_visualFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFiviFrAs",
+        },
+        {
+            input: "camelCase_alias",
+            expected: "caCaal",
+        },
+    ]
+
+    testCases.map((testCase, i) => {
+        it(`should produce correct results for camel case aliases, case #${i + 1}`, () => {
+            const { input, expected } = testCase
+            expect(shorten(input)).to.equal(expected)
+        })
+    })
+
+    it("should produce unique results for different inputs", () => {
+        const uniqueInputs = new Set(testCases.map((x) => x.input))
+        const uniqueExpects = new Set(testCases.map((x) => x.expected))
+
+        expect(uniqueInputs.size).to.equal(testCases.length)
+        expect(uniqueExpects.size).to.equal(testCases.length)
+    })
+})
Evidence
The compliance checklist requires that issue fixes add or update tests in test/functional with an
issue reference when applicable, rather than only adding tests under test/github-issues. The test
file at test/github-issues/9544/issue-9544.test.ts is a per-issue test without corresponding
functional or unit tests. The test/unit/util/string-utils.test.ts file exists and tests other
StringUtils functions (camelCase, snakeCase, hash) but does not include tests for the shorten
function.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/9544/issue-9544.test.ts[1-34]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The tests for the shorten function fix (issue #9544) are only in test/github-issues/9544/ but should be added to the functional/unit test suite per project conventions.

## Issue Context
The project prefers functional tests over per-issue tests. The test/unit/util/string-utils.test.ts file already exists and tests other StringUtils functions (camelCase, snakeCase, hash) but lacks tests for the shorten function. The shorten function is a utility function that should have unit tests alongside other StringUtils functions.

## Fix Focus Areas
- test/unit/util/string-utils.test.ts[1-216] (add a new describe block for shorten function with test cases from issue #9544)
- test/github-issues/9544/issue-9544.test.ts[1-34] (optionally keep for integration testing or remove if unit tests are sufficient)

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Previous review results

Review updated until commit cfcdd94

Results up to commit 19fff0b


🐞 Bugs (2) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider
Action required
1. Incomplete Underscore Pattern Handling 🐞 Bug ✓ Correctness
Description
• The regex /(_)([a-z])/g only matches underscores followed by lowercase letters, ignoring
  uppercase letters, numbers, and other characters
• This creates inconsistent splitting behavior: 'test_value' splits correctly but 'test_Value' or
  'test_123' do not
• The asymmetry with the existing camelCase regex (which handles uppercase) leads to unpredictable
  shortening results for mixed naming conventions
• Can cause unexpected alias collisions or inconsistent database identifiers in production
Code

src/util/StringUtils.ts[99]

+            .replace(/(_)([a-z])/g, " $2")
Evidence
The regex pattern at line 99 only captures lowercase letters after underscores, creating behavioral
inconsistencies. The existing camelCase regex at line 98 handles uppercase letters, but the new
underscore regex doesn't complement this pattern. This is demonstrated by comparing the patterns and
tracing through examples: 'test_value' → 'test value' (converted), but 'test_Value' → 'test_Value'
(not converted), and 'test_123' → 'test_123' (not converted). The function is used in
EntityMetadata.ts line 1036 with separator '_' for table names, and in DriverUtils.ts line 138 for
alias shortening, making this inconsistency critical for database operations.

src/util/StringUtils.ts[99-99]
src/util/StringUtils.ts[98-98]
src/metadata/EntityMetadata.ts[1036-1038]
src/driver/DriverUtils.ts[138-138]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue Description
The underscore handling regex `/(_)([a-z])/g` only matches lowercase letters after underscores, creating inconsistent behavior for mixed-case identifiers (e.g., 'product_ID'), numeric suffixes (e.g., 'version_2'), and other patterns. This causes unpredictable shortening results.

## Issue Context
The `shorten()` function is used to abbreviate database table names and query aliases. It needs to consistently handle various naming conventions including snake_case, camelCase, and mixed patterns. The existing camelCase regex at line 98 handles uppercase letters comprehensively, but the new underscore regex doesn't match this approach.

## Fix Focus Areas
- src/util/StringUtils.ts[99-99]: Update regex pattern from `/(_)([a-z])/g` to `/(_)([a-zA-Z0-9])/g` or `/(_)(\w)/g` to handle uppercase, lowercase, and numeric characters
- test/github-issues/9544/issue-9544.test.ts[5-18]: Add test cases for edge cases including uppercase after underscore, numbers after underscore, consecutive underscores, and trailing underscores

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Missing Test Coverage Edge Cases 🐞 Bug ⛯ Reliability
Description
• Test suite only validates lowercase letters after underscores, missing critical edge cases
• No tests for uppercase after underscore (e.g., 'product_ID'), numbers (e.g., 'version_2'),
  consecutive underscores, or trailing underscores
• Allows the incomplete pattern bug to pass undetected
• Insufficient regression protection for future changes
Code

test/github-issues/9544/issue-9544.test.ts[R5-18]

+    const testCases = [
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_tryonFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFitrFrAs",
+        },
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_visualFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFiviFrAs",
+        },
+        {
+            input: "camelCase_alias",
+            expected: "caCaal",
+        },
+    ]
Evidence
All three test cases in the new test file only use lowercase letters after underscores:
'customFields_tryonFrameAsset', 'customFields_visualFrameAsset', and 'camelCase_alias'. This leaves
critical edge cases untested. The existing documentation example at StringUtils.ts line 84 also only
uses lowercase ('category_with_very_long_name'), so it won't catch the pattern limitation either.
Without tests for mixed-case, numeric, and special patterns, the incomplete regex implementation
passes validation despite being incorrect for real-world usage.

test/github-issues/9544/issue-9544.test.ts[7-8]
test/github-issues/9544/issue-9544.test.ts[11-12]
test/github-issues/9544/issue-9544.test.ts[15-16]
src/util/StringUtils.ts[84-84]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue Description
The test suite only validates the happy path with lowercase letters after underscores. Critical edge cases are missing, allowing bugs in the regex pattern to go undetected. Real-world identifiers often use mixed naming conventions that aren't tested.

## Issue Context
The `shorten()` function is used for database table names and query aliases which can have various formats: mixed-case (product_ID), numeric suffixes (version_2), consecutive separators (test__value), and trailing underscores. Without testing these patterns, the implementation can't be validated as correct.

## Fix Focus Areas
- test/github-issues/9544/issue-9544.test.ts[5-18]: Add test cases for:
 - Uppercase after underscore: 'product_ID' or 'test_Value'
 - Numbers after underscore: 'version_2' or 'test_123'
 - Consecutive underscores: 'test__value'
 - Trailing underscore: 'test_'
 - Mixed patterns: 'test_Value_123' or 'camelCase_ID_2'

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
3. Test added to github-issues directory 📘 Rule violation ✓ Correctness
Description
• The fix for issue #9544 adds a test under test/github-issues/9544/ instead of adding or updating
  tests in test/functional/ or test/unit/util/string-utils.test.ts.
• The compliance rule requires issue fixes to stay in the functional test suite with an issue
  reference in the test comment when applicable.
• While the test includes an issue reference in the describe block, it should be in the functional
  or unit test directory rather than github-issues.
Code

test/github-issues/9544/issue-9544.test.ts[R1-34]

+import { expect } from "chai"
+import { shorten } from "../../../src/util/StringUtils"
+
+describe("github issues > #9544 shorten long camel case alias correctly", () => {
+    const testCases = [
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_tryonFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFitrFrAs",
+        },
+        {
+            input: "SupplierStockInTransit__supplierStock__productVariant_customFields_visualFrameAsset",
+            expected: "SuStInTr__suSt__prVacuFiviFrAs",
+        },
+        {
+            input: "camelCase_alias",
+            expected: "caCaal",
+        },
+    ]
+
+    testCases.map((testCase, i) => {
+        it(`should produce correct results for camel case aliases, case #${i + 1}`, () => {
+            const { input, expected } = testCase
+            expect(shorten(input)).to.equal(expected)
+        })
+    })
+
+    it("should produce unique results for different inputs", () => {
+        const uniqueInputs = new Set(testCases.map((x) => x.input))
+        const uniqueExpects = new Set(testCases.map((x) => x.expected))
+
+        expect(uniqueInputs.size).to.equal(testCases.length)
+        expect(uniqueExpects.size).to.equal(testCases.length)
+    })
+})
Evidence
The compliance checklist (PR Compliance ID 3) requires issue fixes to add or update tests in
test/functional, with an issue reference in the test comment when applicable. The test file was
added to test/github-issues/9544/ instead. The existing unit test file
test/unit/util/string-utils.test.ts already tests other StringUtils functions (camelCase, snakeCase,
hash) and would be the appropriate location for shorten() tests.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/9544/issue-9544.test.ts[1-34]
test/unit/util/string-utils.test.ts[1-5]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test for the shorten() function fix should be added to the existing unit test file for StringUtils rather than creating a new test file in test/github-issues.

## Issue Context
The project prefers functional/unit tests over per-issue tests. There is already a unit test file at test/unit/util/string-utils.test.ts that tests other StringUtils functions (camelCase, snakeCase, hash). The shorten() function tests should be added there with a comment referencing issue #9544.

## Fix Focus Areas
- test/github-issues/9544/issue-9544.test.ts[1-34]
- test/unit/util/string-utils.test.ts[216-216]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. Documentation not updated 📘 Rule violation ✓ Correctness
Description
• The PR checklist indicates documentation has not been updated (checkbox unchecked).
• The shorten() function is a public utility function that can be imported and used by TypeORM
  users.
• The fix changes the behavior of the shorten() function to properly handle camelCase_aliases
  (mixed camelCase and snake_case), which is a user-facing change in functionality.
Code

src/util/StringUtils.ts[99]

+            .replace(/(_)([a-z])/g, " $2")
Evidence
The compliance checklist (PR Compliance ID 2) requires documentation updates for user-facing
changes. The PR description shows the documentation checkbox is unchecked. The shorten() function is
exported from StringUtils and is used for shortening database aliases - a public API. The fix adds
support for mixed camelCase_snake_case patterns, which changes the function's behavior and output
for certain inputs.

Rule 2: Docs updated for user-facing changes
src/util/StringUtils.ts[91-91]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The shorten() function now properly handles mixed camelCase_snake_case patterns (e.g., `camelCase_alias`), but the JSDoc documentation doesn't mention this capability.

## Issue Context
The fix adds a new regex replacement `.replace(/(_)([a-z])/g, " $2")` that splits on underscores followed by lowercase letters. This allows the function to handle patterns like `productVariant_customFields_tryonFrameAsset` correctly. The JSDoc should include an example demonstrating this new capability.

## Fix Focus Areas
- src/util/StringUtils.ts[72-90]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit cfcdd94

@michaelbromley michaelbromley left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mguida22's earlier comment stands - but this is certainly an improvement and will lower the chances of users running into this issue, so IMO certainly worth merging.

@michaelbromley

michaelbromley commented Jan 20, 2026 •

Copy link
Copy Markdown
Member

Actually @OSA413 would you be able to move the unit test for this to a better location as per Qodo's suggestion, so we move away from the issue-based test structure?

• The shorten function is a utility function that already has related tests in other locations
  (test/unit/util/string-utils.test.ts exists for other StringUtils functions), making it a good
  candidate for functional/unit testing.

update: I commented this at the exact moment that Giorgio merged.. but we discussed further and in any case there is still work to be done to clearly define and then move all the other tests.

@gioboa
gioboa merged commit 8a9a376 into typeorm:master Jan 20, 2026
38 checks passed
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

StringUtils shorten() function can result in collisions

8 participants