Skip to content

Conversation

@phenobarbital
Copy link
Owner

@phenobarbital phenobarbital commented Mar 17, 2025

Summary by Sourcery

Adds functionality to cache and retrieve primary key information for Model classes, including the ability to get primary key fields and values. Also, fixes an issue with JSON encoding of lists containing submodels when using Optional types, and increments the version number.

Enhancements:

  • Adds methods to retrieve primary key information for Model classes, including class-level access to primary keys and instance-level access to primary key values.
  • Improves JSON encoding for lists containing submodels, specifically addressing cases where Optional types are used.
  • Adds a method to get a dictionary of primary key fields with their types.
  • Adds a method to get primary key values for an instance as a dictionary.
  • Adds a method to get primary keys without further introspection

@sourcery-ai
Copy link

sourcery-ai bot commented Mar 17, 2025

Reviewer's Guide by Sourcery

This pull request introduces functionality for defining and retrieving primary keys in Model classes, fixes a bug related to JSON encoding of lists with optional submodels, and increments the version number.

Updated class diagram for Model

classDiagram
  class Model {
    +get_primary_keys()
    +get_primary_key_fields()
    +get_primary_key_values()
  }
  Model : +get_primary_keys() - Added method
  Model : +get_primary_key_fields() - Added method
  Model : +get_primary_key_values() - Added method
Loading

File-Level Changes

Change Details Files
Introduces the ability to define and retrieve primary keys for Model classes.
  • Adds a primary_key metadata option to fields in Model classes.
  • Collects fields with the primary_key metadata during class initialization.
  • Adds get_primary_keys, get_primary_key_fields, and get_primary_key_values methods to Model classes for accessing primary key information.
  • Stores primary key information in the __primary_keys__ attribute of the class.
datamodel/abstract.py
Fixes an issue with JSON encoding of lists containing submodels when using Optional types.
  • Adds a check for Optional[T] type hints when processing lists of submodels.
  • Extracts the underlying type from Optional[T] for submodel checking.
datamodel/models.py
Increments the version number.
  • Updates the version from 0.10.10 to 0.10.11.
datamodel/version.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@phenobarbital phenobarbital merged commit 87d6105 into main Mar 17, 2025
1 check passed
Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @phenobarbital - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a test case that verifies the behavior of get_primary_key_fields when a model has multiple primary keys.
  • It might be worth adding a short description of the new methods to the class docstring.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

dc.modelName = dc.__name__

# Override __setattr__ method
setattr(dc, "__setattr__", _dc_method_setattr_)
Copy link

Choose a reason for hiding this comment

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

issue (complexity): Consider extracting the primary key handling logic into dedicated helper functions or class methods to reduce nesting and complexity within the __new__ method, improving readability and maintainability of the metaclass logic by separating concerns and reducing inline definitions, while preserving functionality related to primary keys.

Extract the primary key handling logic from the __new__ method into dedicated helper functions (or even class methods) to reduce nesting and inline complexity. For example, you can define the primary key extractor functions outside of __new__ so that they’re defined once rather than redefined every time a new model is built. This change keeps functionality intact while making the metaclass logic easier to read and maintain.

One possible approach is as follows:

  1. Move inline functions out of __new__:

    Define helper functions for retrieving primary keys and their fields at the class level:

    class ModelMeta(type):
        ...
        @classmethod
        def get_primary_keys(cls):
            return cls.__primary_keys__
    
        @classmethod
        def get_primary_key_fields(cls):
            """Return a dictionary of primary key fields with their types."""
            return {name: cls.__columns__[name] for name in cls.__primary_keys__}
    
        def get_primary_key_values(self):
            """Get primary key values for this instance as a dictionary."""
            return {key: getattr(self, key) for key in self.__primary_keys__}
  2. Assign these methods after class creation instead of defining them inline:

    In your __new__ method, assign the prepared functions instead of inline function definitions:

    def __new__(cls, name, bases, attrs, **kwargs):  # noqa
        ...
        # After selecting and creating dc
        dc.__primary_keys__ = primary_keys
        # Assign the primary key helper methods directly
        dc.get_primary_keys = classmethod(ModelMeta.get_primary_keys)
        dc.get_primary_key_fields = classmethod(ModelMeta.get_primary_key_fields)
        dc.get_primary_key_values = ModelMeta.get_primary_key_values  # instance method
        return dc

This refactoring separates concerns, reduces nested inline definitions, and preserves the functionality of handling primary keys.

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