pyodbc.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # connectors/pyodbc.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. import re
  8. from . import Connector
  9. from .. import util
  10. class PyODBCConnector(Connector):
  11. driver = "pyodbc"
  12. # this is no longer False for pyodbc in general
  13. supports_sane_rowcount_returning = True
  14. supports_sane_multi_rowcount = False
  15. supports_unicode_statements = True
  16. supports_unicode_binds = True
  17. supports_native_decimal = True
  18. default_paramstyle = "named"
  19. use_setinputsizes = False
  20. # for non-DSN connections, this *may* be used to
  21. # hold the desired driver name
  22. pyodbc_driver_name = None
  23. def __init__(
  24. self, supports_unicode_binds=None, use_setinputsizes=False, **kw
  25. ):
  26. super(PyODBCConnector, self).__init__(**kw)
  27. if supports_unicode_binds is not None:
  28. self.supports_unicode_binds = supports_unicode_binds
  29. self.use_setinputsizes = use_setinputsizes
  30. @classmethod
  31. def dbapi(cls):
  32. return __import__("pyodbc")
  33. def create_connect_args(self, url):
  34. opts = url.translate_connect_args(username="user")
  35. opts.update(url.query)
  36. keys = opts
  37. query = url.query
  38. connect_args = {}
  39. for param in ("ansi", "unicode_results", "autocommit"):
  40. if param in keys:
  41. connect_args[param] = util.asbool(keys.pop(param))
  42. if "odbc_connect" in keys:
  43. connectors = [util.unquote_plus(keys.pop("odbc_connect"))]
  44. else:
  45. def check_quote(token):
  46. if ";" in str(token):
  47. token = "{%s}" % token.replace("}", "}}")
  48. return token
  49. keys = dict((k, check_quote(v)) for k, v in keys.items())
  50. dsn_connection = "dsn" in keys or (
  51. "host" in keys and "database" not in keys
  52. )
  53. if dsn_connection:
  54. connectors = [
  55. "dsn=%s" % (keys.pop("host", "") or keys.pop("dsn", ""))
  56. ]
  57. else:
  58. port = ""
  59. if "port" in keys and "port" not in query:
  60. port = ",%d" % int(keys.pop("port"))
  61. connectors = []
  62. driver = keys.pop("driver", self.pyodbc_driver_name)
  63. if driver is None and keys:
  64. # note if keys is empty, this is a totally blank URL
  65. util.warn(
  66. "No driver name specified; "
  67. "this is expected by PyODBC when using "
  68. "DSN-less connections"
  69. )
  70. else:
  71. connectors.append("DRIVER={%s}" % driver)
  72. connectors.extend(
  73. [
  74. "Server=%s%s" % (keys.pop("host", ""), port),
  75. "Database=%s" % keys.pop("database", ""),
  76. ]
  77. )
  78. user = keys.pop("user", None)
  79. if user:
  80. connectors.append("UID=%s" % user)
  81. pwd = keys.pop("password", "")
  82. if pwd:
  83. connectors.append("PWD=%s" % pwd)
  84. else:
  85. authentication = keys.pop("authentication", None)
  86. if authentication:
  87. connectors.append("Authentication=%s" % authentication)
  88. else:
  89. connectors.append("Trusted_Connection=Yes")
  90. # if set to 'Yes', the ODBC layer will try to automagically
  91. # convert textual data from your database encoding to your
  92. # client encoding. This should obviously be set to 'No' if
  93. # you query a cp1253 encoded database from a latin1 client...
  94. if "odbc_autotranslate" in keys:
  95. connectors.append(
  96. "AutoTranslate=%s" % keys.pop("odbc_autotranslate")
  97. )
  98. connectors.extend(["%s=%s" % (k, v) for k, v in keys.items()])
  99. return [[";".join(connectors)], connect_args]
  100. def is_disconnect(self, e, connection, cursor):
  101. if isinstance(e, self.dbapi.ProgrammingError):
  102. return "The cursor's connection has been closed." in str(
  103. e
  104. ) or "Attempt to use a closed connection." in str(e)
  105. else:
  106. return False
  107. def _dbapi_version(self):
  108. if not self.dbapi:
  109. return ()
  110. return self._parse_dbapi_version(self.dbapi.version)
  111. def _parse_dbapi_version(self, vers):
  112. m = re.match(r"(?:py.*-)?([\d\.]+)(?:-(\w+))?", vers)
  113. if not m:
  114. return ()
  115. vers = tuple([int(x) for x in m.group(1).split(".")])
  116. if m.group(2):
  117. vers += (m.group(2),)
  118. return vers
  119. def _get_server_version_info(self, connection, allow_chars=True):
  120. # NOTE: this function is not reliable, particularly when
  121. # freetds is in use. Implement database-specific server version
  122. # queries.
  123. dbapi_con = connection.connection
  124. version = []
  125. r = re.compile(r"[.\-]")
  126. for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)):
  127. try:
  128. version.append(int(n))
  129. except ValueError:
  130. if allow_chars:
  131. version.append(n)
  132. return tuple(version)
  133. def do_set_input_sizes(self, cursor, list_of_tuples, context):
  134. # the rules for these types seems a little strange, as you can pass
  135. # non-tuples as well as tuples, however it seems to assume "0"
  136. # for the subsequent values if you don't pass a tuple which fails
  137. # for types such as pyodbc.SQL_WLONGVARCHAR, which is the datatype
  138. # that ticket #5649 is targeting.
  139. # NOTE: as of #6058, this won't be called if the use_setinputsizes flag
  140. # is False, or if no types were specified in list_of_tuples
  141. cursor.setinputsizes(
  142. [
  143. (dbtype, None, None)
  144. if not isinstance(dbtype, tuple)
  145. else dbtype
  146. for key, dbtype, sqltype in list_of_tuples
  147. ]
  148. )
  149. def set_isolation_level(self, connection, level):
  150. # adjust for ConnectionFairy being present
  151. # allows attribute set e.g. "connection.autocommit = True"
  152. # to work properly
  153. if hasattr(connection, "dbapi_connection"):
  154. connection = connection.dbapi_connection
  155. if level == "AUTOCOMMIT":
  156. connection.autocommit = True
  157. else:
  158. connection.autocommit = False
  159. super(PyODBCConnector, self).set_isolation_level(connection, level)