Skip to content

feat: add support for installing additional postgres extensions - #11888

Merged
gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:feat/install-postgres-extensions
Jan 10, 2026
Merged

gioboa merged 3 commits into
typeorm:masterfrom
Cprakhar:feat/install-postgres-extensions

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 3, 2026

Copy link
Copy Markdown
Collaborator

Description of change

This PR addresses #7584 to introduces the functionality to install additional Postgres extensions during connection setup. Verify changes through updated tests for custom extension installation. Documentation reflects the new extension options.

Pull-Request Checklist

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

@pkg-pr-new

pkg-pr-new Bot commented Jan 3, 2026 •

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

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

commit: 4e371bb

@alumni
alumni requested a review from naorpeled January 3, 2026 12:21
@coveralls

coveralls commented Jan 3, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.885% (-0.006%) from 80.891%
when pulling 4e371bb on Cprakhar:feat/install-postgres-extensions
into db2369c on typeorm:master.

@Cprakhar
Cprakhar force-pushed the feat/install-postgres-extensions branch from fcbb35f to 4152040 Compare January 7, 2026 15:31
@Cprakhar
Cprakhar marked this pull request as ready for review January 7, 2026 16:12
@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 ✅

7584 - PR Code Verified

Compliant requirements:

  • Provide an option to add additional postgres extensions when connecting to a database
  • Extensions should be configurable via an array of strings in the connection configuration
  • Extensions should be installed at the same time as other built-in extensions (like uuid-ossp)
  • Should work with development workflows using synchronize
  • Should ensure necessary database features are enabled automatically

Requires further human verification:

  • Verify that the extension installation works correctly in actual PostgreSQL environments with various extension types
  • Test the behavior when extensions require superuser privileges
  • Validate the warning messages are displayed appropriately in different scenarios
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 Security concerns

SQL injection:
The extension names from the extensions configuration option are directly interpolated into SQL queries using template literals (line 597: CREATE EXTENSION IF NOT EXISTS "${extension}"). While PostgreSQL identifiers are quoted, there's no validation that the extension name is a valid identifier or doesn't contain malicious characters. An attacker who can control the configuration could potentially inject SQL by crafting extension names that break out of the quoted context or exploit PostgreSQL-specific syntax. Extension names should be validated against a whitelist pattern (e.g., alphanumeric and underscores only) before being used in SQL queries.

⚡ Recommended focus areas for review

SQL Injection Risk

Extension names from user configuration are directly interpolated into SQL queries without validation or sanitization. Malicious extension names could potentially break out of the quoted identifier context.

    `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
)
Error Handling

The catch block uses an empty catch with underscore parameter, silently swallowing all errors. This makes debugging difficult and could hide important error information beyond just permission issues.

} catch (_) {
    logger.log(
        "warn",
        `The '${extension}' extension cannot be installed automatically. Please install it manually using superuser rights`,
    )
}
Logic Issue

The condition checks if availableExtensions.size > 0 before validating extension availability, but an empty set would bypass validation entirely. This could lead to attempting to install extensions without proper checking.

if (
    availableExtensions &&
    availableExtensions.size > 0 &&
    !availableExtensions.has(extension)
) {

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 4e371bb

CategorySuggestion                                                                                                                                    Impact
Security
Validate extension names to prevent SQL injection

Validate the extension name using a regex before interpolating it into the
CREATE EXTENSION query to prevent potential SQL injection vulnerabilities.

src/driver/postgres/PostgresDriver.ts [578-605]

 protected async enableCustomExtensions(
     availableExtensions: Set<string>,
     extensionsToInstall: string[],
     connection: any,
 ) {
     if (!extensionsToInstall) return
     const logger = this.connection.logger
     for (const extension of extensionsToInstall) {
+        // Validate extension name to prevent SQL injection
+        if (!/^[a-zA-Z0-9_]+$/.test(extension)) {
+            logger.log(
+                "warn",
+                `Invalid extension name "${extension}". Extension names must contain only alphanumeric characters and underscores.`,
+            )
+            continue
+        }
         if (availableExtensions.has(extension)) {
             try {
                 await this.executeQuery(
                     connection,
                     `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
                 )
             } catch (_) {
                 logger.log(
                     "warn",
                     `The extension "${extension}" cannot be installed automatically. Please install it manually using superuser rights`,
                 )
             }
         } else {
             logger.log(
                 "warn",
                 `The extension "${extension}" is not available on this database. Please install it manually using superuser rights`,
             )
         }
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability by directly using a user-configured string in a query and proposes a valid fix by sanitizing the input, which is a critical security enhancement.

High
  • More

Previous suggestions

Suggestions up to commit e6c8f22
CategorySuggestion                                                                                                                                    Impact
Security
Prevent SQL injection in extension names

Sanitize the extension name before using it in the CREATE EXTENSION query to
prevent potential SQL injection vulnerabilities.

