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

Merged

Conversation

darynaishchenko
Copy link
Contributor

@darynaishchenko darynaishchenko commented Dec 20, 2024

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

It's used for connectors where we need to transform record fields to replace symbols in it. For example source-airtable we need to replace spaces to underscores: from user id to user_id, for example.

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.
    • Added a new class, KeysReplaceTransformation, for processing 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? 🤔


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6e0c785 and b01accf.

📒 Files selected for processing (1)
  • airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-the-guardian-api' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Pytest (Fast)

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

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.

@darynaishchenko
Copy link
Contributor Author

darynaishchenko commented Jan 6, 2025

/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 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 (2)
airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py (1)

35-61: Consider adding error handling for non-string keys

The transformation assumes all dictionary keys are strings. What do you think about adding error handling for non-string keys? Something like this maybe?

     def _transform(data: Dict[str, Any]) -> Dict[str, Any]:
         result = {}
         for key, value in data.items():
+            if not isinstance(key, str):
+                result[key] = value
+                continue
             updated_key = key.replace(old_key, new_key)
             if isinstance(value, dict):
                 result[updated_key] = _transform(value)
             else:
                 result[updated_key] = value
         return result
airbyte_cdk/sources/declarative/declarative_component_schema.yaml (1)

1888-1930: The KeysReplace transformation definition looks good, but should we enhance the examples?

The component is well-defined with clear descriptions and proper type constraints. However, we could make the examples more comprehensive to better illustrate common use cases. What do you think about adding examples that show:

  1. Replacing spaces with underscores in all keys
  2. Using config values for dynamic replacements
  3. Using record values for conditional replacements

Here's a suggested enhancement to the examples:

       examples:
-          - " "
-          - "{{ record.id }}"
-          - "{{ config['id'] }}"
-          - "{{ stream_slice['id'] }}"
+          - " "  # Replace spaces with underscores in keys
+          - "."  # Replace dots with underscores in keys
+          - "{{ config['old_prefix'] }}"  # Replace dynamic prefix from config
+          - "{{ record.old_key_pattern }}"  # Replace pattern from record
       interpolation_context:
         - config
         - record
         - stream_state
         - stream_slice
       new:
         type: string
         title: New value
         description: New value to set.
         examples:
-          - "_"
-          - "{{ record.id }}"
-          - "{{ config['id'] }}"
-          - "{{ stream_slice['id'] }}"
+          - "_"  # Convert spaces to underscores
+          - "_"  # Convert dots to underscores
+          - "{{ config['new_prefix'] }}"  # Use new prefix from config
+          - "{{ record.new_key_pattern }}"  # Use new pattern from record
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 12eeabd and 6e0c785.

📒 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)
🚧 Files skipped from review as they are similar to previous changes (1)
  • unit_tests/sources/declarative/transformations/test_keys_replace_transformation.py
🧰 Additional context used
🪛 GitHub Actions: Linters
airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py

[error] 31-31: Function is missing a type annotation for one or more arguments

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Check: 'source-pokeapi' (skip=false)
  • GitHub Check: Check: 'source-the-guardian-api' (skip=false)
  • GitHub Check: Check: 'source-shopify' (skip=false)
  • GitHub Check: Check: 'source-hardcoded-records' (skip=false)
  • GitHub Check: Pytest (All, Python 3.11, Ubuntu)
  • GitHub Check: Pytest (All, Python 3.10, Ubuntu)
  • GitHub Check: Pytest (Fast)
🔇 Additional comments (8)
airbyte_cdk/sources/declarative/transformations/keys_replace_transformation.py (2)

1-10: LGTM! Clean imports and proper license header.

The imports are well-organized and include only what's needed.


13-25: Great docstring with clear example!

The docstring effectively illustrates the transformation with a practical example. The before/after demonstration makes it very clear how the transformation works.

airbyte_cdk/sources/declarative/models/declarative_component_schema.py (1)

724-739: LGTM! Well-structured model definition

The KeysReplace model follows the established patterns with:

  • Clear field descriptions and examples
  • Proper type constraints
  • Optional parameters field
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (3)

257-259: LGTM! Clean import addition

The import follows the established pattern of the file.


518-518: LGTM! Proper mapping registration

The KeysReplaceModel is correctly mapped to its factory method.


640-646: LGTM! Factory method implementation

The factory method follows the established pattern and correctly passes all required parameters.

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

1244-1244: LGTM! The KeysReplace transformation is properly added to the DeclarativeStream's transformations list.

The addition follows the same pattern as other transformations in the list.


1789-1789: LGTM! The KeysReplace transformation is properly added to the DynamicSchemaLoader's schema_transformations list.

The addition follows the same pattern as other transformations in the list.

Copy link
Contributor

@aldogonzalez8 aldogonzalez8 left a comment

Choose a reason for hiding this comment

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

APPROVED

@aldogonzalez8
Copy link
Contributor

Changes makes sense to me, just left annoying nit comment,

Copy link
Contributor

@maxi297 maxi297 left a comment

Choose a reason for hiding this comment

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

The code is good, the tests are clean! Can we add a bit more context on the PR description to mention which connector this is intended for? This will be valuable context if we need to debug something related to this feature

@darynaishchenko darynaishchenko merged commit 3344441 into main Jan 8, 2025
21 checks passed
@darynaishchenko darynaishchenko deleted the daryna/low-code/add-replace-field-transformations branch January 8, 2025 15:12
rpopov added a commit to rpopov/airbyte-python-cdk that referenced this pull request Jan 8, 2025
* main:
  fix(airbyte-cdk): unable to create custom retriever (airbytehq#198)
  feat(low-code): added keys replace transformation (airbytehq#183)
  feat: add `min` macros (airbytehq#203)
  fix(low-code cdk pagination): Fix the offset strategy so that it resets back to 0 when a stream is an incremental data feed (airbytehq#202)
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.

3 participants