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