src/driver/postgres/PostgresDriver.ts [578-605]

 protected async enableCustomExtensions(
     availableExtensions: Set<string>,
     extensionsToInstall: string[],
     connection: any,
 ) {
     if (!extensionsToInstall) return
     const logger = this.connection.logger
     for (const extension of extensionsToInstall) {
+        // Validate extension name to prevent SQL injection
+        if (!/^[a-zA-Z0-9_]+$/.test(extension)) {
+            logger.log(
+                "warn",
+                `Invalid extension name "${extension}". Extension names must contain only alphanumeric characters and underscores.`,
+            )
+            continue
+        }
         if (availableExtensions.has(extension)) {
             try {
                 await this.executeQuery(
                     connection,
                     `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
                 )
             } catch (_) {
                 logger.log(
                     "warn",
                     `The extension "${extension}" cannot be installed automatically. Please install it manually using superuser rights`,
                 )
             }
         } else {
             logger.log(
                 "warn",
                 `The extension "${extension}" is not available on this database. Please install it manually using superuser rights`,
             )
         }
     }
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential security vulnerability where an unsanitized string from connection options is used in a raw query, and provides a valid fix to harden the code.

Medium
General
Avoid unnecessary database query for extensions

Avoid an unnecessary database query by checking if extensionsToInstall is not
empty before calling getAvailableExtensions.

src/driver/postgres/PostgresDriver.ts [413-429]

 if (installExtensions) {
     const extensionsMetadata = await this.checkMetadataForExtensions()
     const extensionsToInstall = this.options.extensions
     if (extensionsMetadata.hasExtensions)
         await this.enableExtensions(extensionsMetadata, connection)
 
-    if (extensionsToInstall) {
+    if (extensionsToInstall && extensionsToInstall.length > 0) {
         const availableExtensions =
             await this.getAvailableExtensions(connection)
 
         await this.enableCustomExtensions(
             availableExtensions,
             extensionsToInstall,
             connection,
         )
     }
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out an unnecessary database call and proposes a valid optimization by adding a length check, improving performance when extensions is an empty array.

Low
Suggestions up to commit 95024d1
CategorySuggestion                                                                                                                                    Impact
Security
Prevent SQL injection vulnerability

Prevent a potential SQL injection vulnerability by properly escaping the
extension variable before using it in the CREATE EXTENSION query.

src/driver/postgres/PostgresDriver.ts [588-591]

 await this.executeQuery(
     connection,
-    `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
+    `CREATE EXTENSION IF NOT EXISTS ${connection.escapeIdentifier(extension)}`,
 )
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability by using an unescaped variable in a raw query. While the proposed fix using connection.escapeIdentifier is not a valid method on the connection object, it highlights a critical security flaw that should be addressed, making it a high-impact suggestion.

Medium
General
Log error details for debugging

In the catch block of getAvailableExtensions, log the actual error details
instead of a generic warning message to improve debuggability of database
connectivity or permission issues.

src/driver/postgres/PostgresDriver.ts [452-457]

-} catch (_) {
+} catch (error) {
     logger.log(
         "warn",
-        "Could not retrieve available extensions. Extension installation may fail if extensions are not available.",
+        `Could not retrieve available extensions: ${error.message}. Extension installation may fail if extensions are not available.`,
     )
 }
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that swallowing the error details makes debugging harder. Logging the error message would significantly improve the developer experience when troubleshooting issues with extension installation, such as permission errors.

Low
Remove redundant null check

Remove the redundant if (!extensionsToInstall) return check from the
enableCustomExtensions method, as it is already guaranteed to be truthy by the
calling code in afterConnect.

src/driver/postgres/PostgresDriver.ts [578-583]

 protected async enableCustomExtensions(
     availableExtensions: Set<string>,
     extensionsToInstall: string[],
     connection: any,
 ) {
-    if (!extensionsToInstall) return
Suggestion importance[1-10]: 3

__

Why: The suggestion correctly points out a redundant null check. Removing it would be a minor code quality improvement, but the check also makes the method safer for future use in other contexts, so its removal has low impact.

Low
Suggestions up to commit 9a21895
CategorySuggestion                                                                                                                                    Impact
Security
Prevent SQL injection in extension installation

Escape the extension variable before using it in the CREATE EXTENSION query to
prevent a potential SQL injection vulnerability.

src/driver/postgres/PostgresDriver.ts [580-606]

 if (extensionsToInstall && extensionsToInstall.length > 0) {
     for (const extension of extensionsToInstall) {
         if (
             availableExtensions &&
             availableExtensions.size > 0 &&
             !availableExtensions.has(extension)
         ) {
             logger.log(
                 "warn",
                 `Extension '${extension}' is not available in your PostgreSQL installation. Please check the extension name or install it using superuser rights.`,
             )
             continue
         }
 
         try {
+            // Escape double quotes to prevent SQL injection.
+            const escapedExtension = extension.replace(/"/g, '""')
             await this.executeQuery(
                 connection,
-                `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
+                `CREATE EXTENSION IF NOT EXISTS "${escapedExtension}"`,
             )
         } catch (_) {
             logger.log(
                 "warn",
                 `The '${extension}' extension cannot be installed automatically. Please install it manually using superuser rights`,
             )
         }
     }
 }
Suggestion importance[1-10]: 10

__

Why: The suggestion correctly identifies a critical SQL injection vulnerability in the newly added code and provides an accurate and effective solution to prevent it.

High

@gioboa
gioboa requested review from G0maa and alumni January 7, 2026 21:59
Comment thread src/driver/postgres/PostgresDriver.ts Resolved
Comment thread src/driver/postgres/PostgresDriver.ts Resolved

@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 @Cprakhar
I added few comments

@Cprakhar
Cprakhar force-pushed the feat/install-postgres-extensions branch from 9a21895 to 95024d1 Compare January 9, 2026 16:52
@Cprakhar
Cprakhar force-pushed the feat/install-postgres-extensions branch from 95024d1 to e6c8f22 Compare January 9, 2026 17:00

@G0maa G0maa 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 contribution, looks good to me!

@G0maa
G0maa requested a review from gioboa January 10, 2026 18:09

@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 this awesome improvement @Cprakhar 🚀

@gioboa gioboa linked an issue Jan 10, 2026 that may be closed by this pull request
3 of 21 tasks
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

🐞 Bugs (0) 📘 Rule Violations (2) 📎 Requirement Gaps (0) 💡 Suggestions (0)

Grey Divider


Action Required

1. SQL injection risk in extension names 📘 Rule Violation
Description
• User-provided extension names from this.options.extensions are directly interpolated into SQL
  queries without validation or sanitization.
• Malicious extension names could contain SQL injection payloads like "; DROP TABLE users; --.
• While double quotes provide some protection, they don't prevent all injection vectors and the code
  lacks explicit input validation.

security

Code

src/driver/postgres/PostgresDriver.ts[R588-591]

+                    await this.executeQuery(
+                        connection,
+                        `CREATE EXTENSION IF NOT EXISTS "${extension}"`,
+                    )
Evidence
The compliance checklist requires that all external inputs are validated and sanitized to prevent
injection vulnerabilities. The extensions array comes from user configuration
(PostgresConnectionOptions) and is directly interpolated into SQL at line 590 using template
literals. While the existing code uses double quotes around extension names, there's no explicit
validation to ensure extension names contain only safe characters (alphanumeric, underscore,
hyphen). This creates a potential SQL injection vector.

Rule 6: Generic: Security-First Input Validation and Data Handling
src/driver/postgres/PostgresConnectionOptions.ts[104-107]
src/driver/postgres/PostgresDriver.ts[588-591]

Agent Prompt
## Issue description
User-provided extension names are directly interpolated into SQL queries without validation, creating a potential SQL injection vulnerability.

## Issue Context
The `extensions` configuration option accepts an array of strings from user configuration. These strings are used directly in CREATE EXTENSION SQL statements. While PostgreSQL identifiers have restrictions, the code should explicitly validate inputs to prevent injection attacks.

## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[585-591]
- src/driver/postgres/PostgresDriver.ts[415-415]

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



Remediation Recommended

2. Error details swallowed in catch blocks 📘 Rule Violation
Description
• The catch blocks at lines 452, 592 in enableCustomExtensions and getAvailableExtensions
  methods discard error details by using catch (_), preventing proper debugging and monitoring.
• This violates the requirement for error messages to provide actionable context about what failed
  and why.
• Without logging error details, production debugging becomes difficult when extension installation
  fails.

reliability

Code

src/driver/postgres/PostgresDriver.ts[R452-457]

+        } catch (_) {
+            logger.log(
+                "warn",
+                "Could not retrieve available extensions. Extension installation may fail if extensions are not available.",
+            )
+        }
Evidence
The compliance rule requires that errors include relevant variable values and operation context for
production debugging. The code catches errors but discards them with catch (_), only logging
generic warning messages without the actual error details. This pattern appears in both
getAvailableExtensions (line 452) and enableCustomExtensions (line 592), making it impossible to
diagnose why extension queries or installations fail.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/driver/postgres/PostgresDriver.ts[452-457]
src/driver/postgres/PostgresDriver.ts[592-597]

Agent Prompt
## Issue description
The catch blocks discard error details by using `catch (_)`, preventing proper debugging when extension operations fail.

## Issue Context
When extension queries or installations fail, developers need the actual error details (error message, stack trace, error code) to diagnose issues in production. The current implementation only logs generic warnings without the underlying error information.

## Fix Focus Areas
- src/driver/postgres/PostgresDriver.ts[452-457]
- src/driver/postgres/PostgresDriver.ts[592-597]

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


Grey Divider

Qodo Logo

@gioboa
gioboa merged commit fbb625b into typeorm:master Jan 10, 2026
38 checks passed
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
@Cprakhar
Cprakhar deleted the feat/install-postgres-extensions branch January 24, 2026 20:08
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

Development

Successfully merging this pull request may close these issues.

Allow configurable postgres extensions

5 participants