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

refactor: Ensure Flask framework leverages the Flask-SQLAlchemy session (Phase I) #26200

Merged

Conversation

john-bodley
Copy link
Member

@john-bodley john-bodley commented Dec 6, 2023

SUMMARY

Somewhat related to #26186 (though for non-Celery related workflows) this PR ensures that the remainder of the codebase (excluding tests and Alembic migrations) leverage the Flask-SQLAlchemy session (db.session).

This refactor helps to reduce the code complexity and ensures we're not generating any rouge sessions which are often not explicitly closed and can lead to connection pooling issues.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

TESTING INSTRUCTIONS

CI.

ADDITIONAL INFORMATION

  • Has associated issue: [SIP-99A] Primer on managing SQLAlchemy sessions #25107
  • 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

def get_user_by_username(
self, username: str, session: Session = None
) -> Optional[User]:
def get_user_by_username(self, username: str) -> Optional[User]:
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 method was never called with the session parameter.

@@ -152,8 +153,7 @@ def log_with_context( # pylint: disable=too-many-locals
# need to add them back before logging to capture user_id
if user_id is None:
try:
session = current_app.appbuilder.get_session
session.add(g.user)
db.session.add(g.user)
Copy link
Member Author

Choose a reason for hiding this comment

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

Same session as current_app.appbuilder.get_session. Consistency is key here.

@@ -106,7 +106,6 @@ def test_get_datasource_sqlatable(session_with_data: Session) -> None:
result = DatasourceDAO.get_datasource(
datasource_type=DatasourceType.TABLE,
datasource_id=1,
session=session_with_data,
Copy link
Member Author

Choose a reason for hiding this comment

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

The db.session is mocked here and is included as a fixture to the test.

@@ -45,15 +44,14 @@ class DatasourceDAO(BaseDAO[Datasource]):
@classmethod
def get_datasource(
cls,
session: Session,
Copy link
Member Author

Choose a reason for hiding this comment

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

It is not apparent to me why the session was included here. There are unit tests which use a session other than db.session but, per here, the global db.session is mocked to use said session.

@john-bodley john-bodley force-pushed the john-bodley--sip-99-non-celery-sessions branch from 0205b85 to b37c7cf Compare December 6, 2023 21:49
Copy link

codecov bot commented Dec 6, 2023

Codecov Report

Attention: 12 lines in your changes are missing coverage. Please review.

Comparison is base (aaa4a7b) 69.08% compared to head (6b0eb40) 66.87%.

Files Patch % Lines
superset/models/dashboard.py 27.27% 8 Missing ⚠️
superset/utils/database.py 0.00% 2 Missing ⚠️
superset/utils/mock_data.py 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #26200      +/-   ##
==========================================
- Coverage   69.08%   66.87%   -2.22%     
==========================================
  Files        1931     1931              
  Lines       75351    75333      -18     
  Branches     8429     8429              
==========================================
- Hits        52056    50376    -1680     
- Misses      21148    22810    +1662     
  Partials     2147     2147              
Flag Coverage Δ
hive ?
mysql 77.92% <73.91%> (+<0.01%) ⬆️
postgres 78.02% <73.91%> (+<0.01%) ⬆️
presto ?
python 78.16% <73.91%> (-4.62%) ⬇️
sqlite 77.61% <73.91%> (+<0.01%) ⬆️
unit ?

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@john-bodley john-bodley force-pushed the john-bodley--sip-99-non-celery-sessions branch 4 times, most recently from 5486cd6 to 490aeff Compare December 6, 2023 22:46
@john-bodley john-bodley marked this pull request as ready for review December 6, 2023 23:08
)
session.add(dashboard)
session = sqla.inspect(target).session
new_user = session.query(User).filter_by(id=target.id).first()
Copy link
Member Author

Choose a reason for hiding this comment

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

Same logic without the try block.

@michael-s-molina michael-s-molina changed the title chore: Ensure Flask framework leverages Flask-SQLAlchemy session refactpr: Ensure Flask framework leverages Flask-SQLAlchemy session Dec 7, 2023
@michael-s-molina michael-s-molina changed the title refactpr: Ensure Flask framework leverages Flask-SQLAlchemy session refactor: Ensure Flask framework leverages Flask-SQLAlchemy session Dec 7, 2023
@john-bodley john-bodley changed the title refactor: Ensure Flask framework leverages Flask-SQLAlchemy session refactor: Ensure Flask framework leverages the Flask-SQLAlchemy session Dec 11, 2023
@john-bodley
Copy link
Member Author

ping @michael-s-molina @villebro

@michael-s-molina
Copy link
Member

@john-bodley I think it would be great to label this PR with v4.0 and merge it during the breaking window to reuse the test/stabilization efforts that will occur during that period.

@michael-s-molina michael-s-molina added hold! On hold v4.0 Label added by the release manager to track PRs to be included in the 4.0 branch labels Jan 3, 2024
@john-bodley john-bodley force-pushed the john-bodley--sip-99-non-celery-sessions branch from 490aeff to 1a61b1e Compare January 3, 2024 21:21
print(f"- {model.__name__} ({rows} rows in table {model.__tablename__})")
model_rows[model] = rows
session.close()
Copy link
Member Author

Choose a reason for hiding this comment

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

There is no need to explicitly close the session as this is handled by Flask-SQLAlchemy when the session is torn down—be that at the end of request or when a script/shell terminates.

@john-bodley
Copy link
Member Author

Regarding,

@john-bodley I think it would be great to label this PR with v4.0 and merge it during the breaking window to reuse the test/stabilization efforts that will occur during that period.

as discussed with @michael-s-molina, though this is technically a non-breaking change, it seems prudent (from a safety perspective) to hold off merging this until the v4.0 breaking window.

@michael-s-molina michael-s-molina removed the hold! On hold label Jan 16, 2024
@john-bodley john-bodley force-pushed the john-bodley--sip-99-non-celery-sessions branch from 1a61b1e to 6b0eb40 Compare January 17, 2024 00:42
@john-bodley
Copy link
Member Author

@michael-s-molina would you mind reviewing this PR?

Copy link
Member

@michael-s-molina michael-s-molina left a comment

Choose a reason for hiding this comment

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

LGTM

@john-bodley john-bodley merged commit df79522 into apache:master Jan 17, 2024
33 checks passed
@john-bodley john-bodley deleted the john-bodley--sip-99-non-celery-sessions branch January 17, 2024 19:28
Muhammed-baban pushed a commit to intellica-tech/reporting-tool that referenced this pull request Jan 19, 2024
@john-bodley john-bodley changed the title refactor: Ensure Flask framework leverages the Flask-SQLAlchemy session refactor: Ensure Flask framework leverages the Flask-SQLAlchemy session (Phase I) Jan 31, 2024
sfirke pushed a commit to sfirke/superset that referenced this pull request Mar 22, 2024
@mistercrunch mistercrunch added 🏷️ bot A label used by `supersetbot` to keep track of which PR where auto-tagged with release labels 🚢 4.0.0 labels Apr 17, 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/XL v4.0 Label added by the release manager to track PRs to be included in the 4.0 branch 🚢 4.0.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants