U kf@x@s`dZddlmZddlmZddlZddlmZddlm Z ddlm Z ddlm Z ddlm Z dd lm Z dd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!GdddeZ"dddd d!Z#d"dd#d$d%Z$dS)&aProvides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates information about a database connection specification. The URL object is created automatically when :func:`~sqlalchemy.engine.create_engine` is called with a string argument; alternatively, the URL is a public-facing construct which can be used directly and is also accepted directly by ``create_engine()``. ) annotationsN)Any)cast)Dict)Iterable)List)Mapping) NamedTuple)Optional)overload)Sequence)Tuple)Type)Union) parse_qsl)quote) quote_plus)unquote)Dialect)exc)util)plugins)registryc @sDeZdZUdZded<ded<ded<ded<ded <ded <d ed <ed d d d d ejfdddddddddddZedddddZ eddddddZ eddddddZ edd dddZ deddddddddddd Z d!dd"d#d$Zdfdd&dd'd(d)Zdgd*d&dd+d,d-Zdhd.d&dd/d0d1Zd2dd3d4d5Zed6d7d8d9Zed:d;did&dd=d>d?Zdjd&dd=d@dAZdd7dBdCZdd7dDdEZd!ddFdGdHZdId7dJdKZd!d&dLdMdNZd!d&dLdOdPZdd7dQdRZdd7dSdTZdUdVdWdXdYZ dZd7d[d\Z!dkd&dZd]d^d_Z"dld`d!dadbdcddZ#d S)mURLa Represent the components of a URL used to connect to a database. URLs are typically constructed from a fully formatted URL string, where the :func:`.make_url` function is used internally by the :func:`_sa.create_engine` function in order to parse the URL string into its individual components, which are then used to construct a new :class:`.URL` object. When parsing from a formatted URL string, the parsing format generally follows `RFC-1738 `_, with some exceptions. A :class:`_engine.URL` object may also be produced directly, either by using the :func:`.make_url` function with a fully formed URL string, or by using the :meth:`_engine.URL.create` constructor in order to construct a :class:`_engine.URL` programmatically given individual fields. The resulting :class:`.URL` object may be passed directly to :func:`_sa.create_engine` in place of a string argument, which will bypass the usage of :func:`.make_url` within the engine's creation process. .. versionchanged:: 1.4 The :class:`_engine.URL` object is now an immutable object. To create a URL, use the :func:`_engine.make_url` or :meth:`_engine.URL.create` function / method. To modify a :class:`_engine.URL`, use methods like :meth:`_engine.URL.set` and :meth:`_engine.URL.update_query_dict` to return a new :class:`_engine.URL` object with modifications. See notes for this change at :ref:`change_5526`. .. seealso:: :ref:`database_urls` :class:`_engine.URL` contains the following attributes: * :attr:`_engine.URL.drivername`: database backend and driver name, such as ``postgresql+psycopg2`` * :attr:`_engine.URL.username`: username string * :attr:`_engine.URL.password`: password string * :attr:`_engine.URL.host`: string hostname * :attr:`_engine.URL.port`: integer port number * :attr:`_engine.URL.database`: string database name * :attr:`_engine.URL.query`: an immutable mapping representing the query string. contains strings for keys and either strings or tuples of strings for values. str drivernamez Optional[str]usernamepasswordhostz Optional[int]portdatabasez4util.immutabledict[str, Union[Tuple[str, ...], str]]queryNz'Mapping[str, Union[Sequence[str], str]])rrrr r!r"r#returnc Cs@|||d||d|||d||||d||S)aCreate a new :class:`_engine.URL` object. .. seealso:: :ref:`database_urls` :param drivername: the name of the database backend. This name will correspond to a module in sqlalchemy/databases or a third party plug-in. :param username: The user name. :param password: database password. Is typically a string, but may also be an object that can be stringified with ``str()``. .. note:: The password string should **not** be URL encoded when passed as an argument to :meth:`_engine.URL.create`; the string should contain the password characters exactly as they would be typed. .. note:: A password-producing object will be stringified only **once** per :class:`_engine.Engine` object. For dynamic password generation per connect, see :ref:`engines_dynamic_tokens`. :param host: The name of the host. :param port: The port number. :param database: The database name. :param query: A dictionary of string keys to string values to be passed to the dialect and/or the DBAPI upon connect. To specify non-string parameters to a Python DBAPI directly, use the :paramref:`_sa.create_engine.connect_args` parameter to :func:`_sa.create_engine`. See also :attr:`_engine.URL.normalized_query` for a dictionary that is consistently string->list of string. :return: new :class:`_engine.URL` object. .. versionadded:: 1.4 The :class:`_engine.URL` object is now an **immutable named tuple**. In addition, the ``query`` dictionary is also immutable. To create a URL, use the :func:`_engine.url.make_url` or :meth:`_engine.URL.create` function/ method. To modify a :class:`_engine.URL`, use the :meth:`_engine.URL.set` and :meth:`_engine.URL.update_query` methods. rrr r") _assert_str_assert_none_str _assert_port _str_dict)clsrrrr r!r"r#r*E/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/engine/url.pycreates8    z URL.create)r!r$cCs8|dkr dSz t|WStk r2tdYnXdS)Nz(Port argument must be an integer or None)int TypeError)r)r!r*r*r+r's  zURL._assert_port)v paramnamer$cCst|tstd||S)Nz%s must be a string isinstancerr.r)r/r0r*r*r+r%s  zURL._assert_strcCs|dkr |S|||SN)r%r3r*r*r+r&szURL._assert_none_strziOptional[Union[Sequence[Tuple[str, Union[Sequence[str], str]]], Mapping[str, Union[Sequence[str], str]]]])dict_r$cs|dkrtjStdddddtddddddddfd d ddd d d t|tjrl|}n|}tfd d|DS)Nr)valr$cSsdSr4r*r6r*r*r+ _assert_valuesz$URL._str_dict.._assert_valuez Sequence[str]zUnion[str, Tuple[str, ...]]cSsdSr4r*r7r*r*r+r8szUnion[str, Sequence[str]]cs<t|tr|St|tjr0tfdd|DStddS)Nc3s|]}|VqdSr4r*).0elemr8r*r+ sz7URL._str_dict.._assert_value..z?Query dictionary values must be strings or sequences of strings)r2rcollections_abcr tupler.r7r;r*r+r8s  )r/r$cSst|tstd|S)Nz%Query dictionary keys must be stringsr1)r/r*r*r+r%s z"URL._str_dict.._assert_strcsi|]\}}||qSr*r*)r9keyvaluer%r8r*r+ s z!URL._str_dict..)r EMPTY_DICTr r2r=r items immutabledict)r)r5 dict_itemsr*rAr+r(s    z URL._str_dictz1Optional[Mapping[str, Union[Sequence[str], str]]]c Csi}|dk r||d<|dk r$||d<|dk r4||d<|dk rD||d<|dk rT||d<|dk rd||d<|dk rt||d<|jf|S) areturn a new :class:`_engine.URL` object with modifications. Values are used if they are non-None. To set a value to ``None`` explicitly, use the :meth:`_engine.URL._replace` method adapted from ``namedtuple``. :param drivername: new drivername :param username: new username :param password: new password :param host: new hostname :param port: new port :param query: new query parameters, passed a dict of string keys referring to string or sequence of string values. Fully replaces the previous list of arguments. :return: new :class:`_engine.URL` object. .. versionadded:: 1.4 .. seealso:: :meth:`_engine.URL.update_query_dict` Nrrrr r!r"r#)_assert_replace) selfrrrr r!r"r#kwr*r*r+set(s #zURL.setr)rIr$cKsvd|kr||dddD]}||kr||||qd|krP||dd|krj||d|d<|jf|S)z)argument checks before calling _replace()r)rr r"r!r#)r%r&r'r(_replace)rHrInamer*r*r+rG]szURL._assert_replaceFbool) query_stringappendr$cCs|jt||dS)aEReturn a new :class:`_engine.URL` object with the :attr:`_engine.URL.query` parameter dictionary updated by the given query string. E.g.:: >>> from sqlalchemy.engine import make_url >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname") >>> url = url.update_query_string("alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt") >>> str(url) 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt' :param query_string: a URL escaped query string, not including the question mark. :param append: if True, parameters in the existing query string will not be removed; new parameters will be in addition to those present. If left at its default of False, keys present in the given query parameters will replace those of the existing query string. .. versionadded:: 1.4 .. seealso:: :attr:`_engine.URL.query` :meth:`_engine.URL.update_query_dict` rO)update_query_pairsr)rHrNrOr*r*r+update_query_stringlszURL.update_query_stringz+Iterable[Tuple[str, Union[str, List[str]]]])key_value_pairsrOr$cs|ji}|D]\\}}||krLt||||<td||tt|qt|ttfrbt|n|||<q|ri}|D]>}|krtt|t||||<qx||||<qx| fddt  |Dn|j dd| D}|j |dS)aReturn a new :class:`_engine.URL` object with the :attr:`_engine.URL.query` parameter dictionary updated by the given sequence of key/value pairs E.g.:: >>> from sqlalchemy.engine import make_url >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname") >>> url = url.update_query_pairs([("alt_host", "host1"), ("alt_host", "host2"), ("ssl_cipher", "/path/to/crt")]) >>> str(url) 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt' :param key_value_pairs: A sequence of tuples containing two strings each. :param append: if True, parameters in the existing query string will not be removed; new parameters will be in addition to those present. If left at its default of False, keys present in the given query parameters will replace those of the existing query string. .. versionadded:: 1.4 .. seealso:: :attr:`_engine.URL.query` :meth:`_engine.URL.difference_update_query` :meth:`_engine.URL.set` List[str]csi|]}||qSr*r*)r9kZexisting_queryr*r+rBsz*URL.update_query_pairs..cSs(i|] \}}|t|tr t|n|qSr*)r2listr>r9rUr/r*r*r+rBsr#)r#rto_listrrOrr2rWr>updaterJ differenceunionrD)rHrSrOZnew_keysr?r@Z new_queryrUr*rVr+rQs:%      zURL.update_query_pairsz#Mapping[str, Union[str, List[str]]])query_parametersrOr$cCs|j||dS)aReturn a new :class:`_engine.URL` object with the :attr:`_engine.URL.query` parameter dictionary updated by the given dictionary. The dictionary typically contains string keys and string values. In order to represent a query parameter that is expressed multiple times, pass a sequence of string values. E.g.:: >>> from sqlalchemy.engine import make_url >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname") >>> url = url.update_query_dict({"alt_host": ["host1", "host2"], "ssl_cipher": "/path/to/crt"}) >>> str(url) 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt' :param query_parameters: A dictionary with string keys and values that are either strings, or sequences of strings. :param append: if True, parameters in the existing query string will not be removed; new parameters will be in addition to those present. If left at its default of False, keys present in the given query parameters will replace those of the existing query string. .. versionadded:: 1.4 .. seealso:: :attr:`_engine.URL.query` :meth:`_engine.URL.update_query_string` :meth:`_engine.URL.update_query_pairs` :meth:`_engine.URL.difference_update_query` :meth:`_engine.URL.set` rP)rQrD)rHr^rOr*r*r+update_query_dicts/zURL.update_query_dictz Iterable[str])namesr$c sTt|jsStjjjjjj t fddtj |DS)a Remove the given names from the :attr:`_engine.URL.query` dictionary, returning the new :class:`_engine.URL`. E.g.:: url = url.difference_update_query(['foo', 'bar']) Equivalent to using :meth:`_engine.URL.set` as follows:: url = url.set( query={ key: url.query[key] for key in set(url.query).difference(['foo', 'bar']) } ) .. versionadded:: 1.4 .. seealso:: :attr:`_engine.URL.query` :meth:`_engine.URL.update_query_dict` :meth:`_engine.URL.set` csi|]}|j|qSr*rY)r9r?rHr*r+rB4sz/URL.difference_update_query..) rJ intersectionr#rrrrr r!r"rrEr\)rHr`r*rar+difference_update_query s zURL.difference_update_queryzMapping[str, Sequence[str]])r$cCstdd|jDS)aReturn the :attr:`_engine.URL.query` dictionary with values normalized into sequences. As the :attr:`_engine.URL.query` dictionary may contain either string values or sequences of string values to differentiate between parameters that are specified multiple times in the query string, code that needs to handle multiple parameters generically will wish to use this attribute so that all parameters present are presented as sequences. Inspiration is from Python's ``urllib.parse.parse_qs`` function. E.g.:: >>> from sqlalchemy.engine import make_url >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt") >>> url.query immutabledict({'alt_host': ('host1', 'host2'), 'ssl_cipher': '/path/to/crt'}) >>> url.normalized_query immutabledict({'alt_host': ('host1', 'host2'), 'ssl_cipher': ('/path/to/crt',)}) cSs&i|]\}}|t|ts|fn|qSr*)r2r>rXr*r*r+rBSsz(URL.normalized_query..)rrEr#rDrar*r*r+normalized_query;s zURL.normalized_query1.4zThe :meth:`_engine.URL.__to_string__ method is deprecated and will be removed in a future release. Please use the :meth:`_engine.URL.render_as_string` method.T) hide_passwordr$cCs |j|dS)zRender this :class:`_engine.URL` object as a string. :param hide_password: Defaults to True. The password is not shown in the string unless this is set to False. )rfrender_as_string)rHrfr*r*r+ __to_string__Ys zURL.__to_string__csjd}jdk rZ|tjdd7}jdk rR|d|r.) rrrrrr r!r"r#rWsortjoin)rHrfskeysr*rar+rhhs2          zURL.render_as_stringcCs|Sr4rgrar*r*r+__repr__sz URL.__repr__c Cs&|j|j|j|j|j|j|j|jSr4) __class__r,rrrr r!r"r#rar*r*r+__copy__sz URL.__copy__)memor$cCs|Sr4)rz)rHr{r*r*r+ __deepcopy__szURL.__deepcopy__r-cCs tt|Sr4)hashrrar*r*r+__hash__sz URL.__hash__)otherr$cCs^t|to\|j|jko\|j|jko\|j|jko\|j|jko\|j|jko\|j|jko\|j|jkSr4) r2rrrrr r"r#r!rHrr*r*r+__eq__s        z URL.__eq__cCs ||k Sr4r*rr*r*r+__ne__sz URL.__ne__cCs$d|jkr|jS|jddSdS)zReturn the backend name. This is the name that corresponds to the database backend in use, and is the portion of the :attr:`_engine.URL.drivername` that is to the left of the plus sign. +rN)rsplitrar*r*r+get_backend_names zURL.get_backend_namecCs(d|jkr|jS|jddSdS)aReturn the backend name. This is the name that corresponds to the DBAPI driver in use, and is the portion of the :attr:`_engine.URL.drivername` that is to the right of the plus sign. If the :attr:`_engine.URL.drivername` does not include a plus sign, then the default :class:`_engine.Dialect` for this :class:`_engine.URL` is imported in order to get the driver name. rrN)r get_dialectZdriverrrar*r*r+get_driver_names  zURL.get_driver_namezMapping[str, Any]z%Tuple[URL, List[Any], Dict[str, Any]])kwargsr$cstjdd}|dg7}tfdd|D}ddg}|D]}||}|dk rR|}qRdd||fS)Npluginr*rcsg|]}t|qSr*)rload)r9Z plugin_namerrHr*r+ sz,URL._instantiate_plugins..)rrZr#getdictrcZ update_urlpop)rHrZ plugin_namesZloaded_pluginsurZnew_ur*rr+_instantiate_pluginss   zURL._instantiate_plugins Type[Dialect]cCs`d|jkr|j}n|jdd}t|}t|drRt|jtrRt|jt rR|jSt d|SdS)zReturn the "entry point" dialect class. This is normally the dialect itself except in the case when the returned class implements the get_dialect_cls() method. r.dialectrN) rreplacerrhasattrr2rtype issubclassrr)rHrLr)r*r*r+_get_entrypoints    zURL._get_entrypoint) _is_asyncr$cCs&|}|r||}n ||}|S)zoReturn the SQLAlchemy :class:`_engine.Dialect` class corresponding to this URL's driver name. )rZget_async_dialect_clsZget_dialect_cls)rHr entrypointZ dialect_clsr*r*r+rs   zURL.get_dialectzOptional[List[str]]zDict[str, Any])r`rIr$cKs|dk rtddi}dddddg}|D]h}|r>|d }n||krP||}n|}|dk r*t||d r*|dkrtt||||<q*t||||<q*|S) a2Translate url attributes into a dictionary of connection arguments. Returns attributes of this url (`host`, `database`, `username`, `password`, `port`) as a plain dictionary. The attribute names are used as the keys by default. Unset or false attributes are omitted from the final dictionary. :param \**kw: Optional, alternate key names for url attributes. :param names: Deprecated. Same purpose as the keyword-based alternate names, but correlates the name to the original positionally. NzpThe `URL.translate_connect_args.name`s parameter is deprecated. Please pass the alternate names as kw arguments.rer r"rrr!rF)rZwarn_deprecatedrgetattrr)rHr`rIZ translatedZattribute_namesZsnamerLr*r*r+translate_connect_argss$  zURL.translate_connect_args)NNNNNNN)F)F)F)T)T)F)N)$__name__ __module__ __qualname____doc____annotations__ classmethodrrCr,r'r%r&r(rJrGrRrQr_rcpropertyrd deprecatedrirhrxrzr|r~rrrrrrrrr*r*r*r+r.sz 2 A95$P10 '    rzUnion[str, URL]) name_or_urlr$cCs@t|trt|St|ts8t|ds8td|n|SdS)aGiven a string, produce a new URL instance. The format of the URL generally follows `RFC-1738 `_, with some exceptions, including that underscores, and not dashes or periods, are accepted within the "scheme" portion. If a :class:`.URL` object is passed, it is returned as is. .. seealso:: :ref:`database_urls` Z)_sqla_is_testing_if_this_is_a_mock_objectz#Expected string or URL object, got N)r2r _parse_urlrrr ArgumentError)rr*r*r+make_url9s  rr)rLr$c Cs2tdtj}||}|dk r |}|ddk ri}t|dD]@\}}||kr~t||||<td|| |qF|||<qFnd}||d<|ddk rt |d|d<|ddk rt |d|d<| d}| d}|p||d<| d }|d rt |d |d <t j|f|Std |dS) Na (?P[\w\+]+):// (?: (?P[^:/]*) (?::(?P[^@]*))? @)? (?: (?: \[(?P[^/\?]+)\] | (?P[^/:\?]+) )? (?::(?P[^/\?]*))? )? (?:/(?P[^\?]*))? (?:\?(?P.*))? r#rTrripv4hostipv6hostr rLr!z/Could not parse SQLAlchemy URL from string '%s')recompileXmatch groupdictrrrZrrOrrr-rr,rr) rLpatternm componentsr#r?r@rrr*r*r+rUs<           r)%r __future__rcollections.abcabcr=rtypingrrrrrrr r r r r rr urllib.parserrrrZ interfacesrrrZdialectsrrrrrr*r*r*r+sD