Skip to content

Commit b93c6fd

Browse files
authored
Switch back to the intial database while collecting schemas (#17978)
* Switch back to the intial database while collecting schemas * Used finally * Applied linter
1 parent b4917a7 commit b93c6fd

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

sqlserver/datadog_checks/sqlserver/schemas.py

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -193,27 +193,31 @@ def _fetch_for_databases(self):
193193
engine_edition = self._check.static_info_cache.get(STATIC_INFO_ENGINE_EDITION)
194194
with self._check.connection.open_managed_default_connection():
195195
with self._check.connection.get_managed_cursor() as cursor:
196-
for db_name in databases:
197-
try:
198-
if not is_azure_sql_database(engine_edition):
199-
cursor.execute(SWITCH_DB_STATEMENT.format(db_name))
200-
self._fetch_schema_data(cursor, start_time, db_name)
201-
except StopIteration as e:
202-
self._log.error(
203-
"While executing fetch schemas for databse {}, the following exception occured {}".format(
204-
db_name, e
196+
try:
197+
for db_name in databases:
198+
try:
199+
if not is_azure_sql_database(engine_edition):
200+
cursor.execute(SWITCH_DB_STATEMENT.format(db_name))
201+
self._fetch_schema_data(cursor, start_time, db_name)
202+
except StopIteration as e:
203+
self._log.error(
204+
"""While executing fetch schemas for databse {},
205+
the following exception occured {}""".format(
206+
db_name, e
207+
)
205208
)
206-
)
207-
return
208-
except Exception as e:
209-
self._log.error(
210-
"While executing fetch schemas for databse {}, the following exception occured {}".format(
211-
db_name, e
209+
break
210+
except Exception as e:
211+
self._log.error(
212+
"""While executing fetch schemas for databse {},
213+
the following exception occured {}""".format(
214+
db_name, e
215+
)
212216
)
213-
)
214-
# Switch DB back to MASTER
215-
if not is_azure_sql_database(engine_edition):
216-
cursor.execute(SWITCH_DB_STATEMENT.format(self._check.connection.DEFAULT_DATABASE))
217+
finally:
218+
# Switch DB back to MASTER
219+
if not is_azure_sql_database(engine_edition):
220+
cursor.execute(SWITCH_DB_STATEMENT.format(self._check.connection.DEFAULT_DATABASE))
217221

218222
@tracked_method(agent_check_getter=agent_check_getter)
219223
def _collect_schemas_data(self):

0 commit comments

Comments
 (0)