Skip to content

fix(mysql): getVersion returning undefined for PolarDB-X 2.0 - #11837

Merged
pkuczynski merged 2 commits into
typeorm:masterfrom
Missna:fix/getVersion
Jan 8, 2026
Merged

pkuczynski merged 2 commits into
typeorm:masterfrom
Missna:fix/getVersion

Conversation

@Missna

@Missna Missna commented Dec 9, 2025 •

Copy link
Copy Markdown
Contributor

Description of change

  • fix get version return a undefined value when use PolarDB-X 2.0
  • When using the distributed database PolarDB-X 2.0 compatible with MYSQL 8.0, executing the SELECT version () statement returns a column name of uppercase VERSION(), resulting in const version String=result [0] ["version ()"] returning version String as undefined and reporting an error

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as #11838
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

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

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Case Sensitivity

The fix assumes the column name will always be lowercase 'version', but different database systems or configurations might return different casing. Consider using a case-insensitive approach or checking for both 'version' and 'VERSION()' to ensure compatibility across all MySQL-compatible databases.

const result: [{ version: string }] = await this.query(
    "SELECT version() as version",
)

// MariaDB: https://mariadb.com/kb/en/version/
// - "10.2.27-MariaDB-10.2.27+maria~jessie-log"

// MySQL: https://dev.mysql.com/doc/refman/8.4/en/information-functions.html#function_version
// - "8.4.3"
// - "8.4.4-standard"

const versionString = result[0]["version"]

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 4a5af2f

CategorySuggestion                                                                                                                                    Impact
General
Add null check for query result

Add a check to ensure the result from the version query is not empty and
contains the version property before accessing it, preventing potential runtime
errors.

src/driver/mysql/MysqlQueryRunner.ts [3380-3395]

 async getVersion(): Promise<string> {
     const result: [{ version: string }] = await this.query(
         "SELECT version() as version",
     )
     ...
+    if (!result[0] || !result[0]["version"]) {
+        throw new TypeORMError("Failed to retrieve database version")
+    }
     const versionString = result[0]["version"]
     return versionString.replace(/^([\d.]+).*$/, "$1")
 }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies a potential runtime error if the query returns an empty result set. Adding a check improves the robustness of the getVersion method by handling this edge case gracefully.

Low
  • More

Previous suggestions

Suggestions up to commit ce144b8
CategorySuggestion                                                                                                                                    Impact
Possible issue
Add check for empty query result

Add a check to ensure the database version query returns a result before
accessing it, preventing a potential runtime error if the result is unexpectedly
empty.

src/driver/mysql/MysqlQueryRunner.ts [3385-3387]

-const versionString = result[0]["version"]
+if (!result.length) {
+    throw new TypeORMError(`Could not get version from the database.`)
+}
+
+const versionString = result[0].version
 
 return versionString.replace(/^([\d.]+).*$/, "$1")
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies a potential TypeError if the query returns an empty result, but the SELECT version() query is highly unlikely to do so, making this a low-impact robustness improvement.

Low

@Missna

Missna commented Dec 9, 2025

Copy link
Copy Markdown
Contributor Author

When using the distributed database PolarDB-X 2.0 compatible with MYSQL 8.0,start a nestjs server will show a error:

[Nest] 8943 - 2025/12/09 10:42:40 ERROR [TypeOrmModule] Unable to connect to the database (ops-db-connection). Retrying (1)...
TypeError: Cannot read properties of undefined (reading 'replace')
at MysqlQueryRunner.getVersion (/Users/admin/workspace/projects/bff-nestjs/node_modules/.pnpm/[email protected][email protected][email protected][email protected]_ts-node@10.9.2_@types[email protected][email protected]_/node_modules/typeorm/driver/src/driver/mysql/MysqlQueryRunner.ts:3385:30)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async MysqlDriver.connect (/Users/admin/workspace/projects/bff-nestjs/node_modules/.pnpm/[email protected][email protected][email protected][email protected]_ts-node@10.9.2_@types[email protected][email protected]_/node_modules/typeorm/driver/src/driver/mysql/MysqlDriver.ts:398:24)
at async DataSource.initialize (/Users/admin/workspace/projects/bff-nestjs/node_modules/.pnpm/[email protected][email protected][email protected][email protected]_ts-node@10.9.2_@types[email protected][email protected]_/node_modules/typeorm/data-source/src/data-source/DataSource.ts:254:9)

gioboa
gioboa previously requested changes Dec 9, 2025

@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.

Thanks for your help @Missna
Can you add a test to validate this change?

@pkg-pr-new

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

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

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

commit: 4a5af2f

@coveralls

coveralls commented Dec 9, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.87% (+0.001%) from 80.869%
when pulling 4a5af2f on Missna:fix/getVersion
into 35ca51a on typeorm:master.

@OSA413

OSA413 commented Dec 9, 2025

Copy link
Copy Markdown
Collaborator

Can you add a test to validate this change?

A test for PolarDB or for MySQL?

@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.

a test that shows that this fix is solving the issue.
if this was an issue with MySql, let's use it.


UPDATE

I saw your message, it's a PolarDB issue. Anyway, Let's add a test for mysql to validate the correct beaviour.

@pkuczynski pkuczynski changed the title fix: fix get version return undefined fix: get version returning undefined when using PolarDB-X 2.0 Dec 9, 2025
@pkuczynski pkuczynski changed the title fix: get version returning undefined when using PolarDB-X 2.0 fix(mysql): getVersion returning undefined for PolarDB-X 2.0 Dec 9, 2025

@pkuczynski pkuczynski 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.

True, simple test would be useful...

@OSA413

OSA413 commented Dec 10, 2025

Copy link
Copy Markdown
Collaborator

I'm afraid that fixing the version return is not enough to make PolarDBX to work properly with TypeORM, after getting the version it fails at every test saying No database selected.

You can play around with their docker image and see yourself.

(Here was a big message with logs from their container to demonstrate what I'm talking about but docker ate up all the RAM I had before I could send the comment)

@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.

@Missna thanks for opening this PR.
I'm closing this for now because it's stale and without tests, feel free to create a new PR with your improvements. 💪

@gioboa gioboa closed this Jan 7, 2026
@OSA413

OSA413 commented Jan 7, 2026

Copy link
Copy Markdown
Collaborator

Before we go, @Missna can you please test the changes with your environment? I mean, with remote PolarDBX that you are using.

You can install the PR as described here: #11837 (comment)

If that's enough to make PolarDBX working, then I'll try to figure out a test for this PR.

@alumni alumni reopened this Jan 8, 2026
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis ✅

11838 - PR Code Verified

Compliant requirements:

  • Fix the issue where getVersion() returns undefined when using PolarDB-X 2.0
  • Handle the case where SELECT version() returns a column name by using an alias as version
  • Prevent the TypeError by ensuring versionString is properly retrieved from the result

Requires further human verification:

  • Ensure TypeORM can successfully connect to PolarDB-X 2.0 database (requires actual database testing)
  • Verify the fix works with standard MySQL and MariaDB databases (backward compatibility testing)
⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Missing Tests

The PR lacks unit tests to verify that the fix works correctly with PolarDB-X 2.0 and doesn't break existing functionality with standard MySQL and MariaDB databases. Tests should validate that the aliased column name is properly retrieved.

const result: [{ version: string }] = await this.query(
    "SELECT version() as version",
)

// MariaDB: https://mariadb.com/kb/en/version/
// - "10.2.27-MariaDB-10.2.27+maria~jessie-log"

// MySQL: https://dev.mysql.com/doc/refman/8.4/en/information-functions.html#function_version
// - "8.4.3"
// - "8.4.4-standard"

const versionString = result[0]["version"]

return versionString.replace(/^([\d.]+).*$/, "$1")
Backward Compatibility

While adding an alias should work across all MySQL-compatible databases, this change should be verified against standard MySQL and MariaDB to ensure no regression. The column alias approach is the correct solution, but testing is needed to confirm compatibility.

const result: [{ version: string }] = await this.query(
    "SELECT version() as version",
)

@alumni

alumni commented Jan 8, 2026 •

Copy link
Copy Markdown
Collaborator

@OSA413 I would just merge this PR, I don't understand why we requested changes given the fact we have a lot of mysql tests for all these features that are version-specific.

I think this change was anyway what I requested in the PR that fixed the Alibaba-managed MySQL 5.7 (but wasn't implemented and I did not want to insist).

Specifying a column alias is more specific, so it's good to have it, especially since we have experience with MySQL misbehaving.

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Add checks to prevent runtime errors

Add a check to ensure the versionString is valid before use to prevent potential
runtime errors if the database query returns an empty result.

src/driver/mysql/MysqlQueryRunner.ts [3374-3387]

-const result: [{ version: string }] = await this.query(
+const result: { version: string }[] = await this.query(
     "SELECT version() as version",
 )
 
 // MariaDB: https://mariadb.com/kb/en/version/
 // - "10.2.27-MariaDB-10.2.27+maria~jessie-log"
 
 // MySQL: https://dev.mysql.com/doc/refman/8.4/en/information-functions.html#function_version
 // - "8.4.3"
 // - "8.4.4-standard"
 
-const versionString = result[0]["version"]
+const versionString = result?.[0]?.version
+if (!versionString) {
+    throw new TypeORMError("Unable to retrieve database version.")
+}
 
 return versionString.replace(/^([\d.]+).*$/, "$1")
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies a potential runtime error if the database query returns an unexpected result and proposes a robust solution using optional chaining and explicit error handling.

Low
  • More

@alumni
alumni dismissed pkuczynski’s stale review January 8, 2026 01:04

We already have tests. We don't want to add a new test suite for this obscure version.

@alumni
alumni requested a review from OSA413 January 8, 2026 01:35
@alumni
alumni requested a review from gioboa January 8, 2026 01:40
@pkuczynski
pkuczynski dismissed gioboa’s stale review January 8, 2026 09:47

No tests needed according to @alumni

@pkuczynski
pkuczynski merged commit fdcbcba into typeorm:master Jan 8, 2026
37 checks passed
@alumni

alumni commented Jan 8, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the contribution and thanks for merging :)

@Missna

Missna commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Before we go, @Missna can you please test the changes with your environment? I mean, with remote PolarDBX that you are using.

You can install the PR as described here: #11837 (comment)

If that's enough to make PolarDBX working, then I'll try to figure out a test for this PR.

@OSA413 Yes, I have already used it in my project. Before the update, I made modifications using the patch function of pnpm, and it is currently running well

@alumni

alumni commented Jan 8, 2026 •

Copy link
Copy Markdown
Collaborator

BTW, Alibaba's versions of MySQL are known to do crazy things, see also #11553 (PR #11555).

We used to have SELECT version() as `version` in the past, but there were issues with that in Alibaba's AnalyticDB (based on a very old version of MySQL 5.6.16).

I think we can't handle and we can't test all possible custom versions of MySQL out there - especially since Alibaba has a habit of not updating things for a while (experienced the same with Redis while working on their cloud), they don't even release patch updates.

In general, I would report such bugs to Alibaba's services as their behavior is not standard, all we can do here is to make workarounds.

I think the problem with version will be better worked around once we pass a manual override during connection options - this will also allow to improve serverless performance.

@ofir-frd

Copy link
Copy Markdown

/compliance

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

Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #11838
🟢 Fix the issue where MysqlQueryRunner.getVersion() returns undefined when using PolarDB-X
2.0 compatible with MySQL 8.0
Handle the case where the SELECT version() statement returns a column name of uppercase
VERSION() instead of lowercase version()
Prevent the TypeError "Cannot read properties of undefined (reading 'replace')" that
occurs during database connection initialization
⚪ Ensure TypeORM can successfully connect to PolarDB-X 2.0 distributed database
Codebase Duplication Compliance
⚪
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

⚪
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Missing null check: The code accesses result[0]["version"] without validating that result is
non-empty or that the version property exists.

Referred Code
const versionString = result[0]["version"]

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
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.

7 participants