Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(low-code): added keys replace transformation #183

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

darynaishchenko
Copy link
Contributor

@darynaishchenko darynaishchenko commented Dec 20, 2024

Added KeysReplaceTransformations to be able to replace symbols in record keys.

Summary by CodeRabbit

  • New Features

    • Introduced a new transformation component, KeysReplace, for replacing symbols in record keys.
    • Enhanced the DeclarativeStream to include the KeysReplace transformation.
  • Bug Fixes

    • Improved the transformation logic to ensure accurate key replacements in records.
  • Tests

    • Added unit tests for the KeysReplaceTransformation to validate its functionality.

@darynaishchenko darynaishchenko self-assigned this Dec 20, 2024
@github-actions github-actions bot added the enhancement New feature or request label Dec 20, 2024
@darynaishchenko
Copy link
Contributor Author

darynaishchenko commented Dec 20, 2024

/autofix

Auto-Fix Job Info

This job attempts to auto-fix any linting or formating issues. If any fixes are made,
those changes will be automatically committed and pushed back to the PR.

Note: This job can only be run by maintainers. On PRs from forks, this command requires
that the PR author has enabled the Allow edits from maintainers option.

PR auto-fix job started... Check job output.

✅ Changes applied successfully.

Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces a new KeysReplace transformation component to the Airbyte CDK's declarative source framework. This addition allows for dynamic key replacement within record processing, enabling more flexible data transformation. The changes span multiple files, including schema definitions, model implementations, component factories, and a new transformation class, creating a comprehensive mechanism for key substitution during stream processing.

Changes

File Change Summary
airbyte_cdk/sources/declarative/declarative_component_schema.yaml Added KeysReplace transformation definition; updated transformations and schema_transformations lists to include KeysReplace
airbyte_cdk/sources/declarative/models/declarative_component_schema.py Introduced KeysReplace class as a new transformation model; updated transformations list in DeclarativeStream
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py Added method to create KeysReplace transformation and updated model mappings
airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py New file implementing KeysReplaceTransformation with key replacement logic
unit_tests/sources/declarative/transformations/test_keys_replace_transformation.py Added unit test for KeysReplaceTransformation

Sequence Diagram

sequenceDiagram
    participant Stream as DeclarativeStream
    participant Factory as ModelToComponentFactory
    participant Transformation as KeysReplaceTransformation
    
    Stream->>Factory: Request transformation
    Factory-->>Transformation: Create KeysReplaceTransformation
    Stream->>Transformation: Apply transform
    Transformation->>Transformation: Replace keys in record
Loading

Possibly Related PRs

Suggested Reviewers

  • maxi297
  • aldogonzalez8

Hey team! 👋 Quick question - would you be interested in seeing some example use cases for the new KeysReplace transformation? I think it could help illustrate its practical applications. Wdyt? 🤔

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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. (Beta)
  • @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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (5)
airbyte_cdk/sources/declarative/models/declarative_component_schema.py (1)

718-733: LGTM! Consider adding value validation, wdyt?

The KeysReplace schema is well-structured and properly integrated. The fields have clear descriptions and examples.

One suggestion: Consider adding validation to ensure old and new values are not empty strings, as empty replacements could lead to unexpected behavior. Something like:

old: str = Field(
    ...,
    description="Old value to replace.",
    examples=[" ", "_"],
    title="Old value",
    min_length=1
)
unit_tests/sources/declarative/transformations/test_keys_replace_transformation.py (2)

9-10: Consider using a more descriptive constant name

The constant _ANY_VALUE = -1 could be more descriptive. What about something like _DUMMY_VALUE or _PLACEHOLDER_VALUE, wdyt?

-_ANY_VALUE = -1
+_DUMMY_VALUE = -1  # Used as a placeholder in test records

12-15: Consider adding more test cases for better coverage

The current test only covers a basic case. Would you consider adding tests for:

  1. Empty strings in keys
  2. Multiple occurrences of the pattern
  3. Nested dictionaries
  4. Special characters in keys
  5. Edge cases where no replacement is needed

Here's a suggested expansion of the test cases:

def test_transform():
    test_cases = [
        # Basic case
        ({"date time": _DUMMY_VALUE}, {"date_time": _DUMMY_VALUE}),
        # Multiple spaces
        ({"date  time": _DUMMY_VALUE}, {"date__time": _DUMMY_VALUE}),
        # Nested dictionary
        ({"outer space": {"inner space": _DUMMY_VALUE}}, {"outer_space": {"inner_space": _DUMMY_VALUE}}),
        # No replacement needed
        ({"date_time": _DUMMY_VALUE}, {"date_time": _DUMMY_VALUE}),
        # Empty string
        ({"": _DUMMY_VALUE}, {"": _DUMMY_VALUE}),
    ]
    
    for input_record, expected_output in test_cases:
        record = input_record.copy()
        KeysReplaceTransformation(old=" ", new="_").transform(record)
        assert record == expected_output
airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py (1)

12-16: Consider adding docstring and input validation

The class could benefit from documentation and parameter validation. What do you think about:

 @dataclass
 class KeysReplaceTransformation(RecordTransformation):
+    """Transforms record keys by replacing occurrences of a substring with another.
+    
+    Args:
+        old: The substring to replace in record keys
+        new: The substring to replace with
+    
+    Example:
+        >>> transform = KeysReplaceTransformation(old=" ", new="_")
+        >>> record = {"date time": 123}
+        >>> transform.transform(record)
+        >>> assert record == {"date_time": 123}
+    """
     old: str
     new: str
+
+    def __post_init__(self):
+        if not isinstance(self.old, str) or not isinstance(self.new, str):
+            raise ValueError("Both 'old' and 'new' must be strings")
airbyte_cdk/sources/declarative/declarative_component_schema.yaml (1)

1883-1911: LGTM! The KeysReplace transformation component looks well-structured.

The component definition is clear and includes all necessary fields. I particularly like the descriptive examples provided for both old and new values. Just a minor suggestion - would you consider adding a more complex example showing how this could be used with config parameters? Something like:

old: "{{ config['old_key_pattern'] }}"
new: "{{ config['new_key_pattern'] }}"

wdyt?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2ab345f and 1cceccd.

📒 Files selected for processing (5)
  • airbyte_cdk/sources/declarative/declarative_component_schema.yaml (3 hunks)
  • airbyte_cdk/sources/declarative/models/declarative_component_schema.py (3 hunks)
  • airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (4 hunks)
  • airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py (1 hunks)
  • unit_tests/sources/declarative/transformations/test_keys_replace_transformation.py (1 hunks)
🔇 Additional comments (3)
airbyte_cdk/sources/declarative/models/declarative_component_schema.py (1)

1692-1692: LGTM! KeysReplace properly integrated

The KeysReplace transformation is correctly added to both transformation lists in DeclarativeStream and DynamicSchemaLoader.

Also applies to: 1867-1867

airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (1)

239-241: LGTM! The factory implementation looks good

The changes to ModelToComponentFactory follow the established patterns and are consistent with other transformation implementations.

Also applies to: 497-497, 619-623

airbyte_cdk/sources/declarative/declarative_component_schema.yaml (1)

1239-1239: LGTM! The KeysReplace transformation is properly integrated.

The component is correctly added to both transformation lists in DeclarativeStream and DynamicSchemaLoader. The integration maintains schema consistency and allows the transformation to be used in both contexts.

Also applies to: 1784-1784

Comment on lines +17 to +25
def transform(
self,
record: Dict[str, Any],
config: Optional[Config] = None,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
) -> None:
for key in set(record.keys()):
record[key.replace(self.old, self.new)] = record.pop(key)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider handling nested dictionaries recursively

The current implementation only handles top-level keys. Would you consider adding support for nested dictionaries? Here's a suggestion:

     def transform(
         self,
         record: Dict[str, Any],
         config: Optional[Config] = None,
         stream_state: Optional[StreamState] = None,
         stream_slice: Optional[StreamSlice] = None,
     ) -> None:
+        def transform_dict(d: Dict[str, Any]) -> Dict[str, Any]:
+            result = {}
+            for key, value in d.items():
+                new_key = key.replace(self.old, self.new)
+                if isinstance(value, dict):
+                    result[new_key] = transform_dict(value)
+                else:
+                    result[new_key] = value
+            return result
+
+        transformed = transform_dict(record)
+        record.clear()
+        record.update(transformed)
-        for key in set(record.keys()):
-            record[key.replace(self.old, self.new)] = record.pop(key)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def transform(
self,
record: Dict[str, Any],
config: Optional[Config] = None,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
) -> None:
for key in set(record.keys()):
record[key.replace(self.old, self.new)] = record.pop(key)
def transform(
self,
record: Dict[str, Any],
config: Optional[Config] = None,
stream_state: Optional[StreamState] = None,
stream_slice: Optional[StreamSlice] = None,
) -> None:
def transform_dict(d: Dict[str, Any]) -> Dict[str, Any]:
result = {}
for key, value in d.items():
new_key = key.replace(self.old, self.new)
if isinstance(value, dict):
result[new_key] = transform_dict(value)
else:
result[new_key] = value
return result
transformed = transform_dict(record)
record.clear()
record.update(transformed)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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)
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (1)

619-623: Consider adding validation for the old/new parameters.

The implementation looks good, but what do you think about adding validation to ensure that old and new parameters are not empty strings or None? This could help catch configuration issues early. wdyt?

 def create_keys_replace_transformation(
     self, model: KeysReplaceModel, config: Config, **kwargs: Any
 ) -> KeysReplaceTransformation:
+    if not model.old or not model.new:
+        raise ValueError("Both 'old' and 'new' parameters must be non-empty strings")
     return KeysReplaceTransformation(old=model.old, new=model.new)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1cceccd and 12eeabd.

📒 Files selected for processing (2)
  • airbyte_cdk/sources/declarative/declarative_component_schema.yaml (3 hunks)
  • airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • airbyte_cdk/sources/declarative/declarative_component_schema.yaml
🔇 Additional comments (2)
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (2)

239-241: LGTM! Clean import additions.

The imports are well-organized and follow the existing pattern.

Also applies to: 405-407


497-497: LGTM! Clean mapping addition.

The mapping is correctly placed in alphabetical order.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant