Repository navigation
fix(migration): import CSV values exactly or fail before writing - #15516
HarshMN2345 wants to merge 7 commits into
Conversation
…type Strip a UTF-8 BOM from the header, reject invalid UTF-8 rows, report the row number, and treat empty enum/email/url/ip cells as null.
|
Review complete. 🟠 1 high · 🟡 2 medium 💬 Inline comments (3)
🧹 Nitpicks (3) — 🟢 3 low
This PR refactors the CSV migration source's value parsing: cells now flow through a shared
Reviewed commit: 190f0dc |
190f0dc to
471ee86
Compare
🔵 Tier A · Mergeable after minor fixes
CSV migration imports now preserve quoted values, strip a UTF-8 BOM, validate typed cells with row context, and preflight records before sending batches. CSV exports distinguish null from literal Latest changes: The newest commits add a full CSV validation pass before callbacks, improve quoting and null round-tripping in CSV exports, and defer Appwrite row status counters until each buffered batch has been written.
Note Not approving while a bug finding is open: Accept decimal integers with leading zeros
Fix with agent prompt### Issue 1
packages/migration/src/Sources/CSV.php:275-276
**Add regression coverage for CSV source imports**
The existing `CSVTest` exercises export and delimiter detection but does not drive `Sources\CSV` through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.
### Issue 2
packages/migration/src/Sources/CSV.php:421
**Accept decimal integers with leading zeros**
`FILTER_VALIDATE_INT` rejects decimal strings such as `0012` (confirmed with a direct `php -r` check), even though they are valid whole numbers and the previous `is_numeric`/cast path imported them as `12`. A CSV with such a cell now aborts the import.
### Issue 3
packages/migration/src/Sources/CSV.php:422
**Reject float values that overflow to infinity**
`is_numeric('1e9999')` is true, but casting it to float produces `INF` (confirmed with a direct `php -r` check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 4
⏳ Still open from earlier reviews · 2
🔇 Filtered out · 1Findings Hansi considered but did not post.
Merged |
| } | ||
|
|
||
| $parsed = match ($type) { | ||
| Column::TYPE_INTEGER, Column::TYPE_BIG_INT => \filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE), |
There was a problem hiding this comment.
Accept decimal integers with leading zeros
FILTER_VALIDATE_INT rejects decimal strings such as 0012 (confirmed with a direct php -r check), even though they are valid whole numbers and the previous is_numeric/cast path imported them as 12. A CSV with such a cell now aborts the import.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 421
Comment:
**Accept decimal integers with leading zeros**
`FILTER_VALIDATE_INT` rejects decimal strings such as `0012` (confirmed with a direct `php -r` check), even though they are valid whole numbers and the previous `is_numeric`/cast path imported them as `12`. A CSV with such a cell now aborts the import.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
|
|
||
| $parsed = match ($type) { | ||
| Column::TYPE_INTEGER, Column::TYPE_BIG_INT => \filter_var($value, FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE), | ||
| Column::TYPE_FLOAT => \is_numeric($value) ? (float)$value : null, |
There was a problem hiding this comment.
Reject float values that overflow to infinity
is_numeric('1e9999') is true, but casting it to float produces INF (confirmed with a direct php -r check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 422
Comment:
**Reject float values that overflow to infinity**
`is_numeric('1e9999')` is true, but casting it to float produces `INF` (confirmed with a direct `php -r` check), so this path accepts a value that cannot be represented as a finite double. It then reaches destination serialization or validation instead of failing here with the row-specific parsing error.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
There was a problem hiding this comment.
Reworks CSV migration value parsing with stricter validation but breaks valid JSON/structured array elements, leaving one formatKeys branch dead and adding two hygiene issues.
Key findings
- 🟠
parseValuerejects valid JSON array elements — CSV.php:344 - 🟡
formatKeysnever populated:is_arrayguard fails on Document columns — CSV.php:231 - 🟡 Array string items silently trimmed, breaking round-trip — CSV.php:345
| $parsedData[$key] = \array_map( | ||
| fn ($item) => $this->parseValue(\is_string($item) ? \trim($item) : $item, \is_string($type) ? $type : '', $key, $line), | ||
| $arrayValues | ||
| ); |
There was a problem hiding this comment.
🟠 bug · high
parseValue rejects valid JSON array elements
Array columns now route every element through parseValue (packages/migration/src/Sources/CSV.php:344-347). JSON false elements are stringified to "" and rejected by the boolean arm; JSON null, nested arrays, and objects are coerced to null and hit the invalid value throw (packages/migration/src/Sources/CSV.php:416-435). The removed mapper used default => $item and a raw filter_var call, so these payloads previously imported correctly. Importing a CSV whose array column contains e.g. [true,false] or ["a", null, "b"] now aborts the entire row with a validation error on values that are valid for the column.
📋 Prompt for AI Agents
In packages/migration/src/Sources/CSV.php around lines 344-347, change the array_map callback so it only invokes $this->parseValue(...) for scalar non-boolean items: booleans should be returned directly (they are valid for TYPE_BOOLEAN), and nested arrays, objects, and explicit JSON null elements should pass through unchanged — the behavior the removed default => $item mapping provided. Concretely: fn ($item) => \is_bool($item) ? $item : (\is_scalar($item) ? $this->parseValue(\is_string($item) ? $item : (string)$item, \is_string($type) ? $type : '', $key, $line) : $item). Without this, [true,false] throws (because (string)false === "" fails FILTER_VALIDATE_BOOLEAN) and [null] / nested JSON elements abort the whole row with a CODE_VALIDATION exception.
| foreach ($columns as $column) { | ||
| $key = $column['key']; | ||
| $type = $column['type']; | ||
| $format = \is_array($column) && \is_string($column['format'] ?? null) ? $column['format'] : ''; |
There was a problem hiding this comment.
🟡 bug · medium
formatKeys never populated: is_array guard fails on Document columns
The new format detection reads format only when \is_array($column) (packages/migration/src/Sources/CSV.php:231), but columns come from $this->database->listColumns(), which returns Utopia\Database\Document objects (an ArrayObject subclass, not PHP arrays) from find('attributes', ...) (packages/migration/src/Sources/Appwrite/Reader/Database.php:251). The sibling $key and $type reads at lines 229-230 use ArrayAccess with no is_array guard, confirming the runtime shape. As a result $format is always '', formatKeys stays empty, and the empty-cell-to-null rule for enum/email/url/ip columns at line 376 never activates in production.
📋 Prompt for AI Agents
In packages/migration/src/Sources/CSV.php line 231, replace \is_array($column) && \is_string($column['format'] ?? null) ? $column['format'] : '' with \is_string($column['format'] ?? null) ? $column['format'] : '', matching the ArrayAccess pattern used for $column['key'] and $column['type'] on lines 229-230. Columns arrive as Utopia\Database\Document objects (ArrayObject) from listColumns(), so the is_array guard always fails and the enum/email/url/ip empty-cell handling never runs; add a unit test with a Document-backed column so the format path is covered.
| }; | ||
| }, $arrayValues); | ||
| $parsedData[$key] = \array_map( | ||
| fn ($item) => $this->parseValue(\is_string($item) ? \trim($item) : $item, \is_string($type) ? $type : '', $key, $line), |
There was a problem hiding this comment.
🟡 bug · medium
Array string items silently trimmed, breaking round-trip
Every string item of an array column is now passed through trim() before storage (packages/migration/src/Sources/CSV.php:345). A JSON array cell such as [" padded ", "tail "] previously imported verbatim; leading/trailing whitespace inside string array elements is now silently discarded, corrupting data on export→import round-trips for values whose whitespace is meaningful (tokens, serialized blobs, text). The same trim also applies to $permissions entries routed through this path.
📋 Prompt for AI Agents
In packages/migration/src/Sources/CSV.php line 345, remove the \trim($item) call from the array_map callback and pass the raw string item to parseValue (fn ($item) => $this->parseValue(\is_string($item) ? $item : (string)$item, ...)). Trimming array elements silently deletes meaningful leading/trailing whitespace from imported data and breaks export→import round-trips; the whole-cell trim at line 303 already normalizes cell-level whitespace where intended.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Read cells with their quoting, so a quoted "null" and quoted whitespace are kept. Reject values a column cannot hold (integer range, relative or out-of-range dates, string size, enum, email, url, ip) with the row number, and check every row before the first batch is written.
A null exports as bare null, so the strings "null", "" and values with surrounding whitespace are quoted to import back unchanged.
A failed batch write marks every row in it as failed, and the last row of a batch flushes the buffer even when it was skipped itself.
| // Check every row before any is written, so one bad row cannot leave the table half imported | ||
| foreach ($this->readRows($stream, $delimiter, $headers, $schema) as $_) { |
There was a problem hiding this comment.
Add regression coverage for CSV source imports
The existing CSVTest exercises export and delimiter detection but does not drive Sources\CSV through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/migration/src/Sources/CSV.php
Line: 275-276
Comment:
**Add regression coverage for CSV source imports**
The existing `CSVTest` exercises export and delimiter detection but does not drive `Sources\CSV` through this new parser or preflight pass. A focused import test should assert the parsed row values and that an invalid row prevents callbacks, so regressions in the custom quoted-record parsing are observable.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · testing · Reply if this doesn't apply.
Fixes #14333.
Changed in
packages/migration:Sources/CSV.phpnullisNULL, a quoted"null"is the string, and quoted values are not trimmed.yesterday), out-of-range dates (31.02.2026), JSON, strings longer than the column size, enum/email/url/ip values, column min/max, and array elements.NULLfor every column except plain strings; enum, email, url and ip used to get''and reject the batch.Destinations/CSV.php: exports quote"null",""and padded strings, so an export imports back unchanged.Destinations/Appwrite.php: buffered rows are counted only after their batch is written. If the write fails, every row in the batch is counted as an error, not just the last one. The last row of a batch also writes the buffer when it was skipped itself.Tested on the local stack, with a throwaway e2e test that imports each case from the issue and reads the table back:
"null"," pad "NULL/padnull/pad1.7,abc,9999…,maybe,31.02.2026,yesterday,[1,"x",3]NULLCSV row 2: invalid … value for column '…'NULLsuccess: 297with 0 stored$idin a batchsuccess: 2, error: 1success: 0, error: 3$idignored$idusedCSV row 2 is not valid UTF-8.The export → import round trip of
null,"null","", padded, quoted and multi-line values was checked locally. Migrations e2e (testCreateCSV*,testAppwriteMigrationDatabasesRow,testAppwriteMigrationRowsOnDuplicate, DocumentsDB/VectorsDB documents) pass.bin/monorepo check migrationpasses. Inbin/monorepo test migration, onlyAppwriteSdkCoverageTest::testEveryProjectSettingIsMigratedOrSkippedfails, and it is unrelated to this change.Behaviour change: CSV files that used to import with silently changed values (
1.0into an integer,yesterdayinto a datetime) now fail with the row number.