url.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. # engine/url.py
  2. # Copyright (C) 2005-2024 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. """Provides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates
  8. information about a database connection specification.
  9. The URL object is created automatically when
  10. :func:`~sqlalchemy.engine.create_engine` is called with a string
  11. argument; alternatively, the URL is a public-facing construct which can
  12. be used directly and is also accepted directly by ``create_engine()``.
  13. """
  14. from __future__ import annotations
  15. import collections.abc as collections_abc
  16. import re
  17. from typing import Any
  18. from typing import cast
  19. from typing import Dict
  20. from typing import Iterable
  21. from typing import List
  22. from typing import Mapping
  23. from typing import NamedTuple
  24. from typing import Optional
  25. from typing import overload
  26. from typing import Sequence
  27. from typing import Tuple
  28. from typing import Type
  29. from typing import Union
  30. from urllib.parse import parse_qsl
  31. from urllib.parse import quote
  32. from urllib.parse import quote_plus
  33. from urllib.parse import unquote
  34. from .interfaces import Dialect
  35. from .. import exc
  36. from .. import util
  37. from ..dialects import plugins
  38. from ..dialects import registry
  39. class URL(NamedTuple):
  40. """
  41. Represent the components of a URL used to connect to a database.
  42. URLs are typically constructed from a fully formatted URL string, where the
  43. :func:`.make_url` function is used internally by the
  44. :func:`_sa.create_engine` function in order to parse the URL string into
  45. its individual components, which are then used to construct a new
  46. :class:`.URL` object. When parsing from a formatted URL string, the parsing
  47. format generally follows
  48. `RFC-1738 <https://www.ietf.org/rfc/rfc1738.txt>`_, with some exceptions.
  49. A :class:`_engine.URL` object may also be produced directly, either by
  50. using the :func:`.make_url` function with a fully formed URL string, or
  51. by using the :meth:`_engine.URL.create` constructor in order
  52. to construct a :class:`_engine.URL` programmatically given individual
  53. fields. The resulting :class:`.URL` object may be passed directly to
  54. :func:`_sa.create_engine` in place of a string argument, which will bypass
  55. the usage of :func:`.make_url` within the engine's creation process.
  56. .. versionchanged:: 1.4
  57. The :class:`_engine.URL` object is now an immutable object. To
  58. create a URL, use the :func:`_engine.make_url` or
  59. :meth:`_engine.URL.create` function / method. To modify
  60. a :class:`_engine.URL`, use methods like
  61. :meth:`_engine.URL.set` and
  62. :meth:`_engine.URL.update_query_dict` to return a new
  63. :class:`_engine.URL` object with modifications. See notes for this
  64. change at :ref:`change_5526`.
  65. .. seealso::
  66. :ref:`database_urls`
  67. :class:`_engine.URL` contains the following attributes:
  68. * :attr:`_engine.URL.drivername`: database backend and driver name, such as
  69. ``postgresql+psycopg2``
  70. * :attr:`_engine.URL.username`: username string
  71. * :attr:`_engine.URL.password`: password string
  72. * :attr:`_engine.URL.host`: string hostname
  73. * :attr:`_engine.URL.port`: integer port number
  74. * :attr:`_engine.URL.database`: string database name
  75. * :attr:`_engine.URL.query`: an immutable mapping representing the query
  76. string. contains strings for keys and either strings or tuples of
  77. strings for values.
  78. """
  79. drivername: str
  80. """database backend and driver name, such as
  81. ``postgresql+psycopg2``
  82. """
  83. username: Optional[str]
  84. "username string"
  85. password: Optional[str]
  86. """password, which is normally a string but may also be any
  87. object that has a ``__str__()`` method."""
  88. host: Optional[str]
  89. """hostname or IP number. May also be a data source name for some
  90. drivers."""
  91. port: Optional[int]
  92. """integer port number"""
  93. database: Optional[str]
  94. """database name"""
  95. query: util.immutabledict[str, Union[Tuple[str, ...], str]]
  96. """an immutable mapping representing the query string. contains strings
  97. for keys and either strings or tuples of strings for values, e.g.::
  98. >>> from sqlalchemy.engine import make_url
  99. >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt")
  100. >>> url.query
  101. immutabledict({'alt_host': ('host1', 'host2'), 'ssl_cipher': '/path/to/crt'})
  102. To create a mutable copy of this mapping, use the ``dict`` constructor::
  103. mutable_query_opts = dict(url.query)
  104. .. seealso::
  105. :attr:`_engine.URL.normalized_query` - normalizes all values into sequences
  106. for consistent processing
  107. Methods for altering the contents of :attr:`_engine.URL.query`:
  108. :meth:`_engine.URL.update_query_dict`
  109. :meth:`_engine.URL.update_query_string`
  110. :meth:`_engine.URL.update_query_pairs`
  111. :meth:`_engine.URL.difference_update_query`
  112. """ # noqa: E501
  113. @classmethod
  114. def create(
  115. cls,
  116. drivername: str,
  117. username: Optional[str] = None,
  118. password: Optional[str] = None,
  119. host: Optional[str] = None,
  120. port: Optional[int] = None,
  121. database: Optional[str] = None,
  122. query: Mapping[str, Union[Sequence[str], str]] = util.EMPTY_DICT,
  123. ) -> URL:
  124. """Create a new :class:`_engine.URL` object.
  125. .. seealso::
  126. :ref:`database_urls`
  127. :param drivername: the name of the database backend. This name will
  128. correspond to a module in sqlalchemy/databases or a third party
  129. plug-in.
  130. :param username: The user name.
  131. :param password: database password. Is typically a string, but may
  132. also be an object that can be stringified with ``str()``.
  133. .. note:: A password-producing object will be stringified only
  134. **once** per :class:`_engine.Engine` object. For dynamic password
  135. generation per connect, see :ref:`engines_dynamic_tokens`.
  136. :param host: The name of the host.
  137. :param port: The port number.
  138. :param database: The database name.
  139. :param query: A dictionary of string keys to string values to be passed
  140. to the dialect and/or the DBAPI upon connect. To specify non-string
  141. parameters to a Python DBAPI directly, use the
  142. :paramref:`_sa.create_engine.connect_args` parameter to
  143. :func:`_sa.create_engine`. See also
  144. :attr:`_engine.URL.normalized_query` for a dictionary that is
  145. consistently string->list of string.
  146. :return: new :class:`_engine.URL` object.
  147. .. versionadded:: 1.4
  148. The :class:`_engine.URL` object is now an **immutable named
  149. tuple**. In addition, the ``query`` dictionary is also immutable.
  150. To create a URL, use the :func:`_engine.url.make_url` or
  151. :meth:`_engine.URL.create` function/ method. To modify a
  152. :class:`_engine.URL`, use the :meth:`_engine.URL.set` and
  153. :meth:`_engine.URL.update_query` methods.
  154. """
  155. return cls(
  156. cls._assert_str(drivername, "drivername"),
  157. cls._assert_none_str(username, "username"),
  158. password,
  159. cls._assert_none_str(host, "host"),
  160. cls._assert_port(port),
  161. cls._assert_none_str(database, "database"),
  162. cls._str_dict(query),
  163. )
  164. @classmethod
  165. def _assert_port(cls, port: Optional[int]) -> Optional[int]:
  166. if port is None:
  167. return None
  168. try:
  169. return int(port)
  170. except TypeError:
  171. raise TypeError("Port argument must be an integer or None")
  172. @classmethod
  173. def _assert_str(cls, v: str, paramname: str) -> str:
  174. if not isinstance(v, str):
  175. raise TypeError("%s must be a string" % paramname)
  176. return v
  177. @classmethod
  178. def _assert_none_str(
  179. cls, v: Optional[str], paramname: str
  180. ) -> Optional[str]:
  181. if v is None:
  182. return v
  183. return cls._assert_str(v, paramname)
  184. @classmethod
  185. def _str_dict(
  186. cls,
  187. dict_: Optional[
  188. Union[
  189. Sequence[Tuple[str, Union[Sequence[str], str]]],
  190. Mapping[str, Union[Sequence[str], str]],
  191. ]
  192. ],
  193. ) -> util.immutabledict[str, Union[Tuple[str, ...], str]]:
  194. if dict_ is None:
  195. return util.EMPTY_DICT
  196. @overload
  197. def _assert_value(
  198. val: str,
  199. ) -> str:
  200. ...
  201. @overload
  202. def _assert_value(
  203. val: Sequence[str],
  204. ) -> Union[str, Tuple[str, ...]]:
  205. ...
  206. def _assert_value(
  207. val: Union[str, Sequence[str]],
  208. ) -> Union[str, Tuple[str, ...]]:
  209. if isinstance(val, str):
  210. return val
  211. elif isinstance(val, collections_abc.Sequence):
  212. return tuple(_assert_value(elem) for elem in val)
  213. else:
  214. raise TypeError(
  215. "Query dictionary values must be strings or "
  216. "sequences of strings"
  217. )
  218. def _assert_str(v: str) -> str:
  219. if not isinstance(v, str):
  220. raise TypeError("Query dictionary keys must be strings")
  221. return v
  222. dict_items: Iterable[Tuple[str, Union[Sequence[str], str]]]
  223. if isinstance(dict_, collections_abc.Sequence):
  224. dict_items = dict_
  225. else:
  226. dict_items = dict_.items()
  227. return util.immutabledict(
  228. {
  229. _assert_str(key): _assert_value(
  230. value,
  231. )
  232. for key, value in dict_items
  233. }
  234. )
  235. def set(
  236. self,
  237. drivername: Optional[str] = None,
  238. username: Optional[str] = None,
  239. password: Optional[str] = None,
  240. host: Optional[str] = None,
  241. port: Optional[int] = None,
  242. database: Optional[str] = None,
  243. query: Optional[Mapping[str, Union[Sequence[str], str]]] = None,
  244. ) -> URL:
  245. """return a new :class:`_engine.URL` object with modifications.
  246. Values are used if they are non-None. To set a value to ``None``
  247. explicitly, use the :meth:`_engine.URL._replace` method adapted
  248. from ``namedtuple``.
  249. :param drivername: new drivername
  250. :param username: new username
  251. :param password: new password
  252. :param host: new hostname
  253. :param port: new port
  254. :param query: new query parameters, passed a dict of string keys
  255. referring to string or sequence of string values. Fully
  256. replaces the previous list of arguments.
  257. :return: new :class:`_engine.URL` object.
  258. .. versionadded:: 1.4
  259. .. seealso::
  260. :meth:`_engine.URL.update_query_dict`
  261. """
  262. kw: Dict[str, Any] = {}
  263. if drivername is not None:
  264. kw["drivername"] = drivername
  265. if username is not None:
  266. kw["username"] = username
  267. if password is not None:
  268. kw["password"] = password
  269. if host is not None:
  270. kw["host"] = host
  271. if port is not None:
  272. kw["port"] = port
  273. if database is not None:
  274. kw["database"] = database
  275. if query is not None:
  276. kw["query"] = query
  277. return self._assert_replace(**kw)
  278. def _assert_replace(self, **kw: Any) -> URL:
  279. """argument checks before calling _replace()"""
  280. if "drivername" in kw:
  281. self._assert_str(kw["drivername"], "drivername")
  282. for name in "username", "host", "database":
  283. if name in kw:
  284. self._assert_none_str(kw[name], name)
  285. if "port" in kw:
  286. self._assert_port(kw["port"])
  287. if "query" in kw:
  288. kw["query"] = self._str_dict(kw["query"])
  289. return self._replace(**kw)
  290. def update_query_string(
  291. self, query_string: str, append: bool = False
  292. ) -> URL:
  293. """Return a new :class:`_engine.URL` object with the :attr:`_engine.URL.query`
  294. parameter dictionary updated by the given query string.
  295. E.g.::
  296. >>> from sqlalchemy.engine import make_url
  297. >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
  298. >>> url = url.update_query_string("alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt")
  299. >>> str(url)
  300. 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
  301. :param query_string: a URL escaped query string, not including the
  302. question mark.
  303. :param append: if True, parameters in the existing query string will
  304. not be removed; new parameters will be in addition to those present.
  305. If left at its default of False, keys present in the given query
  306. parameters will replace those of the existing query string.
  307. .. versionadded:: 1.4
  308. .. seealso::
  309. :attr:`_engine.URL.query`
  310. :meth:`_engine.URL.update_query_dict`
  311. """ # noqa: E501
  312. return self.update_query_pairs(parse_qsl(query_string), append=append)
  313. def update_query_pairs(
  314. self,
  315. key_value_pairs: Iterable[Tuple[str, Union[str, List[str]]]],
  316. append: bool = False,
  317. ) -> URL:
  318. """Return a new :class:`_engine.URL` object with the
  319. :attr:`_engine.URL.query`
  320. parameter dictionary updated by the given sequence of key/value pairs
  321. E.g.::
  322. >>> from sqlalchemy.engine import make_url
  323. >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
  324. >>> url = url.update_query_pairs([("alt_host", "host1"), ("alt_host", "host2"), ("ssl_cipher", "/path/to/crt")])
  325. >>> str(url)
  326. 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
  327. :param key_value_pairs: A sequence of tuples containing two strings
  328. each.
  329. :param append: if True, parameters in the existing query string will
  330. not be removed; new parameters will be in addition to those present.
  331. If left at its default of False, keys present in the given query
  332. parameters will replace those of the existing query string.
  333. .. versionadded:: 1.4
  334. .. seealso::
  335. :attr:`_engine.URL.query`
  336. :meth:`_engine.URL.difference_update_query`
  337. :meth:`_engine.URL.set`
  338. """ # noqa: E501
  339. existing_query = self.query
  340. new_keys: Dict[str, Union[str, List[str]]] = {}
  341. for key, value in key_value_pairs:
  342. if key in new_keys:
  343. new_keys[key] = util.to_list(new_keys[key])
  344. cast("List[str]", new_keys[key]).append(cast(str, value))
  345. else:
  346. new_keys[key] = (
  347. list(value) if isinstance(value, (list, tuple)) else value
  348. )
  349. new_query: Mapping[str, Union[str, Sequence[str]]]
  350. if append:
  351. new_query = {}
  352. for k in new_keys:
  353. if k in existing_query:
  354. new_query[k] = tuple(
  355. util.to_list(existing_query[k])
  356. + util.to_list(new_keys[k])
  357. )
  358. else:
  359. new_query[k] = new_keys[k]
  360. new_query.update(
  361. {
  362. k: existing_query[k]
  363. for k in set(existing_query).difference(new_keys)
  364. }
  365. )
  366. else:
  367. new_query = self.query.union(
  368. {
  369. k: tuple(v) if isinstance(v, list) else v
  370. for k, v in new_keys.items()
  371. }
  372. )
  373. return self.set(query=new_query)
  374. def update_query_dict(
  375. self,
  376. query_parameters: Mapping[str, Union[str, List[str]]],
  377. append: bool = False,
  378. ) -> URL:
  379. """Return a new :class:`_engine.URL` object with the
  380. :attr:`_engine.URL.query` parameter dictionary updated by the given
  381. dictionary.
  382. The dictionary typically contains string keys and string values.
  383. In order to represent a query parameter that is expressed multiple
  384. times, pass a sequence of string values.
  385. E.g.::
  386. >>> from sqlalchemy.engine import make_url
  387. >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
  388. >>> url = url.update_query_dict({"alt_host": ["host1", "host2"], "ssl_cipher": "/path/to/crt"})
  389. >>> str(url)
  390. 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
  391. :param query_parameters: A dictionary with string keys and values
  392. that are either strings, or sequences of strings.
  393. :param append: if True, parameters in the existing query string will
  394. not be removed; new parameters will be in addition to those present.
  395. If left at its default of False, keys present in the given query
  396. parameters will replace those of the existing query string.
  397. .. versionadded:: 1.4
  398. .. seealso::
  399. :attr:`_engine.URL.query`
  400. :meth:`_engine.URL.update_query_string`
  401. :meth:`_engine.URL.update_query_pairs`
  402. :meth:`_engine.URL.difference_update_query`
  403. :meth:`_engine.URL.set`
  404. """ # noqa: E501
  405. return self.update_query_pairs(query_parameters.items(), append=append)
  406. def difference_update_query(self, names: Iterable[str]) -> URL:
  407. """
  408. Remove the given names from the :attr:`_engine.URL.query` dictionary,
  409. returning the new :class:`_engine.URL`.
  410. E.g.::
  411. url = url.difference_update_query(['foo', 'bar'])
  412. Equivalent to using :meth:`_engine.URL.set` as follows::
  413. url = url.set(
  414. query={
  415. key: url.query[key]
  416. for key in set(url.query).difference(['foo', 'bar'])
  417. }
  418. )
  419. .. versionadded:: 1.4
  420. .. seealso::
  421. :attr:`_engine.URL.query`
  422. :meth:`_engine.URL.update_query_dict`
  423. :meth:`_engine.URL.set`
  424. """
  425. if not set(names).intersection(self.query):
  426. return self
  427. return URL(
  428. self.drivername,
  429. self.username,
  430. self.password,
  431. self.host,
  432. self.port,
  433. self.database,
  434. util.immutabledict(
  435. {
  436. key: self.query[key]
  437. for key in set(self.query).difference(names)
  438. }
  439. ),
  440. )
  441. @property
  442. def normalized_query(self) -> Mapping[str, Sequence[str]]:
  443. """Return the :attr:`_engine.URL.query` dictionary with values normalized
  444. into sequences.
  445. As the :attr:`_engine.URL.query` dictionary may contain either
  446. string values or sequences of string values to differentiate between
  447. parameters that are specified multiple times in the query string,
  448. code that needs to handle multiple parameters generically will wish
  449. to use this attribute so that all parameters present are presented
  450. as sequences. Inspiration is from Python's ``urllib.parse.parse_qs``
  451. function. E.g.::
  452. >>> from sqlalchemy.engine import make_url
  453. >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt")
  454. >>> url.query
  455. immutabledict({'alt_host': ('host1', 'host2'), 'ssl_cipher': '/path/to/crt'})
  456. >>> url.normalized_query
  457. immutabledict({'alt_host': ('host1', 'host2'), 'ssl_cipher': ('/path/to/crt',)})
  458. """ # noqa: E501
  459. return util.immutabledict(
  460. {
  461. k: (v,) if not isinstance(v, tuple) else v
  462. for k, v in self.query.items()
  463. }
  464. )
  465. @util.deprecated(
  466. "1.4",
  467. "The :meth:`_engine.URL.__to_string__ method is deprecated and will "
  468. "be removed in a future release. Please use the "
  469. ":meth:`_engine.URL.render_as_string` method.",
  470. )
  471. def __to_string__(self, hide_password: bool = True) -> str:
  472. """Render this :class:`_engine.URL` object as a string.
  473. :param hide_password: Defaults to True. The password is not shown
  474. in the string unless this is set to False.
  475. """
  476. return self.render_as_string(hide_password=hide_password)
  477. def render_as_string(self, hide_password: bool = True) -> str:
  478. """Render this :class:`_engine.URL` object as a string.
  479. This method is used when the ``__str__()`` or ``__repr__()``
  480. methods are used. The method directly includes additional options.
  481. :param hide_password: Defaults to True. The password is not shown
  482. in the string unless this is set to False.
  483. """
  484. s = self.drivername + "://"
  485. if self.username is not None:
  486. s += quote(self.username, safe=" +")
  487. if self.password is not None:
  488. s += ":" + (
  489. "***"
  490. if hide_password
  491. else quote(str(self.password), safe=" +")
  492. )
  493. s += "@"
  494. if self.host is not None:
  495. if ":" in self.host:
  496. s += f"[{self.host}]"
  497. else:
  498. s += self.host
  499. if self.port is not None:
  500. s += ":" + str(self.port)
  501. if self.database is not None:
  502. s += "/" + self.database
  503. if self.query:
  504. keys = list(self.query)
  505. keys.sort()
  506. s += "?" + "&".join(
  507. f"{quote_plus(k)}={quote_plus(element)}"
  508. for k in keys
  509. for element in util.to_list(self.query[k])
  510. )
  511. return s
  512. def __repr__(self) -> str:
  513. return self.render_as_string()
  514. def __copy__(self) -> URL:
  515. return self.__class__.create(
  516. self.drivername,
  517. self.username,
  518. self.password,
  519. self.host,
  520. self.port,
  521. self.database,
  522. # note this is an immutabledict of str-> str / tuple of str,
  523. # also fully immutable. does not require deepcopy
  524. self.query,
  525. )
  526. def __deepcopy__(self, memo: Any) -> URL:
  527. return self.__copy__()
  528. def __hash__(self) -> int:
  529. return hash(str(self))
  530. def __eq__(self, other: Any) -> bool:
  531. return (
  532. isinstance(other, URL)
  533. and self.drivername == other.drivername
  534. and self.username == other.username
  535. and self.password == other.password
  536. and self.host == other.host
  537. and self.database == other.database
  538. and self.query == other.query
  539. and self.port == other.port
  540. )
  541. def __ne__(self, other: Any) -> bool:
  542. return not self == other
  543. def get_backend_name(self) -> str:
  544. """Return the backend name.
  545. This is the name that corresponds to the database backend in
  546. use, and is the portion of the :attr:`_engine.URL.drivername`
  547. that is to the left of the plus sign.
  548. """
  549. if "+" not in self.drivername:
  550. return self.drivername
  551. else:
  552. return self.drivername.split("+")[0]
  553. def get_driver_name(self) -> str:
  554. """Return the backend name.
  555. This is the name that corresponds to the DBAPI driver in
  556. use, and is the portion of the :attr:`_engine.URL.drivername`
  557. that is to the right of the plus sign.
  558. If the :attr:`_engine.URL.drivername` does not include a plus sign,
  559. then the default :class:`_engine.Dialect` for this :class:`_engine.URL`
  560. is imported in order to get the driver name.
  561. """
  562. if "+" not in self.drivername:
  563. return self.get_dialect().driver
  564. else:
  565. return self.drivername.split("+")[1]
  566. def _instantiate_plugins(
  567. self, kwargs: Mapping[str, Any]
  568. ) -> Tuple[URL, List[Any], Dict[str, Any]]:
  569. plugin_names = util.to_list(self.query.get("plugin", ()))
  570. plugin_names += kwargs.get("plugins", [])
  571. kwargs = dict(kwargs)
  572. loaded_plugins = [
  573. plugins.load(plugin_name)(self, kwargs)
  574. for plugin_name in plugin_names
  575. ]
  576. u = self.difference_update_query(["plugin", "plugins"])
  577. for plugin in loaded_plugins:
  578. new_u = plugin.update_url(u)
  579. if new_u is not None:
  580. u = new_u
  581. kwargs.pop("plugins", None)
  582. return u, loaded_plugins, kwargs
  583. def _get_entrypoint(self) -> Type[Dialect]:
  584. """Return the "entry point" dialect class.
  585. This is normally the dialect itself except in the case when the
  586. returned class implements the get_dialect_cls() method.
  587. """
  588. if "+" not in self.drivername:
  589. name = self.drivername
  590. else:
  591. name = self.drivername.replace("+", ".")
  592. cls = registry.load(name)
  593. # check for legacy dialects that
  594. # would return a module with 'dialect' as the
  595. # actual class
  596. if (
  597. hasattr(cls, "dialect")
  598. and isinstance(cls.dialect, type)
  599. and issubclass(cls.dialect, Dialect)
  600. ):
  601. return cls.dialect
  602. else:
  603. return cast("Type[Dialect]", cls)
  604. def get_dialect(self, _is_async: bool = False) -> Type[Dialect]:
  605. """Return the SQLAlchemy :class:`_engine.Dialect` class corresponding
  606. to this URL's driver name.
  607. """
  608. entrypoint = self._get_entrypoint()
  609. if _is_async:
  610. dialect_cls = entrypoint.get_async_dialect_cls(self)
  611. else:
  612. dialect_cls = entrypoint.get_dialect_cls(self)
  613. return dialect_cls
  614. def translate_connect_args(
  615. self, names: Optional[List[str]] = None, **kw: Any
  616. ) -> Dict[str, Any]:
  617. r"""Translate url attributes into a dictionary of connection arguments.
  618. Returns attributes of this url (`host`, `database`, `username`,
  619. `password`, `port`) as a plain dictionary. The attribute names are
  620. used as the keys by default. Unset or false attributes are omitted
  621. from the final dictionary.
  622. :param \**kw: Optional, alternate key names for url attributes.
  623. :param names: Deprecated. Same purpose as the keyword-based alternate
  624. names, but correlates the name to the original positionally.
  625. """
  626. if names is not None:
  627. util.warn_deprecated(
  628. "The `URL.translate_connect_args.name`s parameter is "
  629. "deprecated. Please pass the "
  630. "alternate names as kw arguments.",
  631. "1.4",
  632. )
  633. translated = {}
  634. attribute_names = ["host", "database", "username", "password", "port"]
  635. for sname in attribute_names:
  636. if names:
  637. name = names.pop(0)
  638. elif sname in kw:
  639. name = kw[sname]
  640. else:
  641. name = sname
  642. if name is not None and getattr(self, sname, False):
  643. if sname == "password":
  644. translated[name] = str(getattr(self, sname))
  645. else:
  646. translated[name] = getattr(self, sname)
  647. return translated
  648. def make_url(name_or_url: Union[str, URL]) -> URL:
  649. """Given a string, produce a new URL instance.
  650. The format of the URL generally follows `RFC-1738
  651. <https://www.ietf.org/rfc/rfc1738.txt>`_, with some exceptions, including
  652. that underscores, and not dashes or periods, are accepted within the
  653. "scheme" portion.
  654. If a :class:`.URL` object is passed, it is returned as is.
  655. .. seealso::
  656. :ref:`database_urls`
  657. """
  658. if isinstance(name_or_url, str):
  659. return _parse_url(name_or_url)
  660. elif not isinstance(name_or_url, URL) and not hasattr(
  661. name_or_url, "_sqla_is_testing_if_this_is_a_mock_object"
  662. ):
  663. raise exc.ArgumentError(
  664. f"Expected string or URL object, got {name_or_url!r}"
  665. )
  666. else:
  667. return name_or_url
  668. def _parse_url(name: str) -> URL:
  669. pattern = re.compile(
  670. r"""
  671. (?P<name>[\w\+]+)://
  672. (?:
  673. (?P<username>[^:/]*)
  674. (?::(?P<password>[^@]*))?
  675. @)?
  676. (?:
  677. (?:
  678. \[(?P<ipv6host>[^/\?]+)\] |
  679. (?P<ipv4host>[^/:\?]+)
  680. )?
  681. (?::(?P<port>[^/\?]*))?
  682. )?
  683. (?:/(?P<database>[^\?]*))?
  684. (?:\?(?P<query>.*))?
  685. """,
  686. re.X,
  687. )
  688. m = pattern.match(name)
  689. if m is not None:
  690. components = m.groupdict()
  691. query: Optional[Dict[str, Union[str, List[str]]]]
  692. if components["query"] is not None:
  693. query = {}
  694. for key, value in parse_qsl(components["query"]):
  695. if key in query:
  696. query[key] = util.to_list(query[key])
  697. cast("List[str]", query[key]).append(value)
  698. else:
  699. query[key] = value
  700. else:
  701. query = None
  702. components["query"] = query
  703. if components["username"] is not None:
  704. components["username"] = unquote(components["username"])
  705. if components["password"] is not None:
  706. components["password"] = unquote(components["password"])
  707. ipv4host = components.pop("ipv4host")
  708. ipv6host = components.pop("ipv6host")
  709. components["host"] = ipv4host or ipv6host
  710. name = components.pop("name")
  711. if components["port"]:
  712. components["port"] = int(components["port"])
  713. return URL.create(name, **components) # type: ignore
  714. else:
  715. raise exc.ArgumentError(
  716. "Could not parse SQLAlchemy URL from string '%s'" % name
  717. )