From 66a7befa0c549b92d42afbb5be2b45da13793250 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Thu, 3 Oct 2019 11:18:06 -0400 Subject: Apply quoting to SQL Server _switch_db Added identifier quoting to the schema name applied to the "use" statement which is invoked when a SQL Server multipart schema name is used within a :class:`.Table` that is being reflected, as well as for :class:`.Inspector` methods such as :meth:`.Inspector.get_table_names`; this accommodates for special characters or spaces in the database name. Additionally, the "use" statement is not emitted if the current database matches the target owner database name being passed. Fixes: #4883 Change-Id: I84419730e94aac3a88d331ad8c24d10aabbc34af --- lib/sqlalchemy/dialects/mssql/base.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'lib/sqlalchemy') diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py index 54f0043c4..d4d303d5d 100644 --- a/lib/sqlalchemy/dialects/mssql/base.py +++ b/lib/sqlalchemy/dialects/mssql/base.py @@ -2174,12 +2174,21 @@ def _db_plus_owner(fn): def _switch_db(dbname, connection, fn, *arg, **kw): if dbname: current_db = connection.scalar("select db_name()") - connection.execute("use %s" % dbname) + if current_db != dbname: + connection.execute( + "use %s" + % connection.dialect.identifier_preparer.quote_schema(dbname) + ) try: return fn(*arg, **kw) finally: - if dbname: - connection.execute("use %s" % current_db) + if dbname and current_db != dbname: + connection.execute( + "use %s" + % connection.dialect.identifier_preparer.quote_schema( + current_db + ) + ) def _owner_plus_db(dialect, schema): -- cgit v1.2.1