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

chore(dao): Add generic type for better type checking #24465

Merged
merged 1 commit into from
Jun 21, 2023

Conversation

john-bodley
Copy link
Member

@john-bodley john-bodley commented Jun 20, 2023

SUMMARY

Per SIP-92 Proposal for restructuring the Python code base #24331 organized all the DAOs to be housed within a shared folder—the result of which highlighted numerous inconsistencies, repetition, and inefficiencies.

This PR (one of many smaller bitesized PRs) improves the typing for DAOs by introducing a generic type to ensure that the model being created, updated, deleted, etc. is in accordance with the DAO.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

TESTING INSTRUCTIONS

ADDITIONAL INFORMATION

  • Has associated issue: [SIP-92] Proposal for restructuring the Python code base #20630
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@@ -38,6 +38,8 @@ def __init__(self, model_id: int):

def run(self) -> Model:
self.validate()
assert self._model
Copy link
Member Author

Choose a reason for hiding this comment

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

This was needed because now Mypy correctly identified that on line #44 self._model could have been None which didn't adhere to the base class definition.

Copy link
Member

Choose a reason for hiding this comment

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

I have a draft SIP recommending a slight refactor of the commands which address this problem.

Copy link
Member Author

Choose a reason for hiding this comment

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

@betodealmeida I’ve been thinking about the DAOs, commands and validation a bit recently and wonder whether we should adopt the “ask for forgiveness” try approach more often which relies less on Python validation and more on the database schema (foreign keys, uniqueness constraints, etc.) for validation, i.e., the DAO or command would fail if invalid.

The benefits are that we would reduce the Python code footprint and prevent possible race conditions.

"""
Generic for saving models
:raises: DAOCreateFailedError
"""
if cls.model_cls is None:
raise DAOConfigError()
if not isinstance(instance_model, cls.model_cls):
Copy link
Member Author

Choose a reason for hiding this comment

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

This is no longer needed. The Mypy checks ensure this can't happen.

try:
db.session.add(instance_model)
if commit:
db.session.commit()
except SQLAlchemyError as ex: # pragma: no cover
db.session.rollback()
raise DAOCreateFailedError(exception=ex) from ex
return instance_model
Copy link
Member Author

Choose a reason for hiding this comment

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

Inconsistent return type detected with the ChartDAO implementation. Note there's no need to return instance_model as it's passed in as in input.

@john-bodley john-bodley marked this pull request as ready for review June 20, 2023 19:46
@john-bodley john-bodley changed the title chore(dao): Add generic type chore(dao): Add generic type for better type checking Jun 20, 2023
@codecov
Copy link

codecov bot commented Jun 20, 2023

Codecov Report

Merging #24465 (57b6df6) into master (c3b5d72) will increase coverage by 0.17%.
The diff coverage is 93.12%.

❗ Current head 57b6df6 differs from pull request most recent head 7a37ac4. Consider uploading reports for the commit 7a37ac4 to get more accurate results

@@            Coverage Diff             @@
##           master   #24465      +/-   ##
==========================================
+ Coverage   68.85%   69.02%   +0.17%     
==========================================
  Files        1901     1901              
  Lines       73969    74000      +31     
  Branches     8119     8116       -3     
==========================================
+ Hits        50931    51082     +151     
+ Misses      20927    20807     -120     
  Partials     2111     2111              
Flag Coverage Δ
hive 53.89% <70.24%> (?)
mysql 79.42% <94.21%> (?)
postgres 79.50% <94.21%> (+0.01%) ⬆️
presto 53.80% <66.94%> (?)
python 83.48% <98.34%> (+0.35%) ⬆️
sqlite 78.01% <93.38%> (+0.01%) ⬆️
unit 54.60% <69.42%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
...ckages/superset-ui-chart-controls/src/constants.ts 100.00% <ø> (ø)
...erset-ui-chart-controls/src/utils/columnChoices.ts 100.00% <ø> (ø)
...packages/superset-ui-core/src/query/types/Query.ts 100.00% <ø> (ø)
superset-frontend/src/SqlLab/actions/sqlLab.js 69.16% <ø> (-0.27%) ⬇️
...d/src/SqlLab/components/SaveDatasetModal/index.tsx 50.00% <0.00%> (ø)
superset-frontend/src/SqlLab/fixtures.ts 100.00% <ø> (ø)
...rset-frontend/src/explore/components/SaveModal.tsx 35.08% <ø> (+0.30%) ⬆️
superset/databases/utils.py 82.22% <ø> (ø)
superset/models/sql_lab.py 79.51% <ø> (+1.60%) ⬆️
superset/result_set.py 97.88% <ø> (ø)
... and 45 more

... and 4 files with indirect coverage changes

📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more

Copy link
Member

@villebro villebro left a comment

Choose a reason for hiding this comment

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

LGTM!

Comment on lines +52 to +56
def __init_subclass__(cls) -> None: # pylint: disable=arguments-differ
cls.model_cls = get_args(
cls.__orig_bases__[0] # type: ignore # pylint: disable=no-member
)[0]

Copy link
Member

Choose a reason for hiding this comment

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

Wow I didn't know Python has added core support for generic types! Adding a reference here for other reviewers: https://peps.python.org/pep-0560/

@john-bodley john-bodley merged commit 92e2ee9 into apache:master Jun 21, 2023
@john-bodley john-bodley deleted the john-bodley--dao-typing branch June 21, 2023 16:30
@mistercrunch mistercrunch added 🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels 🚢 3.0.0 labels Mar 8, 2024
vinothkumar66 pushed a commit to vinothkumar66/superset that referenced this pull request Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels size/L 🚢 3.0.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants