You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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)
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.
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.
In normalizeDefault, sanitize elements of the defaultValue array by escaping single quotes before joining them to prevent generating invalid SQL for simple-enum columns.
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.
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.
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.
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.
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.
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
Category
Suggestion
Impact
Security
Escape quotes in enum values
Escape single quotes in simple-enum array default values to prevent SQL injection.
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.
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.
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.
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.
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)
+ 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.
## 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
• 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
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.
## 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
• 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
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.
## 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
• 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
+ 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.
## 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
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 ("roles" IN ('0','1','2')), which fails when the stored value is a comma-separated string like'0,1'3,0in SQL, causing syntax errors instead of the required'3,0''3,0'were being returned as strings instead of arrays like[3, 0]Solution:
AbstractSqliteQueryRunner.buildCreateColumnSql()since the comma-separated string format makes validation impossibleAbstractSqliteDriver.normalizeDefault()DateUtils.simpleEnumToString()to join array values with commasDateUtils.stringToSimpleEnum()to split comma-separated strings back into arrays and convert numeric enum values appropriatelyVerification:
Pull-Request Checklist
Fixes #6326Fixes #6326