Fix unbound variable in sql when session setup fails (#90439)

Traceback (most recent call last):
  File "/Users/bdraco/home-assistant/homeassistant/helpers/entity_platform.py", line 304, in _async_setup_platform
    await asyncio.shield(task)
  File "/Users/bdraco/home-assistant/homeassistant/components/sql/sensor.py", line 75, in async_setup_platform
    await async_setup_sensor(
  File "/Users/bdraco/home-assistant/homeassistant/components/sql/sensor.py", line 150, in async_setup_sensor
    sessmaker := await hass.async_add_executor_job(
  File "/opt/homebrew/Cellar/python@3.10/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/Users/bdraco/home-assistant/homeassistant/components/sql/sensor.py", line 205, in _validate_and_get_session_maker_for_db_url
    if sess:
UnboundLocalError: local variable 'sess' referenced before assignment
pull/90442/head
J. Nick Koston 2023-03-28 17:52:44 -10:00 committed by GitHub
parent 885be98f8f
commit 5dc96a6952
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 2 additions and 1 deletions

View File

@ -180,11 +180,12 @@ def _validate_and_get_session_maker_for_db_url(db_url: str) -> scoped_session |
This does I/O and should be run in the executor.
"""
sess: Session | None = None
try:
engine = sqlalchemy.create_engine(db_url, future=True)
sessmaker = scoped_session(sessionmaker(bind=engine, future=True))
# Run a dummy query just to test the db_url
sess: Session = sessmaker()
sess = sessmaker()
sess.execute(sqlalchemy.text("SELECT 1;"))
except SQLAlchemyError as err: