Skip to content

Fix csv parser - #106

Merged
abnegate merged 21 commits into
mainfrom
fix-csv-parser
Aug 8, 2025
Merged

abnegate merged 21 commits into
mainfrom
fix-csv-parser

Conversation

@abnegate

@abnegate abnegate commented Aug 7, 2025

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Improved CSV import to better handle required columns, unknown columns, and array-type fields.
    • Enhanced parsing of array fields with support for JSON and comma-separated values.
  • Bug Fixes

    • Unknown columns in CSV files now trigger warnings instead of errors and are skipped during import.
    • Empty CSV values are more accurately mapped to null or empty strings based on the data type.
  • Other Improvements

    • Increased robustness and flexibility for CSV import processes.
    • Updated dependency version constraint for improved package stability.

@coderabbitai

coderabbitai Bot commented Aug 7, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • composer.lock is excluded by !**/*.lock

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The CSV source export logic was updated to improve handling of required and unknown columns, array parsing, and value interpretation. Required columns are now explicitly tracked and enforced, unknown columns are logged as warnings instead of causing errors, and array-type fields use enhanced parsing with JSON and fallback mechanisms. Empty values are handled more precisely.

Changes

Cohort / File(s) Change Summary
CSV Source Handling
src/Migration/Sources/CSV.php
Enhanced required column tracking, header validation, unknown column handling, array parsing, and empty value interpretation. Updated method signatures to support these changes.
Dependency Version Update
composer.json
Restricted the version constraint for utopia-php/database dependency from 0.*.* to 0.71.*.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CSV
    participant Logger

    User->>CSV: Provide CSV file for export
    CSV->>CSV: Track required columns
    CSV->>CSV: Validate headers (enforce required, warn on unknown)
    alt Unknown columns found
        CSV->>Logger: Log warning
    end
    loop For each row
        CSV->>CSV: Parse row
        alt Array-type column
            CSV->>CSV: Try JSON decode
            alt JSON fails
                CSV->>CSV: Fallback to comma-separated parsing
            end
        end
        alt Unknown column in row
            CSV->>CSV: Skip column
        end
        CSV->>CSV: Interpret empty values by type
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Possibly related PRs

  • Fix bad merge #102: Updates error message wording in CSV header validation and parsing methods without changing core functionality.

Suggested reviewers

  • ArnabChatterjee20k

Poem

A CSV tale, with columns anew,
Required ones checked, as all good bunnies do.
Unknowns just warn, no panic or fright,
Arrays parsed smartly, with JSON in sight.
Empty or missing? Now clearly defined—
This code hops forward, robustly aligned! 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-csv-parser

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/Migration/Sources/CSV.php (1)

250-264: Well-implemented array parsing with JSON support.

The dual-format support with fallback is excellent for compatibility. Consider limiting the exposed value in the error message to prevent potential sensitive data leakage:

-                                throw new \Exception("Invalid array format for column '$key': $parsedValue");
+                                throw new \Exception("Invalid array format for column '$key'");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 025b995 and 1584762.

📒 Files selected for processing (1)
  • src/Migration/Sources/CSV.php (8 hunks)
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: in the utopia-php/migration codebase, during the terminology swap from collection/attribute/document...
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite.php:843-851
Timestamp: 2025-06-28T09:47:08.333Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the class constructors and method parameters use the new terminology (like "relatedTable"), but the underlying data structures and API responses still use the legacy keys (like "relatedCollection"). This is an intentional design pattern to allow gradual migration while maintaining compatibility with existing data sources.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: in the utopia-php/migration codebase, the `fromarray` method is not used on row objects, so mismatch...
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Resources/Database/Row.php:60-60
Timestamp: 2025-06-28T09:45:36.026Z
Learning: In the utopia-php/migration codebase, the `fromArray` method is not used on Row objects, so mismatches between `jsonSerialize()` output keys and `fromArray()` input expectations for Row class are not problematic.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: in the utopia-php/migration codebase, during the terminology swap from collection/attribute/document...
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Supabase.php:300-308
Timestamp: 2025-06-28T09:47:58.757Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the user ItzNotABug prefers to keep the existing query logic unchanged even if it becomes semantically incorrect with the new naming. The focus is purely on resource type renaming, not on fixing logical issues that become apparent after the terminology change.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: in the utopia-php/migration codebase, the utopia database package does not have a memory adapter. wh...
Learnt from: abnegate
PR: utopia-php/migration#0
File: :0-0
Timestamp: 2025-07-30T12:06:02.331Z
Learning: In the utopia-php/migration codebase, the Utopia Database package does not have a Memory adapter. When testing classes that require a Database instance (like CSV), use PHPUnit's createMock() method to create proper mocks instead of trying to instantiate real database adapters.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: in the utopia-php/migration codebase, invalid numeric values (like null) in parsed data are acceptab...
Learnt from: ItzNotABug
PR: utopia-php/migration#81
File: src/Migration/Sources/CSV.php:215-233
Timestamp: 2025-07-02T06:24:50.844Z
Learning: In the utopia-php/migration codebase, invalid numeric values (like null) in parsed data are acceptable because the underlying database structure validator will catch and handle these validation errors, so explicit filtering during parsing is not required.

Applied to files:

  • src/Migration/Sources/CSV.php
🧬 Code Graph Analysis (1)
src/Migration/Sources/CSV.php (2)
src/Migration/Resources/Database/Column.php (3)
  • isArray (113-116)
  • isRequired (103-106)
  • Column (8-151)
src/Migration/Exception.php (1)
  • Exception (5-65)
🔇 Additional comments (6)
src/Migration/Sources/CSV.php (6)

5-5: LGTM!

The Console import is correctly added and used for warning messages later in the code.


161-182: Good implementation of required column tracking.

The use of array keys for storing required columns is efficient for O(1) lookups during validation.


197-203: Correct propagation of required columns.

The $requiredColumns parameter is properly passed through the closure and to the validation method.


227-229: Good improvement to error handling.

Skipping unknown columns instead of throwing errors makes the CSV import more resilient while still warning users during header validation.


278-295: Excellent handling of empty values vs nulls.

The distinction between empty strings and null values based on column type is semantically correct and follows database best practices.


399-433: Well-designed validation logic.

The distinction between critical errors (missing required columns) and warnings (unknown columns) is appropriate. The error messages are clear and properly pluralized.

# Conflicts:
#	src/Migration/Sources/CSV.php
# Conflicts:
#	src/Migration/Sources/CSV.php
# Conflicts:
#	composer.lock
# Conflicts:
#	src/Migration/Cache.php
#	src/Migration/Sources/CSV.php

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/Migration/Sources/CSV.php (2)

246-260: json_decode() corner-case: literal null trips the array parser

When the cell contains the JSON literal null, json_decode() returns null
and json_last_error() is JSON_ERROR_NONE, so the fallback branch is skipped.
is_array() then fails and an exception is thrown even though the value is
perfectly valid.

Quick fix ­– treat null as an empty list:

-    if (!\is_array($arrayValues)) {
-        throw new \Exception("Invalid array format for column '$key': $parsedValue");
-    }
+    if ($arrayValues === null) {
+        $arrayValues = [];
+    }
+    if (!\is_array($arrayValues)) {
+        throw new \Exception("Invalid array format for column '$key': $parsedValue");
+    }

This prevents unnecessary hard-stops on otherwise acceptable input.


406-409: Duplicate list of internal columns

validateCSVHeaders() declares its own $internals list instead of re-using
self::ALLOWED_INTERNALS. Updating one but not the other will cause subtle
mismatches.

-    $internals = ['$id', '$permissions', '$createdAt', '$updatedAt'];
+    $internals = \array_keys(self::ALLOWED_INTERNALS);

Keeps the list single-sourced and easier to maintain.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 49d0317 and a7b24ec.

📒 Files selected for processing (2)
  • composer.json (1 hunks)
  • src/Migration/Sources/CSV.php (12 hunks)
✅ Files skipped from review due to trivial changes (1)
  • composer.json
🧰 Additional context used
🧠 Learnings (4)
📚 Learning: 2025-07-30T12:06:02.331Z
Learnt from: abnegate
PR: utopia-php/migration#0
File: :0-0
Timestamp: 2025-07-30T12:06:02.331Z
Learning: In the utopia-php/migration codebase, the Utopia Database package does not have a Memory adapter. When testing classes that require a Database instance (like CSV), use PHPUnit's createMock() method to create proper mocks instead of trying to instantiate real database adapters.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: 2025-06-28T09:47:58.757Z
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Supabase.php:300-308
Timestamp: 2025-06-28T09:47:58.757Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the user ItzNotABug prefers to keep the existing query logic unchanged even if it becomes semantically incorrect with the new naming. The focus is purely on resource type renaming, not on fixing logical issues that become apparent after the terminology change.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: 2025-06-28T09:47:08.333Z
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Sources/Appwrite.php:843-851
Timestamp: 2025-06-28T09:47:08.333Z
Learning: In the utopia-php/migration codebase, during the terminology swap from Collection/Attribute/Document to Table/Column/Row, the class constructors and method parameters use the new terminology (like "relatedTable"), but the underlying data structures and API responses still use the legacy keys (like "relatedCollection"). This is an intentional design pattern to allow gradual migration while maintaining compatibility with existing data sources.

Applied to files:

  • src/Migration/Sources/CSV.php
📚 Learning: 2025-06-28T09:45:36.026Z
Learnt from: ItzNotABug
PR: utopia-php/migration#80
File: src/Migration/Resources/Database/Row.php:60-60
Timestamp: 2025-06-28T09:45:36.026Z
Learning: In the utopia-php/migration codebase, the `fromArray` method is not used on Row objects, so mismatches between `jsonSerialize()` output keys and `fromArray()` input expectations for Row class are not problematic.

Applied to files:

  • src/Migration/Sources/CSV.php
🔇 Additional comments (1)
src/Migration/Sources/CSV.php (1)

522-526: Potential CSV parsing issue with identical enclosure and escape characters

str_getcsv($line, $delimiter, '"', '"') (and the analogous fgetcsv call)
sets both enclosure and escape to ". PHP treats the escape character
literally, so embedded quotes like "He said ""hi""" will no longer be parsed
correctly.

Please confirm this deliberately deviates from RFC 4180; otherwise restore the
default backslash escape:

-    $fields = \str_getcsv($line, $delimiter, '"', '"');
+    $fields = \str_getcsv($line, $delimiter, '"'); // escape char defaults to \

Comment thread src/Migration/Sources/CSV.php
@abnegate
abnegate merged commit c478555 into main Aug 8, 2025
4 checks passed
@abnegate
abnegate deleted the fix-csv-parser branch August 8, 2025 13:10
@coderabbitai coderabbitai Bot mentioned this pull request Sep 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants