Skip to content

fix(sqlite): handle simple-enum arrays correctly - #11865

Merged
gioboa merged 4 commits into
typeorm:masterfrom
Cprakhar:fix/sqlite-simple-enum-array
Jan 15, 2026
Merged

gioboa merged 4 commits into
typeorm:masterfrom
Cprakhar:fix/sqlite-simple-enum-array

Conversation

@Cprakhar

Copy link
Copy Markdown
Collaborator

Description of change

This PR fixes issue #6326 where SQLite simple-enum columns with array: true were failing with CHECK constraint errors.

Problem:

SQLite doesn't support native array types, so TypeORM stores simple-enum arrays as comma-separated strings (e.g., "0,1"). However, the existing implementation had three issues:

  • CHECK constraints were validating against single enum values - The generated CHECK constraint was CHECK ("roles" IN ('0','1','2')), which fails when the stored value is a comma-separated string like '0,1'
  • Array default values weren't properly quoted - Default values like [NumericEnum.GHOST, NumericEnum.ADMIN] were converted to unquoted 3,0 in SQL, causing syntax errors instead of the required '3,0'
  • Array values weren't being converted during hydration - Values stored as '3,0' were being returned as strings instead of arrays like [3, 0]

Solution:

  • Skip CHECK constraint generation for array columns in AbstractSqliteQueryRunner.buildCreateColumnSql() since the comma-separated string format makes validation impossible
  • Properly quote array default values in AbstractSqliteDriver.normalizeDefault()
  • Update DateUtils.simpleEnumToString() to join array values with commas
  • Update DateUtils.stringToSimpleEnum() to split comma-separated strings back into arrays and convert numeric enum values appropriately

Verification:

  • All existing tests in enums-array.test.ts now pass
  • Tests cover creating default values and saving/retrieving arrays with various enum types (numeric, string, heterogeneous)
  • Tested with both sqlite and better-sqlite3 drivers

Pull-Request Checklist

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

Fixes #6326

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

6326 - PR Code Verified

Compliant requirements:

  • Fix CHECK constraint failure when using simple-enum arrays with SQLite
  • Support storing and retrieving simple-enum arrays
  • Handle comma-separated string storage format for arrays in SQLite
  • Allow multiple enum values in the roles array

Requires further human verification:

  • Verify that existing data with simple-enum arrays can be properly migrated
  • Test with actual SQLite 3.22.0 version mentioned in the ticket
  • Validate that the fix works with the exact entity and enum structure from the ticket
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Empty String Handling

The code returns an empty array for empty strings, but doesn't handle the case where the database might store NULL or undefined for empty arrays. Consider if value === "" check is sufficient or if additional null/undefined checks are needed before the split operation.

if (columnMetadata.isArray && typeof value === "string") {
    if (value === "") {
        return []
    }
Condition Logic

The condition column.enum && !column.isArray skips CHECK constraint for arrays, but doesn't verify if the column type is actually 'simple-enum'. This could potentially skip CHECK constraints for non-simple-enum array columns that have enum property set.

if (column.enum && !column.isArray)
    c +=

@pkg-pr-new

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

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

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

commit: f37ce10

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to f37ce10

CategorySuggestion                                                                                                                                    Impact
Security
Sanitize array elements before SQL insertion

In normalizeDefault, sanitize elements of the defaultValue array by escaping
single quotes before joining them to prevent generating invalid SQL for
simple-enum columns.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const sanitizedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${sanitizedValues.join(",")}'`
 }
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a bug in the new code where an enum's default value containing a single quote would generate invalid SQL, and the proposed fix is accurate.

Medium
  • More

Previous suggestions

Suggestions up to commit b9c5130
CategorySuggestion                                                                                                                                    Impact
Security
Escape single quotes in array values

Sanitize array elements for simple-enum default values by escaping single quotes
before joining them to prevent potential SQL injection.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const sanitizedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${sanitizedValues.join(",")}'`
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability in the newly added code for handling simple-enum array default values and provides a valid fix.

High
General
Trim whitespace from split enum values

Add trim() to each item after splitting the enum string by commas to handle
potential leading or trailing whitespace.

src/util/DateUtils.ts [273-281]

 if (columnMetadata.isArray && typeof value === "string") {
     if (value === "") {
         return []
     }
 
     return value
         .split(",")
-        .map((item) => this.parseEnumValue(item, columnMetadata.enum!))
+        .map((item) => this.parseEnumValue(item.trim(), columnMetadata.enum!))
 }
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly proposes trimming whitespace from split enum values, which makes the parsing more robust against common formatting issues.

Low
Suggestions up to commit 922415e
CategorySuggestion                                                                                                                                    Impact
Security
Sanitize enum array elements

Sanitize default enum array values by escaping single quotes to prevent SQL
syntax errors.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const sanitizedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${sanitizedValues.join(",")}'`
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that if a default enum value contains a single quote, it will break the generated SQL syntax, and proposes a valid fix by escaping the quotes.

Medium
Suggestions up to commit 40dbc32
CategorySuggestion                                                                                                                                    Impact
Security
Escape special characters in enum values

Escape single quotes in enum array default values to prevent potential SQL
injection vulnerabilities.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const escapedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${escapedValues.join(",")}'`
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability. If an enum defaultValue contains a single quote, it will break the SQL string literal, and the proposed fix of escaping single quotes is the correct way to prevent this.

Medium
Possible issue
Handle commas in enum values

Address the edge case where enum values contain commas, as the current
split(',') implementation will lead to incorrect parsing and data corruption.

src/util/DateUtils.ts [269-283]

 if (columnMetadata.isArray && typeof value === "string") {
     if (value === "") {
         return []
     }
+    // Note: This assumes enum values don't contain commas
+    // Consider using a different delimiter or escaping mechanism
     return value.split(",").map((v: string): string | number => {
         if (
             columnMetadata.enum &&
             !isNaN(v as any) &&
             columnMetadata.enum.indexOf(parseInt(v)) >= 0
         ) {
             return parseInt(v)
         }
         return v
     })
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a significant flaw in the serialization logic where enum values containing commas would be corrupted. While the improved_code only adds a comment, it highlights a critical edge case that the PR author should address for a robust implementation.

Medium
Suggestions
CategorySuggestion                                                                                                                                    Impact
Security
Escape quotes in enum values

Escape single quotes in simple-enum array default values to prevent SQL
injection.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const escapedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${escapedValues.join(",")}'`
 }
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability if an enum's default value contains a single quote and provides the standard SQL fix, which is crucial for security.

High
General
Trim whitespace from parsed values

Trim whitespace from values when parsing a comma-separated string for an enum
array to handle formatting variations.

src/util/DateUtils.ts [269-283]

 if (columnMetadata.isArray && typeof value === "string") {
     if (value === "") {
         return []
     }
     return value.split(",").map((v: string): string | number => {
+        const trimmed = v.trim()
         if (
             columnMetadata.enum &&
-            !isNaN(v as any) &&
-            columnMetadata.enum.indexOf(parseInt(v)) >= 0
+            !isNaN(trimmed as any) &&
+            columnMetadata.enum.indexOf(parseInt(trimmed)) >= 0
         ) {
-            return parseInt(v)
+            return parseInt(trimmed)
         }
-        return v
+        return trimmed
     })
 }
Suggestion importance[1-10]: 6

__

Why: This suggestion improves the robustness of parsing the stored enum array string by handling potential whitespace, preventing subtle bugs and ensuring data is correctly hydrated.

Low

@coveralls

coveralls commented Dec 21, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.889% (+0.003%) from 80.886%
when pulling f37ce10 on Cprakhar:fix/sqlite-simple-enum-array
into 65dea3c on typeorm:master.

@naorpeled
naorpeled requested review from alumni and gioboa December 21, 2025 16:42

@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 it looks great to me 👏

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

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

Copy link
Copy Markdown

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Impact
Security
Escape quotes in enum values

Escape single quotes in simple-enum array default values to prevent SQL
injection.

src/driver/sqlite-abstract/AbstractSqliteDriver.ts [672-677]

 if (
     Array.isArray(defaultValue) &&
     columnMetadata.type === "simple-enum"
 ) {
-    return `'${defaultValue.join(",")}'`
+    const escapedValues = defaultValue.map(v => 
+        String(v).replace(/'/g, "''")
+    )
+    return `'${escapedValues.join(",")}'`
 }
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential SQL injection vulnerability if an enum's default value contains a single quote and provides the standard SQL fix, which is crucial for security.

High
General
Trim whitespace from parsed values

Trim whitespace from values when parsing a comma-separated string for an enum
array to handle formatting variations.

src/util/DateUtils.ts [269-283]

 if (columnMetadata.isArray && typeof value === "string") {
     if (value === "") {
         return []
     }
     return value.split(",").map((v: string): string | number => {
+        const trimmed = v.trim()
         if (
             columnMetadata.enum &&
-            !isNaN(v as any) &&
-            columnMetadata.enum.indexOf(parseInt(v)) >= 0
+            !isNaN(trimmed as any) &&
+            columnMetadata.enum.indexOf(parseInt(trimmed)) >= 0
         ) {
-            return parseInt(v)
+            return parseInt(trimmed)
         }
-        return v
+        return trimmed
     })
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: This suggestion improves the robustness of parsing the stored enum array string by handling potential whitespace, preventing subtle bugs and ensuring data is correctly hydrated.

Low
  • More

@gioboa
gioboa requested review from G0maa and naorpeled December 25, 2025 10:12
@Cprakhar
Cprakhar force-pushed the fix/sqlite-simple-enum-array branch from 1c3c142 to 40dbc32 Compare January 7, 2026 16:52
Comment thread src/util/DateUtils.ts Resolved
@Cprakhar
Cprakhar force-pushed the fix/sqlite-simple-enum-array branch from 922415e to b9c5130 Compare January 9, 2026 09:01
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Code Review by Qodo (Alpha)

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

Grey Divider


Action Required

1. Missing Quote Escaping in CHECK Constraint 🐞 Bug
Description
• The CHECK constraint generation does not escape single quotes in enum values, producing invalid
  SQL syntax
• When enum values contain apostrophes, the generated CHECK constraint will fail to create the table
• This affects all simple-enum columns in SQLite, not just arrays (arrays are now correctly excluded
  from CHECK constraints)

correctness

Code

src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts[R1954-1957]

+        if (column.enum && !column.isArray)
            c +=
                ' CHECK( "' +
                column.name +
Evidence
The CHECK constraint generation concatenates enum values with simple string wrapping without
escaping quotes. PostgreSQL uses the same escaping pattern (replaceAll) for enum type creation. Test
cases demonstrate that enum values with quotes are legitimate use cases.

src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts[1954-1960]
src/driver/postgres/PostgresQueryRunner.ts[4402-4404]
test/github-issues/10955/entity/FooWithSpecialChars.ts[3-7]

Agent Prompt
## Issue Description
The buildCreateColumnSql method in AbstractSqliteQueryRunner.ts does not escape single quotes when generating CHECK constraints for enum columns. This causes SQL syntax errors when enum values contain apostrophes.

## Issue Context
When an enum with value "user's choice" is used, the current code generates: `CHECK( "column" IN ('user's choice') )` which is invalid SQL. It should generate: `CHECK( "column" IN ('user''s choice') )` with escaped quotes.

PostgreSQL driver uses the same escaping pattern with replaceAll("'", "''") as shown in PostgresQueryRunner.ts line 4403.

## Fix Focus Areas
- src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts[1959-1959] - Add quote escaping in the enum value mapping function

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



Remediation Recommended

2. `defaultValue.join(",")` lacks SQL escaping 📘 Rule Violation
Description
• The code directly joins array values with commas and wraps them in single quotes without escaping
  special characters like quotes or commas within the enum values themselves
• If an enum value contains a single quote (e.g., "O'Brien"), it could break the SQL syntax or
  potentially enable SQL injection
• While the test cases use simple alphanumeric values, the code doesn't validate or sanitize the
  enum values before concatenation

security

Code

src/driver/sqlite-abstract/AbstractSqliteDriver.ts[676]

+            return `'${defaultValue.join(",")}'`
Evidence
The compliance checklist requires proper input validation and sanitization to prevent injection
vulnerabilities (PR Compliance ID 6). The code at line 676 directly concatenates enum values without
escaping, which could lead to SQL syntax errors or injection if enum values contain special
characters. The same pattern appears in line 1959 of AbstractSqliteQueryRunner.ts where enum values
are wrapped in quotes without escaping.

Rule 6: Generic: Security-First Input Validation and Data Handling
src/driver/sqlite-abstract/AbstractSqliteDriver.ts[676-676]
src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts[1959-1959]

Agent Prompt
## Issue description
The code directly concatenates enum values into SQL strings without escaping special characters, which could cause SQL syntax errors or potential injection vulnerabilities if enum values contain single quotes or other special characters.

## Issue Context
SQLite uses single quotes for string literals, and single quotes within strings must be escaped by doubling them (e.g., `'O''Brien'`). The current implementation doesn't handle this case.

## Fix Focus Areas
- src/driver/sqlite-abstract/AbstractSqliteDriver.ts[676-676]
- src/driver/sqlite-abstract/AbstractSqliteQueryRunner.ts[1959-1959]

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


3. `parseEnumValue` missing null/undefined validation 📘 Rule Violation
Description
• The parseEnumValue method doesn't validate if the input value or enumValues parameters are
  null or undefined before processing
• Calling Number(value) on null/undefined will return 0 or NaN, which could lead to incorrect enum
  value matching
• The method could incorrectly convert null/undefined to numeric values if 0 exists in the enum

reliability

Code

src/util/DateUtils.ts[R293-298]

+    private static parseEnumValue(value: any, enumValues: any[]): string | any {
+        const parsedValue = Number(value)
+        return !isNaN(parsedValue) && enumValues.includes(parsedValue)
+            ? parsedValue
+            : value
+    }
Evidence
The compliance checklist requires explicit handling of edge cases including null and empty values
(PR Compliance ID 3). The parseEnumValue method at lines 293-298 doesn't validate its inputs before
processing, which could lead to incorrect behavior when null or undefined values are passed.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/util/DateUtils.ts[293-298]

Agent Prompt
## Issue description
The parseEnumValue method doesn't validate null or undefined inputs, which could lead to incorrect enum value conversion when these edge cases occur.

## Issue Context
The method is called from stringToSimpleEnum which splits comma-separated strings. Empty strings or malformed data could result in null/undefined values being passed to parseEnumValue.

## Fix Focus Areas
- src/util/DateUtils.ts[293-298]

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


4. `stringToSimpleEnum` empty string handling inconsistent 📘 Rule Violation
Description
• The method returns an empty array for empty strings when isArray is true (line 275), but doesn't
  handle the case where the string contains only whitespace or invalid delimiters
• The split(",") operation on strings like " " or ",,," will produce arrays with empty string
  elements that get passed to parseEnumValue
• This could result in unexpected enum values or type conversion issues

reliability

Code

src/util/DateUtils.ts[R273-281]

+        if (columnMetadata.isArray && typeof value === "string") {
+            if (value === "") {
+                return []
+            }
+
+            return value
+                .split(",")
+                .map((item) => this.parseEnumValue(item, columnMetadata.enum!))
+        }
Evidence
The compliance checklist requires explicit handling of edge cases including empty and boundary
values (PR Compliance ID 3). The stringToSimpleEnum method handles the empty string case but doesn't
account for malformed input like whitespace-only strings or multiple consecutive commas, which could
lead to unexpected behavior.

Rule 3: Generic: Robust Error Handling and Edge Case Management
src/util/DateUtils.ts[273-281]

Agent Prompt
## Issue description
The stringToSimpleEnum method doesn't handle malformed comma-separated strings that may contain empty elements or whitespace, which could lead to unexpected enum values.

## Issue Context
When splitting strings like `"1,,2"` or `"1, 2"` (with spaces), the resulting array will contain empty strings or strings with whitespace that should be filtered or trimmed.

## Fix Focus Areas
- src/util/DateUtils.ts[278-280]

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


Grey Divider

Qodo Logo

@gioboa
gioboa merged commit 73227bc into typeorm:master Jan 15, 2026
68 of 71 checks passed
@Cprakhar
Cprakhar deleted the fix/sqlite-simple-enum-array branch January 24, 2026 20:10
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.

CHECK constraint failed with SQLite and simple-enum array

5 participants